Compare commits

...
8 Commits
Author SHA1 Message Date
github-actions[bot] 8b40e707fd chore(release): update release channels to 3.62.1-rc.1 2026-12-05 07:59:21 +00:00
ZyyandCodex 15aabfc861 fix(release): restore GitHub release notes with channel-aware baselines
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:50:18 +08:00
ZyyandCodex 0ebf6739e2 chore: bump version to 3.62.1-rc.1
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:37:36 +08:00
ZyyandCodex b987cca4aa docs(release): base stable version bumps on changes since the last stable release
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:36:01 +08:00
ZyyandCodex 72e82c565e fix(openai): clear only recovery feedback observed before success
Confirm the request still uses the current access token before resetting transient feedback across credential revisions. Track the latest 401 independently from Cloudflare streaks so an overlapping failure cannot suppress or be erased by a successful request.

Co-authored-by: Codex <noreply@openai.com>
2026-12-05 15:30:10 +08:00
47ccdeb737 fix(openai): preserve OAuth recovery and token rotation (#853)
* fix(openai): refresh OAuth tokens rejected before expiry

A 401 on a model request marked a refreshable OAuth account Expired when
its access token had not reached its expiry. Expired accounts are left out
of both selection and scheduled refresh, so the account stayed out of
rotation until it was refreshed by hand, even though the refresh token was
still valid.

Expire the rejected access token instead and let the OAuth worker renew
it, as quota refresh already does for token_revoked. A renewed token that
is rejected again before any successful request still marks the account
Expired.

Constraint: Accounts without a refresh token or a known expiry keep the existing Expired outcome
Rejected: Match the "status=503" text inside the 401 body | free-text matching, and other 401s on unexpired tokens would still strand the account
Rejected: Refresh on every 401 without a bound | an account whose renewed tokens keep failing would refresh in a loop
Confidence: high
Scope-risk: narrow
Tested: Rust 1.99.1 fmt --check; clippy -p provider-openai --all-targets --all-features -D warnings; provider-openai tests (1264 passed); the new selector case and the adapter case fail without the selector change
Not-tested: A live upstream 401 against this build; workspace-wide clippy and tests are left to CI

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(openai): preserve OAuth recovery across concurrent feedback

Report success from native endpoints and upstream adapters, and keep stale
responses from clearing the current OAuth recovery bound. Serialize model
401 and Cookie feedback with token refresh through the account lease.
Recheck credential revisions after acquiring scheduled and manual refresh
leases so a queued snapshot cannot resend an already rotated refresh token.

Cookie feedback skips writes while refresh owns the lease; a later response
can capture cookies without discarding successfully exchanged tokens.

Validated: workspace fmt and strict Clippy; 1265 provider-openai tests;
48 gateway architecture and bootstrap tests. Real upstream and store service
integration remain for live verification and CI.

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

* fix(openai): retain token recovery across cookie revisions

Use the access token and revision that were sent upstream to recognize a successful OAuth request after a concurrent cookie write. Keep account and quota recovery fenced by revision, and preserve newer rejection records and replies from superseded tokens.

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

* fix(openai): preserve account feedback across cookie writes

Reset consecutive Cloudflare failures on a successful request using the current access token. Keep quota and account state fenced by the response revision. A model 401 can shorten expiry while the cookie writer holds the refresh lease; a conflicting write is retried only for the same token.

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

* test(openai): separate risk counters from OAuth rejection

Verify that a successful request using the rejected token breaks a path-block streak without allowing a refreshed token to be rejected indefinitely.

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

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 14:00:11 +08:00
ZyyandCodex b20b0e2013 fix(release): freeze complete notes and expose backend validation
Co-authored-by: Codex <noreply@openai.com>
2026-12-05 02:09:06 +08:00
github-actions[bot] 16fc302d46 chore(release): update release channels to 3.62.0 2026-12-04 17:37:26 +00:00
28 changed files with 1357 additions and 239 deletions

No files matched your search

@@ -20,7 +20,7 @@
调用入口前重新核对当前脚本的副作用、目标版本和待推送提交,保留无关工作区内容,不自动清理或暂存用户文件。
先编辑 `release/notes.md`,保留为未提交改动(已暂存或未暂存均可);其他已跟踪文件的改动应先单独提交。
脚本只改 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,将这些差异与最终工作区中的发布说明一起提交为 `chore: bump version to <version>`。
脚本更新 `release/version.yaml` 的顶层 `version`,按[接口弃用规则](../../../../backend/crates/gateway-plugin/sdk/docs/manifest.md#接口弃用)校验并维护 `plugin-api-deprecations.json`,与手写发布说明一起提交为 `chore: bump version to <version>`。
不要提前单独提交说明或把版本文件改成目标版本;脚本要求说明相对 HEAD 有改动,并自行更新版本号。
本任务需要的提交按[项目约定](../../../../CONTRIBUTING.md#项目约定)保留英文 Conventional Commits 与相应署名。
@@ -31,7 +31,7 @@ release/publish "$release_version"
```
该命令会创建上述版本提交与 annotated tag,原子推送分支和 tag,再从长期分支手动触发 `release.yml`。
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的说明,修改 tag 之后的本地文件不会改变该次构建。
只读预检使用 `release/publish --check "$release_version"`。发布工作流读取 tag 中的手写说明,为常规版本追加安装入口、文档和 GitHub 变更列表。
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
@@ -60,7 +60,8 @@ release/publish "$release_version"
### 验收
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
手写正文应与 tag 内的说明一致,核对安装入口和 `Full Changelog` 指向目标版本,正式版的比较范围从上一正式版开始
- 核对 `backend-validation` 的结果。复用时检查摘要中的源码提交和成功 CI 链接,确认发行提交仅修改版本与说明;未满足复用条件时检查本次完整后端任务,不能把 `quality / backend` 的跳过单独记为测试通过
- 回读 `main:release/version.yaml` 的 `published`。正式版参与同一大版本四个普通通道的比较;RC 参与 RC、Beta、Alpha,Beta 参与 Beta、Alpha,Alpha 只参与自身。实验版只推进 `exp["X.Y.Z"]`。有通道推进时应有 `chore(release): update release channels to <version>` 提交;重复执行或较旧版本未推进任何通道时无提交
- 正式版提升或恢复后,回读 GitHub Latest 的 tag 与镜像 `latest` 的摘要,核对两者均指向预期正式版
- 保留 v3.42.0 在线升级使用的 `update-index` 页面和 v3.42.1 的 `version.yaml` 附件
@@ -9,12 +9,20 @@
3. 使用用户确定的目标版本,建议版本时说明兼容性、能力或修复依据;同名 tag 先区分重试与新发行,不递增版本掩盖冲突
4. 命名与晋级按[版本命名与升级规则](../../../../deploy/README.md#版本命名与升级规则),实验版另读[实验流程](experimental.md#分支与版本)
对比基线选自已公开且 tag 位于目标提交历史内的 GitHub Release
- 推荐正式版号和编写发布说明时,都核对上一正式版到目标提交的最终差异,覆盖期间全部预发行。对于向后兼容的变更,只要有用户可用的新功能,就从上一正式版递增 minor 并将 patch 归零,仅含修复则递增 patch
- alpha、beta、rc 优先对比同一 `X.Y.Z` 的上一常规预发行,没有时对比上一正式版
- exp 对比同一 `X.Y.Z` 的上一实验版,首次实验对比同号正式版
- 没有前序发行的首次发布从仓库起点核对
## 发布说明
读取当前 [notes.md](../../../../release/notes.md)与[项目约定](../../../../CONTRIBUTING.md#项目约定)中的发布说明条目
- 只在发布说明任务中修改 `release/notes.md`,替换为本次版本内容,首行为目标 tag,正文使用中文
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
- 常规版本的安装入口、文档链接和 GitHub 变更列表由工作流在发版时追加
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
@@ -31,7 +39,7 @@
在上一发行基线到 HEAD 的提交中检查是否已有目标版本的备版提交(`chore: bump version to <version>`;查历史时也匹配 `chore(release): prepare v<version>` 和 `chore(release): v<version>`),即使同名 tag 已不存在也要查。命中时先核对该提交对应的发行状态,按[失败恢复](operations.md#恢复与验收)处理,不在旧提交上再叠一个同名提交
发布说明准备好、其他代码已提交后,执行 `release/publish --check <version>`,检查版本、说明、工作区、远端分支与 tag、工具链和插件兼容窗口。
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时先同步再检查。它不替代 CI、发行物验证或实际发布授权
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
+25 -6
View File
@@ -91,17 +91,36 @@ module ReleaseMetadata
"#{APP_NAME}_#{version}_#{platform.fetch('os')}_#{platform.fetch('arch')}.#{platform.fetch('archive')}"
end
# 正式版始终对比上一正式版,常规预发行优先对比同一目标版本的上一预发行
def self.previous_tag(value)
return if value.include?('-exp.')
endpoint = "repos/#{ENV.fetch('GITHUB_REPOSITORY')}/releases?per_page=100"
output, status = Open3.capture2('gh', 'api', '--paginate', endpoint, '--jq',
'.[] | select(.draft == false) | [.tag_name, .prerelease] | @tsv')
raise 'Failed to read published releases' unless status.success?
reachable = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip)
candidates = output.each_line.each_with_object([]) do |line, tags|
tag, prerelease = line.chomp.split("\t")
next unless reachable.include?(tag) && tag.delete_prefix('v').match?(SEMVER) && !tag.include?('+')
next unless prerelease?(tag) == (prerelease == 'true') && sort_key(tag) < sort_key(value)
tags << tag
end
if prerelease?(value)
prefix = "v#{value.split('-', 2).first}-"
previous = candidates.select { |tag| tag.start_with?(prefix) && !tag.include?('-exp.') }.max_by { |tag| sort_key(tag) }
return previous if previous
end
candidates.reject { |tag| prerelease?(tag) }.max_by { |tag| sort_key(tag) }
end
def self.outputs(tag)
value = release_version(YAML.load_file('release/version.yaml').fetch('version'))
raise "Release tag #{tag} does not match v#{value}" unless tag == "v#{value}"
validate_notes(value)
entries = platforms
docker, native = entries.partition { |entry| entry['docker'] == true }
previous = git('tag', '--list', 'v*', '--merged', 'HEAD').lines.map(&:strip).filter_map do |candidate|
next unless candidate.delete_prefix('v').match?(SEMVER)
key = sort_key(candidate)
[key, candidate] if key < sort_key(value)
end.max_by(&:first)&.last
{
'tag' => tag,
'version' => value,
@@ -112,7 +131,7 @@ module ReleaseMetadata
'non_docker_matrix' => JSON.generate('include' => native),
'windows_matrix' => JSON.generate('include' => entries.select { |entry| entry['os'] == 'windows' }),
'docker_platforms' => docker.map { |entry| entry['dockerPlatform'] }.join(','),
'previous_tag' => previous,
'previous_tag' => previous_tag(value),
'prerelease' => prerelease?(value),
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
}
+4 -2
View File
@@ -25,7 +25,7 @@ module ReleaseQuality
rows = capture('gh', 'api', '--paginate', "repos/#{repository}/actions/runs/#{run.fetch('id')}/jobs?per_page=100", '--jq', '.jobs[] | @json')
job = rows.lines.map { |line| JSON.parse(line) }.find { |entry| entry.fetch('name') == 'quality / backend' }
return nil unless job && job.fetch('conclusion') == 'success'
job.fetch('html_url')
{ 'sha' => parent, 'url' => job.fetch('html_url') }
end
end
@@ -37,8 +37,10 @@ if $PROGRAM_NAME == __FILE__
evidence = nil
end
puts "run_backend=#{evidence.nil?}"
puts "backend_source_sha=#{evidence ? evidence.fetch('sha') : ReleaseQuality.capture('git', 'rev-parse', 'HEAD').strip}"
puts "backend_evidence_url=#{evidence ? evidence.fetch('url') : ''}"
if ENV['GITHUB_STEP_SUMMARY']
message = evidence ? "后端质量检查复用版本提交父提交的 [CI 结果](#{evidence});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
message = evidence ? "后端质量检查复用 `#{evidence.fetch('sha')}` 的[成功 CI](#{evidence.fetch('url')});仅版本与发布说明不同" : '未找到可复用的后端 CI 结果,完整检查发行提交'
File.open(ENV.fetch('GITHUB_STEP_SUMMARY'), 'a') { |file| file.puts(message) }
end
end
+38 -3
View File
@@ -51,6 +51,8 @@ jobs:
rust: ${{ steps.toolchains.outputs.rust }}
rust_image: ${{ steps.toolchains.outputs.rust_image }}
run_backend: ${{ steps.quality.outputs.run_backend }}
backend_source_sha: ${{ steps.quality.outputs.backend_source_sha }}
backend_evidence_url: ${{ steps.quality.outputs.backend_evidence_url }}
steps:
- name: Checkout
@@ -68,6 +70,7 @@ jobs:
- name: Read release metadata and seal plugin manifest
id: version
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ inputs.tag }}
run: ruby .github/scripts/release-metadata.rb outputs "$RELEASE_TAG" >> "$GITHUB_OUTPUT"
@@ -97,6 +100,31 @@ jobs:
run_backend: ${{ needs.release-info.outputs.run_backend == 'true' }}
run_frontend: false
backend-validation:
name: backend-validation (${{ needs.release-info.outputs.run_backend == 'true' && 'current release' || 'reused CI' }})
needs: [release-info, quality]
if: ${{ !cancelled() && needs.release-info.result == 'success' }}
runs-on: ubuntu-26.04
timeout-minutes: 5
steps:
- name: Report backend validation evidence
env:
QUALITY_RESULT: ${{ needs.quality.result }}
RUN_BACKEND: ${{ needs.release-info.outputs.run_backend }}
SOURCE_SHA: ${{ needs.release-info.outputs.backend_source_sha }}
EVIDENCE_URL: ${{ needs.release-info.outputs.backend_evidence_url }}
run: |
if [ "$QUALITY_RESULT" != success ]; then
echo "后端质量检查未通过:$QUALITY_RESULT" | tee -a "$GITHUB_STEP_SUMMARY"
exit 1
fi
if [ "$RUN_BACKEND" = true ]; then
echo "后端质量检查已执行并通过,提交:\`$SOURCE_SHA\`" | tee -a "$GITHUB_STEP_SUMMARY"
else
test -n "$EVIDENCE_URL"
echo "后端质量检查复用 \`$SOURCE_SHA\` 的[成功 CI]($EVIDENCE_URL);发行提交仅版本与发布说明不同" | tee -a "$GITHUB_STEP_SUMMARY"
fi
windows:
needs: release-info
name: windows-tests (${{ matrix.arch }})
@@ -411,7 +439,7 @@ jobs:
group: release-publication
queue: max
# 产物准备可与测试重叠,版本标签和 GitHub Release 必须等全部质量与镜像验证通过
needs: [release-info, quality, windows, security, package-assets, build-docker-image]
needs: [release-info, backend-validation, windows, security, package-assets, build-docker-image]
runs-on: ubuntu-26.04
timeout-minutes: 20
permissions:
@@ -522,6 +550,8 @@ jobs:
- name: Prepare release notes
shell: bash
env:
PREVIOUS_TAG: ${{ needs.release-info.outputs.previous_tag }}
RELEASE_TAG: ${{ needs.release-info.outputs.tag }}
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
INSTALLATION_NOTES: |
## Linux 一键安装(Docker Compose)
@@ -537,7 +567,12 @@ jobs:
run: |
ruby <<'RUBY'
notes = File.readlines('release/notes.md').drop(1).join.strip
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}" unless ENV.fetch('BUILD_TYPE') == 'experimental'
unless ENV.fetch('BUILD_TYPE') == 'experimental'
notes += "\n\n#{ENV.fetch('INSTALLATION_NOTES').strip}"
if ENV.fetch('PREVIOUS_TAG').empty?
notes += "\n\n**Full Changelog**: https://github.com/#{ENV.fetch('GITHUB_REPOSITORY')}/commits/#{ENV.fetch('RELEASE_TAG')}"
end
end
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
File.write(output, "#{notes}\n")
RUBY
@@ -552,7 +587,7 @@ jobs:
uses: softprops/action-gh-release@8a0cd651e5b2365bd640854a3fa5dfc70e4875f3 # v3.0.4
with:
tag_name: ${{ needs.release-info.outputs.tag }}
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' }}
generate_release_notes: ${{ needs.release-info.outputs.build_type != 'experimental' && needs.release-info.outputs.previous_tag != '' }}
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
+2 -2
View File
@@ -122,7 +122,7 @@ PR 不接受以下协作规则文件的新增、修改、删除或重命名:
- 业务数据的解析、校验和展示优先复用已有逻辑。新增抽象放在拥有该职责的模块,避免重复事实源或无实际需求的通用层
- 新增代码注释使用中文。提交信息使用英文 Conventional Commits,参考近期历史,按完整功能归并
- AI 参与的提交按实际助手添加 `Co-authored-by: 名称 <邮箱>`,名称与邮箱采用该助手已知的署名身份,并保留其他实际共同作者署名;PR 的 AI 使用披露不替代提交署名
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项
- 发布说明写入 `release/notes.md`,标题首行为目标版本的 `# vX.Y.Z`,手写章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项。常规版本由发布工作流追加安装入口、文档链接和 GitHub 变更列表,比较基线见[版本与说明准备](.agents/skills/cpr-release/references/preparation.md)
- PR 聚焦目标;无关格式化、重构和依赖升级单独处理
## 文档职责与更新条件
@@ -229,7 +229,7 @@ git diff --check
常规容器检查与发行构建共用二进制构建入口,并复用已检查的前端产物;Dockerfile、工具链、依赖或构建配置变化时执行完整源码镜像构建,定期安全检查也覆盖源码构建。两条路径均验证容器运行、安全扫描与关闭行为
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
发行构建与质量检查并行,Windows 两种架构的插件与系统更新测试独立运行。仅当发行提交只修改版本与发布说明,且其父提交有本仓库主分支成功的后端 CI 时复用该结果;缺少证据则完整重跑。`backend-validation` 明确报告本次执行或复用结果,复用时列出被验证的源码提交和 CI 链接。对外发布等待质量、Windows 测试、依赖审计和镜像验证全部成功,构建耗时与测试报告保留 7 天
新增自动规则优先使用现有工具,要求依据明确、结果稳定、误报可控;无法可靠判定的设计与视觉问题保留审查判断,避免把具体源码写法锁成测试
@@ -689,9 +689,19 @@ impl ProviderAdmin for OpenAiAdminProvider {
return Err(provider_admin_error(ProviderAdminErrorKind::Conflict)
.with_public_message("凭据已更新,请刷新账号列表"));
}
let guards = self
.credentials
.acquire_refresh_guards(&current.account)
.await
.map_err(map_credential_admin_error)?;
let current = self
.accounts
.load_credential(&account_id, current.account.revision())
.await
.map_err(map_store_error)?;
let prepared = self
.credentials
.manual_refresh(current)
.manual_refresh(current, guards)
.await
.map_err(map_credential_admin_error)?;
prepared_rotation(prepared, command.account.provider_kind)
@@ -281,7 +281,7 @@ pub struct PreparedCodexCredentialRotation {
refresh_guards: Option<ProviderRefreshGuards>,
}
struct ProviderRefreshGuards {
pub(crate) struct ProviderRefreshGuards {
_capacity: Box<dyn ProviderLeaseGuard>,
_account: Box<dyn ProviderLeaseGuard>,
}
@@ -844,26 +844,13 @@ impl CodexCredentialAdminService {
self
}
/// 官方 RT exchange;结果由 App 在同一 revision/audit 事务中提交
pub async fn manual_refresh(
/// 调用方必须在取得租约后重新读取凭据,并让租约覆盖交换与提交
pub(crate) async fn acquire_refresh_guards(
&self,
current: LoadedCredential,
) -> Result<PreparedCodexCredentialRotation, CodexCredentialAdminError> {
let account_id = current.account.id().clone();
let expected_revision = current.account.revision();
if current.account.provider().as_str() != PROVIDER_NAME {
return Err(CodexCredentialAdminError::NotFound);
}
let runtime = CodexCredentialCodec::decode(&current.credential)
.map_err(|_| CodexCredentialAdminError::InvalidCredential)?;
let oauth = runtime
.authentication
.oauth()
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
let refresh_token = oauth
.refresh_token
.as_ref()
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
account: &ProviderAccount,
) -> Result<ProviderRefreshGuards, CodexCredentialAdminError> {
let account_id = account.id();
let expected_revision = account.revision();
let policy = self
.runtime_policy
.load_refresh_policy()
@@ -895,6 +882,32 @@ impl CodexCredentialAdminService {
return Err(CodexCredentialAdminError::RefreshLeaseUnavailable);
}
};
Ok(ProviderRefreshGuards {
_capacity: capacity_guard,
_account: account_guard,
})
}
/// 官方 RT exchange;结果由 App 在同一 revision/audit 事务中提交
pub(crate) async fn manual_refresh(
&self,
current: LoadedCredential,
guards: ProviderRefreshGuards,
) -> Result<PreparedCodexCredentialRotation, CodexCredentialAdminError> {
let account_id = current.account.id().clone();
if current.account.provider().as_str() != PROVIDER_NAME {
return Err(CodexCredentialAdminError::NotFound);
}
let runtime = CodexCredentialCodec::decode(&current.credential)
.map_err(|_| CodexCredentialAdminError::InvalidCredential)?;
let oauth = runtime
.authentication
.oauth()
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
let refresh_token = oauth
.refresh_token
.as_ref()
.ok_or(CodexCredentialAdminError::MissingRefreshToken)?;
let tokens = self
.refresher
.refresh_with_proxy(
@@ -951,10 +964,7 @@ impl CodexCredentialAdminService {
access_token_expires_at,
next_refresh_at,
)?;
prepared.refresh_guards = Some(ProviderRefreshGuards {
_capacity: capacity_guard,
_account: account_guard,
});
prepared.refresh_guards = Some(guards);
Ok(prepared)
}
@@ -10,6 +10,7 @@ mod eligibility;
mod oauth;
mod profile_statistics;
mod quota;
mod recovery_feedback;
mod recovery_log;
mod refresh;
mod repository;
@@ -0,0 +1,167 @@
//! OpenAI 账号的 OAuth 拒绝记录与 Cloudflare 连续失败反馈
use std::collections::{HashMap, VecDeque};
use std::time::{Duration, SystemTime};
use gateway_core::account::{CredentialRevision, ProviderAccountId};
const STALE_AFTER: Duration = Duration::from_secs(60 * 60);
const CHALLENGE_BACKOFF: [Duration; 4] = [
Duration::from_secs(10),
Duration::from_secs(30),
Duration::from_secs(90),
Duration::from_secs(120),
];
const PATH_BLOCK_THRESHOLD: usize = 3;
#[derive(Default)]
pub(super) struct RecoveryFeedback {
// 跨账号条目重建仍保持顺序,较早的成功不能清除后来创建的记录
last_observation: u64,
accounts: HashMap<ProviderAccountId, AccountFeedback>,
}
struct AccountFeedback {
observed_at: SystemTime,
rejection: Option<TokenRejection>,
challenges: VecDeque<u64>,
path_blocks: VecDeque<u64>,
}
#[derive(Clone, Copy)]
struct TokenRejection {
/// 首次被拒并交给续期的版本;后续 401 不会再授予一次续期
refresh_requested_at: CredentialRevision,
last_observation: u64,
}
impl AccountFeedback {
fn is_active(&self, now: SystemTime) -> bool {
!matches!(now.duration_since(self.observed_at), Ok(age) if age > STALE_AFTER)
}
}
// 超过最大退避或失效阈值的旧失败不会再影响决策
fn record_failure(streak: &mut VecDeque<u64>, observation: u64, limit: usize) -> usize {
if streak.len() == limit {
streak.pop_front();
}
streak.push_back(observation);
streak.len()
}
impl RecoveryFeedback {
fn active_account(
&mut self,
id: &ProviderAccountId,
now: SystemTime,
) -> Option<&AccountFeedback> {
if !self.accounts.get(id)?.is_active(now) {
self.accounts.remove(id);
return None;
}
self.accounts.get(id)
}
fn next_failure(
&mut self,
id: &ProviderAccountId,
now: SystemTime,
) -> (u64, &mut AccountFeedback) {
self.accounts.retain(|_, state| state.is_active(now));
self.last_observation += 1;
let state = self
.accounts
.entry(id.clone())
.or_insert_with(|| AccountFeedback {
observed_at: now,
rejection: None,
challenges: VecDeque::new(),
path_blocks: VecDeque::new(),
});
state.observed_at = now;
(self.last_observation, state)
}
pub(super) fn challenge_delay(
&mut self,
id: &ProviderAccountId,
now: SystemTime,
retry_after: Option<Duration>,
) -> Duration {
let (order, state) = self.next_failure(id, now);
let count = record_failure(&mut state.challenges, order, CHALLENGE_BACKOFF.len());
retry_after
.unwrap_or_default()
.max(CHALLENGE_BACKOFF[count - 1])
}
pub(super) fn path_block_reached_limit(
&mut self,
id: &ProviderAccountId,
now: SystemTime,
) -> bool {
let (order, state) = self.next_failure(id, now);
record_failure(&mut state.path_blocks, order, PATH_BLOCK_THRESHOLD) == PATH_BLOCK_THRESHOLD
}
pub(super) fn pending_refresh(
&mut self,
id: &ProviderAccountId,
now: SystemTime,
) -> Option<CredentialRevision> {
self.active_account(id, now)?
.rejection
.map(|rejected| rejected.refresh_requested_at)
}
pub(super) fn record_rejection(
&mut self,
id: &ProviderAccountId,
refresh_requested_at: CredentialRevision,
now: SystemTime,
) {
let (order, state) = self.next_failure(id, now);
if state
.rejection
.is_none_or(|rejected| rejected.refresh_requested_at <= refresh_requested_at)
{
state.rejection = Some(TokenRejection {
refresh_requested_at,
last_observation: order,
});
}
}
/// 在任何异步核对之前记下已观察到的失败范围
pub(super) fn success_boundary(
&mut self,
id: &ProviderAccountId,
now: SystemTime,
) -> Option<u64> {
self.active_account(id, now)?;
Some(self.last_observation)
}
pub(super) fn confirm_success(
&mut self,
id: &ProviderAccountId,
through: u64,
sent: CredentialRevision,
) {
let Some(state) = self.accounts.get_mut(id) else {
return;
};
if state.rejection.is_some_and(|rejected| {
rejected.refresh_requested_at < sent && rejected.last_observation <= through
}) {
state.rejection = None;
}
state.challenges.retain(|order| *order > through);
state.path_blocks.retain(|order| *order > through);
if state.challenges.is_empty() && state.path_blocks.is_empty() && state.rejection.is_none()
{
self.accounts.remove(id);
}
}
}
@@ -330,6 +330,14 @@ impl CodexCredentialRefreshService {
return Ok(CodexCredentialRefreshOutcome::LeaseUnavailable { account_id });
}
};
// 候选快照在取锁前读取,其他刷新或 Cookie 写回可能已推进版本
match self.repository.load_complete_data(&due.account).await {
Ok(_) => {}
Err(CredentialRepositoryError::RevisionConflict(_)) => {
return Ok(CodexCredentialRefreshOutcome::Stale { account_id });
}
Err(error) => return Err(error.into()),
}
let refresh_token = due
.secret
.refresh_token
@@ -27,9 +27,10 @@ use gateway_core::engine::{
use gateway_core::provider_ports::{
ProviderAccountAdmission, ProviderConcurrencyPool, ProviderCooldownPort, ProviderCooldownScope,
ProviderLeaseAcquisition, ProviderLeaseGuard, ProviderLeasePort, ProviderLeaseRequest,
ProviderSchedulingLeaseRequest, ProviderScopedCooldown, ProviderSessionAffinityKey,
ProviderSessionAffinityPort, ProviderSessionBinding, ProviderSessionClaim,
ProviderSessionExclusionPort, ProviderSessionExclusions, ProviderStoreError,
ProviderRefreshLeaseRequest, ProviderSchedulingLeaseRequest, ProviderScopedCooldown,
ProviderSessionAffinityKey, ProviderSessionAffinityPort, ProviderSessionBinding,
ProviderSessionClaim, ProviderSessionExclusionPort, ProviderSessionExclusions,
ProviderStoreError,
};
use gateway_core::routing::{ProviderKind, UpstreamModelId};
use secrecy::ExposeSecret;
@@ -42,6 +43,7 @@ use super::codec::CodexRuntimeAuthentication;
use super::cookie::CodexCookiePolicy;
use super::eligibility::{CodexSelectionModel, NativeProtocol};
use super::quota::CodexCredentialQuotaService;
use super::recovery_feedback::RecoveryFeedback;
use super::refresh::refresh_recovery_deadline;
use super::repository::{CodexCredentialRepository, CredentialRepositoryError};
use super::scheduling_projection::{SchedulingProjectionCache, SchedulingProjectionKey};
@@ -49,14 +51,6 @@ use super::types::{
CODEX_AUTHENTICATION_KIND_OAUTH, CodexCookie, CodexCookieCaptureOutcome, RuntimeCodexCookie,
};
const CLOUDFLARE_RECOVERY_STALE_AFTER: Duration = Duration::from_secs(60 * 60);
const CLOUDFLARE_CHALLENGE_BACKOFF: [Duration; 4] = [
Duration::from_secs(10),
Duration::from_secs(30),
Duration::from_secs(90),
Duration::from_secs(120),
];
const CLOUDFLARE_PATH_BLOCK_THRESHOLD: u32 = 3;
// 绑定失败会阻止发送,预算容纳短暂调度抖动;可丢失的策略排除记录保持独立预算
const SESSION_AFFINITY_TIMEOUT: Duration = Duration::from_millis(500);
const CYBER_POLICY_TIMEOUT: Duration = Duration::from_millis(100);
@@ -96,13 +90,6 @@ pub enum CodexAccountFailure {
CloudflarePathBlocked,
}
#[derive(Debug, Clone, Copy)]
struct RiskRecoveryState {
challenge_count: u32,
path_block_count: u32,
observed_at: SystemTime,
}
#[derive(Debug, Clone, Copy)]
enum CookieRecovery {
ExpireAt(SystemTime),
@@ -155,7 +142,7 @@ pub struct CodexCredentialSelector {
cooldowns: Arc<dyn ProviderCooldownPort>,
upstream_info: Arc<dyn gateway_core::account::UpstreamInfoSource>,
cookie_policy: CodexCookiePolicy,
risk_recovery: Mutex<HashMap<String, RiskRecoveryState>>,
recovery_feedback: Mutex<RecoveryFeedback>,
account_feedback: Arc<AccountFeedbackStats>,
scheduling_projection: SchedulingProjectionCache,
endpoint_protocols:
@@ -333,7 +320,7 @@ impl CodexCredentialSelector {
cooldowns,
upstream_info,
cookie_policy,
risk_recovery: Mutex::new(HashMap::new()),
recovery_feedback: Mutex::default(),
waiting: ConcurrencyWaitQueue::default(),
reserved_waiting: ConcurrencyWaitQueue::default(),
account_feedback,
@@ -1998,6 +1985,7 @@ impl CodexCredentialSelector {
pub async fn record_failure(
&self,
account: &ProviderAccount,
authentication: &CodexRuntimeAuthentication,
failure: CodexAccountFailure,
message: Option<String>,
) -> Result<(), CredentialSelectionError> {
@@ -2005,40 +1993,8 @@ impl CodexCredentialSelector {
let message = message.filter(|value| !value.trim().is_empty());
match failure {
CodexAccountFailure::CredentialExpired => {
if account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH
&& account.has_refresh_token()
&& account
.access_token_expires_at()
.is_some_and(|expires_at| expires_at <= now)
&& refresh_recovery_deadline(account.access_token_expires_at())
.is_some_and(|deadline| deadline > now)
{
tracing::info!(
account_id = %account.id(),
access_token_expires_at = ?account.access_token_expires_at()
.map(chrono::DateTime::<chrono::Utc>::from),
recovery_deadline = ?refresh_recovery_deadline(account.access_token_expires_at())
.map(chrono::DateTime::<chrono::Utc>::from),
"OpenAI access token expired; retaining account for bounded OAuth refresh recovery"
);
return self
.apply_credential_state(
account,
CredentialState::Ready,
AccountErrorReason::AccessTokenExpired,
now,
message,
)
.await;
}
self.apply_credential_state(
account,
CredentialState::Expired,
AccountErrorReason::AccessTokenExpired,
now,
message,
)
.await
self.record_credential_expiry(account, authentication, now, message)
.await
}
CodexAccountFailure::IdentityVerificationRequired => {
self.apply_credential_state(
@@ -2098,7 +2054,9 @@ impl CodexCredentialSelector {
}
// Cloudflare 挑战:内存退避表(记录风险计数),不写账号事实
CodexAccountFailure::CloudflareChallenge { retry_after } => {
let delay = self.cloudflare_challenge_delay(account.id(), now, retry_after);
let delay = self
.feedback()
.challenge_delay(account.id(), now, retry_after);
let recovery = now
.checked_add(delay)
.map_or(CookieRecovery::Clear, CookieRecovery::ExpireAt);
@@ -2107,8 +2065,7 @@ impl CodexCredentialSelector {
}
// Cloudflare 路径被封:连续超阈值才置 Invalid;否则内存退避
CodexAccountFailure::CloudflarePathBlocked => {
let blocked = self.record_cloudflare_path_block(account.id(), now);
if blocked >= CLOUDFLARE_PATH_BLOCK_THRESHOLD {
if self.feedback().path_block_reached_limit(account.id(), now) {
self.apply_credential_state(
account,
CredentialState::Invalid,
@@ -2125,6 +2082,108 @@ impl CodexCredentialSelector {
}
}
async fn record_credential_expiry(
&self,
sent: &ProviderAccount,
authentication: &CodexRuntimeAuthentication,
now: SystemTime,
message: Option<String>,
) -> Result<(), CredentialSelectionError> {
// 空闲时保持到期写入与恢复标记先于 RT exchange;租约忙也不能丢弃 401
let _guard = if sent.has_refresh_token() && authentication.oauth().is_some() {
self.credential_mutation_guard(sent).await?
} else {
None
};
let mut account = std::borrow::Cow::Borrowed(sent);
for _ in 0..=MAX_ACCOUNT_SNAPSHOT_RETRIES {
match self
.apply_credential_expiry(&account, now, message.clone())
.await
{
Ok(true) => return Ok(()),
Ok(false) | Err(CredentialSelectionError::RevisionConflict(_)) => (),
Err(error) => return Err(error),
}
// Cookie CAS 保留到期时间;若它先推进版本,只对仍是出站 AT 的新快照重试
let Some(latest) = self
.current_account_for_token(sent.id(), authentication)
.await?
else {
return Ok(());
};
if latest.revision() == account.revision() {
return Ok(());
}
account = std::borrow::Cow::Owned(latest);
}
Err(CredentialRepositoryError::RevisionConflict(None).into())
}
async fn apply_credential_expiry(
&self,
account: &ProviderAccount,
now: SystemTime,
message: Option<String>,
) -> Result<bool, CredentialSelectionError> {
let expires_at = account.access_token_expires_at().filter(|_| {
account.authentication_kind() == CODEX_AUTHENTICATION_KIND_OAUTH
&& account.has_refresh_token()
});
let pending_refresh =
expires_at.and_then(|_| self.feedback().pending_refresh(account.id(), now));
if expires_at.is_some_and(|expiry| expiry > now)
&& pending_refresh.is_none_or(|rejected| rejected >= account.revision())
{
// 资源服务拒绝未到期的访问令牌不能证明 refresh token 失效
// 让访问令牌到期并交给 OAuth 续期,条件写入不影响已轮换的凭据
let expired = self
.repository
.store()
.expire_access_token(account, now)
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source)))?;
if !expired {
return Ok(false);
}
self.feedback()
.record_rejection(account.id(), account.revision(), now);
tracing::info!(
account_id = %account.id(),
"OpenAI access token rejected before expiry; deferring to OAuth refresh"
);
return Ok(true);
}
let state = if expires_at.is_some_and(|expiry| expiry <= now)
&& refresh_recovery_deadline(expires_at).is_some_and(|deadline| deadline > now)
{
tracing::info!(
account_id = %account.id(),
access_token_expires_at = ?expires_at
.map(chrono::DateTime::<chrono::Utc>::from),
recovery_deadline = ?refresh_recovery_deadline(expires_at)
.map(chrono::DateTime::<chrono::Utc>::from),
"OpenAI access token expired; retaining account for bounded OAuth refresh recovery"
);
CredentialState::Ready
} else {
CredentialState::Expired
};
self.apply_credential_state(
account,
state,
AccountErrorReason::AccessTokenExpired,
now,
message,
)
.await?;
if let Some(rejected) = pending_refresh {
self.feedback()
.record_rejection(account.id(), rejected, now);
}
Ok(true)
}
async fn apply_credential_state(
&self,
account: &ProviderAccount,
@@ -2145,45 +2204,85 @@ impl CodexCredentialSelector {
Ok(())
}
pub async fn record_success(&self, account: &ProviderAccount) {
self.restore_recoverable_account_state(account).await;
self.risk_recovery
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(account.id().as_str());
// 绑定只在发送前认领,迟到的响应不能迁移或复活已经过期的会话绑定
}
async fn restore_recoverable_account_state(&self, account: &ProviderAccount) {
pub async fn record_success(
&self,
account: &ProviderAccount,
sent_revision: CredentialRevision,
authentication: &CodexRuntimeAuthentication,
) {
let boundary = self
.feedback()
.success_boundary(account.id(), SystemTime::now());
let Ok(current) = self.current_account(account.id()).await else {
return;
};
if current.provider() != &self.provider_kind
|| current.revision() != account.revision()
|| !current.enabled()
if current.provider() != &self.provider_kind || !current.enabled() {
return;
}
let same_revision = current.revision() == account.revision();
if same_revision {
self.restore_recoverable_account_state(&current).await;
}
let Some(through) = boundary else {
return;
};
// Cookie 也会推进版本;版本不同时,只有出站 AT 仍在使用才承认这次成功
if !same_revision
&& !matches!(
self.current_account_for_token(account.id(), authentication)
.await,
Ok(Some(_))
)
{
return;
}
self.feedback()
.confirm_success(account.id(), through, sent_revision);
}
async fn current_account_for_token(
&self,
account_id: &ProviderAccountId,
authentication: &CodexRuntimeAuthentication,
) -> Result<Option<ProviderAccount>, CredentialSelectionError> {
let Some(sent) = authentication.oauth() else {
return Ok(None);
};
let loaded = self
.repository
.store()
.load_current_credential(account_id)
.await
.map_err(|error| CredentialSelectionError::Store(ErrorSource::new(error)))?;
let runtime = self.repository.decode_runtime_credential(&loaded)?;
Ok((loaded.account.enabled()
&& runtime.authentication.oauth().is_some_and(|oauth| {
oauth.access_token.expose_secret() == sent.access_token.expose_secret()
}))
.then_some(loaded.account))
}
async fn restore_recoverable_account_state(&self, current: &ProviderAccount) {
let observed_at = SystemTime::now();
if current.credential_state() != CredentialState::Ready
&& let Err(error) = self
.repository
.apply_state(&current, CredentialState::Ready, observed_at)
.apply_state(current, CredentialState::Ready, observed_at)
.await
{
tracing::warn!(
account_id = %account.id(),
account_id = %current.id(),
error = %error,
"OpenAI credential recovery after successful upstream response failed"
);
}
if let Err(error) = self
.quota
.record_successful_inference(&current, observed_at)
.record_successful_inference(current, observed_at)
.await
{
tracing::warn!(
account_id = %account.id(),
account_id = %current.id(),
error = %error,
"OpenAI quota recovery after successful upstream response failed"
);
@@ -2227,6 +2326,13 @@ impl CodexCredentialSelector {
rejected: parsed.rejected,
});
}
let Some(_guard) = self.credential_mutation_guard(account).await? else {
// 刷新正在交换或提交 token,跳过可由后续响应再次捕获的 Cookie
return Ok(CodexCookieCaptureOutcome {
credential_revision: None,
rejected: parsed.rejected,
});
};
let mut data = self.repository.load_complete_data(account).await?;
let Some(cookies) = data.cookies_mut() else {
return Ok(CodexCookieCaptureOutcome {
@@ -2265,36 +2371,28 @@ impl CodexCredentialSelector {
})
}
fn cloudflare_challenge_delay(
&self,
account_id: &ProviderAccountId,
now: SystemTime,
retry_after: Option<Duration>,
) -> Duration {
let mut recovery = self
.risk_recovery
fn feedback(&self) -> std::sync::MutexGuard<'_, RecoveryFeedback> {
self.recovery_feedback
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let state = active_risk_recovery(&mut recovery, account_id.as_str(), now);
state.challenge_count = state.challenge_count.saturating_add(1);
state.observed_at = now;
let index = usize::try_from(state.challenge_count.saturating_sub(1))
.unwrap_or(usize::MAX)
.min(CLOUDFLARE_CHALLENGE_BACKOFF.len() - 1);
retry_after
.unwrap_or_default()
.max(CLOUDFLARE_CHALLENGE_BACKOFF[index])
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn record_cloudflare_path_block(&self, account_id: &ProviderAccountId, now: SystemTime) -> u32 {
let mut recovery = self
.risk_recovery
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let state = active_risk_recovery(&mut recovery, account_id.as_str(), now);
state.path_block_count = state.path_block_count.saturating_add(1);
state.observed_at = now;
state.path_block_count
/// Cookie 写回不能推进正在交换 RT 的凭据版本
async fn credential_mutation_guard(
&self,
account: &ProviderAccount,
) -> Result<Option<Box<dyn ProviderLeaseGuard>>, CredentialSelectionError> {
match self
.leases
.try_acquire(ProviderLeaseRequest::Refresh(
ProviderRefreshLeaseRequest::new(account.id().clone(), account.revision()),
))
.await
.map_err(|source| CredentialSelectionError::Store(ErrorSource::new(source)))?
{
ProviderLeaseAcquisition::Acquired(guard) => Ok(Some(guard)),
ProviderLeaseAcquisition::Busy { .. } => Ok(None),
}
}
async fn apply_cookie_recovery(
@@ -2302,6 +2400,9 @@ impl CodexCredentialSelector {
account: &ProviderAccount,
recovery: CookieRecovery,
) -> Result<(), CredentialSelectionError> {
let Some(_guard) = self.credential_mutation_guard(account).await? else {
return Ok(());
};
let mut data = self.repository.load_complete_data(account).await?;
if data.cookies().is_empty() {
return Ok(());
@@ -2335,24 +2436,6 @@ fn binding_store_error(
)))
}
fn active_risk_recovery<'a>(
recovery: &'a mut HashMap<String, RiskRecoveryState>,
account_id: &str,
now: SystemTime,
) -> &'a mut RiskRecoveryState {
recovery.retain(|_, state| match now.duration_since(state.observed_at) {
Ok(elapsed) => elapsed <= CLOUDFLARE_RECOVERY_STALE_AFTER,
Err(_) => true,
});
recovery
.entry(account_id.to_owned())
.or_insert(RiskRecoveryState {
challenge_count: 0,
path_block_count: 0,
observed_at: now,
})
}
impl fmt::Debug for CodexCredentialSelector {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
@@ -658,6 +658,7 @@ pub(super) fn cold_json_response_stream(request: ColdJsonResponse) -> EventStrea
let allows_account_state_mutation = request.lease.allows_account_state_mutation();
let image_endpoint = matches!(request.endpoint_path, CODEX_IMAGE_GENERATIONS_PATH | CODEX_IMAGE_EDITS_PATH);
let failure_context = OpenAiFailureContext {
authentication: request.lease.authentication(),
client: &request.client,
selector: &request.selector,
quota: &request.quota,
@@ -726,6 +727,7 @@ pub(super) fn cold_json_response_stream(request: ColdJsonResponse) -> EventStrea
yield ProviderEvent::observation(observation);
}
if allows_account_state_mutation {
request.selector.record_success(&active_account, request.lease.account().revision(), request.lease.authentication()).await;
synchronize_passive_quota_headers(
&request.quota,
&active_account,
@@ -831,6 +833,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
let cyber_policy_scope = lease.cyber_policy_scope().cloned();
let allows_account_state_mutation = lease.allows_account_state_mutation();
let failure_context = OpenAiFailureContext {
authentication: lease.authentication(),
client: &client,
image_endpoint: false,
selector: &selector,
@@ -1243,7 +1246,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
// 完成事实交给下游前更新账号健康,绑定已经在发送前完成
let started = Instant::now();
selector
.record_success(&active_account)
.record_success(&active_account, lease.account().revision(), lease.authentication())
.await;
trace.record("provider.account_success", json!({
"durationMs": started.elapsed().as_millis(),
@@ -1377,7 +1380,7 @@ pub(super) fn cold_response_stream(response: ColdResponse) -> EventStream {
if allows_account_state_mutation && completed && terminal_failure.is_none() {
// 尾部 finish() 也可能产出 completed,账号健康更新先于下游 yield
selector
.record_success(&active_account)
.record_success(&active_account, lease.account().revision(), lease.authentication())
.await;
selector
.observe_cyber_policy_success(cyber_policy_scope.as_ref())
@@ -214,6 +214,7 @@ impl ReplayBoundary {
}
pub(super) struct OpenAiFailureContext<'a> {
pub(super) authentication: &'a crate::credential::CodexRuntimeAuthentication,
pub(super) client: &'a CodexBackendClient,
pub(super) selector: &'a CodexCredentialSelector,
pub(super) quota: &'a Arc<CodexCredentialQuotaService>,
@@ -410,7 +411,12 @@ pub(super) async fn apply_failure(
.await;
if let Err(error) = context
.selector
.record_failure(account, account_failure, failure.error_message.clone())
.record_failure(
account,
context.authentication,
account_failure,
failure.error_message.clone(),
)
.await
{
tracing::warn!(
@@ -419,6 +419,7 @@ fn cold_live_call_stream(request: ColdLiveCall) -> EventStream {
let client = request.client.with_request_profile(profile.clone());
let allows_account_state_mutation = request.lease.allows_account_state_mutation();
let failure_context = OpenAiFailureContext {
authentication: request.lease.authentication(),
client: &client,
image_endpoint: false,
selector: &request.selector,
@@ -526,6 +527,9 @@ fn cold_live_call_stream(request: ColdLiveCall) -> EventStream {
);
}
if allows_account_state_mutation {
request.selector.record_success(&active_account, request.lease.account().revision(), request.lease.authentication()).await;
}
let response_meta = ResponseMeta::for_provider_endpoint(&request_id);
yield ProviderEvent::canonical(GatewayEvent::Started(response_meta.clone()));
let wire = ProtocolWireEvent::raw_http_body(OPENAI_PROTOCOL, response.body).map_err(|_| {
@@ -35,6 +35,7 @@ pub(super) struct ColdMessages {
pub(super) fn cold_messages_stream(mut request: ColdMessages) -> EventStream {
Box::pin(async_stream::try_stream! {
let failure_context = OpenAiFailureContext {
authentication: request.lease.authentication(),
client: &request.client, selector: &request.selector, quota: &request.quota,
response_origin: &request.response_origin, cyber_policy_scope: None,
allows_account_state_mutation: request.lease.allows_account_state_mutation(),
@@ -478,7 +479,12 @@ async fn record_message_failure(request: &ColdMessages, error: &ProviderError) {
// 账号写回复用 selector 的凭据 revision 校验,流内错误不能污染已轮换的凭据
if let Err(error) = request
.selector
.record_failure(request.lease.account(), failure, None)
.record_failure(
request.lease.account(),
request.lease.authentication(),
failure,
None,
)
.await
{
tracing::warn!(account_id = %request.lease.account_id(), error = %error, "Failed to record Messages account failure");
@@ -77,7 +77,7 @@ impl CodexProvider {
model,
requested_service_tier,
});
let events = adapter.execute(UpstreamAdapterInvocation {
let mut events = adapter.execute(UpstreamAdapterInvocation {
operation,
headers,
context,
@@ -85,6 +85,20 @@ impl CodexProvider {
account,
});
let mutation = lease.allows_account_state_mutation();
let selector = Arc::clone(&self.selector);
let success_lease = Arc::clone(&lease);
let events: EventStream = Box::pin(async_stream::try_stream! {
while let Some(event) = events.next().await {
let event = event?;
// 适配器的完成事实由宿主在 RPC 成功结束后发布
if mutation && event.canonical_facts().iter()
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
{
selector.record_success(success_lease.account(), success_lease.account().revision(), success_lease.authentication()).await;
}
yield event;
}
});
let stream = ProviderStream::new(metadata, events, lease);
Ok(if mutation {
stream.with_filtered_account_feedback(
@@ -192,7 +206,12 @@ impl UpstreamAccountConnection for SelectedConnection {
let _ = self
.provider
.selector
.record_failure(self.lease.account(), failure, None)
.record_failure(
self.lease.account(),
self.lease.authentication(),
failure,
None,
)
.await;
if error.kind() == ProviderErrorKind::QuotaExhausted {
schedule_authoritative_quota_refresh_after_failure(
@@ -988,7 +988,7 @@ mod errors {
config.config.auth.oauth_token_endpoint = "http://127.0.0.1:0/oauth/token".to_owned();
let bundle = provider_openai::initialize(
config.config,
refresh_ports(store.clone(), false),
refresh_ports(store.clone(), false, false),
Arc::new(gateway_core::account::UpstreamInfoReader::default()),
)
.await
@@ -1025,6 +1025,39 @@ mod errors {
assert!(prepared.facts().preserve_profile);
}
#[tokio::test]
async fn manual_refresh_rechecks_revision_after_acquiring_the_lease() {
let server = MockServer::start().await;
let (_, store, config) = refresh_fixture(&server, false, true).await;
let before = store.account("acct_refresh_error").unwrap();
let bundle = provider_openai::initialize(
config.config,
refresh_ports(store.clone(), false, true),
Arc::new(gateway_core::account::UpstreamInfoReader::default()),
)
.await
.unwrap();
let error = bundle
.admin
.prepare_refresh(PrepareCredentialRefresh {
account: account_record(&before),
})
.await
.unwrap_err();
assert_eq!(error.kind(), Kind::Conflict);
assert!(server.received_requests().await.unwrap().is_empty());
let current = store.account("acct_refresh_error").unwrap();
let data = store
.repository()
.load_complete_data(&current)
.await
.unwrap();
assert_eq!(
data.oauth().unwrap().refresh_token.as_deref(),
Some("rt-concurrent-refresh")
);
}
async fn refresh_fixture(
server: &MockServer,
busy: bool,
@@ -1053,7 +1086,7 @@ mod errors {
config.config.auth.oauth_token_endpoint = format!("{}/oauth/token", server.uri());
let bundle = provider_openai::initialize(
config.config.clone(),
refresh_ports(store.clone(), busy),
refresh_ports(store.clone(), busy, false),
Arc::new(gateway_core::account::UpstreamInfoReader::default()),
)
.await
@@ -1061,10 +1094,18 @@ mod errors {
(bundle, store, config)
}
fn refresh_ports(store: Arc<MemoryAccountStore>, busy: bool) -> ProviderStorePorts {
fn refresh_ports(
store: Arc<MemoryAccountStore>,
busy: bool,
rotate: bool,
) -> ProviderStorePorts {
let rotate_before_acquire = rotate.then(|| store.clone());
ProviderStorePorts::new(
store,
Arc::new(RefreshLeases { busy }),
Arc::new(RefreshLeases {
busy,
rotate_before_acquire,
}),
Arc::new(MemorySessionAffinity::default()),
Arc::new(MemorySessionExclusions::default()),
Arc::new(TestCatalogCache::default()),
@@ -1079,6 +1120,7 @@ mod errors {
struct RefreshLeases {
busy: bool,
rotate_before_acquire: Option<Arc<MemoryAccountStore>>,
}
impl ProviderLeasePort for RefreshLeases {
@@ -1101,6 +1143,21 @@ mod errors {
ProviderLeaseRequest::Refresh(_) | ProviderLeaseRequest::RefreshCapacity(_)
));
Box::pin(async move {
if let (ProviderLeaseRequest::Refresh(request), Some(store)) =
(&request, &self.rotate_before_acquire)
{
let current = store.account(request.account_id().as_str()).unwrap();
store
.repository()
.rotate_refreshed_oauth_secret(
&current,
secret("concurrent-refresh"),
current.access_token_expires_at(),
None,
)
.await
.unwrap();
}
Ok(if self.busy {
ProviderLeaseAcquisition::Busy { retry_after: None }
} else {
@@ -355,7 +355,9 @@ async fn model_cooldown_survives_success_and_only_blocks_the_matching_account_an
Arc::new(AccountFeedbackStats::default()),
cooldowns.clone(),
);
selector.record_success(&account).await;
selector
.record_success(&account, account.revision(), &oauth_auth("test-first"))
.await;
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
let new_session = attempt(BTreeSet::new());
let request = SelectCodexCredential {
@@ -439,7 +441,9 @@ async fn pinned_model_cooldown_returns_retry_after_without_rotating_or_entering_
attempt: &attempt,
session_affinity_key: None,
};
selector.record_success(&account).await;
selector
.record_success(&account, account.revision(), &oauth_auth("test-original"))
.await;
let error = selector.select(&request).await.unwrap_err();
assert!(
matches!(error, CredentialSelectionError::CapacityUnavailable { retry_after: Some(duration) } if duration > Duration::from_secs(55) && duration <= Duration::from_secs(60)),
@@ -33,8 +33,8 @@ use gateway_core::routing::{
use provider_openai::OFFICIAL_CODEX_BASE_URL;
use provider_openai::credential::{
CodexAccountFailure, CodexCookiePolicy, CodexCredentialCodec, CodexCredentialQuotaService,
CodexCredentialSelector, CredentialSelectionError, ImportCodexOAuthCredential,
SelectCodexCredential,
CodexCredentialSelector, CodexRuntimeAuthentication, CredentialSelectionError,
ImportCodexOAuthCredential, SelectCodexCredential,
};
use provider_openai::profile::{CodexWireProfile, CodexWireProfileState};
use secrecy::ExposeSecret;
@@ -46,6 +46,10 @@ use crate::support::{
TestLeaseCoordinator, account_policy, profile, secret,
};
fn oauth_auth(token: &str) -> CodexRuntimeAuthentication {
CodexRuntimeAuthentication::OAuth(secret(token))
}
fn create_account(store: &Arc<MemoryAccountStore>, id: &str, token: &str) {
block_on(store.seed_oauth_credential(ImportCodexOAuthCredential {
account_id: id.to_owned(),
@@ -192,7 +196,7 @@ async fn smart_reselection_respects_native_and_required_account_boundaries() {
}
}
fn selector(
pub(super) fn selector(
store: &Arc<MemoryAccountStore>,
leases: Arc<TestLeaseCoordinator>,
) -> CodexCredentialSelector {
@@ -975,7 +979,9 @@ async fn record_success_should_not_overwrite_a_newer_session_winner() {
.await
.expect("seed newer affinity");
selector.record_success(&first).await;
selector
.record_success(&first, first.revision(), &oauth_auth("at-first"))
.await;
assert_eq!(
affinity
@@ -1011,7 +1017,13 @@ async fn selector_should_reuse_and_renew_the_account_bound_to_the_same_session()
})
.await
.expect("select first account");
selector.record_success(first.account()).await;
selector
.record_success(
first.account(),
first.account().revision(),
first.authentication(),
)
.await;
let first_account = first.account_id().clone();
let second_attempt = attempt(BTreeSet::new());
@@ -1083,7 +1095,13 @@ async fn selector_should_replace_a_busy_affinity_binding_after_the_fallback_succ
})
.await
.expect("select fallback account");
selector.record_success(selected.account()).await;
selector
.record_success(
selected.account(),
selected.account().revision(),
selected.authentication(),
)
.await;
assert_eq!(
(
@@ -1330,7 +1348,16 @@ fn selector_returns_capacity_error_when_every_redis_lease_is_busy() {
#[test]
fn credential_expired_failure_marks_unified_account_expired() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_primary", "at-primary");
let mut token_only = secret("at-primary");
token_only.refresh_token = None;
block_on(store.seed_oauth_credential(ImportCodexOAuthCredential {
account_id: "acct_primary".to_owned(),
name: "acct_primary".to_owned(),
secret: token_only,
verified_account: profile("chatgpt-acct_primary"),
next_refresh_at: None,
enabled: true,
}));
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
let attempt = attempt(BTreeSet::new());
let lease =
@@ -1347,6 +1374,7 @@ fn credential_expired_failure_marks_unified_account_expired() {
.expect("select account");
block_on(selector.record_failure(
lease.account(),
lease.authentication(),
CodexAccountFailure::CredentialExpired,
None,
))
@@ -1366,6 +1394,211 @@ fn credential_expired_failure_marks_unified_account_expired() {
assert_eq!(account.last_error_message(), None);
}
#[test]
fn credential_expired_failure_refreshes_an_unexpired_oauth_token_once() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_primary", "at-primary");
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
let reject = |account: &ProviderAccount, token: &str| {
block_on(selector.record_failure(
account,
&oauth_auth(token),
CodexAccountFailure::CredentialExpired,
None,
))
.expect("record rejected access token");
store.account("acct_primary").expect("account")
};
// 未到期的访问令牌被拒后只提前到期,凭据版本与状态留给 OAuth 续期处理
let before = store.account("acct_primary").expect("account");
let deferred = reject(&before, "at-primary");
assert_eq!(deferred.credential_state(), CredentialState::Ready);
assert_eq!(deferred.revision(), before.revision());
let status = deferred.status_projection(SystemTime::now(), None);
assert_eq!(status.status, gateway_core::account::AccountStatus::Error);
assert_eq!(
status.error_reason,
Some(AccountErrorReason::AccessTokenExpired)
);
// 同一令牌的并发拒绝不消耗续期机会,续期后的令牌再被拒才写入过期
assert_eq!(
reject(&before, "at-primary").credential_state(),
CredentialState::Ready
);
// 同版本成功须中断连续风控失败,但不能证明被拒的 AT 已经续期
let path_block = || {
block_on(selector.record_failure(
&before,
&oauth_auth("at-primary"),
CodexAccountFailure::CloudflarePathBlocked,
None,
))
.unwrap();
};
path_block();
path_block();
block_on(selector.record_success(&before, before.revision(), &oauth_auth("at-primary")));
path_block();
assert_eq!(
store.account("acct_primary").unwrap().credential_state(),
CredentialState::Ready
);
// 旧请求自己的 Cookie 写回推进了反馈版本,但它使用的仍是被拒的 AT
block_on(selector.capture_response_cookies(
&before,
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
&["__cf_bm=test; Path=/; Secure; HttpOnly; Max-Age=3600".to_owned()],
))
.unwrap();
let with_cookie = store.account("acct_primary").unwrap();
assert!(with_cookie.revision() > before.revision());
block_on(selector.record_success(&with_cookie, before.revision(), &oauth_auth("at-primary")));
block_on(store.repository().rotate_refreshed_oauth_secret(
&with_cookie,
secret("at-refreshed"),
Some(SystemTime::now() + Duration::from_secs(3600)),
None,
))
.expect("rotate access token");
let refreshed = store.account("acct_primary").expect("refreshed account");
// 旧令牌迟到的成功、401 均不能清掉新令牌的恢复限制
block_on(selector.record_success(&before, before.revision(), &oauth_auth("at-primary")));
reject(&before, "at-primary");
for _ in 0..2 {
assert_eq!(
reject(&refreshed, "at-refreshed").credential_state(),
CredentialState::Expired
);
}
}
#[test]
fn successful_request_across_cookie_revision_only_rearms_the_same_access_token() {
for token_changed in [false, true] {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_primary", "initial");
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
let current = || store.account("acct_primary").unwrap();
let reject = |account: &ProviderAccount, token: &str| {
block_on(selector.record_failure(
account,
&oauth_auth(token),
CodexAccountFailure::CredentialExpired,
None,
))
.unwrap();
};
let rotate = |access_token| {
block_on(store.repository().rotate_refreshed_oauth_secret(
&current(),
secret(access_token),
Some(SystemTime::now() + Duration::from_secs(3600)),
None,
))
.unwrap();
};
reject(&current(), "initial");
rotate("renewed");
let block_path = |token: &str| {
block_on(selector.record_failure(
&current(),
&oauth_auth(token),
CodexAccountFailure::CloudflarePathBlocked,
None,
))
.unwrap();
};
block_path("renewed");
let in_flight = current();
// 一条并发响应更新 Cookie,另一条流随后用原请求快照报告成功
let cookie = block_on(selector.capture_response_cookies(
&in_flight,
&Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap(),
&["__cf_bm=test; Path=/; Secure; HttpOnly; Max-Age=3600".to_owned()],
))
.unwrap();
assert!(cookie.credential_revision.is_some());
if token_changed {
rotate("replacement");
}
let current_token = if token_changed {
"replacement"
} else {
"renewed"
};
let sent_auth = oauth_auth("renewed");
let release = store.hold_next_current_credential_read();
let mut success =
std::pin::pin!(selector.record_success(&in_flight, in_flight.revision(), &sent_auth));
assert!(futures::FutureExt::now_or_never(success.as_mut()).is_none());
block_path(current_token);
release.send(()).unwrap();
block_on(success);
reject(&current(), current_token);
let after = current();
if token_changed {
assert_eq!(after.credential_state(), CredentialState::Expired);
} else {
assert_eq!(after.credential_state(), CredentialState::Ready);
assert!(after.access_token_expires_at().unwrap() <= SystemTime::now());
}
// 同一 AT 的成功只中断核对开始前的失败,真正旧 AT 的成功不打断任何失败
block_path(current_token);
if !token_changed {
assert_eq!(current().credential_state(), CredentialState::Ready);
block_path(current_token);
}
assert_eq!(current().credential_state(), CredentialState::Invalid);
}
}
#[test]
fn success_does_not_clear_a_rejection_recorded_while_verifying_the_token() {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_primary", "original");
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
let current = || store.account("acct_primary").unwrap();
let reject = |token: &str| {
block_on(selector.record_failure(
&current(),
&oauth_auth(token),
CodexAccountFailure::CredentialExpired,
None,
))
.unwrap();
};
reject("original");
block_on(store.repository().rotate_refreshed_oauth_secret(
&current(),
secret("renewed"),
Some(SystemTime::now() + Duration::from_secs(3600)),
None,
))
.unwrap();
let sent = current();
let auth = oauth_auth("renewed");
block_on(selector.capture_response_cookies(
&sent,
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
&["__cf_bm=test; Path=/; Secure".to_owned()],
))
.unwrap();
let release = store.hold_next_current_credential_read();
let mut success = std::pin::pin!(selector.record_success(&sent, sent.revision(), &auth));
assert!(futures::FutureExt::now_or_never(success.as_mut()).is_none());
reject("renewed");
assert_eq!(current().credential_state(), CredentialState::Expired);
release.send(()).unwrap();
block_on(success);
// 早先的成功不能重新放开续期:同一 AT 再次被拒时,到期时间仍应在未来
reject("renewed");
assert!(current().access_token_expires_at().unwrap() > SystemTime::now());
}
#[test]
fn credential_expired_failure_keeps_expired_oauth_for_bounded_refresh_recovery() {
let store = Arc::new(MemoryAccountStore::default());
@@ -1385,6 +1618,7 @@ fn credential_expired_failure_keeps_expired_oauth_for_bounded_refresh_recovery()
block_on(selector.record_failure(
&account,
&oauth_auth("at-primary"),
CodexAccountFailure::CredentialExpired,
Some("token_expired".to_owned()),
))
@@ -1429,6 +1663,7 @@ fn rate_limited_failure_records_runtime_cooldown_without_changing_persisted_fact
block_on(selector.record_failure(
lease.account(),
lease.authentication(),
CodexAccountFailure::RateLimited {
retry_after: Some(Duration::from_secs(30)),
},
@@ -1460,6 +1695,7 @@ async fn usage_limit_exhaustion_marks_quota_exhausted_without_usage_probe() {
selector
.record_failure(
&account,
&oauth_auth("at-primary"),
CodexAccountFailure::UsageLimitExhausted {
reset_at: Some(SystemTime::now() + Duration::from_secs(30)),
window_minutes: None,
@@ -1488,6 +1724,7 @@ fn rate_limited_failure_does_not_downgrade_persisted_quota_exhaustion() {
block_on(selector.record_failure(
&account,
&oauth_auth("at-primary"),
CodexAccountFailure::RateLimited {
retry_after: Some(Duration::from_secs(30)),
},
@@ -1521,6 +1758,7 @@ fn rate_limited_failure_does_not_consult_stale_quota_snapshot() {
block_on(selector.record_failure(
&account,
&oauth_auth("at-primary"),
CodexAccountFailure::RateLimited {
retry_after: Some(Duration::from_secs(30)),
},
@@ -1555,6 +1793,7 @@ fn rate_limited_failure_does_not_overwrite_stale_authentication_state() {
block_on(selector.record_failure(
&current,
&oauth_auth("at-primary"),
CodexAccountFailure::RateLimited {
retry_after: Some(Duration::from_secs(30)),
},
@@ -1585,7 +1824,7 @@ fn successful_upstream_response_recovers_non_quota_terminal_states() {
let current = store.account("acct_primary").expect("stale account");
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
block_on(selector.record_success(&current));
block_on(selector.record_success(&current, current.revision(), &oauth_auth("at-primary")));
assert_eq!(
store
@@ -1629,9 +1868,12 @@ fn rate_limited_failures_for_distinct_accounts_do_not_conflict() {
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
block_on(async {
let first_auth = oauth_auth("at-first");
let second_auth = oauth_auth("at-second");
let (first_result, second_result) = futures::join!(
selector.record_failure(
&first,
&first_auth,
CodexAccountFailure::RateLimited {
retry_after: Some(Duration::from_secs(30)),
},
@@ -1639,6 +1881,7 @@ fn rate_limited_failures_for_distinct_accounts_do_not_conflict() {
),
selector.record_failure(
&second,
&second_auth,
CodexAccountFailure::RateLimited {
retry_after: Some(Duration::from_secs(30)),
},
@@ -1671,8 +1914,13 @@ fn native_continuation_surfaces_the_original_accounts_quota_status_to_the_coordi
create_account(&store, "acct_fallback", "at-fallback");
let strict_selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
let original = store.account("acct_original").expect("original account");
block_on(strict_selector.record_failure(&original, CodexAccountFailure::QuotaExhausted, None))
.expect("mark original account exhausted");
block_on(strict_selector.record_failure(
&original,
&oauth_auth("at-original"),
CodexAccountFailure::QuotaExhausted,
None,
))
.expect("mark original account exhausted");
let selector = selector_with_runtime(
&store,
@@ -1811,6 +2059,7 @@ fn identity_verification_failure_isolates_only_selected_account() {
block_on(selector.record_failure(
lease.account(),
lease.authentication(),
CodexAccountFailure::IdentityVerificationRequired,
None,
))
@@ -1858,6 +2107,7 @@ fn cloudflare_challenge_does_not_change_persisted_account_facts() {
block_on(selector.record_failure(
lease.account(),
lease.authentication(),
CodexAccountFailure::CloudflareChallenge { retry_after: None },
None,
))
@@ -1870,7 +2120,105 @@ fn cloudflare_challenge_does_not_change_persisted_account_facts() {
.credential_state(),
CredentialState::Ready
);
block_on(selector.record_success(lease.account()));
block_on(selector.record_success(
lease.account(),
lease.account().revision(),
lease.authentication(),
));
}
#[test]
fn cookie_revision_success_breaks_consecutive_path_blocks_only_for_the_current_token() {
for rotate in [false, true] {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_primary", "old-at");
let selector = selector(&store, Arc::new(TestLeaseCoordinator::default()));
let current = || store.account("acct_primary").unwrap();
let block = |token| {
block_on(selector.record_failure(
&current(),
&oauth_auth(token),
CodexAccountFailure::CloudflarePathBlocked,
None,
))
.unwrap()
};
block("old-at");
block("old-at");
let sent = current();
let cookie = block_on(selector.capture_response_cookies(
&sent,
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
&["__cf_bm=test; Path=/; Secure".to_owned()],
))
.unwrap();
assert!(cookie.credential_revision.is_some());
if rotate {
block_on(store.repository().rotate_refreshed_oauth_secret(
&current(),
secret("new-at"),
Some(SystemTime::now() + Duration::from_secs(3600)),
None,
))
.unwrap();
}
block_on(selector.record_success(&sent, sent.revision(), &oauth_auth("old-at")));
block(if rotate { "new-at" } else { "old-at" });
assert_eq!(
current().credential_state(),
if rotate {
CredentialState::Invalid
} else {
CredentialState::Ready
}
);
}
}
#[test]
fn cookie_lease_does_not_swallow_a_rejected_access_token() {
for cookie_commits_first in [false, true] {
let store = Arc::new(MemoryAccountStore::default());
create_account(&store, "acct_primary", "old-at");
let selector = Arc::new(selector(&store, Arc::new(TestLeaseCoordinator::default())));
let sent = store.account("acct_primary").unwrap();
let reject = |selector: Arc<CodexCredentialSelector>, sent: ProviderAccount| async move {
selector
.record_failure(
&sent,
&oauth_auth("old-at"),
CodexAccountFailure::CredentialExpired,
None,
)
.await
.unwrap();
};
if !cookie_commits_first {
// Cookie 写入已取锁但尚未提交,401 到期时间须保留到提交之后
let selector = Arc::downgrade(&selector);
let sent = sent.clone();
store.on_credential_load(Arc::new(move |_, _, _| {
let reject = reject(selector.upgrade().unwrap(), sent.clone());
Box::pin(async move {
reject.await;
Ok(())
})
}));
}
let cookie = block_on(selector.capture_response_cookies(
&sent,
&Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap(),
&["__cf_bm=test; Path=/; Secure".to_owned()],
))
.unwrap();
assert!(cookie.credential_revision.is_some());
if cookie_commits_first {
block_on(reject(selector.clone(), sent));
}
let current = store.account("acct_primary").unwrap();
assert!(current.access_token_expires_at().unwrap() <= SystemTime::now());
assert_eq!(current.credential_state(), CredentialState::Ready);
}
}
#[test]
@@ -1899,6 +2247,7 @@ fn repeated_cloudflare_path_block_marks_only_the_affected_account_invalid() {
for _ in 0..3 {
block_on(selector.record_failure(
lease.account(),
lease.authentication(),
CodexAccountFailure::CloudflarePathBlocked,
None,
))
@@ -1956,6 +2305,7 @@ fn cloudflare_challenge_expires_provider_owned_cookies_at_cooldown_boundary() {
.expect("select revised account");
block_on(selector.record_failure(
second.account(),
second.authentication(),
CodexAccountFailure::CloudflareChallenge { retry_after: None },
None,
))
@@ -2005,6 +2355,7 @@ fn cloudflare_path_block_deletes_provider_owned_cookies() {
.expect("select revised account");
block_on(selector.record_failure(
second.account(),
second.authentication(),
CodexAccountFailure::CloudflarePathBlocked,
None,
))
@@ -2080,8 +2431,13 @@ fn response_cookie_rotation_returns_a_current_account_for_later_fenced_writes()
assert_eq!(outcome.credential_revision, Some(current.revision().get()));
assert_ne!(current.revision(), lease.account().revision());
block_on(selector.record_failure(&current, CodexAccountFailure::QuotaExhausted, None))
.expect("record failure with current revision");
block_on(selector.record_failure(
&current,
&oauth_auth("at-primary"),
CodexAccountFailure::QuotaExhausted,
None,
))
.expect("record failure with current revision");
assert_eq!(
store
.account("acct_primary")
@@ -116,7 +116,10 @@ impl TokenRefresher for FailingRefresher {
}
}
struct RefreshLeases;
#[derive(Default)]
struct RefreshLeases {
rotate_before_acquire: Option<Arc<MemoryAccountStore>>,
}
impl ProviderLeasePort for RefreshLeases {
fn load_state<'a>(
@@ -134,6 +137,21 @@ impl ProviderLeasePort for RefreshLeases {
request: ProviderLeaseRequest,
) -> BoxFuture<'_, Result<ProviderLeaseAcquisition, ProviderStoreError>> {
Box::pin(async move {
if let (ProviderLeaseRequest::Refresh(request), Some(store)) =
(&request, &self.rotate_before_acquire)
{
let before = store.account(request.account_id().as_str()).unwrap();
store
.repository()
.rotate_refreshed_oauth_secret(
&before,
secret("another-refresh"),
Some(SystemTime::now() + Duration::from_secs(3600)),
None,
)
.await
.unwrap();
}
match request {
ProviderLeaseRequest::RefreshCapacity(_) | ProviderLeaseRequest::Refresh(_) => {
Ok(ProviderLeaseAcquisition::Acquired(Box::new(())))
@@ -220,7 +238,7 @@ fn refresh_service(
CodexCredentialRefreshService::new(
store.repository(),
refresher,
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
runtime_policy,
Arc::new(crate::RecordingDiagnostics::default()),
@@ -268,7 +286,7 @@ async fn shutdown_preserves_inflight_token_rotation_and_skips_queued_accounts()
let service = CodexCredentialRefreshService::new(
store.repository(),
Arc::new(RotatingRefresher(cancellation.clone())),
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(300)),
Arc::new(crate::RecordingDiagnostics::default()),
@@ -355,7 +373,7 @@ async fn scheduled_refresh_stops_retrying_rejected_disabled_credentials() {
upstream: None,
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(5 * 60)),
Arc::new(crate::RecordingDiagnostics::default()),
@@ -603,7 +621,7 @@ async fn scheduled_refresh_persists_the_original_upstream_error_message() {
upstream: None,
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
policy,
Arc::new(crate::RecordingDiagnostics::default()),
@@ -668,7 +686,7 @@ async fn scheduled_refresh_persists_retryable_message_inside_the_two_hour_window
provider_openai::profile::CodexWireProfileState::new(Default::default()),
crate::support::runtime_policy(),
)),
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
policy,
Arc::new(crate::RecordingDiagnostics::default()),
@@ -722,7 +740,7 @@ async fn scheduled_refresh_uses_the_final_message_after_the_two_hour_window() {
upstream: None,
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
policy,
Arc::new(crate::RecordingDiagnostics::default()),
@@ -1044,7 +1062,7 @@ async fn quota_revocation_during_oauth_refresh_preserves_terminal_and_retry_resu
}
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(5 * 60)),
Arc::new(crate::RecordingDiagnostics::default()),
@@ -1092,7 +1110,7 @@ async fn scheduled_refresh_records_native_failure_once_and_keeps_retry_state() {
source: Some(std::io::Error::other("PRIVATE_OAUTH_NATIVE_CAUSE").into()),
},
}),
Arc::new(RefreshLeases),
Arc::new(RefreshLeases::default()),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(300)),
diagnostics.clone(),
@@ -1120,3 +1138,125 @@ async fn scheduled_refresh_records_native_failure_once_and_keeps_retry_state() {
);
assert!(!format!("{:?}", failures[0]).contains("PRIVATE_OAUTH_NATIVE_CAUSE"));
}
struct PausedRefresher {
entered: tokio::sync::Notify,
resume: tokio::sync::Notify,
}
#[async_trait]
impl TokenRefresher for PausedRefresher {
async fn refresh(&self, _: &str) -> Result<TokenPair, RefreshFailure> {
self.entered.notify_one();
self.resume.notified().await;
Ok(TokenPair {
access_token: Some("rotated-access".to_owned()),
refresh_token: Some("rotated-refresh".to_owned()),
id_token: None,
})
}
}
#[tokio::test]
async fn cookie_feedback_during_token_exchange_cannot_discard_rotated_tokens() {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_cookie_refresh";
seed_refreshable_account(&store, id, SystemTime::now(), None).await;
let leases = Arc::new(crate::support::TestLeaseCoordinator::default());
let selector = super::contract::selector(&store, leases.clone());
let origin = url::Url::parse("https://chatgpt.com/backend-api/codex/responses").unwrap();
let headers = vec!["__cf_bm=initial; Path=/; Secure; HttpOnly; Max-Age=3600".to_owned()];
selector
.capture_response_cookies(&store.account(id).unwrap(), &origin, &headers)
.await
.unwrap();
let before = store.account(id).unwrap();
let refresher = Arc::new(PausedRefresher {
entered: Default::default(),
resume: Default::default(),
});
let service = CodexCredentialRefreshService::new(
store.repository(),
refresher.clone(),
leases,
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(300)),
Arc::new(crate::RecordingDiagnostics::default()),
);
let refresh = tokio::spawn(async move { service.refresh_due().await });
refresher.entered.notified().await;
let capture = selector
.capture_response_cookies(
&before,
&origin,
&["__cf_bm=concurrent; Path=/; Secure; HttpOnly; Max-Age=3600".to_owned()],
)
.await
.unwrap();
assert_eq!(capture.credential_revision, None);
selector
.record_failure(
&before,
&provider_openai::credential::CodexRuntimeAuthentication::OAuth(secret(&format!(
"access-{id}"
))),
provider_openai::credential::CodexAccountFailure::CloudflareChallenge {
retry_after: None,
},
None,
)
.await
.unwrap();
assert_eq!(store.account(id).unwrap().revision(), before.revision());
refresher.resume.notify_one();
assert!(matches!(
refresh.await.unwrap().unwrap().as_slice(),
[CodexCredentialRefreshOutcome::Refreshed { .. }]
));
let after = store.account(id).unwrap();
let data = store.repository().load_complete_data(&after).await.unwrap();
let oauth = data.oauth().unwrap();
assert_eq!(oauth.access_token, "rotated-access");
assert_eq!(oauth.refresh_token.as_deref(), Some("rotated-refresh"));
assert_eq!(oauth.cookies[0].value, "initial");
// 提交后释放租约,后续响应仍能更新 Cookie
let capture = selector
.capture_response_cookies(&after, &origin, &headers)
.await
.unwrap();
assert!(capture.credential_revision.is_some());
}
#[tokio::test]
async fn scheduled_refresh_rechecks_revision_after_acquiring_the_lease() {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_refresh_snapshot";
seed_refreshable_account(&store, id, SystemTime::now(), None).await;
let refresher = SingleUseRefresher::new();
let service = CodexCredentialRefreshService::new(
store.repository(),
refresher.clone(),
Arc::new(RefreshLeases {
rotate_before_acquire: Some(store.clone()),
}),
Arc::new(RefreshCredentialState),
MutableRuntimePolicy::new(Duration::from_secs(300)),
Arc::new(crate::RecordingDiagnostics::default()),
);
assert_eq!(
service.refresh_due().await.unwrap(),
vec![CodexCredentialRefreshOutcome::Stale {
account_id: id.to_owned()
}]
);
assert_eq!(refresher.calls(), 0);
let data = store
.repository()
.load_complete_data(&store.account(id).unwrap())
.await
.unwrap();
assert_eq!(
data.oauth().unwrap().refresh_token.as_deref(),
Some("rt-another-refresh")
);
}
@@ -354,3 +354,76 @@ async fn api_key_images_bypass_chatgpt_plan_but_live_requires_oauth() {
}
}
}
#[tokio::test]
async fn successful_images_and_live_rearm_oauth_recovery() {
for request in plan_restricted_requests(json!({"model":"gpt-image-2","prompt":"test"})) {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path_regex("/codex/images/.*"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"data":[]})))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/codex/realtime/calls"))
.respond_with(
ResponseTemplate::new(201)
.insert_header("location", "/v1/live/call_recovery")
.insert_header("content-type", "application/sdp")
.set_body_string("v=0\r\n"),
)
.mount(&server)
.await;
let store = Arc::new(MemoryAccountStore::default());
oauth_account(&store, PLUS, Some("plus")).await;
let provider = provider_with_base_url(&store, server.uri());
let before = super::upstream_adapter::selected_adapter_connection(
provider.clone(),
"req_before_refresh",
Default::default(),
)
.await;
before
.record_failure(gateway_core::error::ProviderError::new(
ProviderErrorKind::Unauthorized,
UpstreamSendState::Sent,
))
.await;
store
.repository()
.rotate_refreshed_oauth_secret(
&store.account(PLUS).unwrap(),
secret("refreshed-endpoint"),
Some(SystemTime::now() + Duration::from_secs(3600)),
None,
)
.await
.unwrap();
let mut stream = provider
.clone()
.execute(
request,
context("req_endpoint_success", CancellationToken::new()),
)
.await
.unwrap();
while let Some(event) = stream.next().await {
event.unwrap();
}
let renewed = super::upstream_adapter::selected_adapter_connection(
provider,
"req_after_success",
Default::default(),
)
.await;
renewed
.record_failure(gateway_core::error::ProviderError::new(
ProviderErrorKind::Unauthorized,
UpstreamSendState::Sent,
))
.await;
let account = store.account(PLUS).unwrap();
assert_eq!(account.credential_state(), CredentialState::Ready);
assert!(account.access_token_expires_at().unwrap() <= SystemTime::now());
}
}
@@ -985,6 +985,7 @@ async fn account_scoped_adapter_preselection_keeps_extension_continuations_out_o
}
struct ConnectionProbe {
completed: bool,
selected: Arc<Mutex<Option<oneshot::Sender<SelectedConnection>>>>,
}
@@ -1004,6 +1005,7 @@ impl UpstreamAdapterPlan for ConnectionProbe {
_: Option<&ProviderAccountId>,
) -> Result<UpstreamAdapterSelection, gateway_core::error::ProviderError> {
Ok(UpstreamAdapterSelection::Adapter(Arc::new(Self {
completed: self.completed,
selected: Arc::clone(&self.selected),
})))
}
@@ -1032,6 +1034,17 @@ impl UpstreamAdapter for ConnectionProbe {
.send(invocation.account)
.is_ok()
);
if self.completed {
let meta = gateway_core::event::ResponseMeta::new("adapter-success", "gpt-5.4");
return Ok(
gateway_core::event::ProviderEvent::canonical(GatewayEvent::Started(
meta.clone(),
))
.with_fact(GatewayEvent::Completed(
meta.with_finish_reason(gateway_core::event::FinishReason::Stop),
)),
);
}
Err(gateway_core::error::ProviderError::new(
ProviderErrorKind::Cancelled,
UpstreamSendState::NotSent,
@@ -1040,14 +1053,24 @@ impl UpstreamAdapter for ConnectionProbe {
}
}
async fn selected_adapter_connection(
pub(super) async fn selected_adapter_connection(
provider: Arc<CodexProvider>,
request_id: &str,
pricing: gateway_core::metering::PricingOverrides,
) -> SelectedConnection {
adapter_connection(provider, request_id, pricing, false).await
}
async fn adapter_connection(
provider: Arc<CodexProvider>,
request_id: &str,
pricing: gateway_core::metering::PricingOverrides,
completed: bool,
) -> SelectedConnection {
let (selected, receiver) = oneshot::channel();
let plan = gateway_core::engine::upstream_adapter::FrozenUpstreamAdapterPlan::new(
Arc::new(ConnectionProbe {
completed,
selected: Arc::new(Mutex::new(Some(selected))),
}),
ExtensionSetReference::new(
@@ -1074,10 +1097,18 @@ async fn selected_adapter_connection(
.execute(planned_request("openai", generate_operation()), context)
.await
.unwrap();
assert_eq!(
stream.next().await.unwrap().unwrap_err().kind(),
ProviderErrorKind::Cancelled
);
let result = stream.next().await.unwrap();
if completed {
assert!(
result
.unwrap()
.canonical_facts()
.iter()
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
);
} else {
assert_eq!(result.unwrap_err().kind(), ProviderErrorKind::Cancelled);
}
receiver.await.unwrap()
}
@@ -1177,6 +1208,7 @@ async fn guardian_reservation_survives_upstream_adapters_and_metadata_precedence
let (selected, receiver) = oneshot::channel();
let plan = gateway_core::engine::upstream_adapter::FrozenUpstreamAdapterPlan::new(
Arc::new(ConnectionProbe {
completed: false,
selected: Arc::new(Mutex::new(Some(selected))),
}),
ExtensionSetReference::new(
@@ -1333,9 +1365,50 @@ async fn upstream_adapter_reloads_rotated_credentials_and_proxy_without_acceptin
UpstreamSendState::Sent,
))
.await;
// 当前凭据被拒时先让访问令牌到期,账号退出调度并交给 OAuth 续期
let rejected = store.account(account_id).unwrap();
assert_eq!(rejected.revision(), revision);
assert_eq!(rejected.credential_state(), CredentialState::Ready);
assert_eq!(
store.account(account_id).unwrap().credential_state(),
CredentialState::Expired
rejected.status_projection(SystemTime::now(), None).status,
gateway_core::account::AccountStatus::Error
);
assert!(upstream.received_requests().await.unwrap().is_empty());
}
#[tokio::test]
async fn successful_adapter_completion_rearms_oauth_recovery() {
let store = Arc::new(MemoryAccountStore::default());
let id = "acct_provider_contract";
create_account(&store, id).await;
let server = MockServer::start().await;
let provider = provider_with_base_url(&store, server.uri());
let before =
selected_adapter_connection(provider.clone(), "req_reject", Default::default()).await;
before
.record_failure(gateway_core::error::ProviderError::new(
ProviderErrorKind::Unauthorized,
UpstreamSendState::Sent,
))
.await;
store
.repository()
.rotate_refreshed_oauth_secret(
&store.account(id).unwrap(),
secret("refreshed-adapter"),
Some(SystemTime::now() + Duration::from_secs(3600)),
None,
)
.await
.unwrap();
let renewed = adapter_connection(provider, "req_complete", Default::default(), true).await;
renewed
.record_failure(gateway_core::error::ProviderError::new(
ProviderErrorKind::Unauthorized,
UpstreamSendState::Sent,
))
.await;
let account = store.account(id).unwrap();
assert_eq!(account.credential_state(), CredentialState::Ready);
assert!(account.access_token_expires_at().unwrap() <= SystemTime::now());
}
@@ -85,6 +85,7 @@ pub(crate) struct MemoryAccountStore {
pending_account_reads: bool,
credential_load_hook: Mutex<Option<Arc<CredentialLoadHook>>>,
credential_loads: AtomicUsize,
next_current_credential_read: Mutex<Option<oneshot::Receiver<()>>>,
}
impl gateway_core::account::UpstreamInfoSource for MemoryAccountStore {
@@ -327,6 +328,12 @@ impl MemoryAccountStore {
.expect("credential hook lock") = Some(hook);
}
pub(crate) fn hold_next_current_credential_read(&self) -> oneshot::Sender<()> {
let (release, held) = oneshot::channel();
*self.next_current_credential_read.lock().unwrap() = Some(held);
release
}
pub(crate) fn credential_loads(&self) -> usize {
self.credential_loads.load(Ordering::SeqCst)
}
@@ -595,6 +602,10 @@ impl ProviderAccountStore for MemoryAccountStore {
&self,
account: &ProviderAccountId,
) -> Result<LoadedCredential, StoreError> {
let held = self.next_current_credential_read.lock().unwrap().take();
if let Some(held) = held {
held.await.expect("release current credential read");
}
let accounts = self.accounts.lock().expect("account store lock");
let stored = accounts
.get(account)
@@ -1027,6 +1038,27 @@ pub(crate) struct TestLeaseCoordinator {
pub(crate) signals: Mutex<BTreeMap<ProviderAccountId, AccountRuntimeSignals>>,
pub(crate) reserved_signals: Mutex<BTreeMap<ProviderAccountId, AccountRuntimeSignals>>,
round_robin_cursor: Mutex<u64>,
refresh_accounts: Arc<Mutex<BTreeSet<ProviderAccountId>>>,
}
struct TestRefreshGuard {
accounts: Arc<Mutex<BTreeSet<ProviderAccountId>>>,
account: ProviderAccountId,
}
impl Drop for TestRefreshGuard {
fn drop(&mut self) {
self.accounts.lock().unwrap().remove(&self.account);
}
}
impl gateway_core::provider_ports::ProviderLeaseGuard for TestRefreshGuard {
fn release(self: Box<Self>) -> BoxFuture<'static, Result<(), ProviderStoreError>> {
Box::pin(async move {
drop(self);
Ok(())
})
}
}
impl ProviderLeasePort for TestLeaseCoordinator {
@@ -1083,6 +1115,27 @@ impl ProviderLeasePort for TestLeaseCoordinator {
request: ProviderLeaseRequest,
) -> BoxFuture<'_, Result<ProviderLeaseAcquisition, ProviderStoreError>> {
Box::pin(async move {
if let ProviderLeaseRequest::Refresh(request) = &request {
let account = request.account_id().clone();
return Ok(
if self
.refresh_accounts
.lock()
.unwrap()
.insert(account.clone())
{
ProviderLeaseAcquisition::Acquired(Box::new(TestRefreshGuard {
accounts: Arc::clone(&self.refresh_accounts),
account,
}))
} else {
ProviderLeaseAcquisition::Busy { retry_after: None }
},
);
}
if matches!(request, ProviderLeaseRequest::RefreshCapacity(_)) {
return Ok(ProviderLeaseAcquisition::Acquired(Box::new(())));
}
let ProviderLeaseRequest::Scheduling(request) = request else {
panic!("expected scheduling lease request");
};
+3 -1
View File
@@ -2014,7 +2014,9 @@ OpenAI 授权码交换与令牌刷新请求的连接超时为 30 秒,单次上
`quota_exhausted`。额度观测不会清除凭据过期、无效或封禁事实;这些事实统一投影为 `error`,并由
`errorReason` 区分。OpenAI 额度查询返回 `401 token_revoked` 时,当前访问令牌立即按过期处理,
已启用账号投影为 `error`,已有 refresh token 仍可续期。取得新访问令牌后按已有额度事实显示状态。
其他额度 401/403 保留原状态,refresh token 是否永久失效由 OAuth 续期结果判断
其他额度 401/403 保留原状态,refresh token 是否永久失效由 OAuth 续期结果判断。
模型请求收到 401 时,有 refresh token 且访问令牌未到期的 OAuth 账号同样先续期,
新令牌在成功请求前再次被拒才记为凭据过期
- xAI 额度百分比取自 `creditUsagePercent`,缺失时为未知。
预付余额保留上游账本符号,非零余额及剩余按量额度可独立证明可用;窗口已过期或缺少可用证据时,
不凭旧快照恢复账号
+4
View File
@@ -1150,6 +1150,10 @@ OpenAI、xAI、Antigravity 的 OAuth 认证及账号后台操作由各 Provider
- OAuth 自动续期按运行时设置的提前量触发,默认 300 秒对齐官方客户端 exp 前 5 分钟的刷新窗口。
每个账号的有效提前量在 [margin, 2×margin] 内由账号 ID 派生稳定错峰偏移,减少同一时刻
到期账号的集中刷新;恢复窗口内的强制刷新不受偏移影响
- OpenAI 手工与后台续期在取得账号刷新租约后复核凭据版本,租约覆盖 RT exchange 与提交。
响应 Cookie 捕获及风控清理共用该租约,避免推进版本导致已换回的 token 无法提交。
模型 401 只按版本写回到期时间或账号状态;若并发写回推进版本,仅对仍在使用的同一 AT 重新处理。
同一 AT 的成功响应可清除更早版本的 401 记录并中断连续风控失败;核对期间新到的失败仍然有效
- xAI 支持 OAuth session 和 Responses API Key;API Key 不执行 OAuth 刷新、身份查询或官方额度操作。OAuth 刷新额度时同步查询官方实时订阅,
只把套餐事实写入现有 quota JSON。明确无付费订阅的个人账号显示 Free;查询失败、缺失字段或
团队身份不推断为 Free,订阅查询失败不影响额度观测
+4 -30
View File
@@ -1,33 +1,7 @@
# v3.62.0
## 新增功能
- 启用在线重启的部署可在管理端「系统更新」中手动重启服务,确认前可查看请求中断影响和插件风险
- OpenAI 原生账号触发轮次限流后,仅暂停该账号对应模型的调度,等待时间取自 `Retry-After`,缺省为 60 秒;账号列表可查看受限模型和恢复时间
## 优化改进
- Codex OAuth 的 SSE 请求复用同一上游 WebSocket 时,在隐私处理后的历史和续接配置匹配时只发送新增输入,支持仅本轮元数据变化或没有新增输入的续接
- Antigravity 自动核验对应平台的官方发布包,版本和构建号一同生效,核验失败时沿用当前画像;下载使用运行数据目录,减少容器临时目录空间不足导致的失败
- 系统更新弹窗按进度显示操作和待生效版本,目标版本一致且插件兼容时点击重启即可生效
- 仪表盘指标与账号排序平滑更新,订阅标识与账号页统一,窄卡片下账号信息分行显示
- 管理端操作按钮独立显示加载状态,账号列表隐藏为零的 Token 用量,矮窗口中保留表格滚动与分页空间,独立应用模式保留页面底部间距
- 管理端内容清理依赖 DOMPurify 升级至 3.5.1
# v3.62.1-rc.1
## 问题修复
- Codex OAuth 历史匹配按官方客户端的回传格式处理已知输出与嵌套内容,修复搜索等历史无法复用的问题,同时保留工具结果变化和未知类型的差异
- Fast 模式按本次选中的账号和模型应用有效分组策略,重试切换账号时重新匹配
- OpenAI Chat Completions 选号时识别会话与线程,修复严格模式下已有可用账号却返回 503 的问题,根请求因模型限制迁移后子线程跟随新账号(#841)
- OpenAI 模型目录刷新失败后从 1 分钟起逐次延长重试间隔,最长 1 小时;后台重试和手动刷新只在连续 30 秒无数据进展时超时(#838、#845)
- OpenAI 额度桶提前重置后,从观察到归零时起等待五分钟,再复查是否需要预热
- OpenAI 请求显式指定 `reasoning.effort: none` 时,若所选账号的模型目录支持 `low` 但不支持 `none`,自动改用 `low`,并同步处理历史中的推理配置更新
- 补齐 `gpt-image-2.6-sunburst` 和 `gpt-image-2.6-flare` 的图像模型计费识别(#850)
- Chat Completions 正确处理空占位消息和可空字段,转发到 Messages 和 GenAI 时保留停止序列
- Chat 转 Responses 支持有名称但没有调用 ID 的工具结果,并正确转换自定义工具的语法定义;经 Codex OAuth 调用时兼容过长的历史调用 ID、特殊字符工具名和旧版搜索工具名,响应还原客户端工具名(#844)
- Antigravity 保留 Google 结构化拒绝的状态、错误原因和重试时间,明确要求验证时将账号标记为待验证并停止调度,原生流已输出内容时以 SSE 错误帧结束(#836)
- Antigravity 调用 Claude 时,同名并行工具的调用与结果数量一致且均缺失 ID,可按出现顺序补齐配对,修复下一轮请求因缺少工具 ID 失败的问题(#848)
- HTTP 和 WebSocket 错误保留可识别的上游请求 ID,账号选择失败时区分额度耗尽和传输方式不匹配
- 客户端 Key 恢复并发和每分钟请求计数时排除插件内部子请求,并支持配置较大的限额
- 出站 HTTP 响应超出 32 MiB 限制后持续拒绝读取,避免后续读取交付已拒绝的缓冲内容
- 停止或重启服务时优先收尾后台任务,超出收尾预算时在日志中标明任务名称
- OpenAI OAuth 账号的访问令牌在到期前收到模型请求 401 时,有刷新令牌的账号会先自动续期。新令牌在首次成功请求前再次被拒时,才将凭据标记为过期(#853)
- 手动和后台续期遇到并发 Cookie 写入时,可正确保存新令牌,并避免重复使用已轮换的刷新令牌
- 并发模型请求返回时,较早请求的成功响应会保留核对期间新收到的 401 和风控失败记录
+5 -5
View File
@@ -1,7 +1,7 @@
version: 3.62.0
version: 3.62.1-rc.1
published:
'3':
stable: 3.61.0
rc: 3.61.1-rc.6
beta: 3.61.1-rc.6
alpha: 3.61.1-rc.6
stable: 3.62.0
rc: 3.62.1-rc.1
beta: 3.62.1-rc.1
alpha: 3.62.1-rc.1