Compare commits

..
19 Commits
Author SHA1 Message Date
ZyyandCodex b5e691c63d fix(dashboard): animate incremental data updates
Preserve chart state across updates and animate capacity, status distribution, and account reordering. Keep metric transition values synchronized when reduced motion is enabled.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 14:50:05 +08:00
Zyy 2d0a52096a fix(workers): prioritize shutdown during background tasks 2026-12-03 13:56:18 +08:00
github-actions[bot] 47620e217a chore(release): update release channels to 3.61.1-rc.2 2026-12-03 05:16:01 +00:00
ZyyandCodex 48aeccd0e0 chore: bump version to 3.61.1-rc.2
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:54:43 +08:00
bdc618701b feat(system): add confirmed manual service restart (#832)
* feat(system): add confirmed manual service restart

Co-authored-by: Codex <noreply@openai.com>

* fix(system): preserve restart for legacy update responses

Co-authored-by: Codex <noreply@openai.com>

* fix(system): require explicit restart support

Co-authored-by: Codex <noreply@openai.com>

* docs(deploy): drop legacy restart notes

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:48:52 +08:00
ZyyandCodex acd76a09dc fix(ui): keep loading feedback with the active action
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:35:57 +08:00
ZyyandCodex 808387442b docs: strengthen frontend interaction verification
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 12:35:57 +08:00
5bc4e3e5c8 fix(routing): scope Fast policy to the selected account (#829)
* fix(gateway): resolve fast policy from the account's hit group

Bound-group fast policies were merged once per API key at snapshot
compile time, so a disabled or forced group on the same key leaked its
policy onto accounts that only belong to other enabled groups. Keep the
per-group policies frozen on the account scope, skip disabled groups
when merging, and resolve the effective fast mode from the account the
request actually hit, falling back to the key-level merged value only
when the account matches no enabled bound group.

* ci: retrigger checks

* style(gateway): rustfmt the account-scoped fast mode helper

* fix(routing): scope Fast policy to selected eligible groups

Co-authored-by: Codex <noreply@openai.com>

* fix(routing): preserve explicit default Fast overrides

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:39:33 +08:00
7e98130cac fix(openai): re-anchor bucket warmup after early quota reset (#830)
* fix(openai): re-anchor bucket warmup after upstream early quota reset

* fix(openai): record initial usage for early reset warmup

Co-authored-by: Codex <noreply@openai.com>

* fix(openai): preserve precise bucket reset boundaries

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
2821a5e3bd fix(protocol): handle empty Chat history and nullable fields (#831)
* fix(protocol): accept null-content system/developer chat messages

Codex 客户端偶尔会发送 content 为 null 的 system 消息,公共校验按空内容拒绝并报
Parameter messages[N].content has an invalid value。允许 system/developer 消息
内容为空,genai 与 messages 转换跳过空内容,responses 目标已自然忽略。

fixes #824

* fix(protocol): normalize empty Chat history and nullable fields

Co-authored-by: Codex <noreply@openai.com>

---------

Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
ZyyandCodex 6a6a167d41 perf(openai): trim SSE history after privacy processing
Match privacy-processed SSE requests against the existing WebSocket history prefix. Keep full input on a mismatch and resume trimming after a matching completed turn.

Record body receipt, authentication, decompression, decoding and execution preparation timings to distinguish ingress delays from upstream latency.

Cover metadata, body and header privacy across reuse, mismatch and resumed reuse.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 11:36:44 +08:00
ZyyandCodex cffb6b35d2 fix(protocol): handle empty Chat history and nullable request fields
Treat explicit null text as empty in Chat content blocks and preserve user input, tool results, and cache breakpoints during conversion. Resolve nullable format and reasoning controls consistently with routing, and forward stop sequences to Messages and GenAI.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex 17e50df06f fix(accounts): hide zero token usage in the account list
Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex f2d95cc3fa fix(errors): clarify account selection and upstream failures
Report WebSocket transport constraints separately from exhausted account quota, including mixed account pools. Clarify routing, concurrency, authentication, permission, transport and protocol failure messages while preserving upstream error details.

Update HTTP and WebSocket regression coverage and document the client error contract. Validate 2,620 tests, workspace Clippy, formatting and architecture checks.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
ZyyandCodex e4f6e1d4e3 fix(protocol): align response request IDs with Codex
Share the four Codex request ID headers across HTTP, WebSocket, diagnostics, and continuation failures. Preserve current-failure IDs and the model execution ID fallback, and remove unsupported aliases.

Update regression coverage and the public API contract.

Co-authored-by: Codex <noreply@openai.com>
2026-12-03 10:28:00 +08:00
github-actions[bot] 66f650f097 chore(release): update release channels to 3.61.1-rc.1 2026-12-02 13:47:28 +00:00
ZyyandCodex ca4d02068a chore: bump version to 3.61.1-rc.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-02 21:33:34 +08:00
Zyy d185a639a9 perf(openai): send incremental SSE history over pooled WebSockets 2026-12-02 21:09:28 +08:00
github-actions[bot] 3078dd9993 chore(release): update release channels to 3.61.0 2026-12-01 13:39:52 +00:00
122 changed files with 3253 additions and 879 deletions
@@ -30,6 +30,8 @@
验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围 验证前按[界面验证](../../../../CONTRIBUTING.md#界面验证)明确本次受影响的用户路径、状态和通过条件。局部修改围绕受影响区域及相关操作验收;主题、窗口尺寸和空/加载/错误状态仅在受影响时补充,共用主题或基础组件变更按主题规范扩大范围
沿实际操作验证待确认、执行中、完成、失败与取消等受影响阶段,同时检查当前弹层和背景区域,核对应该出现的反馈与不应出现的状态。必要时延迟模拟响应以观察过渡状态,不能仅凭请求成功或截图齐全判定交互通过
通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据 通过后按[验证停止条件](../../../../CONTRIBUTING.md#验证)收尾;只有新改动、失败或未解疑点时补验相关部分。补交截图或 PR 材料时复用仍有效的运行证据
## 交付前 ## 交付前
@@ -42,7 +44,7 @@
- **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确 - **样式与状态**:是否使用对应 Token 与 utility,局部样式是否符合适用边界,受影响的主题、窄屏及交互状态是否正确
- **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置 - **模块归属**从调用方核对公开入口。页面或多文件组件通过 `index.vue` 提供界面,其他页面复用整页时引用所属模块的布局入口,独立复用的业务组件按领域放置
- **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属 - **Provider 边界**涉及账号操作、身份配置或定价时,沿接口响应、控件和提交载荷追踪同一条规则。服务端决定的能力使用接口字段,Provider 专属表单解释自己的字段,多个页面共用的编辑流程只维护一份。按[前端职责](../../../../docs/architecture.md#34-前端模块职责)核对归属
- **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,核对 loading、禁用状态的影响范围;沿用请求层错误处理,不在页面叠加同一错误的提示 - **查询与动作**:区分首次加载、刷新、分页、单行与批量操作,明确当前动作的反馈归属及其他控件的禁用范围,避免同一动作在前后景重复显示执行反馈。待确认不等于已提交,复用交互时重新核对 loading、进度与结果的显示条件是否适用于当前动作;沿用请求层错误处理,不在页面叠加同一错误的提示
- **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行 - **运行证据**:按界面验证核对截图与实际交互,证据对应当前实现;页面 PR 的可访问图片和 Draft 条件按该节执行
交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为 交付简述所复用的页面或组件、实际验证范围及缺口;环境不足时如实说明,不能仅凭构建、源码或截图推断未验证的行为
+1
View File
@@ -1887,6 +1887,7 @@ dependencies = [
"tracing", "tracing",
"tracing-appender", "tracing-appender",
"tracing-subscriber", "tracing-subscriber",
"uuid",
"wiremock", "wiremock",
"yaml-rust2 0.13.2", "yaml-rust2 0.13.2",
] ]
@@ -263,10 +263,11 @@ impl ScheduledTask for FreezeRecoveryTask {
context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
if context.cancellation().is_cancelled() { // 中止在途探测,避免把停机当成探测失败而延长冻结
return Ok(()); context
} .cancellation()
self.run_cycle_inner().await; .run_until_cancelled(self.run_cycle_inner())
.await;
Ok(()) Ok(())
}) })
} }
@@ -50,6 +50,8 @@ pub struct SystemUpdatePolicy {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct SystemVersion { pub struct SystemVersion {
pub version: String, pub version: String,
pub instance_id: String,
pub restart_supported: bool,
pub git_sha: String, pub git_sha: String,
pub build_time: String, pub build_time: String,
pub deployment_mode: String, pub deployment_mode: String,
@@ -55,37 +55,44 @@ impl ScheduledTask for ResetCreditAutomationTask {
context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
let settings = self context
.settings .cancellation()
.load_runtime_settings() .run_until_cancelled(self.run_due())
.await .await
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?; .unwrap_or(Ok(()))
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
let due = self
.store
.due_reset_credit_automations(Utc::now(), 100)
.await
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
let work = futures::stream::iter(due)
.map(|account_id| async move {
let id = ProviderAccountId::new(account_id.clone())
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
tracing::warn!(
account_id,
error_kind = error.kind().as_str(),
"自动重置卡任务失败"
);
}
Ok::<_, WorkerTaskError>(())
})
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
.collect::<Vec<_>>();
tokio::select! {
() = context.cancellation().cancelled() => {},
_ = tokio::time::timeout(Duration::from_secs(30), work) => {},
}
Ok(())
}) })
} }
} }
impl ResetCreditAutomationTask {
async fn run_due(&self) -> Result<(), WorkerTaskError> {
let settings = self
.settings
.load_runtime_settings()
.await
.map_err(|_| WorkerTaskError::safe("重置卡设置读取失败"))?;
// 单轮有界,积压沿到期顺序继续;并发复用已有账号刷新配置
let due = self
.store
.due_reset_credit_automations(Utc::now(), 100)
.await
.map_err(|_| WorkerTaskError::safe("重置卡计划读取失败"))?;
let work = futures::stream::iter(due)
.map(|account_id| async move {
let id = ProviderAccountId::new(account_id.clone())
.map_err(|_| WorkerTaskError::safe("重置卡账号 ID 不合法"))?;
if let Err(error) = self.accounts.reconcile_reset_credit_automation(id).await {
tracing::warn!(
account_id,
error_kind = error.kind().as_str(),
"自动重置卡任务失败"
);
}
Ok::<_, WorkerTaskError>(())
})
.buffer_unordered(settings.values.refresh_concurrency.max(1) as usize)
.collect::<Vec<_>>();
let _ = tokio::time::timeout(Duration::from_secs(30), work).await;
Ok(())
}
}
@@ -27,6 +27,8 @@ impl SystemOperations for RecordingSystemOperations {
} }
Ok(SystemVersion { Ok(SystemVersion {
version: "1.0.0".to_owned(), version: "1.0.0".to_owned(),
instance_id: "test-instance".to_owned(),
restart_supported: false,
git_sha: "unknown".to_owned(), git_sha: "unknown".to_owned(),
build_time: "unknown".to_owned(), build_time: "unknown".to_owned(),
deployment_mode: "source".to_owned(), deployment_mode: "source".to_owned(),
@@ -81,6 +81,8 @@ impl UpdateRequest {
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct SystemVersionView { struct SystemVersionView {
version: String, version: String,
instance_id: String,
restart_supported: bool,
git_sha: String, git_sha: String,
build_time: String, build_time: String,
deployment_mode: String, deployment_mode: String,
@@ -97,6 +99,8 @@ impl From<SystemVersion> for SystemVersionView {
Self { Self {
deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(), deployment_mode_label: deployment_mode_label(&version.deployment_mode).to_owned(),
version: version.version, version: version.version,
instance_id: version.instance_id,
restart_supported: version.restart_supported,
git_sha: version.git_sha, git_sha: version.git_sha,
build_time: version.build_time, build_time: version.build_time,
deployment_mode: version.deployment_mode, deployment_mode: version.deployment_mode,
@@ -11,6 +11,7 @@ use gateway_core::{
error::ProviderErrorKind, error::ProviderErrorKind,
policy::{ClientVersionRejection, CodexClientKind}, policy::{ClientVersionRejection, CodexClientKind},
}; };
use gateway_protocol::http::preferred_response_request_id;
use serde_json::{Value, json}; use serde_json::{Value, json};
pub use gateway_core::engine::execution::gateway_error_from_engine; pub use gateway_core::engine::execution::gateway_error_from_engine;
@@ -170,8 +171,8 @@ pub fn engine_error_response(error: &EngineError) -> Response {
}; };
response.headers_mut().append(name, value); response.headers_mut().append(name, value);
} }
if !response.headers().contains_key("x-request-id") if preferred_response_request_id(|name| response.headers().get(name)?.to_str().ok())
&& !response.headers().contains_key("x-oai-request-id") .is_none()
&& let Some(request_id) = error.upstream_request_id() && let Some(request_id) = error.upstream_request_id()
&& let Ok(value) = HeaderValue::from_str(request_id.as_str()) && let Ok(value) = HeaderValue::from_str(request_id.as_str())
{ {
@@ -665,7 +665,7 @@ fn engine_error_response_with_headers(
response_headers: &[ProviderResponseHeader], response_headers: &[ProviderResponseHeader],
) -> Response { ) -> Response {
let response = engine_error_response(error); let response = engine_error_response(error);
let failure_request_ids = ["x-request-id", "x-oai-request-id"] let failure_request_ids = gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS
.into_iter() .into_iter()
.flat_map(|name| { .flat_map(|name| {
response response
@@ -678,8 +678,9 @@ fn engine_error_response_with_headers(
.collect::<Vec<_>>(); .collect::<Vec<_>>();
// 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态 // 失败后仍须交付已采集的 turn state;只隔离 opening 身份,不丢弃会话状态
let mut response = apply_provider_response_headers(response, response_headers); let mut response = apply_provider_response_headers(response, response_headers);
response.headers_mut().remove("x-request-id"); for name in gateway_protocol::http::RESPONSE_REQUEST_ID_HEADERS {
response.headers_mut().remove("x-oai-request-id"); response.headers_mut().remove(name);
}
for (name, value) in failure_request_ids { for (name, value) in failure_request_ids {
response.headers_mut().append(name, value); response.headers_mut().append(name, value);
} }
@@ -37,11 +37,11 @@ pub(crate) fn with_model_request_id(
let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty()); let usable = |value: &HeaderValue| value.to_str().is_ok_and(|id| !id.trim().is_empty());
if !headers.get("x-request-id").is_some_and(usable) { if !headers.get("x-request-id").is_some_and(usable) {
// 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID // 只有别名时沿用同一个上游值,避免外层 middleware 再填入入口 ID
let client_id = headers let client_id = gateway_protocol::http::preferred_response_request_id(|name| {
.get("x-oai-request-id") headers.get(name)?.to_str().ok()
.filter(|value| usable(value)) })
.unwrap_or(&gateway_id) .and_then(|value| HeaderValue::from_str(value).ok())
.clone(); .unwrap_or_else(|| gateway_id.clone());
headers.insert("x-request-id", client_id); headers.insert("x-request-id", client_id);
} }
headers.insert("x-gateway-request-id", gateway_id); headers.insert("x-gateway-request-id", gateway_id);
@@ -7,6 +7,7 @@ use crate::{
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response}, auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
error::gateway_error_response, error::gateway_error_response,
generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation}, generation::{GenerationEndpoint, GenerationHttpRequest, execute_prepared_generation},
router::IngressStarted,
}, },
}; };
use axum::{ use axum::{
@@ -15,18 +16,43 @@ use axum::{
http::{HeaderMap, StatusCode}, http::{HeaderMap, StatusCode},
response::Response, response::Response,
}; };
use std::net::SocketAddr; use std::{net::SocketAddr, time::Instant};
/// `POST /v1/responses` /// `POST /v1/responses`
pub(crate) async fn responses( pub(crate) async fn responses(
State(state): State<ApiState>, State(state): State<ApiState>,
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>, connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
ingress_id: Option<Extension<tower_http::request_id::RequestId>>, ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
ingress_started: Option<Extension<IngressStarted>>,
headers: HeaderMap, headers: HeaderMap,
body: Bytes, body: Bytes,
) -> Response { ) -> Response {
// Bytes extractor 已读完传输正文;此时尚未认证、解压或解析 JSON
let mut encodings = headers.get_all(axum::http::header::CONTENT_ENCODING).iter();
let encoding = match (encodings.next(), encodings.next()) {
(None, _) => "identity",
(Some(value), None) => value
.to_str()
.ok()
.and_then(|value| {
["identity", "gzip", "deflate", "zstd"]
.into_iter()
.find(|known| known.eq_ignore_ascii_case(value.trim()))
})
.unwrap_or("other"),
_ => "other",
};
tracing::info!(target: "request_trace", stage = "http.body.received",
receive_ms = ingress_started.map(|Extension(start)| start.0.elapsed().as_millis()),
encoded_bytes = body.len(), content_encoding = encoding,
"HTTP request body received");
let service = state.data_plane().clone(); let service = state.data_plane().clone();
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await { let started = Instant::now();
let authentication = authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await;
tracing::info!(target: "request_trace", stage = "http.auth.finished",
auth_ms = started.elapsed().as_millis(), accepted = authentication.is_ok(),
"HTTP request authentication finished");
let client = match authentication {
Ok(client) => client, Ok(client) => client,
Err(error) => return client_access_error_response(error), Err(error) => return client_access_error_response(error),
}; };
@@ -42,7 +68,12 @@ pub(crate) async fn responses(
} }
}; };
let execution = service.execution(); let execution = service.execution();
let prepared = match execution.prepare_execution(client).await { let started = Instant::now();
let preparation = execution.prepare_execution(client).await;
tracing::info!(target: "request_trace", stage = "http.execution.prepared",
prepare_ms = started.elapsed().as_millis(), accepted = preparation.is_ok(),
"HTTP execution preparation finished");
let prepared = match preparation {
Ok(prepared) => prepared, Ok(prepared) => prepared,
Err(error) => return gateway_error_response(&error), Err(error) => return gateway_error_response(&error),
}; };
@@ -143,9 +143,20 @@ pub(crate) fn decode_request_with_body(
headers: &HeaderMap, headers: &HeaderMap,
max_decompressed_bytes: usize, max_decompressed_bytes: usize,
) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> { ) -> Result<(DecodedGenerationRequest, Bytes), RequestDecodeError> {
let body = decompress_request_body(body, headers, max_decompressed_bytes)?; let started = std::time::Instant::now();
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))?; let decompressed = decompress_request_body(body, headers, max_decompressed_bytes);
Ok((decoded, Bytes::copy_from_slice(&body))) tracing::info!(target: "request_trace", stage = "http.body.decompressed",
decompress_ms = started.elapsed().as_millis(),
decoded_bytes = decompressed.as_ref().ok().map(|body| body.len()),
accepted = decompressed.is_ok(), "HTTP request body decompressed");
let body = decompressed?;
let started = std::time::Instant::now();
let decoded = decode_request_inner(&body, &OpenAiRequestHeaders::from_headers(headers))
.map(|decoded| (decoded, Bytes::copy_from_slice(&body)));
tracing::info!(target: "request_trace", stage = "http.body.decoded",
decode_ms = started.elapsed().as_millis(), accepted = decoded.is_ok(),
"HTTP request body decoded");
decoded
} }
pub(super) fn decode_request_inner( pub(super) fn decode_request_inner(
@@ -8,6 +8,7 @@ use axum::http::{HeaderName, HeaderValue, StatusCode};
use gateway_core::engine::EngineError; use gateway_core::engine::EngineError;
use gateway_core::error::ProviderErrorKind; use gateway_core::error::ProviderErrorKind;
use gateway_core::event::ProviderResponseHeader; use gateway_core::event::ProviderResponseHeader;
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
use thiserror::Error; use thiserror::Error;
@@ -119,9 +120,12 @@ pub(super) fn response_metadata_event(
response_headers: &[ProviderResponseHeader], response_headers: &[ProviderResponseHeader],
) -> String { ) -> String {
let mut headers = response_event_headers(response_headers); let mut headers = response_event_headers(response_headers);
let client_request_id = preferred_response_request_id(|name| headers.get(name)?.as_str())
.unwrap_or(request_id)
.to_owned();
headers headers
.entry("x-request-id".to_owned()) .entry("x-request-id".to_owned())
.or_insert_with(|| Value::String(request_id.to_owned())); .or_insert(Value::String(client_request_id));
json!({ json!({
"type": "response.metadata", "type": "response.metadata",
"headers": headers, "headers": headers,
@@ -149,7 +153,7 @@ fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<St
let Ok(value) = std::str::from_utf8(header.value()) else { let Ok(value) = std::str::from_utf8(header.value()) else {
continue; continue;
}; };
if matches!(name.as_str(), "x-request-id" | "x-oai-request-id") if RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str())
&& (value.trim().is_empty() || http_value.to_str().is_err()) && (value.trim().is_empty() || http_value.to_str().is_err())
{ {
continue; continue;
@@ -182,8 +186,9 @@ pub(super) fn initial_engine_error_event(
}; };
if upstream.is_none() { if upstream.is_none() {
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头 // 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
headers.remove("x-request-id"); for name in RESPONSE_REQUEST_ID_HEADERS {
headers.remove("x-oai-request-id"); headers.remove(name);
}
} }
let status = if provider let status = if provider
.is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable) .is_some_and(|error| error.kind() == ProviderErrorKind::UpstreamCapacityUnavailable)
@@ -221,7 +226,7 @@ pub(super) fn initial_engine_error_event(
} }
fn has_request_id(headers: &Map<String, Value>) -> bool { fn has_request_id(headers: &Map<String, Value>) -> bool {
headers.contains_key("x-request-id") || headers.contains_key("x-oai-request-id") preferred_response_request_id(|name| headers.get(name)?.as_str()).is_some()
} }
pub(super) fn error_event( pub(super) fn error_event(
@@ -46,6 +46,10 @@ pub(crate) fn router() -> Router<ApiState> {
.merge(super::provider_endpoints::router()) .merge(super::provider_endpoints::router())
} }
/// 在读取正文前保存入口时刻,交给端点区分接收与执行耗时
#[derive(Clone, Copy)]
pub(crate) struct IngressStarted(pub(crate) std::time::Instant);
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
pub(crate) enum DataPlaneNamespace { pub(crate) enum DataPlaneNamespace {
V1, V1,
@@ -19,7 +19,7 @@ use serde_json::json;
use tower_http::request_id::RequestId; use tower_http::request_id::RequestId;
use crate::client_error::{AccessRejection, ProtocolErrorBody}; use crate::client_error::{AccessRejection, ProtocolErrorBody};
use crate::data_plane::router::DataPlaneNamespace; use crate::data_plane::router::{DataPlaneNamespace, IngressStarted};
pub(crate) async fn record_ingress( pub(crate) async fn record_ingress(
State(diagnostics): State<Arc<dyn OperationalDiagnostics>>, State(diagnostics): State<Arc<dyn OperationalDiagnostics>>,
@@ -29,6 +29,9 @@ pub(crate) async fn record_ingress(
let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else { let Some(namespace) = DataPlaneNamespace::for_path(request.uri().path()) else {
return next.run(request).await; return next.run(request).await;
}; };
request
.extensions_mut()
.insert(IngressStarted(std::time::Instant::now()));
let correlation_id = request let correlation_id = request
.extensions() .extensions()
.get::<RequestId>() .get::<RequestId>()
@@ -24,6 +24,27 @@ use tower::ServiceExt as _;
use super::{AdminTestFixture, AdminTestState, unavailable_system}; use super::{AdminTestFixture, AdminTestState, unavailable_system};
#[tokio::test]
async fn version_should_expose_runtime_identity_and_restart_capability() {
let fixture = crate::support::key_fixture().await;
fixture.auth.insert_session("valid-session");
let response = app(fixture.state())
.oneshot(
Request::builder()
.uri("/api/admin/system/version")
.header(header::COOKIE, "cpr_session=valid-session")
.header("x-request-id", "req_system_version")
.body(Body::empty())
.expect("version request"),
)
.await
.expect("version response");
assert_eq!(response.status(), StatusCode::OK);
let body = crate::support::response_json(response).await;
assert_eq!(body["data"]["instanceId"], "test-instance");
assert_eq!(body["data"]["restartSupported"], true);
}
#[test] #[test]
fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() { fn update_detail_query_should_default_to_no_refresh_and_reject_unknown_fields() {
let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object"); let query: UpdateDetailQuery = serde_json::from_str("{}").expect("empty query object");
@@ -256,12 +256,20 @@ async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")])); let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
execution.middleware = Some(middleware.frozen()); execution.middleware = Some(middleware.frozen());
let fixture = Fixture::with_execution(execution).await; let fixture = Fixture::with_execution(execution).await;
let response = fixture.post(chat_request(false)).await; let mut request = chat_request(false);
request["stream_options"] = json!({"include_usage":true});
request["messages"] = json!([
{"role":"developer","content":"brief"},
{"role":"system","content":null},
{"role":"assistant","tool_calls":[]},
{"role":"user","content":[{"type":"text","text":null},{"type":"text","text":"hello"}]}
]);
let response = fixture.post(request.clone()).await;
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
let downstream = json_body(response).await; let downstream = json_body(response).await;
assert_eq!(downstream["object"], "chat.completion"); assert_eq!(downstream["object"], "chat.completion");
let observed = middleware.requests.lock().unwrap(); let observed = middleware.requests.lock().unwrap();
assert_eq!(observed.as_slice(), [chat_request(false)]); assert_eq!(observed.as_slice(), [request]);
assert_eq!( assert_eq!(
middleware.inner.endpoints.lock().unwrap().as_slice(), middleware.inner.endpoints.lock().unwrap().as_slice(),
[PATH] [PATH]
@@ -396,16 +396,16 @@ fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
); );
assert_eq!( assert_eq!(
projected.safe_message(), projected.safe_message(),
"The gateway account pool is busy." "No eligible account currently has capacity for this request."
); );
} }
#[test] #[tokio::test]
fn no_eligible_provider_account_should_preserve_safe_provider_detail() { async fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
let detail = ClientVisibleUpstreamError::new( let detail = ClientVisibleUpstreamError::new(
"no account is eligible for the requested model", "This request requires an upstream WebSocket.",
Some("no_eligible_account".to_owned()), Some("websocket_account_unavailable".to_owned()),
Some("account_unavailable_error".to_owned()), None,
); );
let error = EngineError::Provider( let error = EngineError::Provider(
ProviderError::new( ProviderError::new(
@@ -419,17 +419,24 @@ fn no_eligible_provider_account_should_preserve_safe_provider_detail() {
assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider); assert_eq!(gateway.kind(), GatewayErrorKind::NoAvailableProvider);
assert_eq!( assert_eq!(
gateway.client_message(), gateway.client_message(),
"no account is eligible for the requested model" "This request requires an upstream WebSocket."
); );
assert_eq!(gateway.client_error_code(), Some("no_eligible_account"));
assert_eq!( assert_eq!(
gateway.client_error_type(), gateway.client_error_code(),
Some("account_unavailable_error") Some("websocket_account_unavailable")
); );
assert_eq!(gateway.client_error_type(), None);
assert_eq!( assert_eq!(
gateway.safe_message(), gateway.safe_message(),
"The gateway found no eligible account for this request." "The gateway found no eligible account for this request."
); );
let response = engine_error_response(&error);
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
let body: serde_json::Value =
serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap();
assert_eq!(body["error"]["type"], "server_error");
assert_eq!(body["error"]["code"], "websocket_account_unavailable");
assert_eq!(body["error"]["message"], gateway.client_message());
} }
#[test] #[test]
@@ -508,6 +515,7 @@ fn engine_provider_unsupported_capability_should_remain_unsupported() {
#[test] #[test]
fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() { fn engine_provider_credential_failures_should_not_impersonate_client_auth_failures() {
let mut messages = std::collections::HashSet::new();
for kind in [ for kind in [
ProviderErrorKind::Unauthorized, ProviderErrorKind::Unauthorized,
ProviderErrorKind::PermissionDenied, ProviderErrorKind::PermissionDenied,
@@ -516,11 +524,19 @@ fn engine_provider_credential_failures_should_not_impersonate_client_auth_failur
let mapped = gateway_error_from_engine(&error); let mapped = gateway_error_from_engine(&error);
assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable); assert_eq!(mapped.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!( assert!(
mapped.safe_message(), mapped
"The upstream account cannot access the service." .safe_message()
.to_lowercase()
.contains("upstream account")
); );
messages.insert(mapped.safe_message().to_owned());
} }
assert_eq!(
messages.len(),
2,
"authentication and permission failures must be distinguishable"
);
} }
#[test] #[test]
@@ -577,19 +593,29 @@ fn engine_provider_timeout_and_cancellation_should_remain_distinct() {
} }
#[test] #[test]
fn engine_provider_runtime_failures_should_collapse_to_safe_unavailability() { fn engine_provider_runtime_failures_preserve_the_cause_without_exposing_internal_details() {
let mut messages = std::collections::HashSet::new();
for kind in [ for kind in [
ProviderErrorKind::Transport, ProviderErrorKind::Transport,
ProviderErrorKind::Protocol, ProviderErrorKind::Protocol,
ProviderErrorKind::Unavailable, ProviderErrorKind::Unavailable,
ProviderErrorKind::ProcessTerminated, ProviderErrorKind::ProcessTerminated,
] { ] {
let error = EngineError::Provider(ProviderError::new(kind, UpstreamSendState::Ambiguous)); let error = EngineError::Provider(
ProviderError::new(kind, UpstreamSendState::Ambiguous)
.with_source(std::io::Error::other("PRIVATE_ENDPOINT_AND_CREDENTIAL")),
);
let projected = gateway_error_from_engine(&error); let projected = gateway_error_from_engine(&error);
assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable); assert_eq!(projected.kind(), GatewayErrorKind::UpstreamUnavailable);
assert_eq!(projected.safe_message(), "Upstream service is unavailable."); assert!(!projected.client_message().contains("PRIVATE_"));
messages.insert(projected.client_message().to_owned());
} }
assert_eq!(
messages.len(),
4,
"different failure causes must remain distinguishable"
);
} }
#[test] #[test]
@@ -334,7 +334,7 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
runtime["account_queue_timeout_seconds"] = serde_json::json!(30); runtime["account_queue_timeout_seconds"] = serde_json::json!(30);
runtime["switch_account_on_queue_failure"] = serde_json::json!(false); runtime["switch_account_on_queue_failure"] = serde_json::json!(false);
settings.runtime = serde_json::from_value(runtime).unwrap(); settings.runtime = serde_json::from_value(runtime).unwrap();
settings.fast_mode = FastMode::Disabled; settings.fast_mode = Some(FastMode::Disabled);
}), }),
..Default::default() ..Default::default()
})); }));
@@ -355,8 +355,12 @@ async fn request_settings_reach_query_terminal_without_mutating_authenticated_ba
"model-a" "model-a"
); );
assert_ne!( assert_ne!(
execution.client.policy().account_scope().fast_mode(), execution
FastMode::Disabled .client
.policy()
.account_scope()
.fast_mode_override(),
Some(FastMode::Disabled)
); );
} }
} }
@@ -3300,6 +3300,12 @@ async fn response_ids_are_provider_and_client_independent() {
(&[], MODEL_REQUEST_ID), (&[], MODEL_REQUEST_ID),
(&[("x-request-id", "upstream-primary")], "upstream-primary"), (&[("x-request-id", "upstream-primary")], "upstream-primary"),
(&[("x-oai-request-id", "upstream-alias")], "upstream-alias"), (&[("x-oai-request-id", "upstream-alias")], "upstream-alias"),
(
&[("x-openai-request-id", "upstream-openai")],
"upstream-openai",
),
(&[("x-ms-request-id", "upstream-ms")], "upstream-ms"),
(&[("cf-ray", "trace-only")], MODEL_REQUEST_ID),
( (
&[ &[
("x-request-id", "upstream-primary"), ("x-request-id", "upstream-primary"),
@@ -3315,6 +3321,22 @@ async fn response_ids_are_provider_and_client_independent() {
"upstream-alias", "upstream-alias",
), ),
(&[("x-request-id", "")], MODEL_REQUEST_ID), (&[("x-request-id", "")], MODEL_REQUEST_ID),
(
&[
("x-request-id", "é"),
("x-oai-request-id", " "),
("x-openai-request-id", ""),
("x-ms-request-id", "upstream-ms"),
],
"upstream-ms",
),
(
&[
("x-openai-request-id", "upstream-openai"),
("x-ms-request-id", "upstream-ms"),
],
"upstream-openai",
),
]; ];
for provider in ["openai", "xai"] { for provider in ["openai", "xai"] {
for streaming in [false, true] { for streaming in [false, true] {
@@ -3343,6 +3365,11 @@ async fn response_ids_are_provider_and_client_independent() {
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["x-request-id"], *expected); assert_eq!(response.headers()["x-request-id"], *expected);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
for (name, value) in *upstream_headers {
if *name != "x-request-id" {
assert_eq!(response.headers()[*name].as_bytes(), value.as_bytes());
}
}
assert!( assert!(
!to_bytes(response.into_body(), 64 * 1024) !to_bytes(response.into_body(), 64 * 1024)
.await .await
@@ -3359,7 +3386,12 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
let admin = crate::admin::AdminTestFixture::new().await.services; let admin = crate::admin::AdminTestFixture::new().await.services;
for provider in ["openai", "xai"] { for provider in ["openai", "xai"] {
for streaming in [false, true] { for streaming in [false, true] {
for upstream_headers in [vec![], headers(&[("x-oai-request-id", "actual-error")])] { for upstream_headers in [
vec![],
headers(&[("x-oai-request-id", "actual-error")]),
headers(&[("x-openai-request-id", "actual-error")]),
headers(&[("x-ms-request-id", "actual-error")]),
] {
let expected = if upstream_headers.is_empty() { let expected = if upstream_headers.is_empty() {
MODEL_REQUEST_ID MODEL_REQUEST_ID
} else { } else {
@@ -3367,7 +3399,7 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
}; };
let raw = let raw =
Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#); Bytes::from_static(br#"{"error":{"message":"synthetic upstream detail"}}"#);
let error = let mut error =
ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent) ProviderError::new(ProviderErrorKind::InvalidRequest, UpstreamSendState::Sent)
.with_client_visible_upstream_response( .with_client_visible_upstream_response(
ClientVisibleUpstreamResponse::new( ClientVisibleUpstreamResponse::new(
@@ -3377,12 +3409,25 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
) )
.with_headers(upstream_headers), .with_headers(upstream_headers),
); );
if expected == "actual-error" {
// 最终响应头优先于错误对象中残留的旧观测 ID
error = error.with_upstream_request_id(OpaqueUpstreamValue::new("stale-fact"));
}
let session = failed_session(streaming, EngineError::Provider(error)) let session = failed_session(streaming, EngineError::Provider(error))
.with_response_headers(headers(&[("x-request-id", "earlier-session")])); .with_response_headers(headers(&[
("x-request-id", "earlier-session"),
("x-openai-request-id", "earlier-openai"),
("x-ms-request-id", "earlier-ms"),
]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert_eq!(response.headers()["x-request-id"], expected); assert_eq!(response.headers()["x-request-id"], expected);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
for name in ["x-openai-request-id", "x-ms-request-id"] {
if let Some(value) = response.headers().get(name) {
assert_eq!(value, "actual-error");
}
}
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw); assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), raw);
} }
@@ -3394,12 +3439,16 @@ async fn failure_ids_prefer_the_actual_error_over_session_headers() {
.with_response_headers(headers(&[ .with_response_headers(headers(&[
("x-request-id", "earlier-session"), ("x-request-id", "earlier-session"),
("x-oai-request-id", "earlier-alias"), ("x-oai-request-id", "earlier-alias"),
("x-openai-request-id", "earlier-openai"),
("x-ms-request-id", "earlier-ms"),
])); ]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.status(), StatusCode::BAD_GATEWAY); assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
assert_eq!(response.headers()["x-request-id"], "body-read-error"); assert_eq!(response.headers()["x-request-id"], "body-read-error");
assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1); assert_eq!(response.headers().get_all("x-request-id").iter().count(), 1);
assert!(response.headers().get("x-oai-request-id").is_none()); assert!(response.headers().get("x-oai-request-id").is_none());
assert!(response.headers().get("x-openai-request-id").is_none());
assert!(response.headers().get("x-ms-request-id").is_none());
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
} }
} }
@@ -3414,12 +3463,16 @@ async fn local_execution_failure_uses_the_existing_model_id() {
failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[ failed_session(streaming, EngineError::Deadline).with_response_headers(headers(&[
("x-request-id", "opening-primary"), ("x-request-id", "opening-primary"),
("x-oai-request-id", "opening-alias"), ("x-oai-request-id", "opening-alias"),
("x-openai-request-id", "opening-openai"),
("x-ms-request-id", "opening-ms"),
("x-codex-turn-state", "retained-turn-state"), ("x-codex-turn-state", "retained-turn-state"),
])); ]));
let response = response(&admin, provider, session, streaming).await; let response = response(&admin, provider, session, streaming).await;
assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-request-id"], MODEL_REQUEST_ID);
assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID); assert_eq!(response.headers()["x-gateway-request-id"], MODEL_REQUEST_ID);
assert!(response.headers().get("x-oai-request-id").is_none()); assert!(response.headers().get("x-oai-request-id").is_none());
assert!(response.headers().get("x-openai-request-id").is_none());
assert!(response.headers().get("x-ms-request-id").is_none());
assert_eq!( assert_eq!(
response.headers()["x-codex-turn-state"], response.headers()["x-codex-turn-state"],
"retained-turn-state" "retained-turn-state"
@@ -369,23 +369,25 @@ async fn classified_capacity_error_without_special_code_returns_retryable_websoc
#[tokio::test] #[tokio::test]
async fn final_failure_headers_take_precedence_over_observed_opening_headers() { async fn final_failure_headers_take_precedence_over_observed_opening_headers() {
let provider = upstream_failure(403, b"", vec![header("x-oai-request-id", b"req_final")]) for name in ["x-oai-request-id", "x-openai-request-id", "x-ms-request-id"] {
.with_status(502) let provider = upstream_failure(403, b"", vec![header(name, b"req_final")])
.with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact")); .with_status(502)
let error = initial_error( .with_upstream_request_id(OpaqueUpstreamValue::new("req_stale_fact"));
EngineError::Provider(provider), let error = initial_error(
vec![ EngineError::Provider(provider),
header("x-request-id", b"req_old_opening"), vec![
header("x-codex-turn-state", b"old-turn-state"), header("x-request-id", b"req_old_opening"),
], header("x-codex-turn-state", b"old-turn-state"),
) ],
.await; )
assert_eq!(error["status"], 403); .await;
assert_eq!(error["headers"]["x-oai-request-id"], "req_final"); assert_eq!(error["status"], 403);
assert!(error["headers"].get("x-request-id").is_none()); assert_eq!(error["headers"][name], "req_final");
assert!(!error.to_string().contains("req_old_opening")); assert!(error["headers"].get("x-request-id").is_none());
assert!(!error.to_string().contains("req_stale_fact")); assert!(!error.to_string().contains("req_old_opening"));
assert!(!error.to_string().contains("old-turn-state")); assert!(!error.to_string().contains("req_stale_fact"));
assert!(!error.to_string().contains("old-turn-state"));
}
} }
#[tokio::test] #[tokio::test]
@@ -398,6 +400,8 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
vec![ vec![
header("x-request-id", b"req_old"), header("x-request-id", b"req_old"),
header("x-oai-request-id", b"req_old_alias"), header("x-oai-request-id", b"req_old_alias"),
header("x-openai-request-id", b"req_old_openai"),
header("x-ms-request-id", b"req_old_ms"),
header("x-codex-turn-state", b"observed-turn-state"), header("x-codex-turn-state", b"observed-turn-state"),
], ],
) )
@@ -409,9 +413,11 @@ async fn provider_failure_facts_survive_without_a_complete_http_response() {
"observed-turn-state" "observed-turn-state"
); );
assert!(error["headers"].get("x-oai-request-id").is_none()); assert!(error["headers"].get("x-oai-request-id").is_none());
assert!(error["headers"].get("x-openai-request-id").is_none());
assert!(error["headers"].get("x-ms-request-id").is_none());
assert_eq!( assert_eq!(
error["error"]["message"], error["error"]["message"],
"Upstream service is unavailable." "Communication with the upstream service failed."
); );
} }
@@ -511,6 +517,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
vec![ vec![
header("x-request-id", b"req_old_opening"), header("x-request-id", b"req_old_opening"),
header("x-oai-request-id", b"req_observed"), header("x-oai-request-id", b"req_observed"),
header("x-openai-request-id", b"req_observed_openai"),
header("x-ms-request-id", b"req_observed_ms"),
header("x-codex-turn-state", b"observed-turn-state"), header("x-codex-turn-state", b"observed-turn-state"),
header("x-future-header", b"future-value"), header("x-future-header", b"future-value"),
], ],
@@ -525,6 +533,8 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
"headers": { "headers": {
"x-request-id": "req_old_opening", "x-request-id": "req_old_opening",
"x-oai-request-id": "req_observed", "x-oai-request-id": "req_observed",
"x-openai-request-id": "req_observed_openai",
"x-ms-request-id": "req_observed_ms",
"x-codex-turn-state": "observed-turn-state", "x-codex-turn-state": "observed-turn-state",
"x-future-header": "future-value", "x-future-header": "future-value",
}, },
@@ -548,6 +558,46 @@ async fn opening_ids_stay_in_metadata_but_do_not_identify_initial_failures() {
} }
} }
#[tokio::test]
async fn metadata_prefers_readable_upstream_aliases_before_the_model_id() {
let cases: &[(&str, &[u8], Option<&str>)] = &[
("x-oai-request-id", b"req_oai", Some("req_oai")),
("X-OpenAI-Request-ID", b"req_openai", Some("req_openai")),
("x-ms-request-id", b"req_ms", Some("req_ms")),
("x-ms-request-id", b" \t ", None),
("x-ms-request-id", b"\xc3\xa9", None),
];
for (name, value, expected) in cases {
let trace = Arc::new(AtomicFailureTrace {
initial_errors: Mutex::new(VecDeque::from([EngineError::Deadline])),
..AtomicFailureTrace::default()
});
let (mut socket, _server) = connect(
Arc::clone(&trace),
vec![header("x-request-id", b"\xff"), header(name, value)],
)
.await;
send_request(&mut socket).await;
let metadata = next_event(&mut socket).await;
assert_eq!(metadata["type"], "response.metadata");
let model_id = trace.prepared_request_id.lock().unwrap().clone().unwrap();
assert_eq!(
metadata["headers"]["x-request-id"],
expected.unwrap_or(&model_id)
);
assert_eq!(
metadata["headers"][name.to_ascii_lowercase()].as_str(),
*expected
);
let error = next_event(&mut socket).await;
assert_eq!(error["type"], "error");
assert_eq!(error["headers"]["x-request-id"], "req_ws_atomic");
assert_eq!(error["headers"]["x-gateway-request-id"], "req_ws_atomic");
assert!(error["headers"].get(name.to_ascii_lowercase()).is_none());
socket.close(None).await.unwrap();
}
}
#[tokio::test] #[tokio::test]
async fn header_only_request_middleware_updates_websocket_turn_context() { async fn header_only_request_middleware_updates_websocket_turn_context() {
let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware { let middleware = Arc::new(crate::data_plane::middleware::RequestMiddleware {
@@ -746,13 +796,38 @@ async fn initial_continuation_recovery_delivers_the_official_client_replay_signa
} }
#[tokio::test] #[tokio::test]
async fn locally_exhausted_account_pool_sends_one_official_usage_limit_error() { async fn account_selection_errors_distinguish_quota_from_websocket_requirements() {
let provider = ProviderError::new( let exhausted = ProviderError::new(
ProviderErrorKind::AccountPoolQuotaExhausted, ProviderErrorKind::AccountPoolQuotaExhausted,
UpstreamSendState::NotSent, UpstreamSendState::NotSent,
); );
let error = initial_error(EngineError::Provider(provider), Vec::new()).await; let incompatible = ProviderError::new(
assert_eq!(error["status"], 429); ProviderErrorKind::NoEligibleAccount,
assert_eq!(error["error"]["type"], "usage_limit_reached"); UpstreamSendState::NotSent,
assert_eq!(error["error"]["code"], "usage_limit_reached"); )
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
"This request requires an upstream WebSocket.",
Some("websocket_account_unavailable".to_owned()),
None,
));
for (provider, status, kind, code) in [
(exhausted, 429, "usage_limit_reached", "usage_limit_reached"),
(
incompatible,
503,
"server_error",
"websocket_account_unavailable",
),
] {
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
assert_eq!(error["status"], status);
assert_eq!(error["error"]["type"], kind);
assert_eq!(error["error"]["code"], code);
if status == 503 {
assert_eq!(
error["error"]["message"],
"This request requires an upstream WebSocket."
);
}
}
} }
@@ -313,6 +313,7 @@ fn response_create_should_reject_non_boolean_stream_without_disclosing_body_valu
#[derive(Default)] #[derive(Default)]
struct AtomicFailureTrace { struct AtomicFailureTrace {
prepared_request_id: Mutex<Option<String>>,
starts: AtomicUsize, starts: AtomicUsize,
next_calls: AtomicUsize, next_calls: AtomicUsize,
committed: AtomicBool, committed: AtomicBool,
@@ -414,8 +415,9 @@ struct AtomicFailureExecution {
impl ExecutionService for AtomicFailureExecution { impl ExecutionService for AtomicFailureExecution {
fn middleware_plan( fn middleware_plan(
&self, &self,
_: &gateway_core::engine::execution::PreparedRootExecution, prepared: &gateway_core::engine::execution::PreparedRootExecution,
) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> { ) -> Option<gateway_core::engine::middleware::FrozenMiddlewarePlan> {
*self.trace.prepared_request_id.lock().unwrap() = Some(prepared.request_id().to_string());
self.trace.middleware.clone() self.trace.middleware.clone()
} }
@@ -255,3 +255,71 @@ async fn original_rejected_request_is_dumped_only_when_explicitly_enabled() {
} }
} }
} }
#[tokio::test]
async fn responses_ingress_separates_body_receipt_from_decompression_and_decoding() {
use std::io::Write as _;
use tracing::instrument::WithSubscriber as _;
let recorder = Recorder {
dump_enabled: false,
events: Arc::default(),
};
let events = recorder.events.clone();
let decoded = json!({"model":42,"input":"SENSITIVE_CONTENT".repeat(1024)}).to_string();
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
encoder.write_all(decoded.as_bytes()).unwrap();
let encoded = encoder.finish().unwrap();
let encoded_len = encoded.len();
assert!(encoded_len < decoded.len());
async {
let (router, _) = fixture().await;
let body = Body::from_stream(futures::stream::once(async move {
tokio::time::sleep(std::time::Duration::from_millis(40)).await;
Ok::<_, std::io::Error>(encoded)
}));
let response = router
.oneshot(
Request::post("/v1/responses")
.header("authorization", "Bearer unused-client-route-key")
.header("content-encoding", "gzip")
.body(body)
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
.with_subscriber(recorder)
.await;
let events = events.lock().unwrap();
let phases = events
.iter()
.filter(|event| {
event.get("stage").is_some_and(|stage| {
stage.starts_with("http.body.") || stage == "http.auth.finished"
})
})
.collect::<Vec<_>>();
assert_eq!(
phases
.iter()
.map(|event| event["stage"].as_str())
.collect::<Vec<_>>(),
[
"http.body.received",
"http.auth.finished",
"http.body.decompressed",
"http.body.decoded",
]
);
assert!(phases[0]["receive_ms"].parse::<u64>().unwrap() >= 30);
assert_eq!(phases[0]["encoded_bytes"], encoded_len.to_string());
assert_eq!(phases[0]["content_encoding"], "gzip");
assert_eq!(phases[2]["decoded_bytes"], decoded.len().to_string());
assert_eq!(phases[2]["accepted"], "true");
assert_eq!(phases[3]["accepted"], "false");
assert!(events.iter().flat_map(|event| event.values()).all(|value| {
!value.contains("SENSITIVE_CONTENT") && !value.contains("unused-client-route-key")
}));
}
@@ -91,6 +91,8 @@ impl SystemOperations for VersionSystem {
async fn version(&self) -> Result<SystemVersion, SystemOperationError> { async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
Ok(SystemVersion { Ok(SystemVersion {
version: "3.7.0".to_owned(), version: "3.7.0".to_owned(),
instance_id: "test-instance".to_owned(),
restart_supported: true,
git_sha: "internal-revision".to_owned(), git_sha: "internal-revision".to_owned(),
build_time: "internal-build-time".to_owned(), build_time: "internal-build-time".to_owned(),
deployment_mode: "binary".to_owned(), deployment_mode: "binary".to_owned(),
@@ -108,6 +108,7 @@ pub struct RuntimeAccountDirectory {
providers_with_accounts: BTreeSet<ProviderKind>, providers_with_accounts: BTreeSet<ProviderKind>,
providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>, providers_by_group: BTreeMap<AccountGroupId, BTreeSet<ProviderKind>>,
group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>, group_model_access: BTreeMap<AccountGroupId, AccountModelAccess>,
group_fast_modes: BTreeMap<AccountGroupId, FastMode>,
} }
impl RuntimeAccountDirectory { impl RuntimeAccountDirectory {
@@ -129,6 +130,7 @@ impl RuntimeAccountDirectory {
providers_with_accounts, providers_with_accounts,
providers_by_group, providers_by_group,
group_model_access: BTreeMap::new(), group_model_access: BTreeMap::new(),
group_fast_modes: BTreeMap::new(),
} }
} }
@@ -141,6 +143,12 @@ impl RuntimeAccountDirectory {
self self
} }
#[must_use]
pub fn with_group_fast_modes(mut self, policies: BTreeMap<AccountGroupId, FastMode>) -> Self {
self.group_fast_modes = policies;
self
}
pub(crate) fn accounts_in_group( pub(crate) fn accounts_in_group(
&self, &self,
group: &AccountGroupId, group: &AccountGroupId,
@@ -288,7 +296,7 @@ impl ClientRoutingScope {
pub struct FrozenAccountScope { pub struct FrozenAccountScope {
allow_image_generation: bool, allow_image_generation: bool,
allow_subagents: bool, allow_subagents: bool,
fast_mode: FastMode, fast_mode_override: Option<FastMode>,
request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>, request_profiles: BTreeMap<ProviderKind, super::OpaqueProviderData>,
directory: Arc<RuntimeAccountDirectory>, directory: Arc<RuntimeAccountDirectory>,
client_scope: ClientRoutingScope, client_scope: ClientRoutingScope,
@@ -355,16 +363,34 @@ impl FrozenAccountScope {
self self
} }
/// Key 绑定分组的冻结 Fast 策略,与账号成员资格无关 /// 显式请求覆盖独立于分组策略;None 表示按选中账号的有效分组计算
#[must_use] #[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self { pub const fn with_fast_mode_override(mut self, fast_mode: Option<FastMode>) -> Self {
self.fast_mode = fast_mode; self.fast_mode_override = fast_mode;
self self
} }
#[must_use] #[must_use]
pub const fn fast_mode(&self) -> FastMode { pub const fn fast_mode_override(&self) -> Option<FastMode> {
self.fast_mode self.fast_mode_override
}
/// 只合并当前 Key 授权该账号与模型的启用分组,换号仍使用同一冻结目录
#[must_use]
pub fn fast_mode_for_account(
&self,
account_id: &ProviderAccountId,
upstream_model: &str,
) -> FastMode {
if let Some(mode) = self.fast_mode_override {
return mode;
}
let Some(account) = self.directory.account(account_id) else {
return FastMode::Default;
};
self.matching_groups(account, |access| access.allows(upstream_model))
.filter_map(|id| self.directory.group_fast_modes.get(id))
.fold(FastMode::Default, |mode, other| mode.merge(*other))
} }
#[must_use] #[must_use]
@@ -376,7 +402,7 @@ impl FrozenAccountScope {
Self { Self {
allow_image_generation: true, allow_image_generation: true,
allow_subagents: true, allow_subagents: true,
fast_mode: FastMode::Default, fast_mode_override: None,
request_profiles: BTreeMap::new(), request_profiles: BTreeMap::new(),
directory, directory,
client_scope, client_scope,
@@ -460,18 +486,31 @@ impl FrozenAccountScope {
} }
match &self.client_scope { match &self.client_scope {
ClientRoutingScope::AllAccounts => true, ClientRoutingScope::AllAccounts => true,
ClientRoutingScope::Restricted { .. } => {
self.matching_groups(account, accepts).next().is_some()
}
}
}
fn matching_groups<'a>(
&'a self,
account: &'a RuntimeAccount,
accepts: impl Fn(&AccountModelAccess) -> bool + 'a,
) -> impl Iterator<Item = &'a AccountGroupId> {
let enabled = match &self.client_scope {
ClientRoutingScope::AllAccounts => None,
ClientRoutingScope::Restricted { ClientRoutingScope::Restricted {
enabled_group_ids, .. enabled_group_ids, ..
} => account } => Some(enabled_group_ids),
.group_ids() };
.intersection(enabled_group_ids) account.group_ids().iter().filter(move |id| {
.any(|id| { enabled.is_some_and(|groups| groups.contains(*id))
self.directory && self
.group_model_access .directory
.get(id) .group_model_access
.is_none_or(&accepts) .get(*id)
}), .is_none_or(&accepts)
} })
} }
#[must_use] #[must_use]
@@ -1200,7 +1200,6 @@ where
.with_lease_metadata(Arc::clone(&self.lease_metadata)) .with_lease_metadata(Arc::clone(&self.lease_metadata))
.with_response_control(self.response_control.clone()) .with_response_control(self.response_control.clone())
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned()) .with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
.with_fast_mode(self.plan.fast_mode())
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider())) .with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
.with_pricing(self.plan.pricing()) .with_pricing(self.plan.pricing())
.with_request_location(self.plan.request_location().cloned()) .with_request_location(self.plan.request_location().cloned())
@@ -48,11 +48,17 @@ pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> Gatew
"Mapped model unavailable for this API key. Check the model mapping." "Mapped model unavailable for this API key. Check the model mapping."
}, },
), ),
crate::validation::RoutingError::NoCapableProvider { .. } crate::validation::RoutingError::NoCapableProvider { .. } => GatewayError::new(
| crate::validation::RoutingError::NoCapableProviderEndpoint { .. }
| crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
GatewayErrorKind::NoAvailableProvider, GatewayErrorKind::NoAvailableProvider,
"The gateway has no eligible provider for this request.", "The gateway cannot select a provider for this model and the requested capabilities.",
),
crate::validation::RoutingError::NoCapableProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"No eligible provider is available for the requested API endpoint.",
),
crate::validation::RoutingError::EmptyAccountScope => GatewayError::new(
GatewayErrorKind::NoAvailableProvider,
"This API key has no accounts in its scope. Add accounts or check its enabled account groups.",
), ),
crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new( crate::validation::RoutingError::UnsupportedProviderEndpoint { .. } => GatewayError::new(
GatewayErrorKind::Unsupported, GatewayErrorKind::Unsupported,
+8 -10
View File
@@ -330,7 +330,6 @@ pub struct RequestAttemptContext {
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>, prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
pricing: Arc<crate::metering::PricingOverrides>, pricing: Arc<crate::metering::PricingOverrides>,
request_profile: Option<crate::account::OpaqueProviderData>, request_profile: Option<crate::account::OpaqueProviderData>,
fast_mode: FastMode,
openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings, openai_websocket_pool: crate::settings::OpenAiWebSocketPoolSettings,
openai_request_settings: crate::settings::OpenAiRequestSettings, openai_request_settings: crate::settings::OpenAiRequestSettings,
request_location: Option<crate::account::RequestLocation>, request_location: Option<crate::account::RequestLocation>,
@@ -424,12 +423,6 @@ impl RequestAttemptContext {
self self
} }
#[must_use]
pub const fn with_fast_mode(mut self, fast_mode: FastMode) -> Self {
self.fast_mode = fast_mode;
self
}
#[must_use] #[must_use]
pub fn with_privacy( pub fn with_privacy(
mut self, mut self,
@@ -478,7 +471,6 @@ impl RequestAttemptContext {
request_profile: None, request_profile: None,
prompt_rewrite_rules: None, prompt_rewrite_rules: None,
pricing: Arc::default(), pricing: Arc::default(),
fast_mode: FastMode::Default,
openai_websocket_pool: Default::default(), openai_websocket_pool: Default::default(),
openai_request_settings: Default::default(), openai_request_settings: Default::default(),
request_location: None, request_location: None,
@@ -743,8 +735,14 @@ impl AttemptContext {
} }
#[must_use] #[must_use]
pub const fn fast_mode(&self) -> FastMode { pub fn fast_mode_for_account(
self.request.fast_mode &self,
account: &ProviderAccountId,
upstream_model: &str,
) -> FastMode {
self.account_scope().map_or(FastMode::Default, |scope| {
scope.fast_mode_for_account(account, upstream_model)
})
} }
#[must_use] #[must_use]
+31 -14
View File
@@ -1436,14 +1436,14 @@ impl GatewayError {
pub(crate) const fn concurrency_queue_full() -> Self { pub(crate) const fn concurrency_queue_full() -> Self {
Self::new( Self::new(
GatewayErrorKind::ConcurrencyQueueFull, GatewayErrorKind::ConcurrencyQueueFull,
"The gateway request queue is full.", "The gateway concurrency queue is full.",
) )
} }
pub(crate) const fn concurrency_queue_timeout() -> Self { pub(crate) const fn concurrency_queue_timeout() -> Self {
Self::new( Self::new(
GatewayErrorKind::ConcurrencyQueueTimeout, GatewayErrorKind::ConcurrencyQueueTimeout,
"The request timed out in the gateway queue.", "Timed out waiting for available concurrency in the gateway.",
) )
} }
@@ -1516,20 +1516,25 @@ impl GatewayError {
GatewayErrorKind::Unsupported, GatewayErrorKind::Unsupported,
"Requested capability is unsupported.", "Requested capability is unsupported.",
), ),
ProviderErrorKind::Unauthorized | ProviderErrorKind::PermissionDenied => Self::new( ProviderErrorKind::Unauthorized => Self::new(
GatewayErrorKind::UpstreamUnavailable, GatewayErrorKind::UpstreamUnavailable,
"The upstream account cannot access the service.", "Upstream account authentication failed.",
),
ProviderErrorKind::PermissionDenied => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream account does not have permission for this request.",
), ),
ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else( ProviderErrorKind::RequestPolicyDenied => error.denied_group_feature.map_or_else(
|| Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."), || Self::new(GatewayErrorKind::PolicyDenied, "Request blocked by policy."),
Self::from, Self::from,
), ),
ProviderErrorKind::RateLimited => { ProviderErrorKind::RateLimited => Self::new(
Self::new(GatewayErrorKind::RateLimited, "Request rate limit reached.") GatewayErrorKind::RateLimited,
} "Upstream request rate limit reached.",
),
ProviderErrorKind::QuotaExhausted => Self::new( ProviderErrorKind::QuotaExhausted => Self::new(
GatewayErrorKind::QuotaExhausted, GatewayErrorKind::QuotaExhausted,
"Account quota is exhausted.", "Upstream account quota is exhausted.",
), ),
ProviderErrorKind::AccountPoolQuotaExhausted => Self::new( ProviderErrorKind::AccountPoolQuotaExhausted => Self::new(
GatewayErrorKind::AccountPoolQuotaExhausted, GatewayErrorKind::AccountPoolQuotaExhausted,
@@ -1539,7 +1544,7 @@ impl GatewayError {
ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(), ProviderErrorKind::ConcurrencyQueueTimeout => Self::concurrency_queue_timeout(),
ProviderErrorKind::AccountCapacityUnavailable => Self::new( ProviderErrorKind::AccountCapacityUnavailable => Self::new(
GatewayErrorKind::AccountCapacityUnavailable, GatewayErrorKind::AccountCapacityUnavailable,
"The gateway account pool is busy.", "No eligible account currently has capacity for this request.",
), ),
ProviderErrorKind::NoEligibleAccount => Self::new( ProviderErrorKind::NoEligibleAccount => Self::new(
GatewayErrorKind::NoAvailableProvider, GatewayErrorKind::NoAvailableProvider,
@@ -1559,11 +1564,23 @@ impl GatewayError {
ProviderErrorKind::Cancelled => { ProviderErrorKind::Cancelled => {
Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.") Self::new(GatewayErrorKind::Cancelled, "Request was cancelled.")
} }
ProviderErrorKind::Transport ProviderErrorKind::Transport => Self::new(
| ProviderErrorKind::Protocol GatewayErrorKind::UpstreamUnavailable,
| ProviderErrorKind::Unavailable "Communication with the upstream service failed.",
| ProviderErrorKind::UpstreamCapacityUnavailable ),
| ProviderErrorKind::ProcessTerminated => Self::new( ProviderErrorKind::Protocol => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"Upstream protocol handling failed.",
),
ProviderErrorKind::ProcessTerminated => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The gateway stopped before the request completed.",
),
ProviderErrorKind::UpstreamCapacityUnavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable,
"The upstream service has no capacity for this request.",
),
ProviderErrorKind::Unavailable => Self::new(
GatewayErrorKind::UpstreamUnavailable, GatewayErrorKind::UpstreamUnavailable,
"Upstream service is unavailable.", "Upstream service is unavailable.",
), ),
@@ -5,6 +5,7 @@ use std::sync::{Arc, OnceLock};
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
use event_listener::Event; use event_listener::Event;
use futures::FutureExt as _;
use futures::future::{BoxFuture, pending}; use futures::future::{BoxFuture, pending};
use futures_timer::Delay; use futures_timer::Delay;
@@ -142,6 +143,14 @@ impl CancellationToken {
self.reason().is_some() self.reason().is_some()
} }
/// 取消优先于同时就绪的工作,只用于可安全丢弃的 future
pub async fn run_until_cancelled<T>(&self, work: impl Future<Output = T>) -> Option<T> {
futures::select_biased! {
() = self.cancelled().fuse() => None,
result = work.fuse() => Some(result),
}
}
pub async fn cancelled(&self) { pub async fn cancelled(&self) {
if self.is_cancelled() { if self.is_cancelled() {
return; return;
@@ -158,7 +158,7 @@ impl RateLimits {
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSettings { pub struct ClientSettings {
pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>, pub request_profiles: BTreeMap<ProviderKind, OpaqueProviderData>,
pub fast_mode: FastMode, pub fast_mode_override: Option<FastMode>,
pub limits: RateLimits, pub limits: RateLimits,
} }
@@ -185,18 +185,18 @@ impl ClientPolicy {
pub(crate) fn with_settings( pub(crate) fn with_settings(
mut self, mut self,
profiles: &BTreeMap<ProviderKind, OpaqueProviderData>, profiles: &BTreeMap<ProviderKind, OpaqueProviderData>,
fast_mode: FastMode, fast_mode_override: Option<FastMode>,
limits: RateLimits, limits: RateLimits,
) -> Self { ) -> Self {
if self.account_scope.request_profiles() != profiles if self.account_scope.request_profiles() != profiles
|| self.account_scope.fast_mode() != fast_mode || self.account_scope.fast_mode_override() != fast_mode_override
{ {
self.account_scope = Arc::new( self.account_scope = Arc::new(
self.account_scope self.account_scope
.as_ref() .as_ref()
.clone() .clone()
.with_request_profiles(profiles.clone()) .with_request_profiles(profiles.clone())
.with_fast_mode(fast_mode), .with_fast_mode_override(fast_mode_override),
); );
} }
self.limits = limits; self.limits = limits;
@@ -217,7 +217,7 @@ impl ClientPolicy {
name_snapshot: None, name_snapshot: None,
defaults: Arc::new(ClientSettings { defaults: Arc::new(ClientSettings {
request_profiles: account_scope.request_profiles().clone(), request_profiles: account_scope.request_profiles().clone(),
fast_mode: account_scope.fast_mode(), fast_mode_override: account_scope.fast_mode_override(),
limits, limits,
}), }),
key_id, key_id,
@@ -23,7 +23,7 @@ use std::fmt;
use std::num::{NonZeroU32, NonZeroU64}; use std::num::{NonZeroU32, NonZeroU64};
use std::sync::Arc; use std::sync::Arc;
use crate::account::{AccountSelectionPolicy, FastMode}; use crate::account::AccountSelectionPolicy;
use crate::operation::{CapabilityRequirements, Feature, OperationKind}; use crate::operation::{CapabilityRequirements, Feature, OperationKind};
use crate::validation::{IdentifierError, RoutingError, validate_text}; use crate::validation::{IdentifierError, RoutingError, validate_text};
@@ -767,11 +767,6 @@ impl RoutingPlan {
Arc::clone(&self.pricing) Arc::clone(&self.pricing)
} }
#[must_use]
pub fn fast_mode(&self) -> FastMode {
self.account_scope.fast_mode()
}
/// 本次请求冻结的已编译规则,重试不读取新的全局策略 /// 本次请求冻结的已编译规则,重试不读取新的全局策略
#[must_use] #[must_use]
pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> { pub fn privacy(&self) -> Option<Arc<dyn crate::settings::privacy::CompiledPrivacyPolicy>> {
@@ -19,7 +19,8 @@ use crate::settings::{InvalidSettings, SettingsValues};
#[serde(deny_unknown_fields)] #[serde(deny_unknown_fields)]
pub struct ExecutionSettings { pub struct ExecutionSettings {
pub runtime: SettingsValues, pub runtime: SettingsValues,
pub fast_mode: FastMode, /// None 按选中账号的有效分组解析;Some(Default) 显式跟随客户端
pub fast_mode: Option<FastMode>,
pub client_limits: RateLimits, pub client_limits: RateLimits,
/// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点 /// null 表示不限制总时长;显式时限从请求开始计时,改写不重置计时原点
pub timeout_ms: Option<u64>, pub timeout_ms: Option<u64>,
@@ -38,7 +39,7 @@ struct ExecutionOverrides {
defaults: Arc<ClientSettings>, defaults: Arc<ClientSettings>,
client_key_id: String, client_key_id: String,
input: Arc<ExecutionSettings>, input: Arc<ExecutionSettings>,
fast_mode: Option<SettingOverride<FastMode>>, fast_mode: Option<SettingOverride<Option<FastMode>>>,
client_limits: Option<SettingOverride<RateLimits>>, client_limits: Option<SettingOverride<RateLimits>>,
timeout_ms: Option<SettingOverride<Option<u64>>>, timeout_ms: Option<SettingOverride<Option<u64>>>,
} }
@@ -186,9 +187,10 @@ impl RequestSettings {
#[must_use] #[must_use]
pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy { pub fn apply_policy(&self, policy: ClientPolicy) -> ClientPolicy {
let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None); let values = self.resolve_execution(policy.key_id().as_str(), policy.defaults(), None);
let fast_mode = self.fast_mode_override(policy.key_id().as_str(), policy.defaults());
policy.with_settings( policy.with_settings(
values.runtime.request_profiles(), values.runtime.request_profiles(),
values.fast_mode, fast_mode,
values.client_limits, values.client_limits,
) )
} }
@@ -247,9 +249,7 @@ impl RequestSettings {
} }
ExecutionSettings { ExecutionSettings {
runtime, runtime,
fast_mode: overrides fast_mode: self.fast_mode_override(key, defaults),
.and_then(|scope| scope.fast_mode.as_ref())
.map_or(defaults.fast_mode, |change| change.value),
client_limits: overrides client_limits: overrides
.and_then(|scope| scope.client_limits.as_ref()) .and_then(|scope| scope.client_limits.as_ref())
.map_or(defaults.limits, |change| change.value), .map_or(defaults.limits, |change| change.value),
@@ -259,6 +259,15 @@ impl RequestSettings {
} }
} }
fn fast_mode_override(&self, key: &str, defaults: &ClientSettings) -> Option<FastMode> {
self.execution
.as_ref()
.filter(|scope| scope.client_key_id == key)
.and_then(|scope| scope.fast_mode.as_ref())
.map(|change| change.value)
.unwrap_or(defaults.fast_mode_override)
}
pub(crate) fn execution_deadline( pub(crate) fn execution_deadline(
&self, &self,
key: &ClientApiKeyId, key: &ClientApiKeyId,
@@ -583,12 +583,19 @@ async fn compile_runtime_snapshot(
.map(|group| (group.id.clone(), std::mem::take(&mut group.model_access))) .map(|group| (group.id.clone(), std::mem::take(&mut group.model_access)))
.collect(); .collect();
let account_directory = Arc::new( let account_directory = Arc::new(
RuntimeAccountDirectory::new(accounts).with_group_model_access(group_model_access), RuntimeAccountDirectory::new(accounts)
.with_group_model_access(group_model_access)
.with_group_fast_modes(
groups
.values()
.filter(|group| group.enabled && group.fast_mode != FastMode::Default)
.map(|group| (group.id.clone(), group.fast_mode))
.collect(),
),
); );
let mut client_policies = Vec::with_capacity(facts.client_policies.len()); let mut client_policies = Vec::with_capacity(facts.client_policies.len());
for policy in facts.client_policies { for policy in facts.client_policies {
let mut fast_mode = FastMode::Default;
let mut allow_image_generation = true; let mut allow_image_generation = true;
let mut allow_subagents = true; let mut allow_subagents = true;
let account_scope = if policy.group_ids.is_empty() { let account_scope = if policy.group_ids.is_empty() {
@@ -607,8 +614,7 @@ async fn compile_runtime_snapshot(
let group = groups let group = groups
.get(&group_id) .get(&group_id)
.ok_or(RuntimeSnapshotCompileError::InvalidData)?; .ok_or(RuntimeSnapshotCompileError::InvalidData)?;
// 停用只影响选号,仍绑定的分组继续贡献请求策略 // 功能权限仍按 Key 合并,停用分组不解除生图和子代理限制
fast_mode = fast_mode.merge(group.fast_mode);
allow_image_generation &= group.allow_image_generation; allow_image_generation &= group.allow_image_generation;
allow_subagents &= group.allow_subagents; allow_subagents &= group.allow_subagents;
bound_groups.push(RoutingGroupSnapshot::new( bound_groups.push(RoutingGroupSnapshot::new(
@@ -635,7 +641,6 @@ async fn compile_runtime_snapshot(
account_scope account_scope
.with_image_generation(allow_image_generation) .with_image_generation(allow_image_generation)
.with_subagents(allow_subagents) .with_subagents(allow_subagents)
.with_fast_mode(fast_mode)
.with_request_profiles(policy.request_profiles), .with_request_profiles(policy.request_profiles),
), ),
true, true,
@@ -399,14 +399,13 @@ struct RuntimeSnapshotReconciliationTask {
} }
impl ScheduledTask for RuntimeSnapshotReconciliationTask { impl ScheduledTask for RuntimeSnapshotReconciliationTask {
fn run_cycle( fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
&self,
_context: WorkerCycleContext,
) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
self.publisher context
.refresh_with_mode(RefreshMode::Reconcile) .cancellation()
.run_until_cancelled(self.publisher.refresh_with_mode(RefreshMode::Reconcile))
.await .await
.transpose()
.map(|_| ()) .map(|_| ())
.map_err(|source| { .map_err(|source| {
WorkerTaskError::safe("runtime snapshot reconciliation failed") WorkerTaskError::safe("runtime snapshot reconciliation failed")
@@ -430,10 +429,12 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
let cancellation = context.cancellation(); let cancellation = context.cancellation();
let mut retry_delay = INITIAL_BACKOFF; let mut retry_delay = INITIAL_BACKOFF;
loop { loop {
if cancellation.is_cancelled() { let Some(subscription) = cancellation
.run_until_cancelled(self.subscriptions.subscribe_snapshot_revisions())
.await
else {
return Ok(()); return Ok(());
} };
let subscription = self.subscriptions.subscribe_snapshot_revisions().await;
let mut subscription = match subscription { let mut subscription = match subscription {
Ok(subscription) => { Ok(subscription) => {
retry_delay = INITIAL_BACKOFF; retry_delay = INITIAL_BACKOFF;
@@ -456,7 +457,13 @@ impl DaemonTask for RuntimeSnapshotSubscriptionTask {
}; };
match notified { match notified {
Some(Ok(_)) => { Some(Ok(_)) => {
let _ = self.publisher.refresh().await; if cancellation
.run_until_cancelled(self.publisher.refresh())
.await
.is_none()
{
return Ok(());
}
} }
Some(Err(_)) | None => break, Some(Err(_)) | None => break,
} }
@@ -1138,26 +1138,12 @@ fn plan_with_location(
operation: &Operation, operation: &Operation,
account_selection_policy: AccountSelectionPolicy, account_selection_policy: AccountSelectionPolicy,
request_location: gateway_core::account::RequestLocation, request_location: gateway_core::account::RequestLocation,
) -> RoutingPlan {
plan_with_location_and_fast_policy(
operation,
account_selection_policy,
request_location,
FastMode::Default,
)
}
fn plan_with_location_and_fast_policy(
operation: &Operation,
account_selection_policy: AccountSelectionPolicy,
request_location: gateway_core::account::RequestLocation,
fast_mode: FastMode,
) -> RoutingPlan { ) -> RoutingPlan {
plan_with_profiles( plan_with_profiles(
operation, operation,
account_selection_policy, account_selection_policy,
request_location, request_location,
fast_mode, FastMode::Default,
Default::default(), Default::default(),
) )
} }
@@ -1255,7 +1241,7 @@ fn plan_with_protection(
operation, operation,
Arc::new( Arc::new(
FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts()) FrozenAccountScope::new(directory, ClientRoutingScope::all_accounts())
.with_fast_mode(fast_mode) .with_fast_mode_override(Some(fast_mode))
.with_request_profiles(profiles), .with_request_profiles(profiles),
), ),
&RoutingContext { &RoutingContext {
@@ -6414,6 +6400,8 @@ fn deadline_before_first_event_is_persisted_as_failed_attempt() {
#[test] #[test]
fn global_location_and_group_fast_policy_reach_every_account_retry() { fn global_location_and_group_fast_policy_reach_every_account_retry() {
use gateway_core::routing::{AccountGroupId, RoutingGroupSnapshot};
for mode in [ for mode in [
FastMode::Default, FastMode::Default,
FastMode::Enabled, FastMode::Enabled,
@@ -6425,12 +6413,67 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
timezone: "Asia/Tokyo".parse().unwrap(), timezone: "Asia/Tokyo".parse().unwrap(),
..Default::default() ..Default::default()
}; };
let route_plan = plan_with_location_and_fast_policy( let kind = ProviderKind::new("openai").unwrap();
&operation, let first_group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
plan(&operation).account_selection_policy(), let second_group = AccountGroupId::new(format!("grp_{:032x}", 2)).unwrap();
location.clone(), let second_mode = if mode == FastMode::Disabled {
mode, FastMode::Default
} else {
FastMode::Disabled
};
let directory = Arc::new(
RuntimeAccountDirectory::new(
[
("acct_first", first_group.clone()),
("acct_second", second_group.clone()),
]
.into_iter()
.map(|(account, group)| {
(
ProviderAccountId::new(account).unwrap(),
RuntimeAccount::new(kind.clone(), BTreeSet::from([group])),
)
})
.collect(),
)
.with_group_fast_modes(BTreeMap::from([
(first_group.clone(), mode),
(second_group.clone(), second_mode),
])),
); );
let scope = Arc::new(FrozenAccountScope::new(
Arc::clone(&directory),
ClientRoutingScope::restricted(
vec![
RoutingGroupSnapshot::new(first_group.clone(), "A".into()),
RoutingGroupSnapshot::new(second_group.clone(), "B".into()),
],
BTreeSet::from([first_group, second_group]),
BTreeSet::from([kind.clone()]),
)
.unwrap(),
));
let route_plan = RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(),
gateway_core::settings::SettingsValues::new(2, "smart", Default::default(), None, None)
.with_request_location(location.clone(), true),
vec![kind.clone()],
vec![ProviderModel::new(
kind,
UpstreamModelId::new("gpt-5").unwrap(),
ModelCapabilities::new(BTreeSet::from([operation.kind()]), Some(32_000)),
)],
Vec::new(),
)
.unwrap()
.with_account_directory(directory)
.plan(
&PublicModelId::new("gpt-5").unwrap(),
&operation,
Arc::clone(&scope),
&RoutingContext::default(),
)
.unwrap();
let (coordinator, _, provider) = coordinator(vec![ let (coordinator, _, provider) = coordinator(vec![
Script::Stream { Script::Stream {
account_id: "acct_first", account_id: "acct_first",
@@ -6459,12 +6502,17 @@ fn global_location_and_group_fast_policy_reach_every_account_retry() {
block_on(session.commit_downstream(Some(200))).unwrap(); block_on(session.commit_downstream(Some(200))).unwrap();
let contexts = provider.contexts.lock().unwrap(); let contexts = provider.contexts.lock().unwrap();
assert_eq!(contexts.len(), 2); assert_eq!(contexts.len(), 2);
assert!( for (context, account, expected) in [
contexts (&contexts[0], "acct_first", mode),
.iter() (&contexts[1], "acct_second", second_mode),
.all(|context| context.request_location() == Some(&location) ] {
&& context.fast_mode() == mode) assert_eq!(context.request_location(), Some(&location));
); assert!(Arc::ptr_eq(context.account_scope().unwrap(), &scope));
assert_eq!(
context.fast_mode_for_account(&ProviderAccountId::new(account).unwrap(), "gpt-5"),
expected,
);
}
} }
} }
@@ -3068,8 +3068,14 @@ impl Provider for ChargedProvider {
request: ProviderRequest, request: ProviderRequest,
context: AttemptContext, context: AttemptContext,
) -> Result<ProviderStream, ProviderError> { ) -> Result<ProviderStream, ProviderError> {
self.policies.lock().unwrap().push(context.fast_mode());
let candidate = request.candidate(); let candidate = request.candidate();
self.policies
.lock()
.unwrap()
.push(context.fast_mode_for_account(
&ProviderAccountId::new("acct_start").unwrap(),
candidate.upstream_model().unwrap().as_str(),
));
let metadata = ProviderCallMetadata::new( let metadata = ProviderCallMetadata::new(
candidate.provider().clone(), candidate.provider().clone(),
candidate.upstream_model().unwrap().clone(), candidate.upstream_model().unwrap().clone(),
@@ -4792,7 +4798,7 @@ fn start_snapshot_with_image_policy(
account_scope(&provider, "acct_start") account_scope(&provider, "acct_start")
.as_ref() .as_ref()
.clone() .clone()
.with_fast_mode(fast_mode) .with_fast_mode_override(Some(fast_mode))
.with_image_generation(allow_image_generation), .with_image_generation(allow_image_generation),
), ),
enabled, enabled,
@@ -5526,7 +5532,7 @@ fn entry_settings_freeze_authentication_and_rebase_only_explicit_overrides() {
.execution_values() .execution_values()
.unwrap() .unwrap()
.fast_mode, .fast_mode,
FastMode::Disabled Some(FastMode::Disabled)
); );
assert_eq!( assert_eq!(
prepared prepared
@@ -5649,7 +5655,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
account_scope(&provider, "acct_start") account_scope(&provider, "acct_start")
.as_ref() .as_ref()
.clone() .clone()
.with_fast_mode(FastMode::Disabled) .with_fast_mode_override(Some(FastMode::Disabled))
.with_request_profiles(profiles(name)), .with_request_profiles(profiles(name)),
), ),
true, true,
@@ -5688,7 +5694,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
let configuration = RequestSettings::new(snapshots.acquire().unwrap()) let configuration = RequestSettings::new(snapshots.acquire().unwrap())
.with_execution(parent.client().policy(), previous.timeout_ms); .with_execution(parent.client().policy(), previous.timeout_ms);
let mut values = previous.clone(); let mut values = previous.clone();
values.fast_mode = FastMode::Default; values.fast_mode = Some(FastMode::Default);
values.client_limits = RateLimits::unlimited(); values.client_limits = RateLimits::unlimited();
values.timeout_ms = Some(90_000); values.timeout_ms = Some(90_000);
let mut runtime = serde_json::to_value(&values.runtime).unwrap(); let mut runtime = serde_json::to_value(&values.runtime).unwrap();
@@ -5722,7 +5728,7 @@ fn child_settings_recompute_key_scope_without_inheriting_parent_defaults() {
Some(actual.clone()) Some(actual.clone())
); );
assert_eq!(actual.client_limits.max_concurrency, expected_limit); assert_eq!(actual.client_limits.max_concurrency, expected_limit);
assert_eq!(actual.fast_mode, expected_fast); assert_eq!(actual.fast_mode, Some(expected_fast));
assert_eq!(actual.timeout_ms, expected_timeout); assert_eq!(actual.timeout_ms, expected_timeout);
let facts = serde_json::to_value(actual.runtime).unwrap(); let facts = serde_json::to_value(actual.runtime).unwrap();
assert_eq!(facts["request_profiles"]["openai"]["identity"], profile); assert_eq!(facts["request_profiles"]["openai"]["identity"], profile);
@@ -186,7 +186,10 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
)); ));
let gateway = GatewayError::from_provider(&error); let gateway = GatewayError::from_provider(&error);
assert_eq!(gateway.safe_message(), "Account quota is exhausted."); assert_eq!(
gateway.safe_message(),
"Upstream account quota is exhausted."
);
assert_eq!(gateway.client_message(), message); assert_eq!(gateway.client_message(), message);
assert_eq!(gateway.client_error_code(), Some("quota_exhausted")); assert_eq!(gateway.client_error_code(), Some("quota_exhausted"));
assert_eq!(gateway.client_error_type(), Some("rate_limit_error")); assert_eq!(gateway.client_error_type(), Some("rate_limit_error"));
@@ -53,7 +53,7 @@ fn policy_with_profiles(
Arc::new( Arc::new(
FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts()) FrozenAccountScope::new(Arc::default(), ClientRoutingScope::all_accounts())
.with_request_profiles(overrides) .with_request_profiles(overrides)
.with_fast_mode(FastMode::Disabled), .with_fast_mode_override(Some(FastMode::Disabled)),
), ),
true, true,
RateLimits { RateLimits {
@@ -153,7 +153,7 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
values.runtime = values values.runtime = values
.runtime .runtime
.with_model_mappings(BTreeMap::from([("alias".into(), "model".into())])); .with_model_mappings(BTreeMap::from([("alias".into(), "model".into())]));
values.fast_mode = FastMode::Default; values.fast_mode = Some(FastMode::Default);
values.client_limits = RateLimits::unlimited(); values.client_limits = RateLimits::unlimited();
values.timeout_ms = Some(90_000); values.timeout_ms = Some(90_000);
let changed = original.replace_execution(&values, "plugin").unwrap(); let changed = original.replace_execution(&values, "plugin").unwrap();
@@ -168,14 +168,14 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
parent_values.runtime.request_profiles(), parent_values.runtime.request_profiles(),
&profiles(&[("openai", "parent"), ("xai", "second")]) &profiles(&[("openai", "parent"), ("xai", "second")])
); );
assert_eq!(parent_values.fast_mode, FastMode::Default); assert_eq!(parent_values.fast_mode, Some(FastMode::Default));
let child_settings = rebased.with_execution(&child, Some(60_000)); let child_settings = rebased.with_execution(&child, Some(60_000));
let child_values = child_settings.execution_values().unwrap(); let child_values = child_settings.execution_values().unwrap();
assert_eq!( assert_eq!(
child_values.runtime.request_profiles(), child_values.runtime.request_profiles(),
&profiles(&[("openai", "child"), ("xai", "second")]) &profiles(&[("openai", "child"), ("xai", "second")])
); );
assert_eq!(child_values.fast_mode, FastMode::Disabled); assert_eq!(child_values.fast_mode, Some(FastMode::Disabled));
assert_eq!(child_values.client_limits, child.limits()); assert_eq!(child_values.client_limits, child.limits());
assert_eq!(child_values.timeout_ms, Some(60_000)); assert_eq!(child_values.timeout_ms, Some(60_000));
assert_eq!(child_settings.snapshot().mapped_model("alias"), "model"); assert_eq!(child_settings.snapshot().mapped_model("alias"), "model");
@@ -186,6 +186,81 @@ fn scope_changes_recompute_defaults_and_inherit_only_explicit_overrides() {
); );
} }
#[test]
fn group_fast_policy_survives_settings_resolution_until_explicitly_overridden() {
use gateway_core::{
account::ProviderAccountId,
routing::{AccountGroupId, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory},
};
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
let account = ProviderAccountId::new("acct_group_fast").unwrap();
let provider = ProviderKind::new("openai").unwrap();
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(
RuntimeAccountDirectory::new(BTreeMap::from([(
account.clone(),
RuntimeAccount::new(provider.clone(), [group.clone()].into()),
)]))
.with_group_fast_modes([(group.clone(), FastMode::Disabled)].into()),
),
ClientRoutingScope::restricted(
vec![RoutingGroupSnapshot::new(group.clone(), "Standard".into())],
[group].into(),
[provider].into(),
)
.unwrap(),
));
let key = |name: &str| {
ClientPolicy::new(
ClientApiKeyId::new(name).unwrap(),
PlaintextClientApiKey::new(format!("fixture-{name}")).unwrap(),
scope.clone(),
true,
RateLimits::unlimited(),
)
};
let parent = key("parent");
let settings = RequestSettings::new(snapshot(1, "host")).with_execution(&parent, None);
assert_eq!(settings.execution_values().unwrap().fast_mode, None);
let resolved = |settings: &RequestSettings, key| {
settings
.apply_policy(key)
.account_scope()
.fast_mode_for_account(&account, "model")
};
assert_eq!(resolved(&settings, parent.clone()), FastMode::Disabled);
let unchanged = settings
.replace_execution(&settings.execution_values().unwrap(), "pass-through")
.unwrap();
assert_eq!(resolved(&unchanged, parent.clone()), FastMode::Disabled);
let mut values = settings.execution_values().unwrap();
values.fast_mode = Some(FastMode::Default);
let direct_default = settings
.replace_execution(&values, "follow-client")
.unwrap();
assert_eq!(resolved(&direct_default, parent.clone()), FastMode::Default);
values.fast_mode = Some(FastMode::Enabled);
let enabled = settings.replace_execution(&values, "force-fast").unwrap();
assert_eq!(resolved(&enabled, parent.clone()), FastMode::Enabled);
values.fast_mode = Some(FastMode::Default);
let default = enabled.replace_execution(&values, "follow-client").unwrap();
assert_eq!(resolved(&default, parent.clone()), FastMode::Default);
values.fast_mode = None;
let cleared = default.replace_execution(&values, "group-policy").unwrap();
assert_eq!(resolved(&cleared, parent.clone()), FastMode::Disabled);
assert_eq!(
cleared.inspect()["execution"]["fast_mode"]["value"],
serde_json::Value::Null
);
let child = key("child");
assert_eq!(
resolved(&default.with_execution(&child, None), child),
FastMode::Disabled
);
assert_eq!(resolved(&settings, parent), FastMode::Disabled);
}
#[test] #[test]
fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() { fn explicitly_selecting_the_host_profiles_overrides_keys_after_rebase() {
let host = snapshot(1, "first"); let host = snapshot(1, "first");
@@ -2727,7 +2727,7 @@ fn decompression_setting_should_validate_and_remain_frozen_across_publication()
} }
#[test] #[test]
fn fast_mode_merges_only_bound_groups_without_changing_account_scope() { fn fast_mode_merges_only_enabled_bound_groups_of_the_selected_account() {
use gateway_core::account::ProviderAccountId; use gateway_core::account::ProviderAccountId;
use gateway_core::routing::AccountGroupId; use gateway_core::routing::AccountGroupId;
for (mode, other_mode, expected) in [ for (mode, other_mode, expected) in [
@@ -2758,6 +2758,8 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
let open_group_id = let open_group_id =
AccountGroupId::new("grp_00000000000000000000000000000002").unwrap(); AccountGroupId::new("grp_00000000000000000000000000000002").unwrap();
let account_id = ProviderAccountId::new("acct_fast_policy").unwrap(); let account_id = ProviderAccountId::new("acct_fast_policy").unwrap();
let first_account = ProviderAccountId::new("acct_first_group").unwrap();
let second_account = ProviderAccountId::new("acct_second_group").unwrap();
let facts = SnapshotFacts::new( let facts = SnapshotFacts::new(
revision(1), revision(1),
revision(1), revision(1),
@@ -2786,11 +2788,19 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
) )
.with_fast_mode(other_mode), .with_fast_mode(other_mode),
], ],
vec![SnapshotProviderAccountFacts::new( [&account_id, &first_account, &second_account]
account_id.clone(), .into_iter()
"alpha", .map(|id| SnapshotProviderAccountFacts::new(id.clone(), "alpha"))
)], .collect(),
vec![ vec![
SnapshotAccountGroupMemberFacts::new(
group_id.clone(),
first_account.clone(),
),
SnapshotAccountGroupMemberFacts::new(
open_group_id.clone(),
second_account.clone(),
),
SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()), SnapshotAccountGroupMemberFacts::new(group_id, account_id.clone()),
SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()), SnapshotAccountGroupMemberFacts::new(open_group_id, account_id.clone()),
], ],
@@ -2818,16 +2828,99 @@ fn fast_mode_merges_only_bound_groups_without_changing_account_scope() {
&Default::default(), &Default::default(),
) )
.unwrap(); .unwrap();
for (account, effective) in [
(
&account_id,
if group_enabled { expected } else { other_mode },
),
(
&first_account,
if group_enabled {
mode
} else {
FastMode::Default
},
),
(&second_account, other_mode),
] {
assert_eq!(
plan.account_scope()
.fast_mode_for_account(account, "public-model"),
if bound { effective } else { FastMode::Default },
"account={account}, mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
);
}
assert_eq!( assert_eq!(
plan.fast_mode(), plan.account_scope().allows(&first_account),
if bound { expected } else { FastMode::Default }, !bound || group_enabled
"mode={mode:?}, other={other_mode:?}, enabled={group_enabled}, bound={bound}"
); );
} }
} }
} }
} }
#[test]
fn fast_mode_ignores_unbound_groups_and_groups_that_deny_the_model() {
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId};
use gateway_core::routing::AccountGroupId;
let group = |id| AccountGroupId::new(format!("grp_{id:032x}")).unwrap();
let account = ProviderAccountId::new("acct_model_fast").unwrap();
let facts = SnapshotFacts::new(
revision(1),
revision(1),
SettingsValues::new(3, "smart", BTreeMap::new(), None, None),
vec![SnapshotClientPolicyFacts::new(
ClientApiKeyId::new("key_model_fast").unwrap(),
PlaintextClientApiKey::new("fixture-model-fast").unwrap(),
vec![group(1), group(2)],
RateLimits::unlimited(),
)],
vec![
SnapshotAccountGroupFacts::new(group(1), "Fast".into(), true)
.with_fast_mode(FastMode::Enabled)
.with_model_access(
AccountModelAccess::new(
AccountModelAccessMode::Allowlist,
vec!["fast-model".into()],
)
.unwrap(),
),
SnapshotAccountGroupFacts::new(group(2), "Standard".into(), true)
.with_fast_mode(FastMode::Disabled)
.with_model_access(
AccountModelAccess::new(
AccountModelAccessMode::Denylist,
vec!["fast-model".into()],
)
.unwrap(),
),
SnapshotAccountGroupFacts::new(group(3), "Unbound".into(), true)
.with_fast_mode(FastMode::Disabled),
],
vec![SnapshotProviderAccountFacts::new(account.clone(), "alpha")],
(1..=3)
.map(|id| SnapshotAccountGroupMemberFacts::new(group(id), account.clone()))
.collect(),
);
let snapshot = block_on(
RuntimeSnapshotCompiler::new(
Arc::new(TestSnapshotStore::new(Ok(facts))),
Arc::new(TestCatalog::Unavailable),
)
.compile(),
)
.unwrap();
let scope = snapshot.client_policies().next().unwrap().account_scope();
for (model, expected) in [
("fast-model", FastMode::Enabled),
("standard-model", FastMode::Disabled),
] {
assert!(scope.allows_model(&account, model));
assert_eq!(scope.fast_mode_for_account(&account, model), expected);
}
}
#[test] #[test]
fn group_feature_permissions_merge_independently_with_deny_precedence() { fn group_feature_permissions_merge_independently_with_deny_precedence() {
use gateway_core::account::ProviderAccountId; use gateway_core::account::ProviderAccountId;
+1
View File
@@ -48,6 +48,7 @@ tracing = "0.1.44"
tracing-appender = "0.2.5" tracing-appender = "0.2.5"
tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] }
yaml-rust2 = "0.13.0" yaml-rust2 = "0.13.0"
uuid = { version = "1.23.3", features = ["v4"] }
[dev-dependencies] [dev-dependencies]
hyper = { version = "=1.11.1", default-features = false, features = ["server"] } hyper = { version = "=1.11.1", default-features = false, features = ["server"] }
@@ -37,6 +37,7 @@ const MAX_OFFICIAL_PLUGIN_MANIFEST_SIZE: u64 = 256 * 1024;
/// gateway-admin 消费的真实进程/文件系统操作实现 /// gateway-admin 消费的真实进程/文件系统操作实现
#[derive(Clone)] #[derive(Clone)]
pub struct ProcessSystemOperations { pub struct ProcessSystemOperations {
instance_id: String,
cancellation: CancellationToken, cancellation: CancellationToken,
events: Arc<UpdateEvents>, events: Arc<UpdateEvents>,
config: Arc<SystemUpdateConfig>, config: Arc<SystemUpdateConfig>,
@@ -62,6 +63,7 @@ impl ProcessSystemOperations {
ReleaseFiles::installed(&config) ReleaseFiles::installed(&config)
})); }));
Self { Self {
instance_id: uuid::Uuid::new_v4().to_string(),
cancellation, cancellation,
events: Arc::new(UpdateEvents::default()), events: Arc::new(UpdateEvents::default()),
config: Arc::new(config), config: Arc::new(config),
@@ -350,6 +352,8 @@ impl SystemOperations for ProcessSystemOperations {
.await; .await;
Ok(SystemVersion { Ok(SystemVersion {
version: self.config.version.clone(), version: self.config.version.clone(),
instance_id: self.instance_id.clone(),
restart_supported: self.config.self_restart_enabled,
git_sha: self.config.git_sha.clone(), git_sha: self.config.git_sha.clone(),
build_time: self.config.build_time.clone(), build_time: self.config.build_time.clone(),
deployment_mode: self.config.deployment_mode.clone(), deployment_mode: self.config.deployment_mode.clone(),
+12 -5
View File
@@ -122,11 +122,12 @@ impl WorkerSupervisor {
health: &self.health, health: &self.health,
}; };
let deadline = tokio::time::Instant::now() + timeout; let deadline = tokio::time::Instant::now() + timeout;
for (_, handle) in &mut shutdown.handles { for (worker, handle) in &mut shutdown.handles {
if tokio::time::timeout_at(deadline, &mut *handle) if tokio::time::timeout_at(deadline, &mut *handle)
.await .await
.is_err() .is_err()
{ {
tracing::warn!(target: "gateway_shutdown", %worker, "后台任务收尾超时,强制终止");
handle.abort(); handle.abort();
let _ = handle.await; let _ = handle.await;
} }
@@ -459,6 +460,7 @@ async fn acquire_and_run(
let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind(); let acquisition = AssertUnwindSafe(leader_lease.try_acquire(request)).catch_unwind();
tokio::pin!(acquisition); tokio::pin!(acquisition);
let acquisition = tokio::select! { let acquisition = tokio::select! {
biased;
() = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown, () = cancellation.cancelled() => return ScheduledOutcome::ShuttingDown,
acquisition = &mut acquisition => acquisition, acquisition = &mut acquisition => acquisition,
}; };
@@ -490,12 +492,13 @@ async fn run_local_cycle(
.catch_unwind(); .catch_unwind();
tokio::pin!(cycle); tokio::pin!(cycle);
tokio::select! { tokio::select! {
outcome = &mut cycle => task_result(outcome), biased;
() = cancellation.cancelled() => { () = cancellation.cancelled() => {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
ScheduledOutcome::ShuttingDown ScheduledOutcome::ShuttingDown
} }
outcome = &mut cycle => task_result(outcome),
} }
} }
@@ -527,17 +530,21 @@ async fn run_leased_cycle(
let outcome = loop { let outcome = loop {
tokio::select! { tokio::select! {
result = &mut cycle => break task_result(result), biased;
() = cancellation.cancelled() => { () = cancellation.cancelled() => {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
break ScheduledOutcome::ShuttingDown; break ScheduledOutcome::ShuttingDown;
} }
result = &mut cycle => break task_result(result),
() = &mut renewal => { () = &mut renewal => {
let renewed = renew_guard( let Some(renewed) = cancellation.run_until_cancelled(renew_guard(
guard.as_mut(), guard.as_mut(),
schedule.leader_lease_renewal_interval(), schedule.leader_lease_renewal_interval(),
).await; )).await else {
// 返回循环首个取消分支,统一等待正在执行的周期收尾
continue;
};
if let Err(error) = renewed { if let Err(error) = renewed {
cycle_cancel.cancel(); cycle_cancel.cancel();
let _ = cycle.await; let _ = cycle.await;
@@ -142,6 +142,8 @@ async fn restart_should_request_process_restart_inside_docker() {
config.deployment_mode = "docker".to_owned(); config.deployment_mode = "docker".to_owned();
let shutdown = CancellationToken::new(); let shutdown = CancellationToken::new();
let service = ProcessSystemOperations::new(shutdown.clone(), config); let service = ProcessSystemOperations::new(shutdown.clone(), config);
assert!(!service.update_status().await.expect("status").need_restart);
assert!(service.version().await.expect("version").restart_supported);
service service
.restart(Arc::new(AllowingUpdatePreflight)) .restart(Arc::new(AllowingUpdatePreflight))
.await .await
@@ -152,6 +154,48 @@ async fn restart_should_request_process_restart_inside_docker() {
.expect("shutdown requested"); .expect("shutdown requested");
} }
#[tokio::test]
async fn version_should_distinguish_same_version_service_instances() {
let fixture = Fixture::new();
let config = fixture.config("http://127.0.0.1:1/repos");
let service = ProcessSystemOperations::new(CancellationToken::new(), config.clone());
let version = service.version().await.expect("version");
assert!(!version.instance_id.is_empty());
assert_eq!(
service
.clone()
.version()
.await
.expect("same instance")
.instance_id,
version.instance_id
);
let replacement = ProcessSystemOperations::new(CancellationToken::new(), config);
let restarted = replacement.version().await.expect("new instance");
assert_eq!(restarted.version, version.version);
assert_ne!(restarted.instance_id, version.instance_id);
}
#[tokio::test]
async fn version_should_report_restart_disabled_when_host_rejects_it() {
let fixture = Fixture::new();
let mut config = fixture.config("http://127.0.0.1:1/repos");
config.self_restart_enabled = false;
let shutdown = CancellationToken::new();
let service = ProcessSystemOperations::new(shutdown.clone(), config);
assert!(!service.version().await.expect("version").restart_supported);
assert_eq!(
service
.restart(Arc::new(AllowingUpdatePreflight))
.await
.expect_err("restart disabled")
.kind(),
SystemOperationErrorKind::Conflict
);
assert!(!shutdown.is_cancelled());
}
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn accepted_restart_excludes_system_operations_until_service_release() { async fn accepted_restart_excludes_system_operations_until_service_release() {
let fixture = Fixture::new(); let fixture = Fixture::new();
+30 -3
View File
@@ -219,6 +219,7 @@ enum LeaseStep {
enum RenewStep { enum RenewStep {
Success, Success,
Error, Error,
Pending,
} }
#[derive(Default)] #[derive(Default)]
@@ -268,11 +269,12 @@ impl WorkerLeaderLeaseGuard for FakeLeaseGuard {
fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> { fn renew(&mut self) -> BoxFuture<'_, Result<(), WorkerLeaseError>> {
Box::pin(async move { Box::pin(async move {
lock_unpoisoned(&self.renewals).push(self.worker.clone()); lock_unpoisoned(&self.renewals).push(self.worker.clone());
match lock_unpoisoned(&self.renew_scripts) let step = lock_unpoisoned(&self.renew_scripts)
.get_mut(&self.worker) .get_mut(&self.worker)
.and_then(VecDeque::pop_front) .and_then(VecDeque::pop_front)
.unwrap_or(RenewStep::Success) .unwrap_or(RenewStep::Success);
{ match step {
RenewStep::Pending => pending().await,
RenewStep::Success => Ok(()), RenewStep::Success => Ok(()),
RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")), RenewStep::Error => Err(WorkerLeaseError::safe("expected renewal failure")),
} }
@@ -510,6 +512,31 @@ async fn long_cycle_renews_leader_lease_before_ttl() {
supervisor.shutdown(Duration::from_secs(1)).await; supervisor.shutdown(Duration::from_secs(1)).await;
} }
#[tokio::test(start_paused = true)]
async fn shutdown_signals_the_cycle_while_lease_renewal_is_pending() {
let leases = Arc::new(FakeLeasePort::default());
leases.renew_script(target_worker(), [RenewStep::Pending]);
let task = CancellationTask {
entered: Arc::new(AtomicUsize::new(0)),
observed: Arc::new(AtomicUsize::new(0)),
};
let supervisor = supervisor();
supervisor
.start(
target_plan(task.clone(), renewal_schedule()),
leases.clone(),
Arc::new(RecordingDiagnostics::default()),
)
.unwrap();
yield_until(|| task.entered.load(Ordering::SeqCst) != 0).await;
tokio::time::advance(Duration::from_millis(10)).await;
yield_until(|| leases.renewal_count(&target_worker()) == 1).await;
// 关闭预算短于续租超时,协作取消仍应完成
supervisor.shutdown(Duration::from_millis(1)).await;
assert_eq!(task.observed.load(Ordering::SeqCst), 1);
assert!(lock_unpoisoned(&leases.active_guards).is_empty());
}
#[tokio::test(start_paused = true)] #[tokio::test(start_paused = true)]
async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() { async fn renewal_failure_cancels_old_cycle_before_another_leader_cycle_starts() {
let task = ConcurrentCycleTask { let task = ConcurrentCycleTask {
@@ -248,21 +248,21 @@ impl Execution {
request_body_limit, request_body_limit,
) )
.map_err(|error| fault_error(error, UpstreamSendState::NotSent))?; .map_err(|error| fault_error(error, UpstreamSendState::NotSent))?;
let upstream_model = invocation.metadata.upstream_model().ok_or_else(invalid)?;
let request = UpstreamAdapterRequest { let request = UpstreamAdapterRequest {
adapter_id: declaration.id.clone(), adapter_id: declaration.id.clone(),
provider: declaration.provider, provider: declaration.provider,
upstream_model: invocation upstream_model: upstream_model.as_str().to_owned(),
.metadata
.upstream_model()
.ok_or_else(invalid)?
.as_str()
.to_owned(),
client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(), client_key_id: invocation.context.client_api_key_ref().as_str().to_owned(),
account_id: invocation.account.account_id().as_str().to_owned(), account_id: invocation.account.account_id().as_str().to_owned(),
credential_revision: invocation.account.credential_revision().get(), credential_revision: invocation.account.credential_revision().get(),
protocol: invocation.operation.protocol().to_owned(), protocol: invocation.operation.protocol().to_owned(),
client_transport: invocation.context.client_transport().as_str().to_owned(), client_transport: invocation.context.client_transport().as_str().to_owned(),
fast_mode: invocation.context.fast_mode().as_str().to_owned(), fast_mode: invocation
.context
.fast_mode_for_account(invocation.account.account_id(), upstream_model.as_str())
.as_str()
.to_owned(),
request_elapsed_ms: u64::try_from( request_elapsed_ms: u64::try_from(
invocation.context.timing_started_at().elapsed().as_millis(), invocation.context.timing_started_at().elapsed().as_millis(),
) )
@@ -7,13 +7,16 @@ use serde_json::{Value, json};
#[tokio::test] #[tokio::test]
async fn middleware_preserves_fast_modes_and_sources() { async fn middleware_preserves_fast_modes_and_sources() {
for (mode, expected) in [ for (mode, expected) in [
(FastMode::Default, FastMode::Default), (None, None),
(FastMode::Enabled, FastMode::Enabled), (None, Some(FastMode::Default)),
(FastMode::Disabled, FastMode::Disabled), (Some(FastMode::Default), Some(FastMode::Default)),
(FastMode::Enabled, FastMode::Disabled), (Some(FastMode::Enabled), Some(FastMode::Enabled)),
(FastMode::Ultrafast, FastMode::Ultrafast), (Some(FastMode::Disabled), Some(FastMode::Disabled)),
(FastMode::Enabled, FastMode::Ultrafast), (Some(FastMode::Enabled), Some(FastMode::Disabled)),
(FastMode::Disabled, FastMode::Default), (Some(FastMode::Ultrafast), Some(FastMode::Ultrafast)),
(Some(FastMode::Enabled), Some(FastMode::Ultrafast)),
(Some(FastMode::Disabled), Some(FastMode::Default)),
(Some(FastMode::Enabled), None),
] { ] {
let snapshot = gateway_core::routing::RuntimeSnapshot::new( let snapshot = gateway_core::routing::RuntimeSnapshot::new(
ConfigRevision::new(1).unwrap(), ConfigRevision::new(1).unwrap(),
@@ -43,8 +46,7 @@ async fn middleware_preserves_fast_modes_and_sources() {
let settings = settings.replace_execution(&seed, "seed").unwrap(); let settings = settings.replace_execution(&seed, "seed").unwrap();
let wire = serde_json::to_value(&seed).unwrap(); let wire = serde_json::to_value(&seed).unwrap();
let mut updated = wire.clone(); let mut updated = wire.clone();
updated["fast_mode"] = json!(expected.as_str()); updated["fast_mode"] = json!(expected);
updated["timeout_ms"] = json!(90_000);
let contribution = crate::support::contribution( let contribution = crate::support::contribution(
Capability::Middleware, Capability::Middleware,
vec![Stage::Request], vec![Stage::Request],
@@ -61,8 +63,8 @@ async fn middleware_preserves_fast_modes_and_sources() {
id: "fast-settings", id: "fast-settings",
configuration: json!({ configuration: json!({
"mode":"settings", "expected_settings":wire, "settings":updated, "mode":"settings", "expected_settings":wire, "settings":updated,
"expected_fast_source": if mode == FastMode::Default { Value::Null } else { "expected_fast_source": if mode.is_none() { Value::Null } else {
json!({"instance_id":"seed", "order":1, "value":mode.as_str()}) json!({"instance_id":"seed", "order":1, "value":mode})
}, },
}), }),
bindings: vec![binding( bindings: vec![binding(
@@ -102,11 +104,11 @@ async fn middleware_preserves_fast_modes_and_sources() {
assert_eq!(settings.execution_values().unwrap().fast_mode, expected); assert_eq!(settings.execution_values().unwrap().fast_mode, expected);
assert_eq!( assert_eq!(
settings.execution_values().unwrap().timeout_ms, settings.execution_values().unwrap().timeout_ms,
Some(90_000) Some(60_000)
); );
let sources = settings.inspect(); let sources = settings.inspect();
let fast_source = &sources["execution"]["fast_mode"]; let fast_source = &sources["execution"]["fast_mode"];
if mode == FastMode::Default && expected == FastMode::Default { if mode.is_none() && expected.is_none() {
assert!(fast_source.is_null()); assert!(fast_source.is_null());
} else { } else {
assert_eq!( assert_eq!(
@@ -117,12 +119,9 @@ async fn middleware_preserves_fast_modes_and_sources() {
"fast-settings" "fast-settings"
} }
); );
assert_eq!(fast_source["value"], expected.as_str()); assert_eq!(fast_source["value"], json!(expected));
} }
assert_eq!( assert!(sources["execution"]["timeout_ms"].is_null());
sources["execution"]["timeout_ms"]["instance_id"],
"fast-settings"
);
next.run(request).await next.run(request).await
}) })
}), }),
@@ -1277,7 +1277,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
let baseline = ExecutionSettings { let baseline = ExecutionSettings {
runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None) runtime: SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
.with_request_profiles(profiles("key-default")), .with_request_profiles(profiles("key-default")),
fast_mode: FastMode::Disabled, fast_mode: Some(FastMode::Disabled),
client_limits: RateLimits { client_limits: RateLimits {
max_concurrency: 2, max_concurrency: 2,
requests_per_minute: 10, requests_per_minute: 10,
@@ -1314,7 +1314,7 @@ async fn real_request_plugins_rewrite_settings_in_onion_order() {
gateway_core::routing::ClientRoutingScope::all_accounts(), gateway_core::routing::ClientRoutingScope::all_accounts(),
) )
.with_request_profiles(profiles("key-default")) .with_request_profiles(profiles("key-default"))
.with_fast_mode(baseline.fast_mode), .with_fast_mode_override(baseline.fast_mode),
), ),
true, true,
baseline.client_limits, baseline.client_limits,
@@ -179,7 +179,6 @@ fn context_with_body_limit(
ClientApiKeyId::new(key).unwrap(), ClientApiKeyId::new(key).unwrap(),
) )
.with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation)) .with_upstream_adapters(runtime.execution_registry().upstream_adapters(generation))
.with_fast_mode(mode)
.with_request_body_limit(bytes), .with_request_body_limit(bytes),
NonZeroU32::new(1).unwrap(), NonZeroU32::new(1).unwrap(),
SystemTime::now() + Duration::from_secs(5), SystemTime::now() + Duration::from_secs(5),
@@ -187,7 +186,13 @@ fn context_with_body_limit(
gateway_core::account::RotationStrategy::RoundRobin, gateway_core::account::RotationStrategy::RoundRobin,
std::num::NonZeroU32::new(1).unwrap(), std::num::NonZeroU32::new(1).unwrap(),
), ),
AccountAttemptContext::new(Default::default(), None, None), AccountAttemptContext::new(Default::default(), None, None).with_account_scope(Arc::new(
gateway_core::routing::FrozenAccountScope::new(
Arc::default(),
gateway_core::routing::ClientRoutingScope::all_accounts(),
)
.with_fast_mode_override(Some(mode)),
)),
None, None,
CancellationToken::new(), CancellationToken::new(),
) )
@@ -588,7 +588,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
); );
if let Some(expected) = configuration.get("expected_fast_source") { if let Some(expected) = configuration.get("expected_fast_source") {
let sources = &call.request.head.settings_sources["execution"]; let sources = &call.request.head.settings_sources["execution"];
assert_eq!(sources["input"]["fast_mode"], "default"); assert!(sources["input"]["fast_mode"].is_null());
assert_eq!(&sources["fast_mode"], expected); assert_eq!(&sources["fast_mode"], expected);
} }
if let Some(settings) = configuration.get("settings") { if let Some(settings) = configuration.get("settings") {
@@ -489,7 +489,7 @@ let plugin = PluginBuilder::from_json(manifest_json)?
#### 模型请求与 attempt #### 模型请求与 attempt
`RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 在进入 attempt 前应用宿主 Fast 策略; `RequestCall.request.head` 包含完整 Client Key 与分组归属。request 中间件改写正文后,OpenAI 按选中账号和上游模型解析宿主 Fast 策略,在进入 attempt 前应用;
attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。 attempt 中间件在此基线上继续改写,终端不再应用 Fast 策略。
request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。 request 与 attempt 阶段通过 `append_header` 添加的请求头会进入上游请求,不适合存放插件内部标记或仅供下游读取的信息。
OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。 OpenAI 与 xAI 的上游 headers 先由账号和画像生成,插件同名字段覆盖基线,同名多值按插件顺序保留;不存在按认证、Cookie 或会话名称划分的保护列表。
@@ -498,7 +498,8 @@ CPR 中间件添加的 HTTP 扩展头在发往 Antigravity 时经过该 Provider
实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造 实际账号租约、凭据版本与计费归属仍记录真实选中事实,不随插件修改 header 名称而伪造
request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。 request 阶段 `request.head.settings` 是本次调用的有效设置对象,包含 `runtime`、`fast_mode`、`client_limits` 和 `timeout_ms`。
`fast_mode` 使用 `default`、`enabled`、`ultrafast`、`disabled` 四个值,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。 `fast_mode` 为 `null` 时按选中账号的有效分组解析;显式 `default` 表示跟随客户端,`enabled`、`ultrafast`、`disabled` 覆盖分组策略,具体档位语义见[账号分组](../../../../../docs/api.md#6-账号分组)。
保留该字段不建立新覆盖,改写为 `null` 恢复按分组解析;其他改写形成当前 Key 的显式覆盖,优先于分组策略。attempt 中间件仍可直接改写正文档位
`runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。 `runtime` 使用宿主快照的设置字段,画像已合并 Client Key 设置;可以修改映射、画像、调度、位置及计价等执行参数。
SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。 SDK 仅在对象改变时提交完整替换,`false`、`0`、空映射和合同允许的 `null` 不表示跳过;不做隐式深合并。
线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。 线协议省略 `next.settings` 才表示保留;显式 `null` 仍按完整替换校验,因不符合设置对象合同而拒绝。
@@ -41,7 +41,7 @@ Provider、业务协议和传输名称不能写入宿主兼容清单的 capabili
`TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影; `TypedCall<UpstreamAdapterRequest>` 包含只读的 Key、账号、凭据版本、模型、协议、Header 和宿主续接投影;
原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件 原始请求正文位于 `call.payload`,原始账号凭据不进入插件输入。宿主首次消费冷流才调用插件
`fast_mode` 是本次模型执行的有效设置,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线, `fast_mode` 是按选中账号及上游模型解析后的有效策略,取值为 `default`、`enabled`、`ultrafast` 或 `disabled`,请求设置的显式覆盖优先于分组策略。OpenAI 在 attempt 中间件之前将 Fast 设置应用到正文基线,
适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。 适配器收到经过 attempt 中间件处理的正文;attempt 中间件显式改写档位后,宿主不会在发送前再次应用 Fast 策略。
其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt) 其他请求设置与 Key 作用域的覆盖规则见[模型请求与 attempt](capabilities.md#模型请求与-attempt)
@@ -3,7 +3,10 @@
use crate::chat_completions::{ use crate::chat_completions::{
ChatError, custom_tool_schema, ChatError, custom_tool_schema,
error::{invalid, unsupported}, error::{invalid, unsupported},
request::string, request::{
block_text, empty_history_content, empty_history_part, function_parameters,
reasoning_effort, response_format, stop_sequences, string,
},
validate_request, validate_request,
}; };
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@@ -13,7 +16,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
validate_request(chat)?; validate_request(chat)?;
let mut system = Vec::new(); let mut system = Vec::new();
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) { if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
system.extend(parts(instructions, "instructions", true)?); system.extend(parts(instructions, "instructions", "system")?);
} }
let mut contents = Vec::new(); let mut contents = Vec::new();
let mut calls = BTreeMap::new(); let mut calls = BTreeMap::new();
@@ -30,7 +33,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
system.extend(parts( system.extend(parts(
&message["content"], &message["content"],
&format!("{path}.content"), &format!("{path}.content"),
true, role,
)?); )?);
continue; continue;
} }
@@ -48,7 +51,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
let mut text = Vec::new(); let mut text = Vec::new();
let mut media = Vec::new(); let mut media = Vec::new();
for part in parts(&message["content"], &format!("{path}.content"), false)? { for part in parts(&message["content"], &format!("{path}.content"), role)? {
if let Some(value) = part.get("text").and_then(Value::as_str) { if let Some(value) = part.get("text").and_then(Value::as_str) {
text.push(value.to_owned()); text.push(value.to_owned());
} else { } else {
@@ -61,12 +64,12 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
vec![response] vec![response]
} else { } else {
let mut content = if message["content"].is_null() { let mut content = parts(&message["content"], &format!("{path}.content"), role)?;
Vec::new() if let Some(refusal) = message
} else { .get("refusal")
parts(&message["content"], &format!("{path}.content"), false)? .and_then(Value::as_str)
}; .filter(|v| !v.is_empty())
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) { {
content.push(json!({"text":refusal})); content.push(json!({"text":refusal}));
} }
for (call_index, call) in message for (call_index, call) in message
@@ -105,6 +108,9 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
} }
content content
}; };
if role == "assistant" && content.is_empty() {
continue;
}
append( append(
&mut contents, &mut contents,
if role == "assistant" { "model" } else { "user" }, if role == "assistant" { "model" } else { "user" },
@@ -134,11 +140,10 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
generation.insert(to.into(), value.clone()); generation.insert(to.into(), value.clone());
} }
} }
if let Some(effort) = chat if let Some(stops) = stop_sequences(chat)? {
.get("reasoning_effort") generation.insert("stopSequences".into(), stops);
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort"))) }
.filter(|v| !v.is_null()) if let Some(effort) = reasoning_effort(chat) {
{
let budget: i64 = match effort.as_str() { let budget: i64 = match effort.as_str() {
Some("none") => 0, Some("none") => 0,
Some("minimal" | "low") => 1024, Some("minimal" | "low") => 1024,
@@ -158,11 +163,7 @@ pub fn convert_request(chat: &Map<String, Value>) -> Result<Map<String, Value>,
}, },
); );
} }
if let Some(format) = chat if let Some(format) = response_format(chat) {
.get("response_format")
.or_else(|| chat.get("text").and_then(|v| v.get("format")))
.filter(|v| !v.is_null())
{
match format["type"].as_str() { match format["type"].as_str() {
Some("json_schema") => { Some("json_schema") => {
generation.insert("responseMimeType".into(), json!("application/json")); generation.insert("responseMimeType".into(), json!("application/json"));
@@ -205,7 +206,11 @@ fn append(contents: &mut Vec<Value>, role: &str, parts: Vec<Value>) {
} }
} }
fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> { fn parts(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
if empty_history_content(role, value) {
return Ok(Vec::new());
}
let system = matches!(role, "system" | "developer");
if let Some(text) = value.as_str() { if let Some(text) = value.as_str() {
return Ok(vec![json!({"text":text})]); return Ok(vec![json!({"text":text})]);
} }
@@ -214,12 +219,13 @@ fn parts(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatErro
.ok_or_else(|| invalid(path))? .ok_or_else(|| invalid(path))?
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
.map(|(index, part)| { .map(|(index, part)| {
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let kind = string(part.get("type"), &format!("{path}.type"), false)?; let kind = string(part.get("type"), &format!("{path}.type"), false)?;
match kind { match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
Ok(json!({"text":string(part.get("text"), &format!("{path}.text"), true)?})) Ok(json!({"text":block_text(part.get("text"), &path)?}))
} }
"refusal" if !system => Ok( "refusal" if !system => Ok(
json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}), json!({"text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}),
@@ -314,16 +320,10 @@ fn tools(chat: &Map<String, Value>, result: &mut Map<String, Value>) -> Result<(
let parameters = if kind == "custom" { let parameters = if kind == "custom" {
custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))? custom_tool_schema(definition.get("format"), &format!("{path}.custom.format"))?
} else { } else {
definition function_parameters(definition, &path)?
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
}; };
if !parameters.is_object() {
return Err(invalid(&format!("{path}.function.parameters")));
}
let mut declaration = json!({"name":name,"parametersJsonSchema":parameters}); let mut declaration = json!({"name":name,"parametersJsonSchema":parameters});
if let Some(value) = definition.get("description") { if let Some(value) = definition.get("description").filter(|v| !v.is_null()) {
declaration["description"] = value.clone(); declaration["description"] = value.clone();
} }
declarations.push(declaration); declarations.push(declaration);
@@ -4,7 +4,10 @@ use crate::anthropic::MessagesModelCapabilities;
use crate::chat_completions::{ use crate::chat_completions::{
ChatError, custom_tool_schema, ChatError, custom_tool_schema,
error::{invalid, unsupported}, error::{invalid, unsupported},
request::string, request::{
block_text, empty_history_content, empty_history_part, function_parameters,
reasoning_effort, response_format, stop_sequences, string,
},
validate_request, validate_request,
}; };
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
@@ -37,6 +40,9 @@ pub fn convert_request(
result.insert(field.into(), value.clone()); result.insert(field.into(), value.clone());
} }
} }
if let Some(stops) = stop_sequences(chat)? {
result.insert("stop_sequences".into(), stops);
}
if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) { if let Some(tier) = chat.get("service_tier").and_then(Value::as_str) {
match tier { match tier {
"priority" => { "priority" => {
@@ -53,7 +59,7 @@ pub fn convert_request(
} }
let mut system = Vec::new(); let mut system = Vec::new();
if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) { if let Some(instructions) = chat.get("instructions").filter(|v| !v.is_null()) {
system.extend(content(instructions, "instructions", true)?); system.extend(content(instructions, "instructions", "system")?);
} }
let mut messages = Vec::new(); let mut messages = Vec::new();
let mut calls = BTreeMap::new(); let mut calls = BTreeMap::new();
@@ -70,7 +76,7 @@ pub fn convert_request(
system.extend(content( system.extend(content(
&message["content"], &message["content"],
&format!("{path}.content"), &format!("{path}.content"),
true, role,
)?); )?);
continue; continue;
} }
@@ -84,15 +90,15 @@ pub fn convert_request(
return Err(invalid(&format!("{path}.tool_call_id"))); return Err(invalid(&format!("{path}.tool_call_id")));
} }
vec![ vec![
json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), false)?}), json!({"type":"tool_result","tool_use_id":id,"content":content(&message["content"], &format!("{path}.content"), role)?}),
] ]
} else { } else {
let mut blocks = if message["content"].is_null() { let mut blocks = content(&message["content"], &format!("{path}.content"), role)?;
Vec::new() if let Some(refusal) = message
} else { .get("refusal")
content(&message["content"], &format!("{path}.content"), false)? .and_then(Value::as_str)
}; .filter(|v| !v.is_empty())
if let Some(refusal) = message.get("refusal").and_then(Value::as_str) { {
blocks.push(json!({"type":"text","text":refusal})); blocks.push(json!({"type":"text","text":refusal}));
} }
for (call_index, call) in message for (call_index, call) in message
@@ -130,6 +136,9 @@ pub fn convert_request(
} }
blocks blocks
}; };
if role == "assistant" && blocks.is_empty() {
continue;
}
append_message( append_message(
&mut messages, &mut messages,
if role == "assistant" { if role == "assistant" {
@@ -148,10 +157,7 @@ pub fn convert_request(
} }
result.insert("messages".into(), messages.into()); result.insert("messages".into(), messages.into());
tools(chat, &mut result, capabilities)?; tools(chat, &mut result, capabilities)?;
let format = chat if let Some(format) = response_format(chat) {
.get("response_format")
.or_else(|| chat.get("text").and_then(|v| v.get("format")));
if let Some(format) = format.filter(|v| !v.is_null()) {
match format["type"].as_str() { match format["type"].as_str() {
Some("json_schema") => { Some("json_schema") => {
let schema = format let schema = format
@@ -190,7 +196,11 @@ fn append_message(messages: &mut Vec<Value>, role: &str, blocks: Vec<Value>) {
} }
} }
fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatError> { fn content(value: &Value, path: &str, role: &str) -> Result<Vec<Value>, ChatError> {
if empty_history_content(role, value) {
return Ok(Vec::new());
}
let system = matches!(role, "system" | "developer");
if let Some(text) = value.as_str() { if let Some(text) = value.as_str() {
return Ok(vec![json!({"type":"text","text":text})]); return Ok(vec![json!({"type":"text","text":text})]);
} }
@@ -200,12 +210,13 @@ fn content(value: &Value, path: &str, system: bool) -> Result<Vec<Value>, ChatEr
.ok_or_else(|| invalid(path))? .ok_or_else(|| invalid(path))?
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
{ {
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let kind = string(part.get("type"), &format!("{path}.type"), false)?; let kind = string(part.get("type"), &format!("{path}.type"), false)?;
let block = match kind { let block = match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
json!({"type":"text","text":string(part.get("text"), &format!("{path}.text"), true)?}) json!({"type":"text","text":block_text(part.get("text"), &path)?})
} }
"refusal" if !system => { "refusal" if !system => {
json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?}) json!({"type":"text","text":string(part.get("refusal"), &format!("{path}.refusal"), true)?})
@@ -295,17 +306,11 @@ fn tools(
let schema = if kind == "custom" { let schema = if kind == "custom" {
custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))? custom_tool_schema(declaration.get("format"), &format!("{path}.custom.format"))?
} else { } else {
declaration function_parameters(declaration, &path)?
.get("parameters")
.cloned()
.unwrap_or_else(|| json!({"type":"object","properties":{}}))
}; };
if !schema.is_object() {
return Err(invalid(&format!("{path}.function.parameters")));
}
let mut target = json!({"name":name,"input_schema":schema}); let mut target = json!({"name":name,"input_schema":schema});
for field in ["description", "strict", "cache_control"] { for field in ["description", "strict", "cache_control"] {
if let Some(value) = declaration.get(field) { if let Some(value) = declaration.get(field).filter(|v| !v.is_null()) {
target[field] = value.clone(); target[field] = value.clone();
} }
} }
@@ -393,11 +398,7 @@ fn reasoning(
capabilities: &MessagesModelCapabilities, capabilities: &MessagesModelCapabilities,
max_tokens: u64, max_tokens: u64,
) -> Result<(), ChatError> { ) -> Result<(), ChatError> {
let Some(effort) = chat let Some(effort) = reasoning_effort(chat) else {
.get("reasoning_effort")
.or_else(|| chat.get("reasoning").and_then(|v| v.get("effort")))
.filter(|v| !v.is_null())
else {
return Ok(()); return Ok(());
}; };
let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?; let effort = effort.as_str().ok_or_else(|| invalid("reasoning_effort"))?;
@@ -30,11 +30,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
field: "messages".into(), field: "messages".into(),
expected: "an array", expected: "an array",
})?; })?;
if messages.is_empty() { let mut has_message = false;
return Err(ChatError::EmptyField {
field: "messages".into(),
});
}
for (index, message) in messages.iter().enumerate() { for (index, message) in messages.iter().enumerate() {
let path = format!("messages[{index}]"); let path = format!("messages[{index}]");
let message = message.as_object().ok_or_else(|| invalid(&path))?; let message = message.as_object().ok_or_else(|| invalid(&path))?;
@@ -42,43 +38,51 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") { if !matches!(role, "system" | "developer" | "user" | "assistant" | "tool") {
return Err(unsupported(&format!("{path}.role"))); return Err(unsupported(&format!("{path}.role")));
} }
for (field, allowed) in [ let calls = match message.get("tool_calls") {
("tool_calls", "assistant"), None | Some(Value::Null) => &[][..],
("refusal", "assistant"), Some(Value::Array(calls)) => calls.as_slice(),
("tool_call_id", "tool"), _ => return Err(invalid(&format!("{path}.tool_calls"))),
] { };
if role != allowed && message.get(field).is_some_and(|v| !v.is_null()) { if role != "assistant" && !calls.is_empty() {
return Err(invalid(&format!("{path}.{field}"))); return Err(invalid(&format!("{path}.tool_calls")));
}
let refusal = message.get("refusal").filter(|v| !v.is_null() && *v != "");
if let Some(value) = refusal {
if role != "assistant" {
return Err(invalid(&format!("{path}.refusal")));
} }
string(Some(value), &format!("{path}.refusal"), true)?;
} }
for field in ["function_call", "audio"] { for field in ["function_call", "audio"] {
if message.get(field).is_some_and(|v| !v.is_null()) { if message.get(field).is_some_and(|v| !v.is_null()) {
return Err(unsupported(&format!("{path}.{field}"))); return Err(unsupported(&format!("{path}.{field}")));
} }
} }
for field in ["name", "refusal"] {
if let Some(value) = message.get(field).filter(|v| !v.is_null()) {
string(Some(value), &format!("{path}.{field}"), true)?;
}
}
if role == "tool" { if role == "tool" {
string( string(
message.get("tool_call_id"), message.get("tool_call_id"),
&format!("{path}.tool_call_id"), &format!("{path}.tool_call_id"),
false, false,
)?; )?;
} else if message
.get("tool_call_id")
.is_some_and(|v| !v.is_null() && v != "")
{
return Err(invalid(&format!("{path}.tool_call_id")));
} }
if let Some(content) = message.get("content").filter(|v| !v.is_null()) { let content = message.get("content").unwrap_or(&Value::Null);
if !empty_history_content(role, content) {
if !content.is_string() && !content.is_array() { if !content.is_string() && !content.is_array() {
return Err(invalid(&format!("{path}.content"))); return Err(invalid(&format!("{path}.content")));
} }
has_message = true;
if let Some(parts) = content.as_array() { if let Some(parts) = content.as_array() {
for (part_index, part) in parts.iter().enumerate() { for (part_index, part) in parts.iter().enumerate() {
let part_path = format!("{path}.content[{part_index}]"); let part_path = format!("{path}.content[{part_index}]");
let kind = string(part.get("type"), &format!("{part_path}.type"), false)?; let kind = string(part.get("type"), &format!("{part_path}.type"), false)?;
match kind { match kind {
"text" | "input_text" | "output_text" => { "text" | "input_text" | "output_text" => {
string(part.get("text"), &format!("{part_path}.text"), true)?; block_text(part.get("text"), &part_path)?;
} }
"image_url" | "file" | "input_audio" | "input_image" | "input_file" "image_url" | "file" | "input_audio" | "input_image" | "input_file"
if matches!(role, "user" | "tool") => {} if matches!(role, "user" | "tool") => {}
@@ -89,45 +93,37 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
} }
} }
} }
} else if role != "assistant"
|| (!message
.get("tool_calls")
.is_some_and(|v| v.as_array().is_some_and(|v| !v.is_empty()))
&& !message.get("refusal").is_some_and(Value::is_string))
{
return Err(invalid(&format!("{path}.content")));
} }
if let Some(calls) = message.get("tool_calls").filter(|v| !v.is_null()) { has_message |= refusal.is_some() || !calls.is_empty();
for (call_index, call) in calls for (call_index, call) in calls.iter().enumerate() {
.as_array() let call_path = format!("{path}.tool_calls[{call_index}]");
.ok_or_else(|| invalid(&format!("{path}.tool_calls")))? string(call.get("id"), &format!("{call_path}.id"), false)?;
.iter() let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
.enumerate() if !matches!(kind, "function" | "custom") {
{ return Err(unsupported(&format!("{call_path}.type")));
let call_path = format!("{path}.tool_calls[{call_index}]");
string(call.get("id"), &format!("{call_path}.id"), false)?;
let kind = string(call.get("type"), &format!("{call_path}.type"), false)?;
if !matches!(kind, "function" | "custom") {
return Err(unsupported(&format!("{call_path}.type")));
}
string(
call.get(kind).and_then(|v| v.get("name")),
&format!("{call_path}.{kind}.name"),
false,
)?;
let data_field = if kind == "function" {
"arguments"
} else {
"input"
};
string(
call.get(kind).and_then(|v| v.get(data_field)),
&format!("{call_path}.{kind}.{data_field}"),
true,
)?;
} }
string(
call.get(kind).and_then(|v| v.get("name")),
&format!("{call_path}.{kind}.name"),
false,
)?;
let data_field = if kind == "function" {
"arguments"
} else {
"input"
};
string(
call.get(kind).and_then(|v| v.get(data_field)),
&format!("{call_path}.{kind}.{data_field}"),
true,
)?;
} }
} }
if !has_message {
return Err(ChatError::EmptyField {
field: "messages".into(),
});
}
for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) { for (field, value) in body.iter().filter(|(_, v)| !v.is_null()) {
let valid = match field.as_str() { let valid = match field.as_str() {
"n" => value.as_u64() == Some(1), "n" => value.as_u64() == Some(1),
@@ -150,7 +146,7 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
} }
} }
if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) { if let Some(options) = body.get("stream_options").filter(|v| !v.is_null()) {
if body.get("stream") != Some(&Value::Bool(true)) || !options.is_object() { if !options.is_object() {
return Err(invalid("stream_options")); return Err(invalid("stream_options"));
} }
for field in ["include_usage", "include_obfuscation"] { for field in ["include_usage", "include_obfuscation"] {
@@ -161,13 +157,99 @@ pub fn validate_request(body: &Map<String, Value>) -> Result<(), ChatError> {
return Err(invalid(&format!("stream_options.{field}"))); return Err(invalid(&format!("stream_options.{field}")));
} }
} }
if options.get("include_obfuscation") == Some(&Value::Bool(true)) { if body.get("stream") == Some(&Value::Bool(true))
&& options.get("include_obfuscation") == Some(&Value::Bool(true))
{
return Err(unsupported("stream_options.include_obfuscation")); return Err(unsupported("stream_options.include_obfuscation"));
} }
} }
Ok(()) Ok(())
} }
// 用户输入和工具结果保留原值,空指令或 assistant 正文不生成上游内容块
pub(super) fn empty_history_content(role: &str, content: &Value) -> bool {
can_omit_empty_text(role)
&& (content.is_null()
|| content == ""
|| content
.as_array()
.is_some_and(|parts| parts.iter().all(plain_empty_text)))
}
fn can_omit_empty_text(role: &str) -> bool {
matches!(role, "system" | "developer" | "assistant")
}
fn plain_empty_text(part: &Value) -> bool {
// 只移除纯文本占位,带缓存断点等附加字段的块交给目标转换器
part.get("text")
.is_some_and(|text| text.is_null() || text == "")
&& matches!(
part.get("type").and_then(Value::as_str),
Some("text" | "input_text" | "output_text")
)
&& part.as_object().is_some_and(|fields| {
fields
.iter()
.all(|(key, value)| matches!(key.as_str(), "type" | "text") || value.is_null())
})
}
pub(super) fn empty_history_part(role: &str, part: &Value) -> bool {
can_omit_empty_text(role) && plain_empty_text(part)
}
// 部分 Chat 客户端用显式 null 表示空文本,缺少 text 或其他类型仍按原字段报错
pub(super) fn block_text<'a>(
value: Option<&'a Value>,
part_path: &str,
) -> Result<&'a str, ChatError> {
match value {
Some(Value::Null) => Ok(""),
value => string(value, &format!("{part_path}.text"), true),
}
}
pub(super) fn response_format(body: &Map<String, Value>) -> Option<&Value> {
body.get("response_format")
.filter(|v| !v.is_null())
.or_else(|| body.get("text")?.get("format").filter(|v| !v.is_null()))
}
pub(super) fn reasoning_effort(body: &Map<String, Value>) -> Option<&Value> {
body.get("reasoning_effort")
.filter(|v| !v.is_null())
.or_else(|| {
body.get("reasoning")?
.get("effort")
.filter(|v| !v.is_null())
})
}
pub(super) fn stop_sequences(body: &Map<String, Value>) -> Result<Option<Value>, ChatError> {
match body.get("stop") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(text)) => Ok(Some(json!([text]))),
Some(Value::Array(values)) => {
for (index, value) in values.iter().enumerate() {
if !value.is_string() {
return Err(invalid(&format!("stop[{index}]")));
}
}
Ok((!values.is_empty()).then(|| Value::Array(values.clone())))
}
_ => Err(invalid("stop")),
}
}
pub(super) fn function_parameters(function: &Value, path: &str) -> Result<Value, ChatError> {
match function.get("parameters") {
None | Some(Value::Null) => Ok(json!({"type":"object","properties":{}})),
Some(schema) if schema.is_object() => Ok(schema.clone()),
_ => Err(invalid(&format!("{path}.function.parameters"))),
}
}
pub(super) fn string<'a>( pub(super) fn string<'a>(
value: Option<&'a Value>, value: Option<&'a Value>,
path: &str, path: &str,
@@ -222,28 +304,16 @@ pub(crate) fn request_facts(body: &Map<String, Value>) -> RequestFacts {
.any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")), .any(|tool| tool.get("type").and_then(Value::as_str) == Some("image_generation")),
reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null()) reasoning: body.get("reasoning_effort").is_some_and(|v| !v.is_null())
|| body.get("reasoning").is_some_and(Value::is_object), || body.get("reasoning").is_some_and(Value::is_object),
json_schema: body json_schema: response_format(body)
.get("response_format")
.and_then(|v| v.get("type")) .and_then(|v| v.get("type"))
.and_then(Value::as_str) .and_then(Value::as_str)
== Some("json_schema") == Some("json_schema"),
|| body
.get("text")
.and_then(|v| v.pointer("/format/type"))
.and_then(Value::as_str)
== Some("json_schema"),
..RequestFacts::default() ..RequestFacts::default()
} }
} }
pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> { pub(crate) fn request_effort(body: &Map<String, Value>) -> Option<&str> {
body.get("reasoning_effort") reasoning_effort(body).and_then(Value::as_str)
.and_then(Value::as_str)
.or_else(|| {
body.get("reasoning")
.and_then(|value| value.get("effort"))
.and_then(Value::as_str)
})
} }
/// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持 /// 将无格式约束的 custom 工具表达为字符串参数,受约束格式必须由目标原生支持
@@ -4,7 +4,11 @@ use std::collections::HashSet;
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
use crate::chat_completions::{ChatError as RequestDecodeError, validate_request}; use crate::chat_completions::{
ChatError as RequestDecodeError,
request::{block_text, empty_history_content, empty_history_part},
validate_request,
};
/// 将已验证的 Chat 正文直接转换为 Responses 请求 /// 将已验证的 Chat 正文直接转换为 Responses 请求
pub fn convert_request( pub fn convert_request(
@@ -161,7 +165,6 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
let path = format!("messages[{index}]"); let path = format!("messages[{index}]");
let mut message = object(value, &path)?; let mut message = object(value, &path)?;
let role = required_string(&mut message, "role", &format!("{path}.role"), false)?; let role = required_string(&mut message, "role", &format!("{path}.role"), false)?;
let name = optional(&mut message, "name").filter(|name| name != "");
if role == "tool" { if role == "tool" {
let call_id = required_string( let call_id = required_string(
&mut message, &mut message,
@@ -182,7 +185,8 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
"function_call_output" "function_call_output"
}; };
let mut item = json!({"type": kind, "call_id": call_id, "output": output}); let mut item = json!({"type": kind, "call_id": call_id, "output": output});
if let Some(name) = name { if let Some(name) = optional(&mut message, "name").filter(|name| name != "") {
string(&name, &format!("{path}.name"), true)?;
item["name"] = name; item["name"] = name;
} }
input.push(item); input.push(item);
@@ -193,8 +197,9 @@ fn messages(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
.map(|value| tool_calls(value, &format!("{path}.tool_calls"))) .map(|value| tool_calls(value, &format!("{path}.tool_calls")))
.transpose()? .transpose()?
.unwrap_or_default(); .unwrap_or_default();
let refusal = optional(&mut message, "refusal"); let refusal = optional(&mut message, "refusal").filter(|v| v != "");
let content = optional(&mut message, "content"); let content =
optional(&mut message, "content").filter(|v| !empty_history_content(&role, v));
let is_assistant = role == "assistant"; let is_assistant = role == "assistant";
let mut parts = content let mut parts = content
.map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant)) .map(|value| content_parts(value, &role, &format!("{path}.content"), is_assistant))
@@ -233,20 +238,23 @@ fn content_parts(
is_assistant: bool, is_assistant: bool,
) -> Result<Vec<Value>, RequestDecodeError> { ) -> Result<Vec<Value>, RequestDecodeError> {
let parts = match value { let parts = match value {
Value::String(text) => return Ok(vec![text_part(text, is_assistant)]), Value::String(text) => return Ok(vec![text_part(&text, is_assistant)]),
Value::Array(parts) => parts, Value::Array(parts) => parts,
_ => return Err(invalid_type(path, "a string or an array")), _ => return Err(invalid_type(path, "a string or an array")),
}; };
let mut result = Vec::with_capacity(parts.len()); let mut result = Vec::with_capacity(parts.len());
for (index, value) in parts.into_iter().enumerate() { for (index, value) in parts
.into_iter()
.enumerate()
.filter(|(_, part)| !empty_history_part(role, part))
{
let path = format!("{path}[{index}]"); let path = format!("{path}[{index}]");
let mut part = object(value, &path)?; let mut part = object(value, &path)?;
let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?; let kind = required_string(&mut part, "type", &format!("{path}.type"), false)?;
let mut converted = match kind.as_str() { let mut converted = match kind.as_str() {
"text" | "input_text" | "output_text" => text_part( "text" | "input_text" | "output_text" => {
required_string(&mut part, "text", &format!("{path}.text"), true)?, text_part(block_text(part.get("text"), &path)?, is_assistant)
is_assistant, }
),
"image_url" if matches!(role, "user" | "tool") => image_part( "image_url" if matches!(role, "user" | "tool") => image_part(
required(&mut part, "image_url", &format!("{path}.image_url"))?, required(&mut part, "image_url", &format!("{path}.image_url"))?,
&format!("{path}.image_url"), &format!("{path}.image_url"),
@@ -278,7 +286,7 @@ fn content_parts(
Ok(result) Ok(result)
} }
fn text_part(text: String, is_assistant: bool) -> Value { fn text_part(text: &str, is_assistant: bool) -> Value {
if is_assistant { if is_assistant {
json!({"type": "output_text", "text": text, "annotations": []}) json!({"type": "output_text", "text": text, "annotations": []})
} else { } else {
@@ -376,9 +384,17 @@ fn tools(value: Value) -> Result<Vec<Value>, RequestDecodeError> {
if let Some(nested) = optional(&mut tool, &kind) { if let Some(nested) = optional(&mut tool, &kind) {
tool = object(nested, &format!("{path}.{kind}"))?; tool = object(nested, &format!("{path}.{kind}"))?;
} }
if kind == "function" && tool.get("strict").is_none_or(Value::is_null) { if tool.get("description") == Some(&Value::Null) {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同 tool.remove("description");
tool.insert("strict".into(), false.into()); }
if kind == "function" {
if tool.get("parameters") == Some(&Value::Null) {
tool.remove("parameters");
}
if tool.get("strict").is_none_or(Value::is_null) {
// Chat 的缺省是宽松 schema,不能让 Responses 收紧参数合同
tool.insert("strict".into(), false.into());
}
} }
} }
// hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定 // hosted 工具采用原生 Responses 结构,支持范围由选中的 Provider 决定
+18 -1
View File
@@ -1,4 +1,21 @@
//! 跨协议 HTTP 传输、下游环境头分类与重试时间解析 //! 跨协议 HTTP 头分类、响应关联与重试时间解析
/// 响应关联 ID 的头名与优先级沿用官方 Codex
pub const RESPONSE_REQUEST_ID_HEADERS: [&str; 4] = [
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"x-ms-request-id",
];
/// 从各传输容器提供的可读 HTTP 头值中选取关联 ID,空值不阻止别名回退
pub fn preferred_response_request_id<'a>(
mut header: impl FnMut(&str) -> Option<&'a str>,
) -> Option<&'a str> {
RESPONSE_REQUEST_ID_HEADERS
.iter()
.find_map(|name| header(name).filter(|value| !value.trim().is_empty()))
}
/// 上游可交给客户端的秒级与毫秒级重试等待头 /// 上游可交给客户端的秒级与毫秒级重试等待头
pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"]; pub const RETRY_AFTER_HEADERS: [&str; 2] = ["retry-after", "retry-after-ms"];
@@ -4,7 +4,15 @@ use gateway_protocol::{
chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses}, chat_completions::{CHAT_PROTOCOL, ChatError, genai, messages, parse_request, responses},
request::{request_facts, request_observation}, request::{request_facts, request_observation},
}; };
use serde_json::json; use serde_json::{Map, Value, json};
fn target_requests(body: &Map<String, Value>) -> [Result<Map<String, Value>, ChatError>; 3] {
[
responses::convert_request(body),
messages::convert_request(body, &Default::default()),
genai::convert_request(body),
]
}
#[test] #[test]
fn parsing_retains_original_protocol_and_usage_preference() { fn parsing_retains_original_protocol_and_usage_preference() {
@@ -42,7 +50,7 @@ fn invalid_envelopes_and_chat_controls_keep_safe_field_errors() {
("n", json!(2)), ("n", json!(2)),
("store", json!(true)), ("store", json!(true)),
("previous_response_id", json!("resp_previous")), ("previous_response_id", json!("resp_previous")),
("stream_options", json!({"include_usage":true})), ("stream_options", json!(true)),
] { ] {
let mut request = super::request(); let mut request = super::request();
request.insert(field.into(), value); request.insert(field.into(), value);
@@ -104,9 +112,320 @@ fn capability_facts_only_read_protocol_declarations() {
assert!(!request_facts(CHAT_PROTOCOL, &body).tools); assert!(!request_facts(CHAT_PROTOCOL, &body).tools);
} }
#[test]
fn empty_history_is_omitted_only_when_converting() {
let mut baseline = super::request();
baseline["messages"] = json!([
{"role":"developer","content":"Keep replies short."},
{"role":"user","content":"hello"}
]);
let expected = target_requests(&baseline).map(Result::unwrap);
for role in ["system", "developer", "assistant"] {
for content in [
None,
Some(Value::Null),
Some(json!("")),
Some(json!([])),
Some(json!([{"type":"text","text":""},{"type":"output_text","text":""}])),
Some(json!([{"type":"input_text","text":null}])),
Some(json!([{"type":"text","text":"","prompt_cache_breakpoint":null}])),
] {
let mut placeholder =
json!({"role":role,"tool_calls":[],"refusal":"","tool_call_id":""});
if let Some(content) = content {
placeholder["content"] = content;
}
let mut body = baseline.clone();
body["messages"]
.as_array_mut()
.unwrap()
.insert(1, placeholder.clone());
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
assert_eq!(parsed, body);
assert_eq!(target_requests(&parsed).map(Result::unwrap), expected);
body["messages"] = json!([placeholder]);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("messages"));
}
}
}
}
#[test]
fn empty_history_fields_preserve_tool_calls_results_and_refusals() {
let mut body = super::request();
body["messages"] = json!([
{"role":"user","content":"hello"},
{"role":"assistant","tool_calls":[{"id":"c","type":"function","function":{"name":"f","arguments":"{}"}}]},
{"role":"tool","tool_call_id":"c","content":""},
{"role":"assistant","refusal":"declined"}
]);
let expected = target_requests(&body).map(Result::unwrap);
assert_eq!(expected[0]["input"][1]["call_id"], "c");
assert_eq!(expected[0]["input"][2]["output"], "");
assert_eq!(expected[1]["messages"][1]["content"][0]["type"], "tool_use");
assert_eq!(expected[1]["messages"][3]["content"][0]["text"], "declined");
assert_eq!(
expected[2]["contents"][2]["parts"][0]["functionResponse"]["id"],
"c"
);
assert_eq!(expected[2]["contents"][3]["parts"][0]["text"], "declined");
body["messages"][0] = json!({"role":"user","content":"hello","name":17,"refusal":"","tool_calls":[],"tool_call_id":""});
for content in [
Value::Null,
json!(""),
json!([]),
json!([{"type":"text","text":""}]),
json!([{"type":"output_text","text":null}]),
] {
body["messages"][1]["content"] = content.clone();
body["messages"][3]["content"] = content;
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
}
body["messages"][2]["content"] =
json!([{"type":"text","text":""},{"type":"text","text":"x"},{"type":"text","text":""}]);
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses["input"][2]["output"].as_array().unwrap().len(), 3);
assert_eq!(
messages["messages"][2]["content"][0]["content"]
.as_array()
.unwrap()
.len(),
3
);
assert_eq!(
genai["contents"][2]["parts"][0]["functionResponse"]["response"]["output"],
"\nx\n"
);
body["messages"][2]["content"][0]["text"] = Value::Null;
assert_eq!(
target_requests(&body).map(Result::unwrap),
[responses, messages, genai]
);
body["messages"][2]["content"] = json!("");
body["messages"][2]["name"] = json!(17);
let parsed = parse_request(&serde_json::to_vec(&body).unwrap()).unwrap();
let [responses, messages, genai] = target_requests(&parsed);
assert_eq!(responses.unwrap_err().parameter(), Some("messages[2].name"));
assert_eq!(messages.unwrap(), expected[1]);
assert_eq!(genai.unwrap(), expected[2]);
}
#[test]
fn filters_only_plain_empty_history_parts_and_keeps_source_indices() {
let mut body = super::request();
let blank = json!({"type":"input_text","text":""});
let space = json!({"type":"text","text":" "});
for role in ["system", "developer", "assistant", "user"] {
body["messages"] = json!([{"role":role,"content":[space]}, {"role":"user","content":"hi"}]);
let expected = target_requests(&body).map(Result::unwrap);
body["messages"][0]["content"] = json!([blank, space, blank]);
let actual = target_requests(&body).map(Result::unwrap);
body["messages"][0]["content"][0]["text"] = Value::Null;
assert_eq!(target_requests(&body).map(Result::unwrap), actual);
if role == "user" {
assert_eq!(
actual[0]["input"][0]["content"].as_array().unwrap().len(),
3
);
assert_eq!(actual[1]["messages"][0]["content"][1]["text"], " ");
assert_eq!(actual[2]["contents"][0]["parts"][1]["text"], " ");
} else {
assert_eq!(actual, expected);
}
}
let marked = json!({"type":"text","text":null,"prompt_cache_breakpoint":{"mode":"explicit"}});
body["messages"][0] = json!({"role":"developer","content":[blank,marked]});
let converted = responses::convert_request(&body).unwrap();
assert_eq!(
converted["input"][0]["content"],
json!([{"type":"input_text","text":"","prompt_cache_breakpoint":{"mode":"explicit"}}])
);
body["messages"][0]["role"] = json!("assistant");
assert_eq!(
responses::convert_request(&body).unwrap_err().parameter(),
Some("messages[0].content[1].prompt_cache_breakpoint")
);
for (part, code) in [
(json!({"type":"text"}), "missing_required_parameter"),
(json!({"type":"text","text":17}), "invalid_type"),
(json!({"type":"text","text":{}}), "invalid_type"),
] {
body["messages"][0]["content"] = json!([{"type":"text","text":null},part]);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("messages[0].content[1].text"));
assert_eq!(error.code(), code);
}
}
}
#[test]
fn null_chat_controls_fall_back_to_native_format_and_effort() {
let mut body = super::request();
let schema = json!({"type":"object","properties":{"q":{"type":"string"}}});
body.insert(
"text".into(),
json!({"format":{"type":"json_schema","name":"answer","schema":schema}}),
);
body.insert("reasoning".into(), json!({"effort":"low"}));
let expected = target_requests(&body).map(Result::unwrap);
assert_eq!(expected[1]["output_config"]["format"]["schema"], schema);
assert_eq!(
expected[2]["generationConfig"]["responseJsonSchema"],
schema
);
assert_eq!(expected[1]["thinking"]["budget_tokens"], 1024);
assert_eq!(
expected[2]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
1024
);
body.insert("response_format".into(), Value::Null);
body.insert("reasoning_effort".into(), Value::Null);
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
assert!(request_facts(CHAT_PROTOCOL, &body).json_schema);
body["response_format"] = json!({"type":"text"});
body["reasoning_effort"] = json!("none");
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert!(!request_facts(CHAT_PROTOCOL, &body).json_schema);
assert_eq!(responses["text"]["format"]["type"], "text");
assert!(messages.get("output_config").is_none());
assert!(
genai["generationConfig"]
.get("responseJsonSchema")
.is_none()
);
assert_eq!(messages["thinking"]["type"], "disabled");
assert_eq!(
genai["generationConfig"]["thinkingConfig"]["thinkingBudget"],
0
);
body["reasoning_effort"] = json!(5);
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(error.parameter(), Some("reasoning_effort"));
}
}
#[test]
fn null_function_parameters_follow_each_targets_default() {
let mut body = super::request();
body.insert(
"tools".into(),
json!([{"type":"function","function":{"name":"clock"}}]),
);
let expected = target_requests(&body).map(Result::unwrap);
assert!(expected[0]["tools"][0].get("parameters").is_none());
let default_schema = json!({"type":"object","properties":{}});
assert_eq!(expected[1]["tools"][0]["input_schema"], default_schema);
assert_eq!(
expected[2]["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
default_schema
);
body["tools"][0]["function"] =
json!({"name":"clock","parameters":null,"description":null,"strict":null});
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
let schema =
json!({"type":"object","properties":{"q":{"type":["string","null"],"default":null}}});
body["tools"][0]["function"]["parameters"] = schema.clone();
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses["tools"][0]["parameters"], schema);
assert_eq!(messages["tools"][0]["input_schema"], schema);
assert_eq!(
genai["tools"][0]["functionDeclarations"][0]["parametersJsonSchema"],
schema
);
}
#[test]
fn stop_sequences_are_mapped_only_for_targets_that_support_them() {
let mut body = super::request();
let baseline = target_requests(&body).map(Result::unwrap);
for stop in [Value::Null, json!([])] {
body.insert("stop".into(), stop);
assert_eq!(target_requests(&body).map(Result::unwrap), baseline);
}
for (stop, expected) in [
(json!(" END"), json!([" END"])),
(json!([" END", "\n"]), json!([" END", "\n"])),
] {
body["stop"] = stop;
let [responses, messages, genai] = target_requests(&body).map(Result::unwrap);
assert_eq!(responses, baseline[0]);
assert_eq!(messages["stop_sequences"], expected);
assert_eq!(genai["generationConfig"]["stopSequences"], expected);
}
for (stop, param) in [(json!(5), "stop"), (json!(["end", null]), "stop[1]")] {
body["stop"] = stop;
let [responses, messages, genai] = target_requests(&body);
assert_eq!(responses.unwrap(), baseline[0]);
for result in [messages, genai] {
assert_eq!(result.unwrap_err().parameter(), Some(param));
}
}
}
#[test]
fn stream_options_affect_only_streaming_delivery() {
for stream in [None, Some(false), Some(true)] {
let mut body = super::request();
if let Some(stream) = stream {
body.insert("stream".into(), json!(stream));
}
let expected = target_requests(&body).map(Result::unwrap);
body.insert(
"stream_options".into(),
json!({"include_usage":true, "include_obfuscation":false}),
);
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
body["stream_options"]["include_obfuscation"] = json!(true);
if stream == Some(true) {
for error in target_requests(&body).map(Result::unwrap_err) {
assert_eq!(
error.parameter(),
Some("stream_options.include_obfuscation")
);
}
} else {
assert_eq!(target_requests(&body).map(Result::unwrap), expected);
}
}
}
#[test] #[test]
fn all_targets_apply_the_same_common_request_validation() { fn all_targets_apply_the_same_common_request_validation() {
for (field, value, parameter) in [ for (field, value, parameter) in [
(
"messages",
json!([{"role":"system","content":null},{"role":"developer","content":null}]),
"messages",
),
(
"messages",
json!([{"role":"developer"},{"role":"assistant","audio":{"id":"audio"}}]),
"messages[1].audio",
),
(
"messages",
json!([{"role":"system","content":42}]),
"messages[0].content",
),
(
"messages",
json!([{"role":"system","content":null},{"role":"user","content":null}]),
"messages[1].content",
),
(
"messages",
json!([{"role":"tool","tool_call_id":"c","content":null}]),
"messages[0].content",
),
(
"messages",
json!([{"role":"system","content":null,"tool_calls":[{}]}]),
"messages[0].tool_calls",
),
( (
"messages", "messages",
json!([{"role":"assistant","content":"ok","refusal":17}]), json!([{"role":"assistant","content":"ok","refusal":17}]),
@@ -114,13 +433,18 @@ fn all_targets_apply_the_same_common_request_validation() {
), ),
( (
"messages", "messages",
json!([{"role":"user","content":"ok","name":17}]), json!([{"role":"assistant","tool_calls":{}}]),
"messages[0].name", "messages[0].tool_calls",
), ),
( (
"messages", "messages",
json!([{"role":"user","content":"ok","tool_calls":[]}]), json!([{"role":"developer","tool_call_id":"c"}]),
"messages[0].tool_calls", "messages[0].tool_call_id",
),
(
"messages",
json!([{"role":"user","content":"ok","refusal":"declined"}]),
"messages[0].refusal",
), ),
( (
"messages", "messages",
@@ -130,8 +454,8 @@ fn all_targets_apply_the_same_common_request_validation() {
("n", json!(2), "n"), ("n", json!(2), "n"),
( (
"stream_options", "stream_options",
json!({"include_usage":true}), json!({"include_usage":1}),
"stream_options", "stream_options.include_usage",
), ),
] { ] {
let mut body = super::request(); let mut body = super::request();
@@ -140,11 +464,7 @@ fn all_targets_apply_the_same_common_request_validation() {
.err() .err()
.unwrap(); .unwrap();
assert_eq!(expected.parameter(), Some(parameter)); assert_eq!(expected.parameter(), Some(parameter));
for result in [ for result in target_requests(&body) {
responses::convert_request(&body),
messages::convert_request(&body, &Default::default()),
genai::convert_request(&body),
] {
assert_eq!(result.unwrap_err(), expected); assert_eq!(result.unwrap_err(), expected);
} }
} }
+53 -1
View File
@@ -1,9 +1,61 @@
//! 验证传输头部分类,以及响应中的连接级和身份字段过滤 //! 验证传输头部分类,以及响应中的连接级和身份字段过滤
use gateway_protocol::http::{ use gateway_protocol::http::{
is_transport_managed_request_header, parse_retry_after_seconds, response_header_is_forwardable, is_transport_managed_request_header, parse_retry_after_seconds, preferred_response_request_id,
response_header_is_forwardable,
}; };
#[test]
fn response_request_ids_follow_official_header_priority() {
let names = [
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"x-ms-request-id",
];
let mut headers = http::HeaderMap::new();
for name in names {
headers.insert(name, http::HeaderValue::from_static(name));
}
headers.insert("cf-ray", http::HeaderValue::from_static("trace-only"));
for name in names {
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
Some(name),
);
headers.remove(name);
}
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
None,
);
}
#[test]
fn response_request_ids_skip_unusable_first_values_without_rewriting_headers() {
let mut headers = http::HeaderMap::new();
headers.insert(
"x-request-id",
http::HeaderValue::from_bytes(b"\xff").unwrap(),
);
headers.append(
"x-request-id",
http::HeaderValue::from_static("second-value"),
);
headers.insert("x-oai-request-id", http::HeaderValue::from_static(" \t "));
headers.insert("x-openai-request-id", http::HeaderValue::from_static(""));
headers.insert(
"x-ms-request-id",
http::HeaderValue::from_static(" opaque-id "),
);
assert_eq!(
preferred_response_request_id(|name| headers.get(name)?.to_str().ok()),
Some(" opaque-id "),
);
assert_eq!(headers["x-request-id"].as_bytes(), b"\xff");
assert_eq!(headers.get_all("x-request-id").iter().count(), 2);
}
#[test] #[test]
fn retry_after_should_accept_nonnegative_seconds_and_http_dates() { fn retry_after_should_accept_nonnegative_seconds_and_http_dates() {
for (header, expected) in [ for (header, expected) in [
+13 -10
View File
@@ -240,18 +240,21 @@ pub(crate) struct StaleModelRequestRecoveryTask {
impl ScheduledTask for StaleModelRequestRecoveryTask { impl ScheduledTask for StaleModelRequestRecoveryTask {
fn run_cycle( fn run_cycle(
&self, &self,
_context: WorkerCycleContext, context: WorkerCycleContext,
) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> { ) -> futures::future::BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
gateway_core::engine::ExecutionStore::recover_expired( context
self.execution.as_ref(), .cancellation()
SystemTime::now(), .run_until_cancelled(gateway_core::engine::ExecutionStore::recover_expired(
) self.execution.as_ref(),
.await SystemTime::now(),
.map(|_| ()) ))
.map_err(|source| { .await
WorkerTaskError::safe("stale request recovery failed").with_source(source) .transpose()
}) .map(|_| ())
.map_err(|source| {
WorkerTaskError::safe("stale request recovery failed").with_source(source)
})
}) })
} }
} }
@@ -452,6 +452,13 @@ impl CatalogService {
&self, &self,
cancellation: &gateway_core::lifecycle::CancellationToken, cancellation: &gateway_core::lifecycle::CancellationToken,
) -> Result<(), gateway_core::task::WorkerTaskError> { ) -> Result<(), gateway_core::task::WorkerTaskError> {
cancellation
.run_until_cancelled(self.refresh_due_accounts())
.await
.unwrap_or(Ok(()))
}
async fn refresh_due_accounts(&self) -> Result<(), gateway_core::task::WorkerTaskError> {
use futures::{StreamExt, stream}; use futures::{StreamExt, stream};
use gateway_core::task::WorkerTaskError; use gateway_core::task::WorkerTaskError;
let catalogs = self let catalogs = self
@@ -484,9 +491,9 @@ impl CatalogService {
let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len(); let offset = self.refresh_cursor.fetch_add(32, Ordering::Relaxed) % due.len();
due.rotate_left(offset); due.rotate_left(offset);
due.truncate(32); due.truncate(32);
let mut updates=stream::iter(due).map(|account|async move { let mut updates = stream::iter(due)
tokio::select! {biased;_=cancellation.cancelled()=>Ok(()),result=self.account_models(account.id(),true)=>result.map(|_|())} .map(|account| async move { self.account_models(account.id(), true).await })
}).buffer_unordered(4); .buffer_unordered(4);
let mut first_error = None; let mut first_error = None;
while let Some(result) = updates.next().await { while let Some(result) = updates.next().await {
if let Err(error) = result if let Err(error) = result
@@ -298,6 +298,13 @@ impl QuotaService {
&self, &self,
cancel: &CancellationToken, cancel: &CancellationToken,
) -> Result<(), WorkerTaskError> { ) -> Result<(), WorkerTaskError> {
cancel
.run_until_cancelled(self.refresh_due_accounts())
.await
.unwrap_or(Ok(()))
}
async fn refresh_due_accounts(&self) -> Result<(), WorkerTaskError> {
let accounts = self let accounts = self
.accounts .accounts
.list_for_provider(&self.kind, false) .list_for_provider(&self.kind, false)
@@ -355,13 +362,7 @@ impl QuotaService {
due.rotate_left(offset); due.rotate_left(offset);
due.truncate(32); due.truncate(32);
let mut results = stream::iter(due) let mut results = stream::iter(due)
.map(|id| async move { .map(|id| async move { self.refresh(&id).await })
tokio::select! {
biased;
_ = cancel.cancelled() => Ok(()),
result = self.refresh(&id) => result,
}
})
.buffer_unordered(4); .buffer_unordered(4);
while let Some(result) = results.next().await { while let Some(result) = results.next().await {
if let Err(e) = result if let Err(e) = result
@@ -103,30 +103,43 @@ struct RefreshTask {
impl ScheduledTask for RefreshTask { impl ScheduledTask for RefreshTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
let (candidates, concurrency) = self.credentials.refresh_candidates().await?; let cancellation = context.cancellation();
if candidates.is_empty() || context.cancellation().is_cancelled() { let Some(batch) = cancellation
.run_until_cancelled(self.credentials.refresh_candidates())
.await
else {
return Ok(());
};
let (candidates, concurrency) = batch?;
if candidates.is_empty() {
return Ok(()); return Ok(());
} }
let mut catalogs = self let Some(catalogs) = cancellation
.catalog .run_until_cancelled(self.catalog.capture_refresh_catalogs(&candidates))
.capture_refresh_catalogs(&candidates)
.await .await
.unwrap_or_else(|_| { else {
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录"); return Ok(());
Default::default() };
}); let mut catalogs = catalogs.unwrap_or_else(|_| {
tracing::warn!("Antigravity 目录读取失败,凭据续期后重新查询目录");
Default::default()
});
let mut updates = stream::iter(candidates) let mut updates = stream::iter(candidates)
.map(|loaded| { .map(|loaded| {
let cancellation = context.cancellation();
let catalog = catalogs.remove(loaded.account.id()); let catalog = catalogs.remove(loaded.account.id());
async move { async move {
if cancellation.is_cancelled() { if cancellation.is_cancelled() {
return Ok(()); return Ok(());
} }
let revision = self.credentials.refresh_due(&loaded).await?; let revision = self.credentials.refresh_due(&loaded).await?;
self.catalog cancellation
.after_credential_refresh(loaded.account.id(), revision, catalog) .run_until_cancelled(self.catalog.after_credential_refresh(
loaded.account.id(),
revision,
catalog,
))
.await .await
.unwrap_or(Ok(()))
} }
}) })
.buffer_unordered(concurrency); .buffer_unordered(concurrency);
@@ -775,6 +775,7 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
for streaming in [false, true] { for streaming in [false, true] {
let fixture = Fixture::new(&upstream.uri()); let fixture = Fixture::new(&upstream.uri());
let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}}); let mut body = json!({"model":"fixture-model","stream":streaming,"messages":[{"role":"user","content":"hello"}],"max_completion_tokens":100,"reasoning_effort":"high","temperature":0.3,"top_p":0.8,"tools":[{"type":"function","function":{"name":"pwd","parameters":{"type":"object"}}}],"tool_choice":"required","response_format":{"type":"json_schema","json_schema":{"name":"result","schema":{"type":"object"}}}});
body["stop"] = json!(["END", " STOP"]);
body["messages"].as_array_mut().unwrap().insert( body["messages"].as_array_mut().unwrap().insert(
0, 0,
json!({"role":"system","content":"Preserve the caller's project rules."}), json!({"role":"system","content":"Preserve the caller's project rules."}),
@@ -877,6 +878,10 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
json!([{"text": if streaming { "Apply the caller's project rules." } else { "Preserve the caller's project rules." }}]) json!([{"text": if streaming { "Apply the caller's project rules." } else { "Preserve the caller's project rules." }}])
); );
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100); assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
assert_eq!(
body["request"]["generationConfig"]["stopSequences"],
json!(["END", " STOP"])
);
assert_eq!( assert_eq!(
body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"], body["request"]["generationConfig"]["thinkingConfig"]["thinkingBudget"],
24576 24576
@@ -1,6 +1,6 @@
//! 额度桶重置后的延迟预热、使用证据复核和持久化领取 //! 额度桶重置后的延迟预热、使用证据复核和持久化领取
use super::snapshot::BucketUseTime; use super::snapshot::BucketTimestamp;
use super::*; use super::*;
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use gateway_core::account::QuotaWarmupStateUpdate; use gateway_core::account::QuotaWarmupStateUpdate;
@@ -10,18 +10,21 @@ const RESET_WARMUP_DELAY_SECONDS: i64 = 5 * 60;
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
struct BucketProgress { struct BucketProgress {
reset_at: Option<i64>, reset_at: Option<BucketTimestamp>,
completed_reset_at: Option<i64>, completed_reset_at: Option<BucketTimestamp>,
last_warmup_at: Option<BucketUseTime>, last_warmup_at: Option<BucketTimestamp>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
credit_reset: Option<CreditReset>, credit_reset: Option<CreditReset>,
retry_at: Option<i64>, retry_at: Option<i64>,
// 本登记周期内已观察到用量或触顶;用于被动识别上游提前重置后的归零快照
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
observed_used: bool,
} }
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
struct CreditReset { struct CreditReset {
started_at: DateTime<Utc>, started_at: DateTime<Utc>,
previous_window_end: Option<i64>, previous_window_end: Option<BucketTimestamp>,
} }
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
@@ -55,8 +58,24 @@ impl WarmupProgress {
fn reconcile(&mut self, account: &ProviderAccount, snapshot: &CodexAccountQuotaSnapshot) { fn reconcile(&mut self, account: &ProviderAccount, snapshot: &CodexAccountQuotaSnapshot) {
for window in enabled_windows(account, snapshot) { for window in enabled_windows(account, snapshot) {
let progress = self.buckets.entry(window.key().to_owned()).or_default(); let progress = self.buckets.entry(window.key().to_owned()).or_default();
let observed_reset = window.reset_at().map(|at| at.timestamp()); let observed_reset = window.reset_at().map(BucketTimestamp);
if let Some(reset) = progress.reset_at { if let Some(reset) = progress.reset_at {
// 上游系统级统一重置或在代理外提前重置不会经过 consume_reset_credit:
// 本周期已观察到用量,而新快照在周期到期前显示归零且未触顶,
// 说明周期已提前重开,把边界被动改锚到观测时刻,沿用既有延迟预热
if progress.credit_reset.is_none()
&& progress.observed_used
&& window.used_percent() == Some(0.0)
&& !window.limit_reached()
{
let observed_at = DateTime::<Utc>::from(snapshot.observed_at());
if observed_at < reset.0 {
progress.reset_at = Some(BucketTimestamp(observed_at));
progress.retry_at = None;
progress.observed_used = false;
continue;
}
}
let last_use = snapshot let last_use = snapshot
.last_used_at .last_used_at
.get(window.source()) .get(window.source())
@@ -67,7 +86,7 @@ impl WarmupProgress {
let observed_at = DateTime::<Utc>::from(snapshot.observed_at()); let observed_at = DateTime::<Utc>::from(snapshot.observed_at());
let used_after_reset = last_use.is_some_and(|used| match &progress.credit_reset { let used_after_reset = last_use.is_some_and(|used| match &progress.credit_reset {
Some(credit) => used.0 >= credit.started_at, Some(credit) => used.0 >= credit.started_at,
None => used.0.timestamp() >= reset, None => used >= reset,
}); });
let previous_end = progress let previous_end = progress
.credit_reset .credit_reset
@@ -76,10 +95,14 @@ impl WarmupProgress {
.unwrap_or(reset); .unwrap_or(reset);
let newly_used = used_after_reset let newly_used = used_after_reset
|| (observed_reset.is_some_and(|next| next > previous_end) || (observed_reset.is_some_and(|next| next > previous_end)
&& observed_at.timestamp() >= reset && observed_at >= reset.0
&& window.used_percent().is_some_and(|used| used > 0.0)); && window.used_percent().is_some_and(|used| used > 0.0));
if newly_used { if newly_used {
progress.complete(reset); progress.complete(reset);
} else {
progress.observed_used = progress.observed_used
|| window.limit_reached()
|| window.used_percent().is_some_and(|used| used > 0.0);
} }
} }
// 空闲桶的 resetAt 可能随查询滚动;已登记的本轮边界不能被新查询推迟 // 空闲桶的 resetAt 可能随查询滚动;已登记的本轮边界不能被新查询推迟
@@ -91,6 +114,8 @@ impl WarmupProgress {
{ {
progress.reset_at = Some(reset); progress.reset_at = Some(reset);
progress.retry_at = None; progress.retry_at = None;
progress.observed_used =
window.limit_reached() || window.used_percent().is_some_and(|used| used > 0.0);
} }
} }
} }
@@ -100,25 +125,30 @@ impl WarmupProgress {
account: &ProviderAccount, account: &ProviderAccount,
snapshot: &CodexAccountQuotaSnapshot, snapshot: &CodexAccountQuotaSnapshot,
started_at: DateTime<Utc>, started_at: DateTime<Utc>,
confirmed_at: i64, confirmed_at: DateTime<Utc>,
) -> bool { ) -> bool {
let mut registered = false; let mut registered = false;
for window in for window in
enabled_windows(account, snapshot).filter(|w| w.kind() == CodexQuotaWindowKind::Weekly) enabled_windows(account, snapshot).filter(|w| w.kind() == CodexQuotaWindowKind::Weekly)
{ {
let bucket = self.buckets.entry(window.key().to_owned()).or_default(); let bucket = self.buckets.entry(window.key().to_owned()).or_default();
bucket.reset_at = Some(confirmed_at); bucket.reset_at = Some(BucketTimestamp(confirmed_at));
bucket.retry_at = None; bucket.retry_at = None;
bucket.observed_used = false;
bucket.credit_reset = Some(CreditReset { bucket.credit_reset = Some(CreditReset {
started_at, started_at,
previous_window_end: window.reset_at().map(|at| at.timestamp()), previous_window_end: window.reset_at().map(BucketTimestamp),
}); });
registered = true; registered = true;
} }
registered registered
} }
fn due(&self, account: &ProviderAccount, now: DateTime<Utc>) -> Vec<(String, String, i64)> { fn due(
&self,
account: &ProviderAccount,
now: DateTime<Utc>,
) -> Vec<(String, String, BucketTimestamp)> {
account account
.quota_settings() .quota_settings()
.iter() .iter()
@@ -126,7 +156,8 @@ impl WarmupProgress {
let warmup = settings.warmup.as_ref()?; let warmup = settings.warmup.as_ref()?;
let progress = self.buckets.get(key)?; let progress = self.buckets.get(key)?;
let reset = progress.reset_at?; let reset = progress.reset_at?;
(now.timestamp() >= reset.saturating_add(RESET_WARMUP_DELAY_SECONDS) (now.signed_duration_since(reset.0)
>= chrono::Duration::seconds(RESET_WARMUP_DELAY_SECONDS)
&& progress && progress
.retry_at .retry_at
.is_none_or(|retry| now.timestamp() >= retry) .is_none_or(|retry| now.timestamp() >= retry)
@@ -138,11 +169,12 @@ impl WarmupProgress {
} }
impl BucketProgress { impl BucketProgress {
fn complete(&mut self, reset: i64) { fn complete(&mut self, reset: BucketTimestamp) {
self.completed_reset_at = Some(self.completed_reset_at.map_or(reset, |old| old.max(reset))); self.completed_reset_at = Some(self.completed_reset_at.map_or(reset, |old| old.max(reset)));
self.reset_at = None; self.reset_at = None;
self.credit_reset = None; self.credit_reset = None;
self.retry_at = None; self.retry_at = None;
self.observed_used = false;
} }
} }
@@ -196,7 +228,7 @@ impl CodexCredentialQuotaService {
return Ok(()); return Ok(());
} }
let request_id = request_id.to_string(); let request_id = request_id.to_string();
let confirmed_at = Utc::now().timestamp(); let confirmed_at = Utc::now();
for _ in 0..QUOTA_MERGE_ATTEMPTS { for _ in 0..QUOTA_MERGE_ATTEMPTS {
let Some(account) = self.store.get_account(original.id()).await? else { let Some(account) = self.store.get_account(original.id()).await? else {
return Ok(()); return Ok(());
@@ -386,7 +418,7 @@ impl CodexCredentialQuotaService {
.buckets .buckets
.entry(window.key().to_owned()) .entry(window.key().to_owned())
.or_default() .or_default()
.last_warmup_at = Some(BucketUseTime(now)); .last_warmup_at = Some(BucketTimestamp(now));
} }
progress.reconcile(account, &snapshot); progress.reconcile(account, &snapshot);
if self if self
@@ -1,6 +1,7 @@
//! 额度权威读取、刷新、错误反馈与服务组装 //! 额度权威读取、刷新、错误反馈与服务组装
use super::*; use super::*;
use gateway_core::lifecycle::CancellationToken;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum QuotaRefreshAuthority { enum QuotaRefreshAuthority {
@@ -145,16 +146,36 @@ impl CodexCredentialQuotaService {
&self, &self,
now: SystemTime, now: SystemTime,
) -> Result<CodexQuotaSyncSummary, CodexCredentialQuotaError> { ) -> Result<CodexQuotaSyncSummary, CodexCredentialQuotaError> {
let mut accounts = self.repository.list_for_provider(true).await?; self.synchronize_until(now, &CancellationToken::new()).await
}
pub async fn synchronize_until(
&self,
now: SystemTime,
cancellation: &CancellationToken,
) -> Result<CodexQuotaSyncSummary, CodexCredentialQuotaError> {
let mut summary = CodexQuotaSyncSummary::default();
let Some(accounts) = cancellation
.run_until_cancelled(self.repository.list_for_provider(true))
.await
else {
return Ok(summary);
};
let mut accounts = accounts?;
accounts.retain(|account| { accounts.retain(|account| {
account.authentication_kind() == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH account.authentication_kind() == crate::credential::CODEX_AUTHENTICATION_KIND_OAUTH
}); });
let mut summary = CodexQuotaSyncSummary::default();
let account_ids = accounts let account_ids = accounts
.iter() .iter()
.map(|account| account.id().clone()) .map(|account| account.id().clone())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let observed = self.store.get_quotas(&account_ids).await?; let Some(observed) = cancellation
.run_until_cancelled(self.store.get_quotas(&account_ids))
.await
else {
return Ok(summary);
};
let observed = observed?;
let observed_snapshots = observed let observed_snapshots = observed
.iter() .iter()
.filter_map(|obs| { .filter_map(|obs| {
@@ -190,20 +211,30 @@ impl CodexCredentialQuotaService {
if accounts.is_empty() { if accounts.is_empty() {
return Ok(summary); return Ok(summary);
} }
let client = match self.global_profile_client().await { let client = match cancellation
Ok(client) => client, .run_until_cancelled(self.global_profile_client())
Err(error) => { .await
{
Some(Ok(client)) => client,
other => {
// 身份配置失败尚未发出请求,也需要释放已预留的首查任务 // 身份配置失败尚未发出请求,也需要释放已预留的首查任务
self.scheduling.defer_failed_initial_refreshes( self.scheduling.defer_failed_initial_refreshes(
&pending_initial, &pending_initial,
self.initial_sync_delays.as_ref(), self.initial_sync_delays.as_ref(),
); );
return Err(error); return other.transpose().map(|_| summary);
} }
}; };
for account in accounts { for account in accounts {
let observed_at = SystemTime::now(); let observed_at = SystemTime::now();
match self.fetch_usage(&client, &account).await { // 查询及其重试可以取消,已取得的额度事实继续完成本账号写入
let Some(usage) = cancellation
.run_until_cancelled(self.fetch_usage(&client, &account))
.await
else {
break;
};
match usage {
Ok(FetchedCodexQuota { account, value }) => { Ok(FetchedCodexQuota { account, value }) => {
// 单账号解析或落库失败只影响该账号;其余账号继续同步 // 单账号解析或落库失败只影响该账号;其余账号继续同步
match self match self
@@ -111,11 +111,11 @@ impl CodexQuotaWindow {
} }
} }
/// 自然窗口按整秒划界,用卡操作还需区分同一秒内先后的使用 /// 额度桶边界与使用时间保留亚秒精度,读取时兼容已有整秒记录
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub(super) struct BucketUseTime(pub(super) DateTime<Utc>); pub(super) struct BucketTimestamp(pub(super) DateTime<Utc>);
impl<'de> Deserialize<'de> for BucketUseTime { impl<'de> Deserialize<'de> for BucketTimestamp {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)] #[derive(Deserialize)]
#[serde(untagged)] #[serde(untagged)]
@@ -144,7 +144,7 @@ pub struct CodexAccountQuotaSnapshot {
quota: QuotaState, quota: QuotaState,
windows: Vec<CodexQuotaWindow>, windows: Vec<CodexQuotaWindow>,
unconfirmed_limits: BTreeMap<String, f64>, unconfirmed_limits: BTreeMap<String, f64>,
pub(super) last_used_at: BTreeMap<String, BucketUseTime>, pub(super) last_used_at: BTreeMap<String, BucketTimestamp>,
pub(super) recovery: Option<QuotaRecovery>, pub(super) recovery: Option<QuotaRecovery>,
} }
@@ -472,7 +472,7 @@ pub(crate) fn parse_account_quota_snapshot(
usage usage
.iter() .iter()
.filter_map(|(source, at)| { .filter_map(|(source, at)| {
Some((source.clone(), BucketUseTime::deserialize(at).ok()?)) Some((source.clone(), BucketTimestamp::deserialize(at).ok()?))
}) })
.collect() .collect()
}) })
@@ -12,6 +12,7 @@ use gateway_core::error::ErrorSource;
use gateway_core::account::{ use gateway_core::account::{
AccountErrorReason, CredentialState, ProviderAccount, ProviderAccountId, ProviderRefreshQuery, AccountErrorReason, CredentialState, ProviderAccount, ProviderAccountId, ProviderRefreshQuery,
}; };
use gateway_core::lifecycle::CancellationToken;
use gateway_core::provider_ports::{ use gateway_core::provider_ports::{
ProviderCredentialStatePort, ProviderLeaseAcquisition, ProviderLeasePort, ProviderLeaseRequest, ProviderCredentialStatePort, ProviderLeaseAcquisition, ProviderLeasePort, ProviderLeaseRequest,
ProviderRefreshCapacityRequest, ProviderRefreshLeaseRequest, ProviderRefreshPolicy, ProviderRefreshCapacityRequest, ProviderRefreshLeaseRequest, ProviderRefreshPolicy,
@@ -220,17 +221,42 @@ impl CodexCredentialRefreshService {
pub async fn refresh_due( pub async fn refresh_due(
&self, &self,
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> { ) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
self.refresh_due_excluding(&BTreeSet::new()).await self.refresh_due_until(&CancellationToken::new()).await
}
pub async fn refresh_due_until(
&self,
cancellation: &CancellationToken,
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
self.refresh_batch(&BTreeSet::new(), cancellation).await
} }
pub async fn refresh_due_excluding( pub async fn refresh_due_excluding(
&self, &self,
excluded: &BTreeSet<ProviderAccountId>, excluded: &BTreeSet<ProviderAccountId>,
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> { ) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
let policy = self.runtime_policy.load_refresh_policy().await?; self.refresh_batch(excluded, &CancellationToken::new())
let (due, mut outcomes) = self.list_due_refresh(excluded, policy).await?; .await
}
async fn refresh_batch(
&self,
excluded: &BTreeSet<ProviderAccountId>,
cancellation: &CancellationToken,
) -> Result<Vec<CodexCredentialRefreshOutcome>, CodexCredentialRefreshError> {
let load_candidates = async {
let policy = self.runtime_policy.load_refresh_policy().await?;
let (due, outcomes) = self.list_due_refresh(excluded, policy).await?;
Ok::<_, CodexCredentialRefreshError>((policy, due, outcomes))
};
let Some(batch) = cancellation.run_until_cancelled(load_candidates).await else {
return Ok(Vec::new());
};
let (policy, due, mut outcomes) = batch?;
outcomes.reserve(due.len()); outcomes.reserve(due.len());
let refreshed = stream::iter(due.into_iter().map(|credential| async move { // 停止领取新账号,已发出的令牌交换继续写回
let candidates = due.into_iter().take_while(|_| !cancellation.is_cancelled());
let refreshed = stream::iter(candidates.map(|credential| async move {
let account_id = credential.account.id().to_string(); let account_id = credential.account.id().to_string();
let snapshot = let snapshot =
gateway_core::account::AccountHistorySnapshot::from_account(&credential.account); gateway_core::account::AccountHistorySnapshot::from_account(&credential.account);
@@ -564,6 +564,7 @@ impl CodexCredentialSelector {
err, err,
CredentialSelectionError::CapacityUnavailable { .. } CredentialSelectionError::CapacityUnavailable { .. }
| CredentialSelectionError::NoEligibleCredential | CredentialSelectionError::NoEligibleCredential
| CredentialSelectionError::WebSocketUnavailable { .. }
| CredentialSelectionError::QuotaExhausted | CredentialSelectionError::QuotaExhausted
) )
}, },
@@ -939,6 +940,7 @@ impl CodexCredentialSelector {
_ => None, _ => None,
}; };
let mut catalog_rejected = 0_usize; let mut catalog_rejected = 0_usize;
let mut websocket_rejected = false;
let mut native_accounts = BTreeSet::new(); let mut native_accounts = BTreeSet::new();
for account in accounts { for account in accounts {
let adapter = if let Some(model) = adapter_model.as_ref() { let adapter = if let Some(model) = adapter_model.as_ref() {
@@ -1043,14 +1045,22 @@ impl CodexCredentialSelector {
(account.revision(), runtime.authentication.api_protocol()), (account.revision(), runtime.authentication.api_protocol()),
); );
} }
if (request.requires_websocket if required_protocol
&& runtime.transport == super::ResponsesTransport::Http) .is_some_and(|protocol| runtime.authentication.api_protocol() != protocol)
|| required_protocol.is_some_and(|protocol| {
runtime.authentication.api_protocol() != protocol
})
{ {
continue; continue;
} }
if request.requires_websocket
&& runtime.transport == super::ResponsesTransport::Http
{
// 仅记录基础状态正常的 HTTP 账号,失效或已耗尽账号不能掩盖真实额度失败
websocket_rejected |= (diagnostic
|| account.status_projection(SystemTime::now(), None).status
== AccountStatus::Normal)
&& !request.attempt.excluded_accounts().contains(account.id())
&& !request.attempt.excludes_proxy(account.outbound_proxy());
continue;
}
} }
eligible.push(account); eligible.push(account);
} }
@@ -1475,7 +1485,7 @@ impl CodexCredentialSelector {
Err(CredentialSelectionError::CapacityUnavailable { Err(CredentialSelectionError::CapacityUnavailable {
retry_after: shortest_retry, retry_after: shortest_retry,
}) })
} else if quota_exhausted { } else if quota_exhausted && !websocket_rejected {
Err(CredentialSelectionError::QuotaExhausted) Err(CredentialSelectionError::QuotaExhausted)
} else if cyber_policy_scope } else if cyber_policy_scope
.as_ref() .as_ref()
@@ -1496,6 +1506,8 @@ impl CodexCredentialSelector {
{ {
// 仅明确的会话策略排除使用此分类,空池、传输和容量失败保持原分类 // 仅明确的会话策略排除使用此分类,空池、传输和容量失败保持原分类
Err(CredentialSelectionError::SessionPolicyRestricted) Err(CredentialSelectionError::SessionPolicyRestricted)
} else if websocket_rejected {
Err(CredentialSelectionError::WebSocketUnavailable { quota_exhausted })
} else { } else {
Err(CredentialSelectionError::NoEligibleCredential) Err(CredentialSelectionError::NoEligibleCredential)
}; };
@@ -2465,6 +2477,10 @@ pub enum CredentialSelectionError {
IneligibleSessionAccountTimeout(&'static str), IneligibleSessionAccountTimeout(&'static str),
#[error("no eligible Codex account")] #[error("no eligible Codex account")]
NoEligibleCredential, NoEligibleCredential,
#[error(
"no available WebSocket account; compatible account quota exhausted: {quota_exhausted}"
)]
WebSocketUnavailable { quota_exhausted: bool },
#[error("upstream safety policy temporarily excludes accounts for this session")] #[error("upstream safety policy temporarily excludes accounts for this session")]
SessionPolicyRestricted, SessionPolicyRestricted,
#[error("all eligible Codex accounts have exhausted their quota")] #[error("all eligible Codex accounts have exhausted their quota")]
@@ -3,6 +3,7 @@
use super::*; use super::*;
use crate::transport::protocol::responses::is_replaceable_response_prelude; use crate::transport::protocol::responses::is_replaceable_response_prelude;
use gateway_core::error::{ProxyConnectionHint, TransientRetryPolicy}; use gateway_core::error::{ProxyConnectionHint, TransientRetryPolicy};
use gateway_protocol::http::preferred_response_request_id;
/// OpenAI 失败对 Smart 账号分数的结构化 reason 闭集 /// OpenAI 失败对 Smart 账号分数的结构化 reason 闭集
/// ///
@@ -731,10 +732,16 @@ pub(super) fn continuation_recovery_error(
.map(|response| response.headers().to_vec()) .map(|response| response.headers().to_vec())
.unwrap_or_default(); .unwrap_or_default();
// 流内拒绝没有原始 HTTP 失败响应,仍需把该次失败的关联 ID 交给 HTTP 客户端 // 流内拒绝没有原始 HTTP 失败响应,仍需把该次失败的关联 ID 交给 HTTP 客户端
if !headers.iter().any(|header| { if preferred_response_request_id(|name| {
header.name().eq_ignore_ascii_case("x-request-id") let header = headers
|| header.name().eq_ignore_ascii_case("x-oai-request-id") .iter()
}) && let Some(request_id) = error.upstream_request_id() .find(|header| header.name().eq_ignore_ascii_case(name))?;
let value = reqwest::header::HeaderValue::from_bytes(header.value()).ok()?;
value.to_str().ok()?;
std::str::from_utf8(header.value()).ok()
})
.is_none()
&& let Some(request_id) = error.upstream_request_id()
{ {
headers.push(ProviderResponseHeader::new( headers.push(ProviderResponseHeader::new(
"x-request-id", "x-request-id",
@@ -863,7 +863,7 @@ impl Provider for CodexProvider {
&& codex_guardian_role(payload.body(), payload.context()) && codex_guardian_role(payload.body(), payload.context())
== Some(CodexGuardianRole::Housekeeper)) == Some(CodexGuardianRole::Housekeeper))
&& let Some(tier) = fast_policy_tier( && let Some(tier) = fast_policy_tier(
context.fast_mode(), context.fast_mode_for_account(lease.account_id(), upstream_model.as_str()),
payload.body().get("service_tier").and_then(Value::as_str), payload.body().get("service_tier").and_then(Value::as_str),
|tier| { |tier| {
self.catalog self.catalog
@@ -980,6 +980,7 @@ impl CodexProvider {
let processed = self.prepare_generate_request(&generate, upstream, &context); let processed = self.prepare_generate_request(&generate, upstream, &context);
let native_scope = processed.checked_native_continuation_scope(&context, direct_model)?; let native_scope = processed.checked_native_continuation_scope(&context, direct_model)?;
let mut upstream_request = processed.upstream; let mut upstream_request = processed.upstream;
upstream_request.client_api_key_id = Some(context.client_api_key_ref().as_str().to_owned());
let session_transport_key = let session_transport_key =
derive_codex_transport_key(&upstream_request, context.client_api_key_ref()); derive_codex_transport_key(&upstream_request, context.client_api_key_ref());
let previous_session = processed.previous_session; let previous_session = processed.previous_session;
@@ -886,6 +886,27 @@ fn selection_failure(error: &CredentialSelectionError) -> ProviderError {
ProviderErrorKind::NoEligibleAccount, ProviderErrorKind::NoEligibleAccount,
UpstreamSendState::NotSent, UpstreamSendState::NotSent,
), ),
CredentialSelectionError::WebSocketUnavailable { quota_exhausted } => provider_error(
ProviderErrorKind::NoEligibleAccount,
UpstreamSendState::NotSent,
)
.with_diagnostic(
ProviderDiagnostic::new(if *quota_exhausted {
"WebSocket 账号额度耗尽,HTTP/SSE 账号不符合本次传输要求"
} else {
"请求需要上游 WebSocket,HTTP/SSE 账号不符合本次传输要求"
})
.with_classification("account_selection", "websocket_account_unavailable"),
)
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
if *quota_exhausted {
"WebSocket-compatible accounts have exhausted their quota; HTTP/SSE-only accounts cannot serve this request. Enable WebSocket on an available account or use HTTP/SSE in the client."
} else {
"This request requires an upstream WebSocket, but no compatible account is available. Enable WebSocket on an available account or use HTTP/SSE in the client."
},
Some("websocket_account_unavailable".to_owned()),
None,
)),
CredentialSelectionError::QuotaExhausted => provider_error( CredentialSelectionError::QuotaExhausted => provider_error(
ProviderErrorKind::AccountPoolQuotaExhausted, ProviderErrorKind::AccountPoolQuotaExhausted,
UpstreamSendState::NotSent, UpstreamSendState::NotSent,
@@ -142,12 +142,9 @@ pub(super) struct OpenAiOAuthRefreshTask {
impl ScheduledTask for OpenAiOAuthRefreshTask { impl ScheduledTask for OpenAiOAuthRefreshTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
if context.cancellation().is_cancelled() {
return Ok(());
}
let outcomes = self let outcomes = self
.service .service
.refresh_due() .refresh_due_until(context.cancellation())
.await .await
.map_err(|error| WorkerTaskError::safe("令牌刷新失败").with_source(error))?; .map_err(|error| WorkerTaskError::safe("令牌刷新失败").with_source(error))?;
let mut changed = Vec::new(); let mut changed = Vec::new();
@@ -272,10 +269,11 @@ impl ScheduledTask for OpenAiDesktopReleaseTask {
impl ScheduledTask for OpenAiQuotaTask { impl ScheduledTask for OpenAiQuotaTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
if context.cancellation().is_cancelled() { match self
return Ok(()); .quota
} .synchronize_until(std::time::SystemTime::now(), context.cancellation())
match self.quota.synchronize().await { .await
{
Ok(summary) if summary.has_operational_failures() => { Ok(summary) if summary.has_operational_failures() => {
tracing::warn!( tracing::warn!(
updated = summary.updated, updated = summary.updated,
@@ -300,10 +298,14 @@ impl ScheduledTask for OpenAiQuotaTask {
impl ScheduledTask for OpenAiCatalogTask { impl ScheduledTask for OpenAiCatalogTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
if context.cancellation().is_cancelled() { let Some(catalogs) = context
.cancellation()
.run_until_cancelled(self.catalog.refresh_catalogs())
.await
else {
return Ok(()); return Ok(());
} };
let result = match self.catalog.refresh_catalogs().await { let result = match catalogs {
Ok(_) | Err(CodexCredentialCatalogError::NoEligibleCredential) => Ok(()), Ok(_) | Err(CodexCredentialCatalogError::NoEligibleCredential) => Ok(()),
Err(error) => Err(WorkerTaskError::safe("模型目录同步失败").with_source(error)), Err(error) => Err(WorkerTaskError::safe("模型目录同步失败").with_source(error)),
}; };
@@ -401,10 +403,18 @@ impl OpenAiWarmupTask {
impl ScheduledTask for OpenAiWarmupTask { impl ScheduledTask for OpenAiWarmupTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
let cron_result = self.run_cron_cycle(&context).await; let cancellation = context.cancellation();
let bucket_result = tokio::select! { let Some(cron_result) = cancellation
() = context.cancellation().cancelled() => return Ok(()), .run_until_cancelled(self.run_cron_cycle())
result = self.quota.execute_bucket_warmup_at(chrono::Utc::now()) => result, .await
else {
return Ok(());
};
let Some(bucket_result) = cancellation
.run_until_cancelled(self.quota.execute_bucket_warmup_at(chrono::Utc::now()))
.await
else {
return Ok(());
}; };
if let Err(error) = bucket_result { if let Err(error) = bucket_result {
tracing::warn!(error = %error, "OpenAI quota bucket warmup cycle failed"); tracing::warn!(error = %error, "OpenAI quota bucket warmup cycle failed");
@@ -415,10 +425,7 @@ impl ScheduledTask for OpenAiWarmupTask {
} }
impl OpenAiWarmupTask { impl OpenAiWarmupTask {
async fn run_cron_cycle(&self, context: &WorkerCycleContext) -> Result<(), WorkerTaskError> { async fn run_cron_cycle(&self) -> Result<(), WorkerTaskError> {
if context.cancellation().is_cancelled() {
return Ok(());
}
let policy = self let policy = self
.quota .quota
.runtime_policy() .runtime_policy()
@@ -460,11 +467,7 @@ impl OpenAiWarmupTask {
return Ok(()); return Ok(());
} }
tracing::info!(%slot, model, "OpenAI account warmup cycle started"); tracing::info!(%slot, model, "OpenAI account warmup cycle started");
let outcome = tokio::select! { match self.quota.execute_warmup(model).await {
() = context.cancellation().cancelled() => return Ok(()),
outcome = self.quota.execute_warmup(model) => outcome,
};
match outcome {
Ok(summary) => { Ok(summary) => {
tracing::info!( tracing::info!(
warmed_up = summary.warmed_up, warmed_up = summary.warmed_up,
@@ -349,23 +349,6 @@ impl CodexBackendClient {
.iter() .iter()
.map(|(name, value)| (name.as_str(), value.as_bytes())), .map(|(name, value)| (name.as_str(), value.as_bytes())),
); );
// 审计未启用时跳过 artifact 构造:payload 快照会深拷贝整个请求 body,
// 且位于首字节前的关键路径上
if websocket_audit_dir().is_some() {
let artifact = websocket_audit_artifact_from_attempt(
&websocket_request,
opening.connection.opening_audit_snapshot(),
// 插件准备后只由受控 wire capture 记录实际正文,不把原生 JSON 冒充最终帧
self.outbound_middleware
.is_none()
.then(|| websocket_payload_audit_snapshot(&websocket_request)),
);
if let Err(error) =
write_websocket_audit_artifact_from_env(&artifact, self.timezone).await
{
tracing::warn!(error = %error, "Failed to write Codex WebSocket audit artifact");
}
}
let mut connection_profile = websocket_connection_profile( let mut connection_profile = websocket_connection_profile(
&headers, &headers,
&self.middleware_headers, &self.middleware_headers,
@@ -436,7 +419,7 @@ impl CodexBackendClient {
self.egress_key self.egress_key
) )
}); });
let prepared = prepare_response_create_request_with_pool( let mut prepared = prepare_response_create_request_with_pool(
&opening, &opening,
pool, pool,
&self.websocket_origin_breaker, &self.websocket_origin_breaker,
@@ -451,6 +434,32 @@ impl CodexBackendClient {
), ),
) )
.await; .await;
let can_reduce_history = self.protocol == OpenAiUpstreamProtocol::Codex
&& plugin_payload.is_none()
&& requirement == TransportRequirement::NewChain
&& request.stream()
&& !request.websocket_frame
&& request.downstream_websocket_connection_id.is_none();
if let Ok(WebSocketFastPath::Ready(socket)) = &mut prepared {
socket.prepare_http_history(can_reduce_history.then_some(&mut websocket_request));
}
// 审计未启用时跳过 artifact 构造:payload 快照会深拷贝整个请求 body,
// 且位于首字节前的关键路径上
if websocket_audit_dir().is_some() {
let artifact = websocket_audit_artifact_from_attempt(
request,
opening.connection.opening_audit_snapshot(),
// 插件准备后只由受控 wire capture 记录实际正文,不把原生 JSON 冒充最终帧
self.outbound_middleware
.is_none()
.then(|| websocket_payload_audit_snapshot(&websocket_request)),
);
if let Err(error) =
write_websocket_audit_artifact_from_env(&artifact, self.timezone).await
{
tracing::warn!(error = %error, "Failed to write Codex WebSocket audit artifact");
}
}
let prepared = match prepared { let prepared = match prepared {
Ok(WebSocketFastPath::Ready(prepared)) => prepared, Ok(WebSocketFastPath::Ready(prepared)) => prepared,
Ok(WebSocketFastPath::Missed) => { Ok(WebSocketFastPath::Missed) => {
@@ -5,25 +5,10 @@ pub(crate) mod evidence;
use super::client::CodexClientVisibleUpstreamResponse; use super::client::CodexClientVisibleUpstreamResponse;
use super::protocol::responses::{ResponsesSseFailure, UsageLimitWindow, upstream_error_object}; use super::protocol::responses::{ResponsesSseFailure, UsageLimitWindow, upstream_error_object};
use base64::{Engine as _, engine::general_purpose::STANDARD}; use base64::{Engine as _, engine::general_purpose::STANDARD};
use gateway_protocol::http::{RESPONSE_REQUEST_ID_HEADERS, preferred_response_request_id};
use reqwest::{StatusCode, header::HeaderMap}; use reqwest::{StatusCode, header::HeaderMap};
use serde_json::Value; use serde_json::Value;
const UPSTREAM_REQUEST_ID_HEADERS: &[&str] = &[
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"openai-request-id",
"request-id",
];
const UPSTREAM_TRACE_HEADERS: &[&str] = &[
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"openai-request-id",
"request-id",
"cf-ray",
];
const IDENTITY_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error"; const IDENTITY_AUTHORIZATION_ERROR_HEADER: &str = "x-openai-authorization-error";
const IDENTITY_ERROR_JSON_HEADER: &str = "x-error-json"; const IDENTITY_ERROR_JSON_HEADER: &str = "x-error-json";
/// 上游拒绝相对业务 payload 的发送阶段 /// 上游拒绝相对业务 payload 的发送阶段
@@ -368,7 +353,7 @@ impl CodexUpstreamDiagnostics {
let Ok(name) = reqwest::header::HeaderName::from_bytes(name.as_bytes()) else { let Ok(name) = reqwest::header::HeaderName::from_bytes(name.as_bytes()) else {
continue; continue;
}; };
if !UPSTREAM_REQUEST_ID_HEADERS.contains(&name.as_str()) { if !RESPONSE_REQUEST_ID_HEADERS.contains(&name.as_str()) {
continue; continue;
} }
// 与官方 wrapped error 一致,只接受合法 HTTP 标量头;任意对象和数组不作 ID // 与官方 wrapped error 一致,只接受合法 HTTP 标量头;任意对象和数组不作 ID
@@ -381,14 +366,18 @@ impl CodexUpstreamDiagnostics {
mapped.insert(name, value); mapped.insert(name, value);
} }
} }
first_header(&mapped, UPSTREAM_REQUEST_ID_HEADERS) preferred_response_request_id(|name| mapped.get(name)?.to_str().ok())
.map(str::trim)
.map(str::to_owned)
} }
pub fn from_headers(status_code: Option<u16>, headers: &HeaderMap) -> Self { pub fn from_headers(status_code: Option<u16>, headers: &HeaderMap) -> Self {
Self { Self {
headers_observed_at: Some(std::time::SystemTime::now()), headers_observed_at: Some(std::time::SystemTime::now()),
status_code, status_code,
request_id: first_header(headers, UPSTREAM_REQUEST_ID_HEADERS), request_id: preferred_response_request_id(|name| headers.get(name)?.to_str().ok())
.map(str::trim)
.map(str::to_owned),
identity_authorization_error: header_value( identity_authorization_error: header_value(
headers, headers,
IDENTITY_AUTHORIZATION_ERROR_HEADER, IDENTITY_AUTHORIZATION_ERROR_HEADER,
@@ -416,13 +405,10 @@ impl CodexUpstreamDiagnostics {
} }
} }
fn first_header(headers: &HeaderMap, names: &[&str]) -> Option<String> {
names.iter().find_map(|name| header_value(headers, name))
}
fn trace_headers(headers: &HeaderMap) -> Vec<(String, String)> { fn trace_headers(headers: &HeaderMap) -> Vec<(String, String)> {
UPSTREAM_TRACE_HEADERS RESPONSE_REQUEST_ID_HEADERS
.iter() .iter()
.chain([&"cf-ray"])
.filter_map(|name| header_value(headers, name).map(|value| ((*name).to_string(), value))) .filter_map(|name| header_value(headers, name).map(|value| ((*name).to_string(), value)))
.collect() .collect()
} }
@@ -95,7 +95,7 @@ pub struct CodexResponsesRequest {
pub client_ip: Option<String>, pub client_ip: Option<String>,
/// 客户端 User-Agent,仅用于管理端使用记录展示 /// 客户端 User-Agent,仅用于管理端使用记录展示
pub client_user_agent: Option<String>, pub client_user_agent: Option<String>,
/// 已鉴权客户端 API key 的稳定 ID,仅用于事实归因 /// 已鉴权 Client Key 的稳定 ID,用于约束连接内的历史续接
pub client_api_key_id: Option<String>, pub client_api_key_id: Option<String>,
/// 是否偏好 WebSocket 传输 /// 是否偏好 WebSocket 传输
pub use_websocket: bool, pub use_websocket: bool,
@@ -0,0 +1,152 @@
//! 物理 WS 的响应归属与 HTTP 全量输入的增量续接
use std::{
collections::BTreeMap,
hash::{Hash, Hasher},
};
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::transport::protocol::{
responses::CodexResponsesRequest, websocket::websocket_response_completed_id,
};
#[derive(Default)]
pub(super) struct WebSocketContinuationState {
latest_response_id: Option<String>,
history: Option<HttpHistory>,
}
impl WebSocketContinuationState {
pub(super) fn latest_response_id(&self) -> Option<&str> {
self.latest_response_id.as_deref()
}
pub(super) fn begin_http_request(self, request: &mut CodexResponsesRequest) -> Self {
let body = request.body();
let Some(owner) = request.client_api_key_id.as_deref() else {
return Self::default();
};
if request.store() || !request.generate() || body.contains_key("previous_response_id") {
return Self::default();
}
// 每轮元数据随当前帧照常发送,模型、工具及未知正文属性均参与前缀校验
let properties: BTreeMap<_, _> = body
.iter()
.filter(|(key, _)| !matches!(key.as_str(), "input" | "client_metadata"))
.collect();
let mut input = Prefix {
count: 0,
digest: fingerprint((owner, properties)),
};
let Some(Value::Array(items)) = request.body_mut().get_mut("input") else {
return Self::default();
};
let cut = self
.history
.as_ref()
.map_or(0, |last| last.total.count.min(items.len()));
input.extend(&items[..cut]);
let reuse = self.history.is_some_and(|last| last.total == input) && cut < items.len();
input.extend(&items[cut..]);
if reuse && let Some(id) = self.latest_response_id.filter(|id| !id.is_empty()) {
items.drain(..cut);
request.set_previous_response_id(Some(id));
}
Self {
latest_response_id: None,
history: Some(HttpHistory {
input,
total: input,
added: 0,
}),
}
}
pub(super) fn observe(&mut self, event: Option<&str>, value: &Value) {
if let Some(history) = &mut self.history {
match event {
Some("response.output_item.added") => history.added += 1,
Some("response.output_item.done") => {
let index = history.total.count - history.input.count;
if let Some(item) = value.get("item").filter(|i| i.is_object())
&& value["output_index"].as_u64() == Some(index as u64)
{
history.total.push(item);
} else {
self.history = None;
}
}
Some("response.completed") => {
// 完整终态优先;省略输出的终态只采用连续完成的流式项
if let Some(output) =
value.pointer("/response/output").and_then(Value::as_array)
&& !output.is_empty()
{
let observed = history.total.count - history.input.count;
if output.len() < history.added.max(observed) {
self.history = None;
} else {
history.total = history.input;
history.total.extend(output);
}
} else if history.total.count == history.input.count
|| history.total.count - history.input.count < history.added
{
self.history = None;
}
}
Some("response.incomplete") => self.history = None,
_ => {}
}
}
if let Some(id) = websocket_response_completed_id(value) {
self.latest_response_id = Some(id);
}
}
}
struct HttpHistory {
input: Prefix,
total: Prefix,
added: usize,
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct Prefix {
count: usize,
digest: [u8; 32],
}
impl Prefix {
fn extend(&mut self, items: &[Value]) {
for item in items {
self.push(item);
}
}
fn push(&mut self, item: &Value) {
self.digest = fingerprint((self.digest, item));
self.count += 1;
}
}
// Value 的 Hash 忽略对象键顺序、保留数组顺序;摘要只在当前进程的连接租约内比较
fn fingerprint(value: impl Hash) -> [u8; 32] {
struct DigestHasher(Sha256);
impl Hasher for DigestHasher {
fn write(&mut self, bytes: &[u8]) {
self.0.update(bytes);
}
fn finish(&self) -> u64 {
u64::from_be_bytes(self.0.clone().finalize().as_chunks::<8>().0[0])
}
}
let mut hasher = DigestHasher(Sha256::new());
value.hash(&mut hasher);
hasher.0.finalize().into()
}
@@ -14,6 +14,7 @@ use super::{
breaker::{ breaker::{
WebSocketOriginBreaker, WebSocketOriginBreakerDecision, WebSocketOriginBreakerPermit, WebSocketOriginBreaker, WebSocketOriginBreakerDecision, WebSocketOriginBreakerPermit,
}, },
continuation::WebSocketContinuationState,
error::CodexWebSocketExchangeError, error::CodexWebSocketExchangeError,
exchange::{ exchange::{
CodexWebSocketStreamingExchange, WebSocketStreamPoolReturn, stream_websocket_response, CodexWebSocketStreamingExchange, WebSocketStreamPoolReturn, stream_websocket_response,
@@ -25,12 +26,12 @@ use super::{
}, },
pool::{ pool::{
self, CodexWebSocketPool, CodexWebSocketPoolKey, PooledWebSocketConnection, self, CodexWebSocketPool, CodexWebSocketPoolKey, PooledWebSocketConnection,
WebSocketContinuationState, WebSocketPoolAcquire, WebSocketPoolBypassReason, WebSocketPoolAcquire, WebSocketPoolBypassReason, WebSocketPoolConnectLease,
WebSocketPoolConnectLease, WebSocketPoolConnectOutcome, WebSocketPoolDecision, WebSocketPoolConnectOutcome, WebSocketPoolDecision, WebSocketPoolLease,
WebSocketPoolLease,
}, },
pump::{PumpLogContext, PumpedWebSocket, transport_metric_reason}, pump::{PumpLogContext, PumpedWebSocket, transport_metric_reason},
}; };
use crate::transport::protocol::responses::CodexResponsesRequest;
/// WebSocket 快路径的控制流结果;预算未命中不代表连接失败 /// WebSocket 快路径的控制流结果;预算未命中不代表连接失败
pub(crate) enum WebSocketFastPath<T> { pub(crate) enum WebSocketFastPath<T> {
@@ -90,6 +91,16 @@ impl PoolBinding {
} }
impl PreparedWebSocket { impl PreparedWebSocket {
/// 只有获得物理连接的独占租约后,才能使用其上一轮前缀
pub(crate) fn prepare_http_history(&mut self, request: Option<&mut CodexResponsesRequest>) {
let previous = std::mem::take(&mut self.connection.continuation);
if let Some(request) = request
&& matches!(self.binding, PoolBinding::Pooled { .. })
{
self.connection.continuation = previous.begin_http_request(request);
}
}
pub(crate) fn max_message_bytes(&self) -> Option<usize> { pub(crate) fn max_message_bytes(&self) -> Option<usize> {
self.connection.metadata.max_message_bytes self.connection.metadata.max_message_bytes
} }
@@ -5,11 +5,12 @@ use serde_json::Value;
use crate::transport::protocol::websocket::{ use crate::transport::protocol::websocket::{
websocket_event_type, websocket_metadata_headers, websocket_metadata_turn_state, websocket_event_type, websocket_metadata_headers, websocket_metadata_turn_state,
websocket_response_completed_id, websocket_response_is_interrupted, websocket_response_is_interrupted,
}; };
use crate::transport::response_meta; use crate::transport::response_meta;
use super::super::pool::{CodexWebSocketConnectionMetadata, WebSocketContinuationState}; use super::super::continuation::WebSocketContinuationState;
use super::super::pool::CodexWebSocketConnectionMetadata;
use super::CodexWebSocketExchangeError; use super::CodexWebSocketExchangeError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -71,9 +72,7 @@ pub(super) fn reduce_websocket_event(
}); });
let event = websocket_event_type(&value); let event = websocket_event_type(&value);
if let Some(response_id) = websocket_response_completed_id(&value) { continuation.observe(event, &value);
continuation.record_completed(response_id);
}
let terminal = match event { let terminal = match event {
Some("response.completed") => Some(WebSocketTerminalKind::Completed), Some("response.completed") => Some(WebSocketTerminalKind::Completed),
@@ -10,10 +10,8 @@ use tokio::sync::{Mutex, mpsc, oneshot};
use tokio_util::sync::CancellationToken; use tokio_util::sync::CancellationToken;
use super::super::{ use super::super::{
pool::{ continuation::WebSocketContinuationState,
CodexWebSocketConnectionMetadata, PooledWebSocketConnection, WebSocketContinuationState, pool::{CodexWebSocketConnectionMetadata, PooledWebSocketConnection, WebSocketPoolLease},
WebSocketPoolLease,
},
pump::{ pump::{
PumpExitReason, PumpedWebSocket, WebSocketConnectionObservation, transport_metric_reason, PumpExitReason, PumpedWebSocket, WebSocketConnectionObservation, transport_metric_reason,
}, },
@@ -2,6 +2,7 @@
mod audit; mod audit;
mod breaker; mod breaker;
mod continuation;
mod control; mod control;
mod coordinator; mod coordinator;
mod error; mod error;
@@ -36,7 +36,6 @@ pub(crate) use self::{
}, },
state::{ state::{
CodexWebSocketConnectionMetadata, PooledWebSocketConnection, WebSocketConnectionLifetime, CodexWebSocketConnectionMetadata, PooledWebSocketConnection, WebSocketConnectionLifetime,
WebSocketContinuationState,
}, },
}; };
@@ -14,6 +14,7 @@ use uuid::Uuid;
use super::super::super::{ use super::super::super::{
diagnostics::CodexUpstreamDiagnostics, response_meta::CodexResponseMetadata, diagnostics::CodexUpstreamDiagnostics, response_meta::CodexResponseMetadata,
}; };
use super::super::continuation::WebSocketContinuationState;
use super::super::pump::{PumpedWebSocket, WebSocketConnectionObservation}; use super::super::pump::{PumpedWebSocket, WebSocketConnectionObservation};
use super::lease::WebSocketPoolConnectOutcome; use super::lease::WebSocketPoolConnectOutcome;
@@ -255,29 +256,13 @@ impl From<super::CodexWebSocketPoolConfig> for WebSocketConnectionLifetime {
pub(crate) struct PooledWebSocketConnection { pub(crate) struct PooledWebSocketConnection {
pub(crate) websocket: PumpedWebSocket, pub(crate) websocket: PumpedWebSocket,
pub(crate) metadata: CodexWebSocketConnectionMetadata, pub(crate) metadata: CodexWebSocketConnectionMetadata,
pub(crate) continuation: WebSocketContinuationState, pub(in crate::transport::websocket) continuation: WebSocketContinuationState,
pub(crate) created_at: Instant, pub(crate) created_at: Instant,
pub(crate) lifetime: WebSocketConnectionLifetime, pub(crate) lifetime: WebSocketConnectionLifetime,
// 首个已写入请求决定搜索能力,None 表示仅完成握手,后续工具变化不能覆盖此事实 // 首个已写入请求决定搜索能力,None 表示仅完成握手,后续工具变化不能覆盖此事实
pub(crate) initial_search_declared: Option<bool>, pub(crate) initial_search_declared: Option<bool>,
} }
/// 只随具体 WebSocket 生命周期存在的续接状态
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct WebSocketContinuationState {
latest_response_id: Option<String>,
}
impl WebSocketContinuationState {
pub(crate) fn latest_response_id(&self) -> Option<&str> {
self.latest_response_id.as_deref()
}
pub(crate) fn record_completed(&mut self, response_id: String) {
self.latest_response_id = Some(response_id);
}
}
pub(super) enum WebSocketPoolSlot { pub(super) enum WebSocketPoolSlot {
Idle { Idle {
connection: Box<PooledWebSocketConnection>, connection: Box<PooledWebSocketConnection>,
@@ -1,7 +1,7 @@
//! 验证通用额度桶延迟预热的时间边界、使用证据和重启去重 //! 验证通用额度桶延迟预热的时间边界、使用证据和重启去重
use super::*; use super::*;
use gateway_core::account::{OpaqueProviderData, QuotaObservation}; use gateway_core::account::{OpaqueProviderData, QuotaObservation, QuotaWarmupStateUpdate};
async fn setup() -> ( async fn setup() -> (
Arc<MemoryAccountStore>, Arc<MemoryAccountStore>,
@@ -112,7 +112,7 @@ async fn mount_warmup(server: &MockServer, expected: u64) {
} }
#[tokio::test] #[tokio::test]
async fn waits_five_minutes_and_claim_survives_service_restart() { async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart() {
let (store, server, now, reset) = setup().await; let (store, server, now, reset) = setup().await;
let quota = service(&store, &server); let quota = service(&store, &server);
mount_usage(&server, reset + 604800, 0, 1).await; mount_usage(&server, reset + 604800, 0, 1).await;
@@ -127,6 +127,30 @@ async fn waits_five_minutes_and_claim_survives_service_restart() {
0 0
); );
assert!(server.received_requests().await.unwrap().is_empty()); assert!(server.received_requests().await.unwrap().is_empty());
let account = store.account("acct_bucket_warmup").unwrap();
let mut legacy = store
.load_quota_warmup_state(&account)
.await
.unwrap()
.unwrap();
// 升级前的进度以整秒持久化,新读取器仍须沿用该边界与并发领取约束。
legacy.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset);
let observed_at = store
.get_quotas(std::slice::from_ref(account.id()))
.await
.unwrap()[0]
.observed_at;
assert!(
store
.compare_and_swap_quota_warmup_state(QuotaWarmupStateUpdate {
account: &account,
expected_version: legacy.version,
expected_quota_observed_at: Some(observed_at),
data: legacy.data,
})
.await
.unwrap()
);
let (one, two) = tokio::join!( let (one, two) = tokio::join!(
quota.execute_bucket_warmup_at(now), quota.execute_bucket_warmup_at(now),
quota.execute_bucket_warmup_at(now) quota.execute_bucket_warmup_at(now)
@@ -522,3 +546,119 @@ async fn reset_credit_consume_starts_warmup_after_previous_cycle_was_completed()
1 1
); );
} }
#[tokio::test]
async fn early_reset_after_first_usage_snapshot_warms_once_after_restart() {
let (store, server, now, reset) = setup_window(3 * 86400, 90).await;
let quota = service(&store, &server);
quota.execute_bucket_warmup_at(now).await.unwrap();
let account = store.account("acct_bucket_warmup").unwrap();
let detected = Utc::now();
let observed_at = SystemTime::from(detected);
store
.compare_and_swap_quota(QuotaObservation {
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: OpaqueProviderData::new(usage(reset, 0).as_object().unwrap().clone()),
observed_at,
state: QuotaState::allowed(observed_at),
quota_pause: None,
expected_connection: None,
plan_type: None,
})
.await
.unwrap();
let boundary = detected;
assert_eq!(
quota
.execute_bucket_warmup_at(boundary + chrono::Duration::seconds(299))
.await
.unwrap()
.warmed_up,
0
);
assert!(server.received_requests().await.unwrap().is_empty());
mount_usage(&server, reset + 604800, 0, 1).await;
mount_warmup(&server, 1).await;
assert_eq!(
service(&store, &server)
.execute_bucket_warmup_at(boundary + chrono::Duration::minutes(5))
.await
.unwrap()
.warmed_up,
1
);
assert_eq!(
service(&store, &server)
.execute_bucket_warmup_at(boundary + chrono::Duration::minutes(10))
.await
.unwrap()
.warmed_up,
0
);
}
#[tokio::test]
async fn early_reset_distinguishes_usage_within_the_same_second() {
for used_after_reset in [false, true] {
let (store, server, now, reset) = setup_window(3 * 86400, 90).await;
let quota = service(&store, &server);
quota.execute_bucket_warmup_at(now).await.unwrap();
let second = now.timestamp() - 2;
let detected = Utc.timestamp_opt(second, 900_000_000).unwrap();
let before = Utc.timestamp_opt(second, 100_000_000).unwrap();
let account = store.account("acct_bucket_warmup").unwrap();
let mut document = usage(reset, 0);
document["_cpr_bucket_last_used_at"] = json!({"codex": before});
let observe = |document: serde_json::Value, observed: chrono::DateTime<Utc>| {
let account = account.clone();
let store = store.clone();
async move {
let observed_at = SystemTime::from(observed);
store
.compare_and_swap_quota(QuotaObservation {
account_id: account.id().clone(),
expected_revision: account.revision(),
quota: OpaqueProviderData::new(document.as_object().unwrap().clone()),
observed_at,
state: QuotaState::allowed(observed_at),
quota_pause: None,
expected_connection: None,
plan_type: None,
})
.await
.unwrap();
}
};
observe(document.clone(), detected).await;
quota.execute_bucket_warmup_at(detected).await.unwrap();
if used_after_reset {
let after = Utc.timestamp_opt(second, 950_000_000).unwrap();
document["_cpr_bucket_last_used_at"] = json!({"codex": after});
observe(document, after).await;
}
let restarted = service(&store, &server);
let due = detected + chrono::Duration::minutes(5);
assert_eq!(
restarted
.execute_bucket_warmup_at(due - chrono::Duration::milliseconds(1))
.await
.unwrap()
.warmed_up,
0
);
assert!(server.received_requests().await.unwrap().is_empty());
let expected = u64::from(!used_after_reset);
mount_usage(&server, reset + 604800, 0, expected).await;
mount_warmup(&server, expected).await;
assert_eq!(
restarted
.execute_bucket_warmup_at(due)
.await
.unwrap()
.warmed_up,
expected,
"used_after_reset={used_after_reset}"
);
}
}
@@ -71,6 +71,45 @@ fn local_service(
) )
} }
#[tokio::test]
async fn shutdown_interrupts_pending_usage_and_preserves_completed_observations() {
let store = Arc::new(MemoryAccountStore::default());
for id in ["acct_quota_a", "acct_quota_b", "acct_quota_c"] {
create_account(&store, id).await;
}
let server = MockServer::start().await;
let second = Arc::new(tokio::sync::Notify::new());
let received = second.clone();
let calls = std::sync::atomic::AtomicUsize::new(0);
Mock::given(method("GET"))
.and(path("/api/codex/usage"))
.respond_with(move |_: &wiremock::Request| {
let response = ResponseTemplate::new(200).set_body_json(usage_ok());
if calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 1 {
received.notify_one();
return response.set_delay(Duration::from_secs(60));
}
response
})
.mount(&server)
.await;
let service = local_service(&store, &server, zero_delays());
let cancellation = gateway_core::lifecycle::CancellationToken::new();
let cycle = service.synchronize_until(SystemTime::now(), &cancellation);
let stop = async {
second.notified().await;
cancellation.cancel();
};
let (summary, ()) =
tokio::time::timeout(Duration::from_secs(5), async { tokio::join!(cycle, stop) })
.await
.expect("shutdown while upstream is pending");
assert_eq!(summary.unwrap().updated, 1);
assert_eq!(usage_requests(&server).await, 2);
mount_usage(&server, 200).await;
assert_eq!(service.synchronize().await.unwrap().updated, 2);
}
#[tokio::test] #[tokio::test]
async fn disabled_account_without_quota_is_observed_when_initial_delay_expires() { async fn disabled_account_without_quota_is_observed_when_initial_delay_expires() {
let store = Arc::new(MemoryAccountStore::default()); let store = Arc::new(MemoryAccountStore::default());
@@ -247,6 +247,58 @@ async fn seed_refreshable_account(
.await; .await;
} }
#[tokio::test]
async fn shutdown_preserves_inflight_token_rotation_and_skips_queued_accounts() {
struct RotatingRefresher(gateway_core::lifecycle::CancellationToken);
#[async_trait]
impl TokenRefresher for RotatingRefresher {
async fn refresh(&self, _: &str) -> Result<TokenPair, RefreshFailure> {
self.0.cancel();
tokio::task::yield_now().await;
Ok(TokenPair {
access_token: Some("new-access".to_owned()),
refresh_token: Some("new-refresh".to_owned()),
id_token: None,
})
}
}
let store = Arc::new(MemoryAccountStore::default());
let cancellation = gateway_core::lifecycle::CancellationToken::new();
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(RotatingRefresher(cancellation.clone())),
Arc::new(RefreshLeases),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(300)),
Arc::new(crate::RecordingDiagnostics::default()),
);
for id in ["acct_rotation_a", "acct_rotation_b"] {
seed_refreshable_account(&store, id, SystemTime::now(), None).await;
}
let outcomes = service.refresh_due_until(&cancellation).await.unwrap();
let [CodexCredentialRefreshOutcome::Refreshed { account_id, .. }] = outcomes.as_slice() else {
panic!("only the started exchange should finish");
};
let account = store.account(account_id).expect("refreshed account");
let stored = store
.load_credential(account.id(), account.revision())
.await
.expect("stored rotation");
let runtime = CodexCredentialCodec::decode(&stored.credential).expect("runtime credential");
assert_eq!(
runtime
.authentication
.oauth()
.expect("OAuth credential")
.refresh_token
.as_ref()
.expect("rotated refresh token")
.expose_secret(),
"new-refresh"
);
}
#[tokio::test] #[tokio::test]
async fn scheduled_refresh_rotates_tokens_without_enabling_scheduling() { async fn scheduled_refresh_rotates_tokens_without_enabling_scheduling() {
let store = Arc::new(MemoryAccountStore::default()); let store = Arc::new(MemoryAccountStore::default());
@@ -61,7 +61,7 @@ fn chat_operation(stream: bool) -> Operation {
unreachable!() unreachable!()
}; };
let mut body = json!({"model":"gpt-5.4", "stream":stream, let mut body = json!({"model":"gpt-5.4", "stream":stream,
"reasoning_effort":"xhigh", "reasoning_effort":"xhigh", "stop":"END",
"messages":[{"role":"user","content":"hello"}]}); "messages":[{"role":"user","content":"hello"}]});
if stream { if stream {
body["stream_options"] = json!({"include_usage":true}); body["stream_options"] = json!({"include_usage":true});
@@ -293,13 +293,15 @@ async fn chat_reaches_each_selected_protocol_with_target_header_boundaries() {
} }
assert!(terminal_seen); assert!(terminal_seen);
let requests = server.received_requests().await.unwrap(); let requests = server.received_requests().await.unwrap();
let headers = &requests let request = requests
.iter() .iter()
.find(|request| request.method == "POST") .find(|request| request.method == "POST")
.unwrap() .unwrap();
.headers; let headers = &request.headers;
let body: Value = serde_json::from_slice(&request.body).unwrap();
assert_eq!(headers.get("x-business-extension").unwrap(), "keep"); assert_eq!(headers.get("x-business-extension").unwrap(), "keep");
if target == ApiKeyProtocol::Messages { if target == ApiKeyProtocol::Messages {
assert_eq!(body["stop_sequences"], json!(["END"]));
for name in [ for name in [
"session-id", "session-id",
"thread-id", "thread-id",
@@ -309,7 +311,7 @@ async fn chat_reaches_each_selected_protocol_with_target_header_boundaries() {
assert!(!headers.contains_key(name)); assert!(!headers.contains_key(name));
} }
} else { } else {
let body: Value = serde_json::from_slice(&requests[0].body).unwrap(); assert!(body.get("stop_sequences").is_none() && body.get("stop").is_none());
assert_eq!(body["reasoning"]["effort"], "xhigh"); assert_eq!(body["reasoning"]["effort"], "xhigh");
assert!(body.get("max_output_tokens").is_none()); assert!(body.get("max_output_tokens").is_none());
for name in [ for name in [
@@ -154,7 +154,7 @@ async fn account_client_preparation_keeps_ca_read_cause_without_exposing_path()
assert!(diagnostic.as_str().contains("OS cause:")); assert!(diagnostic.as_str().contains("OS cause:"));
assert!(!diagnostic.as_str().contains("PRIVATE_")); assert!(!diagnostic.as_str().contains("PRIVATE_"));
let gateway = gateway_core::error::GatewayError::from_provider(&snapshot); let gateway = gateway_core::error::GatewayError::from_provider(&snapshot);
assert_eq!(gateway.safe_message(), "Upstream service is unavailable."); assert_eq!(gateway.safe_message(), "Upstream protocol handling failed.");
assert_eq!(gateway.diagnostic(), Some(diagnostic)); assert_eq!(gateway.diagnostic(), Some(diagnostic));
} }
@@ -1660,7 +1660,6 @@ pub(super) fn context_with_middleware(
ModelRequestId::new(request_id).expect("request id"), ModelRequestId::new(request_id).expect("request id"),
ClientApiKeyId::new("key_openai_contract").expect("client key id"), ClientApiKeyId::new("key_openai_contract").expect("client key id"),
) )
.with_fast_mode(fast_mode)
.with_middleware( .with_middleware(
Some(plan), Some(plan),
Arc::from([]), Arc::from([]),
@@ -1671,8 +1670,12 @@ pub(super) fn context_with_middleware(
NonZeroU32::MIN, NonZeroU32::MIN,
SystemTime::now() + Duration::from_secs(30), SystemTime::now() + Duration::from_secs(30),
account_policy(), account_policy(),
AccountAttemptContext::new(BTreeSet::new(), None, None) AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new(
.with_account_scope(contract_account_scope()), contract_account_scope()
.as_ref()
.clone()
.with_fast_mode_override(Some(fast_mode)),
)),
None, None,
CancellationToken::new(), CancellationToken::new(),
) )
@@ -1696,14 +1699,23 @@ fn context_with_pricing(
fast_mode: FastMode, fast_mode: FastMode,
pricing: gateway_core::metering::PricingOverrides, pricing: gateway_core::metering::PricingOverrides,
) -> AttemptContext { ) -> AttemptContext {
context_for_request( AttemptContext::new(
RequestAttemptContext::new( RequestAttemptContext::new(
ModelRequestId::new(request_id).expect("request id"), ModelRequestId::new(request_id).expect("request id"),
ClientApiKeyId::new("key_openai_contract").expect("client key id"), ClientApiKeyId::new("key_openai_contract").expect("client key id"),
) )
.with_fast_mode(fast_mode)
.with_pricing(Arc::new(pricing)) .with_pricing(Arc::new(pricing))
.with_request_location(Some(global_request_location())), .with_request_location(Some(global_request_location())),
NonZeroU32::MIN,
SystemTime::now() + Duration::from_secs(30),
account_policy(),
AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new(
contract_account_scope()
.as_ref()
.clone()
.with_fast_mode_override(Some(fast_mode)),
)),
None,
cancellation, cancellation,
) )
} }
@@ -8714,6 +8726,77 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
let original = operation.clone(); let original = operation.clone();
let provider = provider_with_catalog_and_base_url(&store, base_url).await; let provider = provider_with_catalog_and_base_url(&store, base_url).await;
let catalog = provider.query_model_capabilities().await.unwrap(); let catalog = provider.query_model_capabilities().await.unwrap();
let groups: Vec<_> = (1..=2)
.map(|id| {
gateway_core::routing::AccountGroupId::new(format!("grp_{id:032x}")).unwrap()
})
.collect();
let provider_kind = ProviderKind::new("openai").unwrap();
// 同一个 Key 绑定两个互不相交的账号组,另一个组不能改写本次账号的档位
let scope = Arc::new(FrozenAccountScope::new(
Arc::new(
RuntimeAccountDirectory::new(
["acct_provider_contract", other]
.into_iter()
.zip(&groups)
.map(|(id, group)| {
(
ProviderAccountId::new(id).unwrap(),
RuntimeAccount::new(
provider_kind.clone(),
[group.clone()].into(),
),
)
})
.collect(),
)
.with_group_fast_modes(
[
(groups[0].clone(), fast_mode),
(
groups[1].clone(),
if fast_mode == FastMode::Disabled {
FastMode::Enabled
} else {
FastMode::Disabled
},
),
]
.into(),
),
),
ClientRoutingScope::restricted(
groups
.iter()
.map(|id| {
gateway_core::routing::RoutingGroupSnapshot::new(
id.clone(),
id.to_string(),
)
})
.collect(),
groups.into_iter().collect(),
[provider_kind].into(),
)
.unwrap(),
));
let context = AttemptContext::new(
RequestAttemptContext::new(
ModelRequestId::new("req_service_tier").unwrap(),
ClientApiKeyId::new("key_openai_contract").unwrap(),
),
NonZeroU32::MIN,
SystemTime::now() + Duration::from_secs(30),
account_policy(),
AccountAttemptContext::new(
BTreeSet::new(),
Some(ProviderAccountId::new("acct_provider_contract").unwrap()),
None,
)
.with_account_scope(scope),
None,
CancellationToken::new(),
);
let mut stream = provider let mut stream = provider
.execute( .execute(
planned_request_with_presentation( planned_request_with_presentation(
@@ -8722,11 +8805,7 @@ async fn responses_should_observe_and_bill_the_outbound_service_tier_on_both_tra
"gpt-5.4", "gpt-5.4",
catalog[0].presentation().cloned(), catalog[0].presentation().cloned(),
), ),
context_with_fast_policy( context,
"req_service_tier",
CancellationToken::new(),
fast_mode,
),
) )
.await .await
.expect("provider stream"); .expect("provider stream");
@@ -11555,12 +11634,23 @@ async fn assert_error_body_read_failure(image: bool) {
#[tokio::test] #[tokio::test]
async fn websocket_failure_headers_override_opening_id_without_changing_raw_events() { async fn websocket_failure_headers_override_opening_id_without_changing_raw_events() {
assert_websocket_failure_headers( for (headers, expected) in [
json!({"X-Request-Id": "req-current-error", "authorization": "synthetic-private-token"}), (
Some("req-current-error"), json!({"X-Request-Id": "req-current-error", "authorization": "synthetic-private-token"}),
false, "req-current-error",
) ),
.await; (
json!({"x-request-id": "", "x-oai-request-id": "é", "X-OpenAI-Request-ID": "req-openai", "x-ms-request-id": "req-ms"}),
"req-openai",
),
(
json!({"x-openai-request-id": " ", "X-Ms-Request-Id": "req-ms"}),
"req-ms",
),
(json!({"x-ms-request-id": 123}), "123"),
] {
assert_websocket_failure_headers(headers, Some(expected), false).await;
}
} }
#[tokio::test] #[tokio::test]
@@ -11570,6 +11660,7 @@ async fn websocket_failure_without_valid_headers_does_not_claim_opening_request_
json!({}), json!({}),
json!({"x-request-id": " "}), json!({"x-request-id": " "}),
json!({"x-request-id": ["invalid"], "x-oai-request-id": "\r\ninvalid"}), json!({"x-request-id": ["invalid"], "x-oai-request-id": "\r\ninvalid"}),
json!({"x-openai-request-id": {"invalid": true}, "x-ms-request-id": "é"}),
] { ] {
assert_websocket_failure_headers(headers, None, false).await; assert_websocket_failure_headers(headers, None, false).await;
} }
@@ -11577,12 +11668,14 @@ async fn websocket_failure_without_valid_headers_does_not_claim_opening_request_
#[tokio::test] #[tokio::test]
async fn reused_websocket_response_failed_uses_current_request_id() { async fn reused_websocket_response_failed_uses_current_request_id() {
assert_websocket_failure_headers( for name in ["X-Oai-Request-Id", "X-OpenAI-Request-ID", "X-Ms-Request-Id"] {
json!({"x-request-id": "", "X-Oai-Request-Id": "req-reused-error"}), assert_websocket_failure_headers(
Some("req-reused-error"), json!({"x-request-id": "", (name): "req-reused-error"}),
true, Some("req-reused-error"),
) true,
.await; )
.await;
}
} }
async fn assert_websocket_failure_headers(headers: Value, request_id: Option<&str>, reuse: bool) { async fn assert_websocket_failure_headers(headers: Value, request_id: Option<&str>, reuse: bool) {
@@ -12541,14 +12634,14 @@ fn quota_continuation_operation(use_websocket: bool) -> Operation {
#[tokio::test] #[tokio::test]
async fn quota_continuation_opening_rejection_projects_replay_without_losing_upstream_facts() { async fn quota_continuation_opening_rejection_projects_replay_without_losing_upstream_facts() {
for use_websocket in [false, true] { for use_websocket in [false, true] {
for (status, code, projects_replay) in [ for (status, code, projects_replay, id_header) in [
(429, "usage_limit_reached", true), (429, "usage_limit_reached", true, "x-ms-request-id"),
(429, "project_spend_limit_exceeded", false), (429, "project_spend_limit_exceeded", false, "x-request-id"),
(402, "insufficient_quota", true), (402, "insufficient_quota", true, "x-openai-request-id"),
(429, "quota_exceeded", false), (429, "quota_exceeded", false, "x-request-id"),
(429, "rate_limit_exceeded", false), (429, "rate_limit_exceeded", false, "x-request-id"),
(429, "slow_down", false), (429, "slow_down", false, "x-request-id"),
(429, "unknown_error", false), (429, "unknown_error", false, "x-request-id"),
] { ] {
let store = Arc::new(MemoryAccountStore::default()); let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_provider_contract").await; create_account(&store, "acct_provider_contract").await;
@@ -12561,7 +12654,7 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
ResponseTemplate::new(status) ResponseTemplate::new(status)
.insert_header("retry-after", "129600") .insert_header("retry-after", "129600")
.insert_header("retry-after-ms", "129600123") .insert_header("retry-after-ms", "129600123")
.insert_header("x-request-id", "req-upstream-quota") .insert_header(id_header, "req-upstream-quota")
.set_body_json(&original), .set_body_json(&original),
) )
.expect(1) .expect(1)
@@ -12614,9 +12707,19 @@ async fn quota_continuation_opening_rejection_projects_replay_without_losing_ups
response response
.headers() .headers()
.iter() .iter()
.any(|header| header.name() == "x-request-id" .any(|header| header.name() == id_header
&& header.value().as_ref() == b"req-upstream-quota") && header.value().as_ref() == b"req-upstream-quota")
); );
assert_eq!(
error.upstream_request_id().unwrap().as_str(),
"req-upstream-quota"
);
assert!(
!response
.headers()
.iter()
.any(|header| header.name() == "x-request-id")
);
assert_eq!( assert_eq!(
store store
.account("acct_provider_contract") .account("acct_provider_contract")
@@ -13303,8 +13406,7 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
RequestAttemptContext::new( RequestAttemptContext::new(
ModelRequestId::new(format!("req_fast_turn_{index}")).unwrap(), ModelRequestId::new(format!("req_fast_turn_{index}")).unwrap(),
key, key,
) ),
.with_fast_mode(fast_mode),
NonZeroU32::new(1).unwrap(), NonZeroU32::new(1).unwrap(),
SystemTime::now() + Duration::from_secs(30), SystemTime::now() + Duration::from_secs(30),
account_policy(), account_policy(),
@@ -13313,7 +13415,12 @@ async fn fast_policy_changes_preserve_the_websocket_continuation_and_meter_each_
None, None,
Some(ProviderAccountStateOwner::new(provider_kind, account)), Some(ProviderAccountStateOwner::new(provider_kind, account)),
) )
.with_account_scope(contract_account_scope()), .with_account_scope(Arc::new(
contract_account_scope()
.as_ref()
.clone()
.with_fast_mode_override(Some(fast_mode)),
)),
binding, binding,
CancellationToken::new(), CancellationToken::new(),
) )
@@ -13451,43 +13558,78 @@ async fn oauth_http_transport_rejects_websocket_only_warmup_without_sending() {
} }
#[tokio::test] #[tokio::test]
async fn oauth_http_transport_rejects_downstream_websocket_chain_without_sending() { async fn websocket_selection_distinguishes_http_only_accounts_from_exhausted_quota() {
let store = Arc::new(MemoryAccountStore::default()); for (http_enabled, http_exhausted, with_exhausted_ws) in [
create_account(&store, "acct_provider_contract").await; (true, false, false),
store.set_oauth_transport( (true, false, true),
"acct_provider_contract", (true, true, true),
provider_openai::credential::ResponsesTransport::Http, (false, false, true),
); ] {
let upstream = MockServer::start().await; let store = Arc::new(MemoryAccountStore::default());
let operation = Operation::Generate(GenerateRequest::from_protocol_payload( create_account_with_enabled(&store, "acct_provider_contract", http_enabled).await;
ProtocolPayload::json_object( store.set_oauth_transport(
"openai", "acct_provider_contract",
json!({"model":"gpt-5.4", "input":"hello", "store":false, "stream":true}) provider_openai::credential::ResponsesTransport::Http,
.as_object() );
.unwrap() if http_exhausted {
.clone(), exhaust_account_quota(&store, "acct_provider_contract").await;
) }
.unwrap() if with_exhausted_ws {
.with_context(Map::from_iter([ create_account(&store, "acct_scope_new").await;
("use_websocket".to_owned(), json!(true)), exhaust_account_quota(&store, "acct_scope_new").await;
( }
"downstream_websocket_connection_id".to_owned(), let upstream = MockServer::start().await;
json!("client-connection"), let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
), ProtocolPayload::json_object(
])), "openai",
)); json!({"model":"gpt-5.4", "input":"hello", "store":false, "stream":true})
let result = provider_with_base_url(&store, upstream.uri()) .as_object()
.execute( .unwrap()
planned_request("openai", operation), .clone(),
context("req_oauth_http_ws_chain", CancellationToken::new()), )
) .unwrap()
.await; .with_context(Map::from_iter([
let Err(error) = result else { ("use_websocket".to_owned(), json!(true)),
panic!("connection-local chain needs an upstream WebSocket") (
}; "downstream_websocket_connection_id".to_owned(),
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount); json!("client-connection"),
assert_eq!(error.send_state(), UpstreamSendState::NotSent); ),
assert!(upstream.received_requests().await.unwrap().is_empty()); ])),
));
let result = provider_with_base_url(&store, upstream.uri())
.execute(
planned_request("openai", operation),
context("req_oauth_http_ws_chain", CancellationToken::new()),
)
.await;
let Err(error) = result else {
panic!("connection-local chain needs an upstream WebSocket")
};
if http_enabled && !http_exhausted {
assert_eq!(error.kind(), ProviderErrorKind::NoEligibleAccount);
let gateway = gateway_core::error::GatewayError::from_provider(&error);
assert_eq!(
gateway.client_error_code(),
Some("websocket_account_unavailable")
);
assert!(gateway.client_message().contains("HTTP/SSE"));
assert_eq!(
gateway.client_message().contains("exhausted their quota"),
with_exhausted_ws
);
assert_eq!(
gateway
.diagnostic()
.and_then(gateway_core::error::ProviderDiagnostic::code),
Some("websocket_account_unavailable")
);
} else {
assert_eq!(error.kind(), ProviderErrorKind::AccountPoolQuotaExhausted);
assert!(error.client_visible_upstream_error().is_none());
}
assert_eq!(error.send_state(), UpstreamSendState::NotSent);
assert!(upstream.received_requests().await.unwrap().is_empty());
}
} }
#[tokio::test] #[tokio::test]
@@ -255,6 +255,161 @@ async fn privacy_workspace_alias_matches_websocket_opening_and_reused_frames() {
captured.await.unwrap(); captured.await.unwrap();
} }
#[tokio::test]
async fn privacy_history_matching_uses_the_sanitized_request() {
for rewrite_body in [false, true] {
let turns = if rewrite_body { 4 } else { 2 };
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_provider_contract").await;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let output = json!({"type":"message","id":"msg_workspace","role":"assistant",
"status":"completed","content":[{"type":"output_text","text":"ok"}]});
let server_output = output.clone();
let captured = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut metadata = String::new();
let mut socket =
crate::transport::accept_codex_test_websocket_with(stream, |request, _| {
if rewrite_body {
assert_eq!(
request.headers()["authorization"],
"Bearer configured-token"
);
}
metadata = request.headers()["x-codex-turn-metadata"]
.to_str()
.unwrap()
.to_owned();
})
.await;
let mut frames = Vec::new();
for n in 0..turns {
let frame = timeout(Duration::from_secs(10), socket.next())
.await
.unwrap()
.unwrap()
.unwrap()
.into_text()
.unwrap();
frames.push(serde_json::from_str::<Value>(&frame).unwrap());
let mut output = server_output.clone();
output["id"] = json!(format!("msg_workspace_{n}"));
let completed = json!({"type":"response.completed","response":{
"id":format!("resp_workspace_{n}"),"model":"gpt-5.4",
"status":"completed","output":[output]
}});
socket
.send(Message::Text(completed.to_string().into()))
.await
.unwrap();
}
(metadata, frames)
});
let provider = provider_with_base_url(&store, format!("http://{address}"));
let mut config = workspace_policy();
if rewrite_body {
let mut rewrite = rule(
PrivacyScope::RequestBody,
"$.input[*].content[*].text",
PrivacyAction::RegexReplace,
);
rewrite.id = "rewrite-input".into();
rewrite.steps[0].pattern = Some("hello".into());
rewrite.steps[0].replacement = "hellohello".into();
config.rules.push(rewrite);
let mut header = rule(
PrivacyScope::RequestHeader,
"authorization",
PrivacyAction::SetValue,
);
header.id = "rewrite-header".into();
header.steps[0].value = json!("Bearer configured-token");
config.rules.push(header);
}
let mut history = vec![
json!({"type":"message","role":"user","content":[{
"type":"input_text","text":"read /Users/alex/projects/private/note.txt"
}]}),
json!({"type":"message","role":"user","content":[{
"type":"input_text","text":"hello"
}]}),
];
let next = json!({"type":"message","role":"user","content":[{
"type":"input_text","text":"continue hello"
}]});
for n in 0..turns {
if n > 0 {
let mut previous = output.clone();
previous["id"] = json!(format!("msg_workspace_{}", n - 1));
history.extend([previous, next.clone()]);
}
if rewrite_body && n == 2 {
config.rules[1].steps[0].replacement = "greetings".into();
}
let Operation::Generate(original) =
workspace_operation("workspace-history", "acct_provider_contract")
else {
unreachable!();
};
let mut body = original.protocol_payload().body().clone();
body.insert("input".into(), json!(history));
body.insert("stream".into(), json!(true));
let request = GenerateRequest::from_protocol_payload(
ProtocolPayload::json_object("openai", body)
.unwrap()
.with_context(original.protocol_payload().context().clone()),
)
.with_provider_session_state(
original.provider_session_state("openai").unwrap().clone(),
);
let mut stream = provider
.clone()
.execute(
planned_request("openai", Operation::Generate(request)),
privacy_context(&config, false),
)
.await
.unwrap();
timeout(Duration::from_secs(15), async {
while let Some(event) = stream.next().await {
event.unwrap();
}
})
.await
.unwrap();
}
let (metadata, frames) = captured.await.unwrap();
assert_workspace_alias(&metadata, &frames[0]);
assert!(
frames
.iter()
.all(|frame| frame["client_metadata"]["x-codex-turn-metadata"]
== frames[0]["client_metadata"]["x-codex-turn-metadata"])
);
assert!(frames[0].get("previous_response_id").is_none());
assert_eq!(frames[1]["previous_response_id"], "resp_workspace_0");
let mut expected_next = next.clone();
if rewrite_body {
assert_eq!(frames[0]["input"][1]["content"][0]["text"], "hellohello");
expected_next["content"][0]["text"] = json!("continue hellohello");
}
assert_eq!(frames[1]["input"], json!([expected_next]));
if rewrite_body {
assert!(frames[2].get("previous_response_id").is_none());
let mut expected_full = history[..6].to_vec();
expected_full[1]["content"][0]["text"] = json!("greetings");
for index in [3, 5] {
expected_full[index]["content"][0]["text"] = json!("continue greetings");
}
assert_eq!(frames[2]["input"], json!(expected_full));
assert_eq!(frames[3]["previous_response_id"], "resp_workspace_2");
expected_next["content"][0]["text"] = json!("continue greetings");
assert_eq!(frames[3]["input"], json!([expected_next]));
}
}
}
fn assert_metadata_filtered(raw: &str, client_copy: bool) { fn assert_metadata_filtered(raw: &str, client_copy: bool) {
let metadata: Value = serde_json::from_str(raw).unwrap(); let metadata: Value = serde_json::from_str(raw).unwrap();
assert!(metadata.get("workspaces").is_none()); assert!(metadata.get("workspaces").is_none());
@@ -855,7 +855,7 @@ async fn child_queue_timeout_does_not_rebind_or_allow_provider_fallback() {
assert_eq!(error.kind(), ProviderErrorKind::ConcurrencyQueueTimeout); assert_eq!(error.kind(), ProviderErrorKind::ConcurrencyQueueTimeout);
assert_eq!( assert_eq!(
gateway_core::error::GatewayError::from_provider(&error).client_message(), gateway_core::error::GatewayError::from_provider(&error).client_message(),
"The request timed out in the gateway queue." "Timed out waiting for available concurrency in the gateway."
); );
assert!(error.retry_is_prohibited()); assert!(error.retry_is_prohibited());
assert_eq!(affinity.binding_count(), 1); assert_eq!(affinity.binding_count(), 1);
@@ -235,7 +235,13 @@ impl gateway_core::engine::upstream_adapter::UpstreamAdapter for AdapterProbe {
Some("chatgpt-acct_provider_contract".as_bytes().to_vec()) Some("chatgpt-acct_provider_contract".as_bytes().to_vec())
); );
assert!(header("cookie").is_none()); assert!(header("cookie").is_none());
assert_eq!(invocation.context.fast_mode(), FastMode::Disabled); assert_eq!(
invocation.context.fast_mode_for_account(
invocation.account.account_id(),
invocation.metadata.upstream_model().unwrap().as_str(),
),
FastMode::Disabled,
);
let Operation::Generate(generate) = &invocation.operation else { let Operation::Generate(generate) = &invocation.operation else {
panic!("adapter must receive the original operation kind"); panic!("adapter must receive the original operation kind");
}; };
@@ -304,7 +310,6 @@ async fn upstream_adapter_reuses_selected_native_account_inside_attempt_onion_an
ModelRequestId::new("req_adapter_native").unwrap(), ModelRequestId::new("req_adapter_native").unwrap(),
ClientApiKeyId::new("key_openai_contract").unwrap(), ClientApiKeyId::new("key_openai_contract").unwrap(),
) )
.with_fast_mode(FastMode::Disabled)
.with_upstream_adapters(Some( .with_upstream_adapters(Some(
gateway_core::engine::upstream_adapter::FrozenUpstreamAdapterPlan::new( gateway_core::engine::upstream_adapter::FrozenUpstreamAdapterPlan::new(
Arc::new(AdapterProbe { Arc::new(AdapterProbe {
@@ -322,8 +327,12 @@ async fn upstream_adapter_reuses_selected_native_account_inside_attempt_onion_an
NonZeroU32::MIN, NonZeroU32::MIN,
SystemTime::now() + Duration::from_secs(5), SystemTime::now() + Duration::from_secs(5),
account_policy(), account_policy(),
AccountAttemptContext::new(BTreeSet::new(), None, None) AccountAttemptContext::new(BTreeSet::new(), None, None).with_account_scope(Arc::new(
.with_account_scope(contract_account_scope()), contract_account_scope()
.as_ref()
.clone()
.with_fast_mode_override(Some(FastMode::Disabled)),
)),
None, None,
CancellationToken::new(), CancellationToken::new(),
); );
@@ -255,13 +255,29 @@ fn diagnostics_should_not_treat_cf_ray_as_a_request_id() {
} }
#[test] #[test]
fn diagnostics_should_accept_the_oai_request_id_header() { fn diagnostics_should_prefer_official_request_ids_and_preserve_all_trace_aliases() {
let names = [
"x-request-id",
"x-oai-request-id",
"x-openai-request-id",
"x-ms-request-id",
];
let mut headers = HeaderMap::new(); let mut headers = HeaderMap::new();
headers.insert("x-oai-request-id", HeaderValue::from_static("oai_req_1")); for name in names {
headers.insert(name, HeaderValue::from_static(name));
}
for (index, name) in names.iter().enumerate() {
let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(500), &headers);
assert_eq!(diagnostics.request_id.as_deref(), Some(*name));
for remaining in &names[index..] {
assert_eq!(trace_header(&diagnostics, remaining), Some(*remaining));
}
headers.insert(*name, HeaderValue::from_static(" \t "));
}
headers.insert("x-request-id", HeaderValue::from_bytes(b"\xff").unwrap());
headers.insert("x-ms-request-id", HeaderValue::from_static("req_ms"));
let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(500), &headers); let diagnostics = CodexUpstreamDiagnostics::from_headers(Some(500), &headers);
assert_eq!(diagnostics.request_id.as_deref(), Some("req_ms"));
assert_eq!(diagnostics.request_id.as_deref(), Some("oai_req_1"));
} }
#[test] #[test]
@@ -0,0 +1,97 @@
//! HTTP 全量历史在池化 WS 上的连续增量、分支与身份隔离
use super::*;
#[tokio::test]
async fn http_history_follows_completed_output_on_its_own_connection() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let tool = json!({"type":"function_call","name":"lookup","call_id":"c","arguments":"{}"});
let message = json!({"type":"message","role":"assistant","content":"ok"});
let (frames, mut seen) = tokio::sync::mpsc::unbounded_channel();
let server = tokio::spawn({
let tool = tool.clone();
let message = message.clone();
async move {
// 更换会话池键后在另一条连接上从全量重新开始
for turns in [0..6, 6..9] {
let (socket, _) = listener.accept().await.unwrap();
let mut ws = accept_codex_test_websocket(socket).await;
for turn in turns {
let frame = ws.next().await.unwrap().unwrap().into_text().unwrap();
frames
.send(serde_json::from_str::<Value>(&frame).unwrap())
.unwrap();
let output = if turn == 0 {
for event in ["response.output_item.added", "response.output_item.done"] {
let event = json!({"type":event,"item":tool,"output_index":0});
ws.send(Message::Text(event.to_string().into()))
.await
.unwrap();
}
json!([])
} else {
json!([message])
};
if turn == 6 {
// 终态只列出一项,但先前已开始两项,下一轮须重新建立基线
for index in 0..2 {
let added = json!({"type":"response.output_item.added","output_index":index,"item":message});
ws.send(Message::Text(added.to_string().into()))
.await
.unwrap();
}
}
let terminal = json!({"type":"response.completed","response":{
"id":format!("resp_{turn}"),"output":output
}});
ws.send(Message::Text(terminal.to_string().into()))
.await
.unwrap();
}
}
}
});
let backend = CodexBackendClient::new(
reqwest::Client::builder().no_proxy().build().unwrap(),
format!("http://{addr}"),
test_wire_profile(),
)
.with_websocket_pool(Arc::new(CodexWebSocketPool::default()));
let mut history = vec![json!({"role":"user","content":"start"})];
for turn in 0..9 {
let next = json!({"role":"user","content":format!("turn {turn}")});
match turn {
0 => {}
1 => {
history.push(tool.clone());
history.push(json!({"type":"function_call_output","call_id":"c","output":"found"}));
}
_ => {
history.push(message.clone());
history.push(next);
}
}
if turn == 3 {
history[0]["content"] = json!("edited");
}
let instructions = if turn < 4 { "original" } else { "changed" };
let mut request = codex_request("model", instructions, history.clone());
request.client_api_key_id = Some(if turn < 5 { "key-a" } else { "key-b" }.into());
request.local_conversation_id = Some(if turn < 6 { "session" } else { "other" }.into());
backend
.create_response(&request, request_context("req", Some("acct")))
.await
.unwrap();
let sent = seen.recv().await.unwrap();
if matches!(turn, 1 | 2 | 8) {
assert_eq!(sent["previous_response_id"], format!("resp_{}", turn - 1));
assert_eq!(sent["input"], json!([history.last().unwrap()]));
} else {
assert!(sent.get("previous_response_id").is_none(), "turn {turn}");
assert_eq!(sent["input"], json!(history));
}
}
server.await.unwrap();
}
@@ -8,6 +8,7 @@ use provider_openai::transport::{
mod breaker; mod breaker;
mod cleanup; mod cleanup;
mod continuation;
mod diagnostics; mod diagnostics;
mod fingerprint; mod fingerprint;
mod metadata; mod metadata;
@@ -414,6 +414,30 @@ impl GrokCredentialQuotaService {
&self, &self,
account_id: &ProviderAccountId, account_id: &ProviderAccountId,
) -> Result<GrokQuotaSnapshot, GrokQuotaError> { ) -> Result<GrokQuotaSnapshot, GrokQuotaError> {
let (account, document) = self.fetch_billing(account_id).await?;
self.store_billing(&account, document).await
}
/// 定时同步只取消远端查询,已读取的额度按同一凭据版本写回
pub(crate) async fn synchronize_account(
&self,
account_id: &ProviderAccountId,
cancellation: &gateway_core::lifecycle::CancellationToken,
) -> Result<(), GrokQuotaError> {
let Some(billing) = cancellation
.run_until_cancelled(self.fetch_billing(account_id))
.await
else {
return Ok(());
};
let (account, document) = billing?;
self.store_billing(&account, document).await.map(|_| ())
}
async fn fetch_billing(
&self,
account_id: &ProviderAccountId,
) -> Result<(ProviderAccount, serde_json::Map<String, serde_json::Value>), GrokQuotaError> {
let loaded = self let loaded = self
.repository .repository
.load_current(account_id) .load_current(account_id)
@@ -450,16 +474,23 @@ impl GrokCredentialQuotaService {
Ok(None) => {} Ok(None) => {}
Err(error) => tracing::warn!(%error, "xAI subscription query failed"), Err(error) => tracing::warn!(%error, "xAI subscription query failed"),
} }
Ok((loaded.account, document))
}
async fn store_billing(
&self,
account: &ProviderAccount,
document: serde_json::Map<String, serde_json::Value>,
) -> Result<GrokQuotaSnapshot, GrokQuotaError> {
let observed_at = Utc::now(); let observed_at = Utc::now();
let presentation = billing_presentation(&document)?; let presentation = billing_presentation(&document)?;
let quota = loaded let quota = account
.account
.quota() .quota()
.merge_observation(quota_access_observation(&presentation, observed_at.into())); .merge_observation(quota_access_observation(&presentation, observed_at.into()));
self.repository self.repository
.replace_quota( .replace_quota(
loaded.account.id().clone(), account.id().clone(),
loaded.account.revision(), account.revision(),
document, document,
observed_at.into(), observed_at.into(),
quota, quota,
@@ -467,8 +498,8 @@ impl GrokCredentialQuotaService {
.await .await
.map_err(map_quota_repository_error)?; .map_err(map_quota_repository_error)?;
let snapshot = GrokQuotaSnapshot { let snapshot = GrokQuotaSnapshot {
account_id: loaded.account.id().clone(), account_id: account.id().clone(),
credential_revision: loaded.account.revision(), credential_revision: account.revision(),
observed_at, observed_at,
billing: presentation, billing: presentation,
}; };
@@ -13,6 +13,7 @@ use gateway_core::account::{
AccountErrorReason, CredentialRevision, CredentialState, LoadedCredential, ProviderAccountId, AccountErrorReason, CredentialRevision, CredentialState, LoadedCredential, ProviderAccountId,
ProviderRefreshQuery, ProviderRefreshQuery,
}; };
use gateway_core::lifecycle::CancellationToken;
use gateway_core::provider_ports::{ use gateway_core::provider_ports::{
ProviderCredentialStatePort, ProviderLeaseAcquisition, ProviderLeasePort, ProviderLeaseRequest, ProviderCredentialStatePort, ProviderLeaseAcquisition, ProviderLeasePort, ProviderLeaseRequest,
ProviderRefreshCapacityRequest, ProviderRefreshLeaseRequest, ProviderRefreshPolicy, ProviderRefreshCapacityRequest, ProviderRefreshLeaseRequest, ProviderRefreshPolicy,
@@ -374,7 +375,14 @@ impl GrokCredentialRefreshService {
pub async fn refresh_due( pub async fn refresh_due(
&self, &self,
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> { ) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
self.refresh_due_excluding(&[]).await self.refresh_due_until(&CancellationToken::new()).await
}
pub async fn refresh_due_until(
&self,
cancellation: &CancellationToken,
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
self.refresh_batch(&[], cancellation).await
} }
async fn refresh_rejected( async fn refresh_rejected(
@@ -520,11 +528,27 @@ impl GrokCredentialRefreshService {
&self, &self,
excluded_account_ids: &[ProviderAccountId], excluded_account_ids: &[ProviderAccountId],
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> { ) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
let policy = self.runtime_policy.load_refresh_policy().await?; self.refresh_batch(excluded_account_ids, &CancellationToken::new())
let batch = self .await
.repository }
.list_due_refresh_batch_excluding(excluded_account_ids, policy)
.await?; async fn refresh_batch(
&self,
excluded_account_ids: &[ProviderAccountId],
cancellation: &CancellationToken,
) -> Result<Vec<GrokCredentialRefreshOutcome>, GrokCredentialRefreshError> {
let load_candidates = async {
let policy = self.runtime_policy.load_refresh_policy().await?;
let batch = self
.repository
.list_due_refresh_batch_excluding(excluded_account_ids, policy)
.await?;
Ok::<_, GrokCredentialRefreshError>((policy, batch))
};
let Some(batch) = cancellation.run_until_cancelled(load_candidates).await else {
return Ok(Vec::new());
};
let (policy, batch) = batch?;
let mut outcomes = batch let mut outcomes = batch
.failed_account_ids .failed_account_ids
.into_iter() .into_iter()
@@ -537,27 +561,38 @@ impl GrokCredentialRefreshService {
if credentials if credentials
.iter() .iter()
.any(|credential| credential.outbound_proxy.is_none()) .any(|credential| credential.outbound_proxy.is_none())
&& self.refresher.prepare_cycle().await.is_err()
{ {
if credentials let Some(prepared) = cancellation
.iter() .run_until_cancelled(self.refresher.prepare_cycle())
.all(|credential| credential.outbound_proxy.is_none()) .await
{ else {
return Err(GrokCredentialRefreshError::Preparation); return Ok(outcomes);
} };
// 默认出口发现失败不能阻止其他出口上的账号刷新 if prepared.is_err() {
credentials.retain(|credential| { if credentials
if credential.outbound_proxy.is_some() { .iter()
return true; .all(|credential| credential.outbound_proxy.is_none())
{
return Err(GrokCredentialRefreshError::Preparation);
} }
outcomes.push(GrokCredentialRefreshOutcome::Failed { // 默认出口发现失败不能阻止其他出口上的账号刷新
account_id: credential.account_id.clone(), credentials.retain(|credential| {
if credential.outbound_proxy.is_some() {
return true;
}
outcomes.push(GrokCredentialRefreshOutcome::Failed {
account_id: credential.account_id.clone(),
});
false
}); });
false }
});
} }
outcomes.reserve(credentials.len()); outcomes.reserve(credentials.len());
let refreshed = stream::iter(credentials.into_iter().map(|credential| async move { // 停止领取新账号,已发出的令牌交换继续写回
let candidates = credentials
.into_iter()
.take_while(|_| !cancellation.is_cancelled());
let refreshed = stream::iter(candidates.map(|credential| async move {
let account_id = credential.account_id.clone(); let account_id = credential.account_id.clone();
( (
account_id, account_id,
@@ -103,12 +103,9 @@ impl ScheduledTask for XaiCliReleaseTask {
impl ScheduledTask for XaiOAuthRefreshTask { impl ScheduledTask for XaiOAuthRefreshTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
if context.cancellation().is_cancelled() {
return Ok(());
}
let outcomes = self let outcomes = self
.service .service
.refresh_due() .refresh_due_until(context.cancellation())
.await .await
.map_err(|error| WorkerTaskError::safe("令牌刷新失败").with_source(error))?; .map_err(|error| WorkerTaskError::safe("令牌刷新失败").with_source(error))?;
let failures = outcomes let failures = outcomes
@@ -148,27 +145,41 @@ pub(super) struct XaiQuotaCatalogTask {
impl ScheduledTask for XaiQuotaCatalogTask { impl ScheduledTask for XaiQuotaCatalogTask {
fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> { fn run_cycle(&self, context: WorkerCycleContext) -> BoxFuture<'_, Result<(), WorkerTaskError>> {
Box::pin(async move { Box::pin(async move {
let accounts = self let cancellation = context.cancellation();
.accounts let Some(accounts) = cancellation
.list_for_provider(&self.provider_kind, true) .run_until_cancelled(self.accounts.list_for_provider(&self.provider_kind, true))
.await .await
else {
return Ok(());
};
let accounts = accounts
.map_err(|source| WorkerTaskError::safe("账号列表读取失败").with_source(source))?; .map_err(|source| WorkerTaskError::safe("账号列表读取失败").with_source(source))?;
let mut failures = QuotaCatalogFailure::default(); let mut failures = QuotaCatalogFailure::default();
let now = SystemTime::now(); let now = SystemTime::now();
let accounts = self.reserve_periodic_refreshes(accounts, now); let accounts = self.reserve_periodic_refreshes(accounts, now);
for account in accounts { for account in accounts
if context.cancellation().is_cancelled() { .into_iter()
return Ok(()); .take_while(|_| !cancellation.is_cancelled())
} {
match self.quota.refresh_account(account.id()).await { match self
Ok(_) | Err(GrokQuotaError::AccountUnavailable) => {} .quota
.synchronize_account(account.id(), cancellation)
.await
{
Ok(()) | Err(GrokQuotaError::AccountUnavailable) => {}
Err(error) => { Err(error) => {
failures.quota_failures = failures.quota_failures.saturating_add(1); failures.quota_failures = failures.quota_failures.saturating_add(1);
failures.first_quota_error.get_or_insert(error); failures.first_quota_error.get_or_insert(error);
} }
} }
} }
match self.catalog.query_models().await { let Some(catalog) = cancellation
.run_until_cancelled(self.catalog.query_models())
.await
else {
return Ok(());
};
match catalog {
Ok(_) | Err(GrokCredentialCatalogError::NoEligibleCredential) => {} Ok(_) | Err(GrokCredentialCatalogError::NoEligibleCredential) => {}
Err(error) => failures.catalog_error = Some(error), Err(error) => failures.catalog_error = Some(error),
} }
+5 -1
View File
@@ -789,6 +789,8 @@ metrics_exporter = "none"
WebSocket 会话完成,进程退出时强制断开剩余连接。待写费用、已入队的观测与后台清理保留 WebSocket 会话完成,进程退出时强制断开剩余连接。待写费用、已入队的观测与后台清理保留
`host.worker_shutdown_timeout_seconds`(默认 30 秒)的收尾预算;客户端在新进程就绪后重新连接 `host.worker_shutdown_timeout_seconds`(默认 30 秒)的收尾预算;客户端在新进程就绪后重新连接
若重启耗尽收尾预算,查看日志中「后台任务收尾超时,强制终止」的 `worker` 字段,定位超时任务
费用被写入队列接管不等于已落库。数据库持续失败、收尾超时或进程强制退出时,未持久化费用与 费用被写入队列接管不等于已落库。数据库持续失败、收尾超时或进程强制退出时,未持久化费用与
未写入的观测可能丢失,重启不会恢复这些内存队列。延长收尾预算不能保证费用不丢失 未写入的观测可能丢失,重启不会恢复这些内存队列。延长收尾预算不能保证费用不丢失
@@ -1001,9 +1003,11 @@ alpha、beta、rc、exp 在 GitHub 标记为 Pre-release,不覆盖 GitHub Late
在线更新要求官方构建且起始版本不低于 **v3.18.1**,版本选择遵循上述规则;源码等非官方构建返回不支持原因,不提供可用更新。 在线更新要求官方构建且起始版本不低于 **v3.18.1**,版本选择遵循上述规则;源码等非官方构建返回不支持原因,不提供可用更新。
不满足在线更新条件时,使用完整发行包或镜像[手动部署](#镜像升级与源码构建)。 不满足在线更新条件时,使用完整发行包或镜像[手动部署](#镜像升级与源码构建)。
点击「下载更新」后,操作日志显示下载、校验与安装过程,完成后显示「待重启」及待生效版本。点击「立即重启」后才使用新程序。 点击「下载更新」后,操作日志显示下载、校验与安装过程,完成后显示「待重启」及待生效版本。点击「重启服务」并确认后才使用新程序。
「当前版本」表示正在运行的版本,「通道最新」显示所选通道已发布的版本。通道版本较低时仍显示其版本号,并提示无可用更新 「当前版本」表示正在运行的版本,「通道最新」显示所选通道已发布的版本。通道版本较低时仍显示其版本号,并提示无可用更新
启用在线重启的部署,在没有更新时也可点击「检查更新」左侧的「重启服务」。确认框提示请求中断影响,有不兼容插件时同时展示清单;取消不执行重启。服务恢复后页面自动刷新,未启用在线重启时按钮不可用
手动更换镜像或程序后,更新器会核对安装文件并校准历史状态,不以旧成功记录推断需要重启。 手动更换镜像或程序后,更新器会核对安装文件并校准历史状态,不以旧成功记录推断需要重启。
运行期间检测到外部文件变动或文件缺失时会报告异常,需要核对完整发行包并重启服务后再检查。 运行期间检测到外部文件变动或文件缺失时会报告异常,需要核对完整发行包并重启服务后再检查。
回滚入口只接受与记录指纹一致的完整备份;缺少指纹,或备份被替换、丢失时,不提供在线回滚, 回滚入口只接受与记录指纹一致的完整备份;缺少指纹,或备份被替换、丢失时,不提供在线回滚,
+35 -18
View File
@@ -328,18 +328,19 @@ print(completion.choices[0].message.content)
| 字段 | 支持与映射 | | 字段 | 支持与映射 |
| --- | --- | | --- | --- |
| `messages[].role` | `system`、`developer`、`user`、`assistant`、`tool`,保持顺序;assistant 文本历史转为 `output_text` | | `messages[].role` | `system`、`developer`、`user`、`assistant`、`tool`,保持顺序;assistant 文本历史转为 `output_text` |
| `messages[].content` | 字符串或内容块数组;user 和 tool 可包含图片、文件与音频,assistant 支持文本与拒绝内容 | | `messages[].content` | 字符串或内容块数组。所有角色的 `text`、`input_text`、`output_text` 块均将显式 `"text": null` 按空字符串处理。缺少 `text` 或传入其他非字符串值时返回 `400`。user 和 tool 可包含图片、文件与音频,assistant 支持文本与拒绝内容 |
| `system`、`developer`、`assistant` 的空正文 | 正文缺省、为 `null` 或 `""` 时省略。数组中移除没有附加信息的空文本块,保留空白字符和带缓存断点的块。数组为空时仍转换 assistant 的工具调用和拒绝内容。全部消息均为空占位时返回 `400` |
| `image_url` 内容块 | HTTP(S) URL 或非空 `data:image/...;base64,...`,保留 `detail`,网关不代取图片 | | `image_url` 内容块 | HTTP(S) URL 或非空 `data:image/...;base64,...`,保留 `detail`,网关不代取图片 |
| `file` 内容块 | `file.file_id`、`file.file_data`、`file.file_url` 至少提供一种,保留可选 `filename`;URL 和非 PDF 文件为网关的 Responses 扩展,实际支持由上游判断 | | `file` 内容块 | `file.file_id`、`file.file_data`、`file.file_url` 至少提供一种,保留可选 `filename`;URL 和非 PDF 文件为网关的 Responses 扩展,实际支持由上游判断 |
| `input_audio` 内容块 | Chat 的 `data` 和 `format` 转为 Responses `audio_url` data URL;原生音频引用与 `input_text`、`input_image`、`input_file` 内容块也可携带 | | `input_audio` 内容块 | Chat 的 `data` 和 `format` 转为 Responses `audio_url` data URL;原生音频引用与 `input_text`、`input_image`、`input_file` 内容块也可携带 |
| `messages[].refusal`、assistant 的 `refusal` 内容块 | 保留拒绝历史;assistant 同时有工具调用或拒绝内容时,`content` 可省略或为 `null` | | `messages[].refusal`、assistant 的 `refusal` 内容块 | 保留 assistant 拒绝历史,各角色消息的 `refusal: ""` 按缺省处理 |
| `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果;保留 ID、参数或输入字符串,不解析或执行工具;custom 结果须携带前序调用历史 | | `messages[].tool_calls`、`messages[].tool_call_id` | function 和 custom 调用分别映射到对应 Responses 调用及结果,保留 ID、参数或输入字符串。空调用列表按缺省处理。tool 必须携带调用 ID 和结果,其他角色忽略空 ID。custom 结果须携带前序调用历史 |
| `messages[].name` | tool 消息的工具名随结果携带;其他角色的名称作为辅助信息忽略 | | `messages[].name` | Responses 将 tool 消息的非空字符串名称随结果携带。Messages 和 GenAI 通过调用 ID 匹配历史。其他角色的名称作为辅助信息忽略 |
| `tools` | 展开 function/custom 定义,保留 schema、format 及原生工具对象;function 的 `strict` 省略或 `null` 时使用 `false` | | `tools` | 展开 function/custom 定义,保留 schema、format 及原生工具对象。function 的 `parameters: null` 按省略处理,`strict` 省略或为 `null` 时使用 `false` |
| `tool_choice`、`parallel_tool_calls` | 展开指定 function/custom 和 `allowed_tools` 选择;原生选择与并行布尔值交给上游 | | `tool_choice`、`parallel_tool_calls` | 展开指定 function/custom 和 `allowed_tools` 选择;原生选择与并行布尔值交给上游 |
| `web_search_options` | `{}` 即要求上游执行 `web_search`;支持 `search_context_size` 与 `user_location.approximate` | | `web_search_options` | `{}` 即要求上游执行 `web_search`;支持 `search_context_size` 与 `user_location.approximate` |
| `response_format` | 映射到 `text.format`,保留 JSON Schema;未知格式交给上游 | | `response_format` | 非 `null` 时优先于 `text.format`,保留 JSON Schema;未知格式交给 Responses 上游 |
| `reasoning_effort`、`verbosity` | 覆盖 `reasoning.effort`、`text.verbosity`,不固定枚举档位 | | `reasoning_effort`、`verbosity` | 非 `null` 时分别覆盖 `reasoning.effort`、`text.verbosity`,取值范围由 Responses 上游决定 |
| `max_completion_tokens`、`max_tokens`、`max_output_tokens` | 映射到 `max_output_tokens`,按本行从左到右的顺序优先 | | `max_completion_tokens`、`max_tokens`、`max_output_tokens` | 映射到 `max_output_tokens`,按本行从左到右的顺序优先 |
| `temperature`、`top_p` | 原值进入 Provider;是否生效见下文正文兼容规则 | | `temperature`、`top_p` | 原值进入 Provider;是否生效见下文正文兼容规则 |
| `user`、`safety_identifier`、`service_tier`、`prompt_cache_key`、`prompt_cache_retention` | 同语义字段保留原值 | | `user`、`safety_identifier`、`service_tier`、`prompt_cache_key`、`prompt_cache_retention` | 同语义字段保留原值 |
@@ -348,8 +349,8 @@ print(completion.choices[0].message.content)
| `logprobs`、`top_logprobs` | `logprobs: true` 请求输出文本 logprobs,并携带 `top_logprobs`;返回值位于 Chat 的 `choices[].logprobs` | | `logprobs`、`top_logprobs` | `logprobs: true` 请求输出文本 logprobs,并携带 `top_logprobs`;返回值位于 Chat 的 `choices[].logprobs` |
| 内容块的 `prompt_cache_breakpoint` | 对象原样携带;assistant 输出消息不支持此选项 | | 内容块的 `prompt_cache_breakpoint` | 对象原样携带;assistant 输出消息不支持此选项 |
可选映射参数为 `null` 时按未提供处理。`stop`、`seed`、`frequency_penalty`、`presence_penalty`、 可选映射参数为 `null` 时按未提供处理。`stop` 的字符串或字符串数组在 Messages 中映射为 `stop_sequences`,在 GenAI 中映射为 `generationConfig.stopSequences`。空数组按省略处理,Responses 忽略此参数。
`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。 `seed`、`frequency_penalty`、`presence_penalty`、`logit_bias` 和 `prediction` 没有对应的 Responses 控制语义,接受后忽略,不保证生效。
消息的 `reasoning_content` 和 `reasoning` 作为辅助历史忽略,不转为用户正文 消息的 `reasoning_content` 和 `reasoning` 作为辅助历史忽略,不转为用户正文
`n`、`store`、`background`、`modalities` 和 `functions` 可省略或为 `null`。非空值仅接受 `n: 1`、`store: false`、`background: false`、`modalities: ["text"]` 和 `functions: []`。 `n`、`store`、`background`、`modalities` 和 `functions` 可省略或为 `null`。非空值仅接受 `n: 1`、`store: false`、`background: false`、`modalities: ["text"]` 和 `functions: []`。
@@ -364,7 +365,7 @@ Messages 目标直接生成 `system`、`messages`、`tool_use`/`tool_result`
`service_tier: priority` 映射为 `speed: fast` 并补充目标 beta,`default` 映射为 `standard_only`;不代表两种上游有相同的服务承诺 `service_tier: priority` 映射为 `speed: fast` 并补充目标 beta,`default` 映射为 `standard_only`;不代表两种上游有相同的服务承诺
GenAI 目标直接生成 `systemInstruction`、`contents`、`functionCall`/`functionResponse` 和 `generationConfig`。 GenAI 目标直接生成 `systemInstruction`、`contents`、`functionCall`/`functionResponse` 和 `generationConfig`。
两个目标都校验工具调用与结果的配对;custom 工具以单个字符串输入包装成函数,并在 Chat 回程还原。 两个目标都校验工具调用与结果的配对。函数省略参数定义时使用空对象 schema。custom 工具以单个字符串输入包装成函数,并在 Chat 回程还原。
Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.type: text`;grammar 等受约束格式返回 `400`,`param` 指向原始格式字段。 Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.type: text`;grammar 等受约束格式返回 `400`,`param` 指向原始格式字段。
多模态字段按目标能力映射,不支持的内容或声明返回字段错误,不转成另一平台协议重试 多模态字段按目标能力映射,不支持的内容或声明返回字段错误,不转成另一平台协议重试
@@ -380,9 +381,9 @@ Messages、GenAI 和 xAI 的 custom 工具只接受未指定格式或 `format.ty
索引对应合并后的消息正文。流式结果保留正文中的行内链接,并在结束前通过 `delta.annotations` 交付结构化引用, 索引对应合并后的消息正文。流式结果保留正文中的行内链接,并在结束前通过 `delta.annotations` 交付结构化引用,
索引对应实际交付的合并正文 索引对应实际交付的合并正文
`stream_options` 仅在 `stream: true` 时可提供, `stream_options` 仅在 `stream: true` 时生效,非流式请求也可携带该对象。
`include_usage: true` 在完整上游用量可用时于结束前追加 `choices: []` 的用量块,其余块的 `usage` 为 `null`。 流式请求设置 `include_usage: true` 时,网关在完整上游用量可用时于结束前追加 `choices: []` 的用量块,其余块的 `usage` 为 `null`。
未提供完整用量时不补造 Token 数;缺省不启用流长度混淆,`include_obfuscation: true` 不受支持,`false` 可接受 未提供完整用量时不补造 Token 数。流式请求支持省略 `include_obfuscation` 或设为 `false`,设为 `true` 时返回 `400`
响应对象的额外普通属性、非必要事件不影响已有内容映射;无法表达的业务输出、缺少必要终态或终态冲突会失败, 响应对象的额外普通属性、非必要事件不影响已有内容映射;无法表达的业务输出、缺少必要终态或终态冲突会失败,
不补造成功终态。SSE 已开始后通过 `data: {"error": ...}` 交付错误,再以 `[DONE]` 结束, 不补造成功终态。SSE 已开始后通过 `data: {"error": ...}` 交付错误,再以 `[DONE]` 结束,
@@ -666,6 +667,8 @@ Responses WebSocket 接受文本消息,`response.create` 在同一连接串行
| WS → SSE | 通常保留下游 WS。需要完整重放的 OpenAI 大包回退按下述规则重连 | | WS → SSE | 通常保留下游 WS。需要完整重放的 OpenAI 大包回退按下述规则重连 |
| WS → WS | 保留当前绑定的上游 WS,支持下一轮续接 | | WS → WS | 保留当前绑定的上游 WS,支持下一轮续接 |
Codex OAuth 的 SSE 客户端可以每轮提交完整历史。网关先执行隐私规则,再用处理后的内容匹配历史。复用同一上游 WS 时,若同一 Client Key 的请求配置和历史前缀匹配上一轮已完成的输入、输出,网关使用 `previous_response_id` 和新增输入续接。换连接或历史不匹配时发送本次完整输入。此优化用于 `store=false` 的生成请求;显式续接和出站插件接管的帧沿用各自的传输合同
活跃客户端 WS 的绑定不受普通空闲回收期限约束;上游 Close(不限关闭码)、EOF、传输读写失败、总寿命到期或连接被回收仍可能使连接内续接失效, 活跃客户端 WS 的绑定不受普通空闲回收期限约束;上游 Close(不限关闭码)、EOF、传输读写失败、总寿命到期或连接被回收仍可能使连接内续接失效,
网关在收到绑定上游的失效通知且下游空闲时,以关闭码 1000 要求客户端重连并发送完整输入。 网关在收到绑定上游的失效通知且下游空闲时,以关闭码 1000 要求客户端重连并发送完整输入。
终态后的结算先完成,已接收或正在处理的客户端消息先按原合同执行;启用 WS 帧中间件时保留连接。 终态后的结算先完成,已接收或正在处理的客户端消息先按原合同执行;启用 WS 帧中间件时保留连接。
@@ -698,6 +701,9 @@ OAuth 账号默认 `prefer_websocket`,客户端使用 HTTP/SSE 时仍可能选
可将账号上游传输方式设为 `http`,固定使用 HTTP/SSE。Responses API Key 账号默认使用 HTTP/SSE, 可将账号上游传输方式设为 `http`,固定使用 HTTP/SSE。Responses API Key 账号默认使用 HTTP/SSE,
也可配置 `prefer_websocket`;Messages API Key 账号只支持 `http`。 也可配置 `prefer_websocket`;Messages API Key 账号只支持 `http`。
OpenAI 的协议预热、依赖 WS 的非持久化新链和连接内续接要求账号支持上游 WS。 OpenAI 的协议预热、依赖 WS 的非持久化新链和连接内续接要求账号支持上游 WS。
`503 websocket_account_unavailable` 表示无法选出可用的 WS 账号,而授权范围内仍有基础状态正常的
HTTP/SSE 账号被传输要求排除;可将账号上游传输改为 WS,或将客户端改为 HTTP/SSE。
若兼容 WS 的账号均已耗尽额度,提示同时保留该原因,不将混合原因简化为整个账号池额度耗尽。
HTTP 入站的 Codex 压缩请求未显式指定 `use_websocket: true` 且不依赖 WS 时,保留上游 HTTP/SSE; HTTP 入站的 Codex 压缩请求未显式指定 `use_websocket: true` 且不依赖 WS 时,保留上游 HTTP/SSE;
压缩根据 turn metadata 中的 `request_kind: compaction` 或输入中的 `compaction_trigger` 识别。 压缩根据 turn metadata 中的 `request_kind: compaction` 或输入中的 `compaction_trigger` 识别。
WS 入站的压缩沿用常规传输策略。 WS 入站的压缩沿用常规传输策略。
@@ -733,10 +739,14 @@ OpenAI 因大小走 HTTP/SSE 且需要完整重放的请求,在
生成请求、Messages 输入计数、Images 和 Search 的 HTTP 响应在建立模型执行后返回两个关联 ID,OpenAI 与 xAI 规则相同: 生成请求、Messages 输入计数、Images 和 Search 的 HTTP 响应在建立模型执行后返回两个关联 ID,OpenAI 与 xAI 规则相同:
- `x-gateway-request-id` 为模型执行 ID - `x-gateway-request-id` 为模型执行 ID
- `x-request-id` 优先取有效的上游同名头,其次取上游 `x-oai-request-id`,最后取模型执行 ID - `x-request-id` 按 `x-request-id`、`x-oai-request-id`、`x-openai-request-id`、`x-ms-request-id`
顺序取有效上游值;全部缺失、为空或不可读时取模型执行 ID
错误正文读取失败时仍返回已知上游 ID 与允许下发的会话头(如 turn state)。只有在建立执行前拒绝请求时才使用中间件的入口关联 错误正文读取失败时仍返回已知上游 ID 与允许下发的会话头(如 turn state)。只有在建立执行前拒绝请求时才使用中间件的入口关联
网关合成的 WebSocket `response.metadata` 采用相同的 ID 选择顺序。失败响应仅关联本次失败,
不沿用先前握手或会话的 request ID
WebSocket 在交付业务事件前合成的错误保留已确认的失败状态和结构化 `message/type/code`,容量恢复按[重试规则](#容量拒绝与重试)处理。缺少结构化错误时使用安全提示。错误的 `headers` 携带允许下发的响应头,优先返回失败的上游 request ID,缺失时使用网关关联 ID。`x-gateway-request-id` 单独标识网关请求 WebSocket 在交付业务事件前合成的错误保留已确认的失败状态和结构化 `message/type/code`,容量恢复按[重试规则](#容量拒绝与重试)处理。缺少结构化错误时使用安全提示。错误的 `headers` 携带允许下发的响应头,优先返回失败的上游 request ID,缺失时使用网关关联 ID。`x-gateway-request-id` 单独标识网关请求
### 模型目录 ### 模型目录
@@ -941,7 +951,8 @@ Client Key 日周预算超限返回 `429`,`error.type` 为官方额度耗尽
OpenAI 选号阶段确认本次可选账号全部额度耗尽时,HTTP 返回 `429`,WebSocket 错误帧返回 OpenAI 选号阶段确认本次可选账号全部额度耗尽时,HTTP 返回 `429`,WebSocket 错误帧返回
`status: 429`,两者的 `error.type` 与 `error.code` 均为 `usage_limit_reached`,提示客户端停止 `status: 429`,两者的 `error.type` 与 `error.code` 均为 `usage_limit_reached`,提示客户端停止
本轮自动重试,等待额度恢复或补充可用账号。空账号池、认证失效和临时容量不足不按额度耗尽处理; 本轮自动重试,等待额度恢复或补充可用账号。空账号池、认证失效、临时容量不足,以及仍有正常账号因
HTTP/SSE 配置无法承接 WS 请求的混合原因,不按整个账号池额度耗尽处理;
仍有其他可用 Provider 或可安全恢复的续写时,网关先按现有路由规则尝试恢复 仍有其他可用 Provider 或可安全恢复的续写时,网关先按现有路由规则尝试恢复
带 `previous_response_id` 的 OpenAI 原生续写仍绑定原账号。若该账号明确拒绝请求且额度已耗尽, 带 `previous_response_id` 的 OpenAI 原生续写仍绑定原账号。若该账号明确拒绝请求且额度已耗尽,
@@ -1368,6 +1379,8 @@ OpenAI OAuth 账号的 `capabilities.quotaSettingsSupported` 为真。通过 `PO
该轮存在对应通用桶的请求使用证据或新窗口非零用量时跳过,不把重置前的使用或具名桶用量算入本轮。 该轮存在对应通用桶的请求使用证据或新窗口非零用量时跳过,不把重置前的使用或具名桶用量算入本轮。
正常请求的额度反馈即使用量取整为 0% 也保留使用证据,主动额度刷新不会清除;成功的账号预热同样计入。 正常请求的额度反馈即使用量取整为 0% 也保留使用证据,主动额度刷新不会清除;成功的账号预热同样计入。
无重置时间时等待后续观测,不通过空闲窗口滚动的倒计时推迟已登记的边界。 无重置时间时等待后续观测,不通过空闲窗口滚动的倒计时推迟已登记的边界。
本周期已观察到用量或触顶,随后已有快照在原边界前显示 0% 且未触顶时,从该次观测起满 5 分钟复查并预热。
该判断只消费已保存的额度,不增加发现重置的轮询;始终为 0% 的空闲桶仍按原边界处理。
手动或自动用卡确认成功后,已开启预热的通用周桶从确认时间起满 5 分钟复查。额度恢复且本轮空闲时才发送,重试最近一次用卡时沿用原预热进度。 手动或自动用卡确认成功后,已开启预热的通用周桶从确认时间起满 5 分钟复查。额度恢复且本轮空闲时才发送,重试最近一次用卡时沿用原预热进度。
同批到期的通用窗口合并一次请求,领取进度跨重启保留;已领取请求发生超时或取消时不自动重放。 同批到期的通用窗口合并一次请求,领取进度跨重启保留;已领取请求发生超时或取消时不自动重放。
账号停用、凭据不可用、额度耗尽或达到调度上限时不执行;复查失败最多每 5 分钟重查 账号停用、凭据不可用、额度耗尽或达到调度上限时不执行;复查失败最多每 5 分钟重查
@@ -1771,7 +1784,8 @@ OAuth 账号优先按可归属整个账号的实际周/月额度窗口统计,
Antigravity 按部署时区汇总今天及前 6 天,`usage.windowKind` 为 `recent_week`,管理端显示“近一周”;其他 Provider 默认使用过去 24 小时,返回 `daily`。 Antigravity 按部署时区汇总今天及前 6 天,`usage.windowKind` 为 `recent_week`,管理端显示“近一周”;其他 Provider 默认使用过去 24 小时,返回 `daily`。
Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计;账号请求小时图仍独立展示最近 24 个 UTC 小时桶 Token 与模型用量共用该范围,上游额度快照缺失时仍可展示本地统计;账号请求小时图仍独立展示最近 24 个 UTC 小时桶
账号列表展示额度桶时,Token 取自使用率对应窗口的 `localUsage`。桶内所有窗口的使用率均未知时取第一个展示窗口。窗口用量为零时显示 `0`,缺少统计时显示 `—` 账号列表展示额度桶时,Token 取自使用率对应窗口的 `localUsage`。桶内所有窗口的使用率均未知时取第一个展示窗口。
缺少窗口统计时显示 `—`。账号列表统一隐藏为零的 Token 用量
批量导入 AT / RT 使用 `accounts` JSON 数组,最多 200 项,不接受纯文本 token 列表。例如: 批量导入 AT / RT 使用 `accounts` JSON 数组,最多 200 项,不接受纯文本 token 列表。例如:
@@ -2163,7 +2177,8 @@ GET 和 POST 均返回 `enabled`、`leadMinutes`、`weeklyTriggerRemainingPercen
`allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。分组与账号共用[模型限制编辑器](#账号模型限制)。可从成员账号的目录勾选模型,也可在创建或编辑分组时手动添加目录外的 ID。分组和账号分别保存规则,账号自身的限制继续生效。 `allowlist` 和 `denylist` 使用区分大小写的完整模型 ID。分组与账号共用[模型限制编辑器](#账号模型限制)。可从成员账号的目录勾选模型,也可在创建或编辑分组时手动添加目录外的 ID。分组和账号分别保存规则,账号自身的限制继续生效。
Key 绑定多个组时,按模型分别合并启用组中的合格账号。例如两个组分别允许 X 和 Y,X 请求只能使用允许 X 的组内账号。 Key 绑定多个组时,按模型分别合并启用组中的合格账号。例如两个组分别允许 X 和 Y,X 请求只能使用允许 X 的组内账号。
`fastMode` 默认跟随客户端。策略合并包括 Key 绑定的禁用分组,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端 `fastMode` 默认跟随客户端。每次选定账号后,只合并当前 Key 绑定、已启用、包含该账号且允许本次上游模型的分组策略。
其他账号的分组、停用分组和不允许该模型的分组不参与。同一账号命中多个有效分组时,优先级依次为 `disabled`、`enabled`、`ultrafast`、`default`。未绑定分组的 Key 跟随客户端
| 值 | OpenAI Responses 顶层 `service_tier` | | 值 | OpenAI Responses 顶层 `service_tier` |
| --- | --- | | --- | --- |
@@ -2175,7 +2190,7 @@ Key 绑定多个组时,按模型分别合并启用组中的合格账号。例
目标档位缺少目录支持时保留原请求。 目标档位缺少目录支持时保留原请求。
OAuth 和 Responses API Key 共用上述档位规则,出站兼容层不额外删除原生 Responses 的 `auto/default`。 OAuth 和 Responses API Key 共用上述档位规则,出站兼容层不额外删除原生 Responses 的 `auto/default`。
宿主策略在 request 中间件之后应用,形成 attempt 输入基线;attempt 中间件继续改写档位时,以改写后的实际发送值为准。 宿主策略在 request 中间件之后应用,形成 attempt 输入基线;attempt 中间件继续改写档位时,以改写后的实际发送值为准。
HTTP 和每个 WebSocket `response.create` 均使用请求开始时的分组策略,同一请求重试保持该策略; HTTP 和每个 WebSocket `response.create` 均冻结请求开始时的分组配置,重试按实际选中的账号和上游模型计算策略。
HTTP 请求头及新建 WS 的握手提示按当时的最终出站档位构造;复用 WS 时不重发握手头, HTTP 请求头及新建 WS 的握手提示按当时的最终出站档位构造;复用 WS 时不重发握手头,
每个 `response.create` 仍独立应用档位策略,请求档位统计与本地费用估算使用各帧的最终出站档位 每个 `response.create` 仍独立应用档位策略,请求档位统计与本地费用估算使用各帧的最终出站档位
@@ -3421,6 +3436,8 @@ Provider metadata 分别保留 `requestedServiceTier` 与 `upstreamServiceTier`
版本接口只读本地构建和通道摘要,缓存未就绪时返回 `updateCached=false`、`latestVersion=null`。`updateChannel` 按运行版本推导,为 `stable`、`alpha`、`beta`、`rc`、`exp` 或 `unknown` 版本接口只读本地构建和通道摘要,缓存未就绪时返回 `updateCached=false`、`latestVersion=null`。`updateChannel` 按运行版本推导,为 `stable`、`alpha`、`beta`、`rc`、`exp` 或 `unknown`
`restartSupported` 表示部署是否启用在线重启,与是否安装更新无关。`instanceId` 是当前宿主实例的随机标识,在该实例生命周期内保持不变,每次启动重新生成。重启前读取该标识,重启后须同时确认标识已变化且运行版本符合目标,不能仅凭版本号判断同版本重启完成
详情与安装接口的 `channel` 只对本次操作有效,省略时取运行通道。响应的 `policy` 包含 `channel` 和 `availableChannels`。普通实例可选 `stable`、`rc`、`beta`、`alpha`,实验实例仅可选 `exp`。 详情与安装接口的 `channel` 只对本次操作有效,省略时取运行通道。响应的 `policy` 包含 `channel` 和 `availableChannels`。普通实例可选 `stable`、`rc`、`beta`、`alpha`,实验实例仅可选 `exp`。
未知枚举值返回参数错误。禁用通道、跨实验线、跨大版本、降级或同版本重装返回 `40901`。安装时同时提交已确认的 `channel` 和 `targetVersion`,服务端按[升级规则](../deploy/README.md#版本命名与升级规则)复核目标 未知枚举值返回参数错误。禁用通道、跨实验线、跨大版本、降级或同版本重装返回 `40901`。安装时同时提交已确认的 `channel` 和 `targetVersion`,服务端按[升级规则](../deploy/README.md#版本命名与升级规则)复核目标
+12 -4
View File
@@ -231,7 +231,7 @@ flowchart LR
Runtime 将插件改写交回同一设置编译器;API 在认证、版本检查与正文解压前传递有效配置,不按业务接口增加设置包装。HTTP 超时由路由终端消费,`None` 清除本次超时。 Runtime 将插件改写交回同一设置编译器;API 在认证、版本检查与正文解压前传递有效配置,不按业务接口增加设置包装。HTTP 超时由路由终端消费,`None` 清除本次超时。
OpenAI 的 Fast 设置在 attempt 中间件前形成正文基线;OpenAI / xAI 的插件头修改覆盖账号与画像生成的同名头,不按字段名拦截。 OpenAI 的 Fast 设置在 attempt 中间件前形成正文基线;OpenAI / xAI 的插件头修改覆盖账号与画像生成的同名头,不按字段名拦截。
HTTP 正文的寿命覆盖惰性读取,WebSocket 升级后由独立连接取消信号和冻结发布代次接管,101 响应正文结束不会取消会话 HTTP 正文的寿命覆盖惰性读取,WebSocket 升级后由独立连接取消信号和冻结发布代次接管,101 响应正文结束不会取消会话
- **模型设置按请求重算**:Key 自身的画像、Fast 和限额默认值独立保留;`RequestSettings` 统一按宿主默认、当前 Key 默认、插件显式覆盖的顺序解析。 - **模型设置按请求重算**:Key 自身的画像和限额默认值独立保留;`RequestSettings` 统一按宿主默认、当前 Key 默认、插件显式覆盖的顺序解析。Fast 分组默认值在选定账号后计算,请求设置只保留显式覆盖。
认证、插件使用的 `ExecutionSettings` 视图和执行终端共用该规则。设置改写经过编译后由终端复用结果,截止时间仍相对请求开始时刻计算,不发布全局配置。 认证、插件使用的 `ExecutionSettings` 视图和执行终端共用该规则。设置改写经过编译后由终端复用结果,截止时间仍相对请求开始时刻计算,不发布全局配置。
子调用保留显式改写,在目标 Key 作用域重算默认值;Key 限额、Fast 和模型超时的覆盖绑定原 Key,同级调用互不改写。 子调用保留显式改写,在目标 Key 作用域重算默认值;Key 限额、Fast 和模型超时的覆盖绑定原 Key,同级调用互不改写。
原生 Responses WebSocket 每轮从当前快照重新认证,保留握手的显式改写;已经开始的执行不随全局发布改变。具体字段与来源合同见 [SDK 中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#http-入口) 原生 Responses WebSocket 每轮从当前快照重新认证,保留握手的显式改写;已经开始的执行不随全局发布改变。具体字段与来源合同见 [SDK 中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#http-入口)
@@ -555,9 +555,10 @@ Store 将策略与设置 revision 原子持久化;编译结果随快照、计
每条规则跨承载副本原子提交;发送前拒绝携带 `NotSent` 和禁止重试标记。被规则改写的握手头参与 WS 池身份,防止复用旧值, 每条规则跨承载副本原子提交;发送前拒绝携带 `NotSent` 和禁止重试标记。被规则改写的握手头参与 WS 池身份,防止复用旧值,
关闭策略不进入改写管线。字段与执行限制见[隐私策略 API](api.md#隐私策略) 关闭策略不进入改写管线。字段与执行限制见[隐私策略 API](api.md#隐私策略)
Fast 策略由 Core 合并 Client Key 的全部绑定分组并随同一快照链路冻结,禁用分组也参与合并; Fast 分组配置由 Core 随账号目录冻结,选号后通过同一账号范围解析器合并当前 Key 授权该账号与模型的启用分组策略。
不按所选账号的分组重新解释。档位优先级与字段合同见[账号分组 API](api.md#6-账号分组)。 请求设置中的显式 Fast 覆盖优先于分组策略;未覆盖时,换号按新账号重算,仍使用请求开始时的快照,不读取新的全局配置。
OpenAI Provider 在独立编码请求上、生成上游头与观测前统一应用顶层档位覆盖,HTTP、WS 与重试共用。 档位优先级与字段合同见[账号分组 API](api.md#6-账号分组)。
OpenAI Provider 在选定账号后、attempt 中间件前应用顶层档位覆盖,HTTP、WS 与重试共用;上游适配器取得同一账号与模型的有效策略。
该策略不改变选号、会话亲和或共享原始请求;每个新 WS 请求重新取得当前策略。 该策略不改变选号、会话亲和或共享原始请求;每个新 WS 请求重新取得当前策略。
WS 路由提示属于握手,连接复用时不重发;档位变化不重建连接或打断 `previous_response_id` 续写, WS 路由提示属于握手,连接复用时不重发;档位变化不重建连接或打断 `previous_response_id` 续写,
各帧正文及计费仍使用本次请求的最终档位 各帧正文及计费仍使用本次请求的最终档位
@@ -809,6 +810,7 @@ Continuation 受原请求的 Client Key、账号范围、Provider 和发送/交
- OpenAI Provider 在发送前按上游握手声明的消息大小上限检查最终出站帧,新链可选择 HTTP;超限的 connection-local - OpenAI Provider 在发送前按上游握手声明的消息大小上限检查最终出站帧,新链可选择 HTTP;超限的 connection-local
续接和已标记为需要重放的 HTTP/WS 增量返回 `ClientReplayRequired`,由客户端重发 续接和已标记为需要重放的 HTTP/WS 增量返回 `ClientReplayRequired`,由客户端重发
完整历史。预检拒绝先释放连接及租约,不消耗 WS 故障预算;Provider session state 只携带元数据,不保存 transcript 完整历史。预检拒绝先释放连接及租约,不消耗 WS 故障预算;Provider session state 只携带元数据,不保存 transcript
- Codex OAuth 的 HTTP 全量历史由独占租用的上游 WS 比较。连接只持有上一轮的响应 ID、项数和绑定 Client Key 与请求属性的前缀摘要,随连接回收;增量只改写出站帧,本次完整请求仍可用于安全回退
- OpenAI 在有效输出交付前收到可安全重放的明确额度拒绝时,先隔离账号,再投影 `ClientReplayRequired`; - OpenAI 在有效输出交付前收到可安全重放的明确额度拒绝时,先隔离账号,再投影 `ClientReplayRequired`;
丢弃未交付的原错误帧,由客户端提交完整历史开启新链,不把原增量输入交给其他账号。 丢弃未交付的原错误帧,由客户端提交完整历史开启新链,不把原增量输入交给其他账号。
真实错误分类、状态码、发送状态和上游诊断保持不变,客户端合同见 [Responses API](api.md#3-模型数据面与模型目录) 真实错误分类、状态码、发送状态和上游诊断保持不变,客户端合同见 [Responses API](api.md#3-模型数据面与模型目录)
@@ -1365,6 +1367,11 @@ API 输出模型执行与上游请求的关联信息,具体响应头规则见
失败终态及中间失败的上游请求 ID 优先取对应 `ProviderError`,缺失时再取该 attempt 的响应 失败终态及中间失败的上游请求 ID 优先取对应 `ProviderError`,缺失时再取该 attempt 的响应
observation、调用 metadata;最终失败的关联头不与 opening 身份混合 observation、调用 metadata;最终失败的关联头不与 opening 身份混合
Responses HTTP 的 `request_trace` 按入口 ID 记录正文接收、认证、解压、解码和执行准备阶段。
`http.body.received` 的 `receive_ms` 从入口 middleware 开始,覆盖正文读取及 extractor 开销;
`encoded_bytes` 是解压前实际收到的正文字节数,`http.body.decompressed` 的 `decoded_bytes` 是解压后大小。
这些计时不属于模型执行耗时,也不能单独解释为客户端纯网络上传时间
正常路径的请求行仍在首次合法 ProviderStream 建立后随 attempt 合并创建。已进入 Core 执行会话、 正常路径的请求行仍在首次合法 ProviderStream 建立后随 attempt 合并创建。已进入 Core 执行会话、
但在首次合法冷流建立前发生的无可用账号、准备失败、超时或取消,复用同一请求表补写失败终态与 但在首次合法冷流建立前发生的无可用账号、准备失败、超时或取消,复用同一请求表补写失败终态与
诊断快照;没有实际 attempt 时计数为零,账号与传输保持空值。Provider 的准备过程不得发送本次请求的 诊断快照;没有实际 attempt 时计数为零,账号与传输保持空值。Provider 的准备过程不得发送本次请求的
@@ -1510,6 +1517,7 @@ Core 与 Store 在各自的探针上声明接收请求所需的依赖。API 的
Host 对管理端重启、OS 关闭信号和内部取消使用统一策略:停止监听并拒绝新连接注册, Host 对管理端重启、OS 关闭信号和内部取消使用统一策略:停止监听并拒绝新连接注册,
不等待存量会话,随后在独立预算内取消并等待 Worker 排空队列和完成后台清理。 不等待存量会话,随后在独立预算内取消并等待 Worker 排空队列和完成后台清理。
额度查询、目录同步和冻结探测在关闭时取消,OAuth 刷新停止领取新账号,宿主在关闭预算内等待已开始的令牌交换和写回。逾期任务终止时记录任务标识。
剩余连接随进程退出终止。观测队列和费用 writer 分别收尾,费用被 Store 接管不代表已写入 PostgreSQL; 剩余连接随进程退出终止。观测队列和费用 writer 分别收尾,费用被 Store 接管不代表已写入 PostgreSQL;
排空超时、持续写入失败或进程异常退出时,未落库的观测和费用都可能丢失。 排空超时、持续写入失败或进程异常退出时,未落库的观测和费用都可能丢失。
重启不恢复内存费用队列,也不执行隐式业务重放;费用接管与幂等写入边界见[Client Key 结算](#client-key-限额与结算)。 重启不恢复内存费用队列,也不执行隐式业务重放;费用接管与幂等写入边界见[Client Key 结算](#client-key-限额与结算)。

Some files were not shown because too many files have changed in this diff Show More