mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-05 08:00:53 +00:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ebf6739e2 | ||
|
|
b987cca4aa | ||
|
|
72e82c565e | ||
|
|
47ccdeb737 | ||
|
|
b20b0e2013 | ||
|
|
16fc302d46 | ||
|
|
95c35d0a67 | ||
|
|
259a2e1ba0 | ||
|
|
2f51412625 | ||
|
|
32f3b11ddf | ||
|
|
c2891e14ce |
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 中已经生成的完整说明,不再查询 PR 或附加另一份自动日志;修改 tag 之后的本地文件不会改变该次构建。
|
||||
|
||||
只调整已发布页面的标题或正文时,编辑对应 GitHub Release 的 `name` 或 `body` 并回读核对;
|
||||
保持已有 tag、源码提交、附件和预发行状态,不重新执行发布入口。
|
||||
@@ -60,7 +60,8 @@ release/publish "$release_version"
|
||||
### 验收
|
||||
|
||||
- 发布完成后核对 GitHub Release 的版本、正式版/预发行状态和中文变更正文;对照平台清单与工作流确认归档、校验和及镜像产物。
|
||||
工作流附加的安装说明和自动提交列表按其当前配置处理,不用它们替代手写的中文变更说明。
|
||||
正文应与 tag 内的说明一致,正式版的 `Full Changelog` 从上一正式版开始,PR 和直接提交覆盖本次范围;自动列表不替代手写的中文变更说明
|
||||
- 核对 `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,21 @@
|
||||
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,正文使用中文
|
||||
- 常规版本按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句。安装命令和文档入口由工作流附加
|
||||
- 常规版本的手写正文按「新增功能」「优化改进」「问题修复」「升级须知」归类,省略空章节;单一改动可直接写一句
|
||||
- `release/publish` 生成安装入口、文档链接和变更列表,保存到说明末尾的 `cpr-release:generated` 标记区块;重新准备说明时整块保留或移除,不在区块中手写内容
|
||||
- 自动列表按实际提交中的 PR 编号补齐 GitHub 遗漏的合并记录,并列出直接提交;仍需对照完整 diff 核实中文正文,剔除回退或重复的用户影响
|
||||
- 每条用一句短语讲清一个用户可感知的结果,不加句号,例如「系统更新:确认当前平台有安装包后才提示升级」
|
||||
- 同一变化只写一次,保留会影响使用或升级的默认值和限制,不展开实现过程、逐条翻译提交或写未经验证的承诺
|
||||
- 剔除回退、重复及未进入发行范围的内容,升级事项须能追溯到实际迁移、配置或兼容变化
|
||||
@@ -31,7 +40,8 @@
|
||||
在上一发行基线到 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、发行物验证或实际发布授权
|
||||
预检输出基线、目标提交和完整正文,核对 `Full Changelog` 范围、PR 列表及直接提交;正式执行也使用相同生成入口,将最终正文随版本提交保存
|
||||
预检不修改文件、Git 引用或远端状态;远端存在本地未知提交或缺少已发布的基线 tag 时,先同步再检查。它不替代 CI、发行物验证或实际发布授权
|
||||
|
||||
按[验证要求](../../../../CONTRIBUTING.md#验证)核对目标提交的证据,区分通过、失败、跳过与未执行
|
||||
数据库变更同时读取[迁移冻结规则](../../../../backend/migrations/README.md#冻结规则):
|
||||
|
||||
@@ -97,11 +97,6 @@ module ReleaseMetadata
|
||||
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 +107,6 @@ 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,
|
||||
'prerelease' => prerelease?(value),
|
||||
'build_type' => value.split('+', 2).first.include?('-exp.') ? 'experimental' : 'release'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
require_relative 'release-metadata'
|
||||
|
||||
# 预检与发布共用日志范围;生成结果随版本提交保存,构建时不再查询可变的 PR 信息
|
||||
module ReleaseNotes
|
||||
START = '<!-- cpr-release:generated -->'
|
||||
FINISH = '<!-- /cpr-release:generated -->'
|
||||
|
||||
def self.manual_body(document)
|
||||
body = document.lines.drop(1).join.strip
|
||||
return body unless body.include?(START) || body.include?(FINISH)
|
||||
unless body.scan(START).length == 1 && body.scan(FINISH).length == 1 && body.end_with?(FINISH) &&
|
||||
body.index(START) < body.index(FINISH)
|
||||
raise 'Invalid generated release notes block; keep the complete block at the end or remove it'
|
||||
end
|
||||
body.split(START, 2).first.rstrip
|
||||
end
|
||||
|
||||
def self.body(value)
|
||||
ReleaseMetadata.validate_notes(value)
|
||||
document = File.read('release/notes.md')
|
||||
manual_body(document)
|
||||
unless value.include?('-exp.') || document.include?(START)
|
||||
raise 'Release notes are not prepared; use release/publish to generate and commit the final body'
|
||||
end
|
||||
document.lines.drop(1).join.strip + "\n"
|
||||
end
|
||||
|
||||
# 只选已公开且属于目标历史的发行;首次实验版可以以同号正式版为基线
|
||||
def self.previous_tag(value, releases, reachable)
|
||||
core, stage = value.split('-', 2)
|
||||
candidates = releases.select do |release|
|
||||
tag = release.fetch('tag_name')
|
||||
raw = tag.delete_prefix('v')
|
||||
tag == "v#{raw}" && raw.match?(ReleaseMetadata::SEMVER) && !raw.include?('+') &&
|
||||
!release.fetch('draft') && release.fetch('prerelease') == ReleaseMetadata.prerelease?(raw) &&
|
||||
reachable.include?(tag)
|
||||
end.map { |release| release.fetch('tag_name') }
|
||||
lower = candidates.select { |tag| ReleaseMetadata.sort_key(tag) < ReleaseMetadata.sort_key(value) }
|
||||
if stage
|
||||
same_line = lower.select do |tag|
|
||||
previous_core, previous_stage = tag.delete_prefix('v').split('-', 2)
|
||||
previous_core == core && previous_stage &&
|
||||
previous_stage.start_with?('exp.') == stage.start_with?('exp.')
|
||||
end
|
||||
return same_line.max_by { |tag| ReleaseMetadata.sort_key(tag) } unless same_line.empty?
|
||||
return candidates.find { |tag| tag == "v#{core}" } if stage.start_with?('exp.')
|
||||
end
|
||||
lower.reject { |tag| ReleaseMetadata.prerelease?(tag) }.max_by { |tag| ReleaseMetadata.sort_key(tag) }
|
||||
end
|
||||
|
||||
class Generator
|
||||
def initialize(repository)
|
||||
raise 'Invalid GitHub repository' unless repository.match?(%r{\A[\w.-]+/[\w.-]+\z})
|
||||
@repository = repository
|
||||
@endpoint = "repos/#{repository}"
|
||||
@url = "https://github.com/#{repository}"
|
||||
end
|
||||
|
||||
def api(path, data: nil, paginate: false)
|
||||
args = ['gh', 'api', "#{@endpoint}/#{path}"]
|
||||
args.concat(['--method', 'POST', '--input', '-']) if data
|
||||
args.concat(['--paginate', '--jq', '.[] | @json']) if paginate
|
||||
output, error, status = Open3.capture3(*args, stdin_data: data ? JSON.generate(data) : '')
|
||||
raise "Cannot read release information: #{error.strip}" unless status.success?
|
||||
paginate ? output.lines.map { |line| JSON.parse(line) } : JSON.parse(output)
|
||||
end
|
||||
|
||||
def commits(base, head)
|
||||
range = base ? "#{base}..#{head}" : head
|
||||
ReleaseMetadata.git('log', '--first-parent', '--reverse', '--format=%H %s', range, '--').lines.map do |line|
|
||||
sha, subject = line.strip.split(' ', 2)
|
||||
[sha, subject]
|
||||
end.reject do |sha, _|
|
||||
paths = ReleaseMetadata.git('diff-tree', '--root', '--no-commit-id', '--name-only', '-r', sha).lines.map(&:strip)
|
||||
!paths.empty? && (paths - %w[release/version.yaml release/notes.md]).empty?
|
||||
end
|
||||
end
|
||||
|
||||
def markdown(text)
|
||||
text.gsub(/[\\`*_\[\]<>]/) { |character| "\\#{character}" }
|
||||
end
|
||||
|
||||
def changelog(base, head, value, github_head)
|
||||
# 没有前序发行时从仓库起点列举,不让 GitHub 自动猜测另一条发行线
|
||||
# 未推送的提交由本地历史补齐,避免要求预检先写远端
|
||||
github_range = base && ReleaseMetadata.git('merge-base', base, github_head) == ReleaseMetadata.git('rev-parse', "#{base}^{commit}")
|
||||
generated = if github_range
|
||||
api('releases/generate-notes', data: {
|
||||
tag_name: "v#{value}", target_commitish: github_head, previous_tag_name: base
|
||||
}).fetch('body').gsub("\r\n", "\n").strip
|
||||
else
|
||||
''
|
||||
end
|
||||
listed = generated.scan(%r{#{Regexp.escape(@url)}/pull/(\d+)\b}).flatten.map(&:to_i).uniq
|
||||
missing = []
|
||||
direct = []
|
||||
commits(base, head).each do |sha, subject|
|
||||
# 只识别合并提交格式,不把正文中的 Issue 引用猜成 PR
|
||||
number = subject[/\(#(\d+)\)\z/, 1] || subject[/\AMerge pull request #(\d+)\b/, 1]
|
||||
unless number
|
||||
direct << "* #{markdown(subject)} ([#{sha[0, 9]}](#{@url}/commit/#{sha}))"
|
||||
next
|
||||
end
|
||||
number = number.to_i
|
||||
next if listed.include?(number)
|
||||
pull = api("pulls/#{number}")
|
||||
raise "Referenced PR ##{number} is not merged" unless pull.fetch('merged')
|
||||
missing << "* #{markdown(pull.fetch('title'))} by @#{pull.fetch('user').fetch('login')} in #{@url}/pull/#{number}"
|
||||
listed << number
|
||||
end
|
||||
unless missing.empty?
|
||||
heading = "## What's Changed"
|
||||
generated = if generated.include?(heading)
|
||||
generated.sub(heading, "#{heading}\n#{missing.join("\n")}")
|
||||
else
|
||||
["#{heading}\n#{missing.join("\n")}", generated].reject(&:empty?).join("\n\n")
|
||||
end
|
||||
end
|
||||
# 直接提交也有明确链接,不能把 PR 列表当成完整变更范围
|
||||
generated += "\n\n## 其他提交\n#{direct.join("\n")}" unless direct.empty?
|
||||
link = base ? "#{@url}/compare/#{base}...v#{value}" : "#{@url}/commits/#{head}"
|
||||
generated += "\n\n**Full Changelog**: #{link}" unless generated.include?(link)
|
||||
warn "日志范围:#{base || '仓库起点'} → #{head};#{listed.length} 个 PR,#{direct.length} 个直接提交"
|
||||
warn "已补齐自动列表遗漏:#{missing.join("\n")}" unless missing.empty?
|
||||
generated.strip
|
||||
end
|
||||
|
||||
def prepare(value, head: 'HEAD', github_head: head)
|
||||
value = ReleaseMetadata.release_version(value)
|
||||
ReleaseMetadata.validate_notes(value)
|
||||
head = ReleaseMetadata.git('rev-parse', '--verify', "#{head}^{commit}")
|
||||
github_head = ReleaseMetadata.git('rev-parse', '--verify', "#{github_head}^{commit}")
|
||||
unless ReleaseMetadata.git('merge-base', head, github_head) == github_head
|
||||
raise 'GitHub source commit must be an ancestor of the release source'
|
||||
end
|
||||
reachable = ReleaseMetadata.git('tag', '--list', 'v*', '--merged', head).lines.map(&:strip)
|
||||
releases = api('releases?per_page=100', paginate: true)
|
||||
unknown = releases.map { |release| release.fetch('tag_name') } - ReleaseMetadata.git('tag', '--list', 'v*').lines.map(&:strip)
|
||||
base = ReleaseNotes.previous_tag(value, releases, reachable + unknown)
|
||||
raise "Published baseline tag #{base} is missing locally; fetch remote tags before preparing notes" if unknown.include?(base)
|
||||
manual = ReleaseNotes.manual_body(File.read('release/notes.md'))
|
||||
raise 'Release notes must contain a handwritten description' if manual.empty?
|
||||
warn "发布基线:#{base || '仓库起点'};目标:v#{value};源码:#{head}"
|
||||
return "# v#{value}\n\n#{manual}\n" if value.include?('-exp.')
|
||||
installation = <<~MARKDOWN.strip
|
||||
## Linux 一键安装(Docker Compose)
|
||||
|
||||
```bash
|
||||
curl -fsSLO #{@url.sub('github.com', 'raw.githubusercontent.com')}/v#{value}/deploy/install.sh && CPR_RELEASE_TAG=v#{value} bash install.sh
|
||||
```
|
||||
|
||||
## 📚 文档
|
||||
|
||||
- [GitHub 仓库](#{@url})
|
||||
- [部署指南](#{@url}/blob/v#{value}/deploy/README.md)
|
||||
MARKDOWN
|
||||
"# v#{value}\n\n#{manual}\n\n#{START}\n#{installation}\n\n#{changelog(base, head, value, github_head)}\n#{FINISH}\n"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
begin
|
||||
command, value, repository, github_head = ARGV
|
||||
case command
|
||||
when 'prepare'
|
||||
raise 'prepare requires VERSION REPOSITORY GITHUB_HEAD' unless ARGV.length == 4
|
||||
puts ReleaseNotes::Generator.new(repository).prepare(value, github_head: github_head)
|
||||
when 'body'
|
||||
raise 'body requires VERSION' unless ARGV.length == 2
|
||||
puts ReleaseNotes.body(value)
|
||||
else
|
||||
raise 'usage: release-notes.rb prepare VERSION REPOSITORY GITHUB_HEAD | body VERSION'
|
||||
end
|
||||
rescue StandardError => error
|
||||
warn "error: #{error.message}"
|
||||
exit 1
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -45,12 +45,13 @@ jobs:
|
||||
non_docker_matrix: ${{ steps.version.outputs.non_docker_matrix }}
|
||||
windows_matrix: ${{ steps.version.outputs.windows_matrix }}
|
||||
docker_platforms: ${{ steps.version.outputs.docker_platforms }}
|
||||
previous_tag: ${{ steps.version.outputs.previous_tag }}
|
||||
prerelease: ${{ steps.version.outputs.prerelease }}
|
||||
build_type: ${{ steps.version.outputs.build_type }}
|
||||
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
|
||||
@@ -75,6 +76,11 @@ jobs:
|
||||
id: toolchains
|
||||
run: ruby .github/scripts/toolchains.rb >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Verify committed release notes
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
run: ruby .github/scripts/release-notes.rb body "$VERSION" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
- name: Check reusable backend CI evidence
|
||||
id: quality
|
||||
env:
|
||||
@@ -97,6 +103,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 +442,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,25 +553,8 @@ jobs:
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
env:
|
||||
BUILD_TYPE: ${{ needs.release-info.outputs.build_type }}
|
||||
INSTALLATION_NOTES: |
|
||||
## Linux 一键安装(Docker Compose)
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://raw.githubusercontent.com/${{ github.repository }}/${{ needs.release-info.outputs.tag }}/deploy/install.sh && CPR_RELEASE_TAG=${{ needs.release-info.outputs.tag }} bash install.sh
|
||||
```
|
||||
|
||||
## 📚 文档
|
||||
|
||||
- [GitHub 仓库](https://github.com/${{ github.repository }})
|
||||
- [部署指南](https://github.com/${{ github.repository }}/blob/${{ needs.release-info.outputs.tag }}/deploy/README.md)
|
||||
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'
|
||||
output = File.join(ENV.fetch('RUNNER_TEMP'), 'release-notes.md')
|
||||
File.write(output, "#{notes}\n")
|
||||
RUBY
|
||||
VERSION: ${{ needs.release-info.outputs.version }}
|
||||
run: ruby .github/scripts/release-notes.rb body "$VERSION" > "$RUNNER_TEMP/release-notes.md"
|
||||
|
||||
- name: Generate release asset provenance
|
||||
uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2
|
||||
@@ -552,8 +566,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' }}
|
||||
previous_tag: ${{ needs.release-info.outputs.previous_tag }}
|
||||
generate_release_notes: false
|
||||
prerelease: ${{ needs.release-info.outputs.prerelease == 'true' }}
|
||||
# action 保留已公开 Release 的状态,新 Release 上传完成后仍保持草稿
|
||||
draft: true
|
||||
|
||||
+2
-2
@@ -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`,手写章节标题和正文使用中文;命令、配置键、协议名等保留原文。只说明本次版本的实际变化,按影响交代升级事项。发行入口将自动变更列表和安装入口保存到末尾的生成区块,工作流按提交中的完整正文发布,基线与预检要求见[版本与说明准备](.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 天
|
||||
|
||||
新增自动规则优先使用现有工具,要求依据明确、结果稳定、误报可控;无法可靠判定的设计与视觉问题保留审查判断,避免把具体源码写法锁成测试
|
||||
|
||||
|
||||
@@ -484,7 +484,6 @@ impl TryFrom<(ClientKeyPage, crate::time::TimePresenter)> for ClientKeyListData
|
||||
let next_cursor = page
|
||||
.next_cursor
|
||||
.map(wire_cursor)
|
||||
.transpose()?
|
||||
.as_ref()
|
||||
.map(encode_client_key_cursor)
|
||||
.transpose()?;
|
||||
@@ -597,7 +596,8 @@ impl From<ClientKeyMutation> for MutatedClientKeyData {
|
||||
}
|
||||
|
||||
/// 解码后的 Client Key 游标字段
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ClientKeyCursorData {
|
||||
pub sort: ClientKeySort,
|
||||
pub value: ClientKeyCursorValue,
|
||||
@@ -614,25 +614,12 @@ pub enum ClientKeyCursorValue {
|
||||
LastUsedAt(Option<DateTime<Utc>>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
struct CursorWire {
|
||||
sort: ClientKeySort,
|
||||
value: ClientKeyCursorValue,
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// 把 owner 游标编码为不透明 wire 值
|
||||
pub fn encode_client_key_cursor(
|
||||
cursor: &ClientKeyCursorData,
|
||||
) -> Result<String, WireValidationError> {
|
||||
validate_client_key_cursor(cursor)?;
|
||||
let bytes = serde_json::to_vec(&CursorWire {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value.clone(),
|
||||
id: cursor.id.clone(),
|
||||
})
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let bytes = serde_json::to_vec(cursor).map_err(|_| WireValidationError::new("cursor"))?;
|
||||
Ok(URL_SAFE_NO_PAD.encode(bytes))
|
||||
}
|
||||
|
||||
@@ -644,13 +631,8 @@ pub fn decode_client_key_cursor(encoded: &str) -> Result<ClientKeyCursorData, Wi
|
||||
let bytes = URL_SAFE_NO_PAD
|
||||
.decode(encoded)
|
||||
.map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor: CursorWire =
|
||||
let cursor: ClientKeyCursorData =
|
||||
serde_json::from_slice(&bytes).map_err(|_| WireValidationError::new("cursor"))?;
|
||||
let cursor = ClientKeyCursorData {
|
||||
sort: cursor.sort,
|
||||
value: cursor.value,
|
||||
id: cursor.id,
|
||||
};
|
||||
validate_client_key_cursor(&cursor)?;
|
||||
Ok(cursor)
|
||||
}
|
||||
@@ -724,20 +706,18 @@ fn domain_cursor(cursor: ClientKeyCursorData) -> Result<ClientKeyCursor, WireVal
|
||||
})
|
||||
}
|
||||
|
||||
fn wire_cursor(cursor: ClientKeyCursor) -> Result<ClientKeyCursorData, WireValidationError> {
|
||||
fn wire_cursor(cursor: ClientKeyCursor) -> ClientKeyCursorData {
|
||||
let value = match cursor.value {
|
||||
DomainCursorValue::Name(value) => ClientKeyCursorValue::Name(value),
|
||||
DomainCursorValue::Enabled(value) => ClientKeyCursorValue::Enabled(value),
|
||||
DomainCursorValue::CreatedAt(value) => ClientKeyCursorValue::CreatedAt(value),
|
||||
DomainCursorValue::LastUsedAt(value) => ClientKeyCursorValue::LastUsedAt(value),
|
||||
};
|
||||
let cursor = ClientKeyCursorData {
|
||||
ClientKeyCursorData {
|
||||
sort: wire_sort(cursor.sort),
|
||||
value,
|
||||
id: cursor.id.to_string(),
|
||||
};
|
||||
validate_client_key_cursor(&cursor)?;
|
||||
Ok(cursor)
|
||||
}
|
||||
}
|
||||
|
||||
fn client_key_id(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! 验证 Client Key 管理接口的预算、密钥输入与查询合同
|
||||
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
use chrono::{DateTime, TimeZone as _, Utc};
|
||||
use gateway_api::admin::client_keys::{
|
||||
self, ClientKeyCursorData, ClientKeyCursorValue, ClientKeyListData, ClientKeyMutationRequest,
|
||||
@@ -475,12 +476,41 @@ fn client_key_cursor_should_round_trip_and_reject_noncanonical_input() {
|
||||
};
|
||||
let encoded = encode_client_key_cursor(&cursor).expect("encode cursor");
|
||||
let decoded = decode_client_key_cursor(&encoded).expect("decode cursor");
|
||||
let wire = json!({
|
||||
"sort": { "field": "createdAt", "direction": "desc" },
|
||||
"value": { "kind": "createdAt", "value": "2026-07-18T08:00:00Z" },
|
||||
"id": "key_cursor"
|
||||
});
|
||||
|
||||
assert_eq!(decoded, cursor);
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(&URL_SAFE_NO_PAD.decode(&encoded).unwrap())
|
||||
.unwrap(),
|
||||
wire
|
||||
);
|
||||
assert!(!encoded.contains("key_cursor"));
|
||||
for invalid in ["", "not-base64!", "e30"] {
|
||||
assert!(decode_client_key_cursor(invalid).is_err());
|
||||
}
|
||||
for (field, value) in [
|
||||
("unknownField", json!(true)),
|
||||
("id", json!(" ")),
|
||||
("value", json!({ "kind": "enabled", "value": true })),
|
||||
(
|
||||
"sort",
|
||||
json!({ "field": "createdAt", "direction": "desc", "unknownField": true }),
|
||||
),
|
||||
] {
|
||||
let mut invalid = wire.clone();
|
||||
invalid[field] = value;
|
||||
let encoded = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&invalid).unwrap());
|
||||
assert_eq!(
|
||||
decode_client_key_cursor(&encoded)
|
||||
.expect_err("reject invalid cursor fields")
|
||||
.field(),
|
||||
"cursor"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -416,6 +416,11 @@ impl HttpBody {
|
||||
return Err(HttpError::sent("read size"));
|
||||
}
|
||||
loop {
|
||||
if self.received > 32 * 1024 * 1024 {
|
||||
// 累计量封存超限结果,后续读取不能交付已拒绝的缓冲
|
||||
self.pending = Bytes::new();
|
||||
return Err(HttpError::sent("response size"));
|
||||
}
|
||||
// 已缓冲的数据和就绪帧也受本次期限约束,不能绕过 owner 的读取预算
|
||||
if Instant::now() >= deadline {
|
||||
return Err(HttpError::sent("response deadline").with_kind(HttpErrorKind::Timeout));
|
||||
@@ -445,9 +450,6 @@ impl HttpBody {
|
||||
}
|
||||
};
|
||||
self.received = self.received.saturating_add(self.pending.len());
|
||||
if self.received > 32 * 1024 * 1024 {
|
||||
return Err(HttpError::sent("response size"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,6 +158,60 @@ async fn managed_http_caps_chunks_and_recovers_capacity_after_body_drop() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_http_body_limit_rejects_all_reads_after_exceeding_capacity() {
|
||||
let limit = 32 * 1024 * 1024;
|
||||
let server = MockServer::start().await;
|
||||
let client = HttpClient::new().unwrap();
|
||||
for size in [limit, limit + 1] {
|
||||
server.reset().await;
|
||||
Mock::given(any())
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(vec![42; size]))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let mut response = client
|
||||
.open(
|
||||
request(server.uri()),
|
||||
None,
|
||||
&local_network(),
|
||||
Duration::from_secs(10),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let mut received = 0;
|
||||
let result = loop {
|
||||
match response.body.read(64 * 1024).await {
|
||||
Ok(Some(chunk)) => received += chunk.len(),
|
||||
result => break result,
|
||||
}
|
||||
};
|
||||
if size == limit {
|
||||
assert!(result.unwrap().is_none());
|
||||
assert_eq!(received, limit);
|
||||
} else {
|
||||
assert!(received <= limit);
|
||||
let error = result.unwrap_err();
|
||||
assert_eq!(error.kind(), HttpErrorKind::Response);
|
||||
assert_eq!(error.send_state, UpstreamSendState::Sent);
|
||||
assert_eq!(error.reason(), "response size");
|
||||
assert_eq!(
|
||||
response.body.read(1).await.unwrap_err().reason(),
|
||||
"response size"
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.body
|
||||
.read_with_timeout(1, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.reason(),
|
||||
"response size"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_http_deadline_and_invalid_headers_preserve_send_facts() {
|
||||
let server = MockServer::start().await;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Chat 到 Responses 的字段、媒体和工具映射回归
|
||||
//! Chat 到 Responses 的字段、媒体和工具映射
|
||||
|
||||
use gateway_protocol::chat_completions::responses::convert_request;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Responses 到 Chat 的完整响应、SSE增量及历史字段回归
|
||||
//! Responses 到 Chat 的完整响应、流式增量、用量与错误投影
|
||||
|
||||
use gateway_protocol::chat_completions::{
|
||||
ChatAccumulator, ChatError, ChatIdentity,
|
||||
@@ -7,86 +7,67 @@ use gateway_protocol::chat_completions::{
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct Session(Vec<Value>);
|
||||
impl Session {
|
||||
fn new(events: Vec<Value>) -> Self {
|
||||
Self(events)
|
||||
}
|
||||
fn with_batch(mut self, events: Vec<Value>) -> Self {
|
||||
self.0.extend(events);
|
||||
self
|
||||
}
|
||||
}
|
||||
struct Fixture(Session);
|
||||
struct Projection {
|
||||
json: Option<Value>,
|
||||
chunks: Vec<Value>,
|
||||
error: Option<ChatError>,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new(events: Session) -> Self {
|
||||
Self(events)
|
||||
}
|
||||
fn post(&self, request: Value) -> Projection {
|
||||
let identity = chat_identity();
|
||||
let mut result = Projection {
|
||||
json: None,
|
||||
chunks: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
if request["stream"] == true {
|
||||
let mut encoder = ChatStreamEncoder::new(
|
||||
identity,
|
||||
request["stream_options"]["include_usage"] == true,
|
||||
);
|
||||
for event in &self.0.0 {
|
||||
match encoder.push_event(event["type"].as_str(), event) {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => {
|
||||
result.error = Some(error);
|
||||
return result;
|
||||
}
|
||||
fn project_events(events: &[Value], streaming: bool, include_usage: bool) -> Projection {
|
||||
let identity = chat_identity();
|
||||
let mut result = Projection {
|
||||
json: None,
|
||||
chunks: Vec::new(),
|
||||
error: None,
|
||||
};
|
||||
if streaming {
|
||||
let mut encoder = ChatStreamEncoder::new(identity, include_usage);
|
||||
for event in events {
|
||||
match encoder.push_event(event["type"].as_str(), event) {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => {
|
||||
result.error = Some(error);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
match encoder.finish() {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
}
|
||||
match encoder.finish() {
|
||||
Ok(chunks) => result.chunks.extend(chunks),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
} else {
|
||||
let projected = if events.len() == 1 {
|
||||
events[0]
|
||||
.get("response")
|
||||
.ok_or(ChatError::IncompleteStream)
|
||||
.and_then(|value| project_response(value, &identity))
|
||||
} else {
|
||||
let projected = if self.0.0.len() == 1 {
|
||||
self.0.0[0]
|
||||
.get("response")
|
||||
.ok_or(ChatError::IncompleteStream)
|
||||
.and_then(|value| project_response(value, &identity))
|
||||
} else {
|
||||
let mut encoder = ChatStreamEncoder::new(identity, true);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
let mut collect = || {
|
||||
for event in &self.0.0 {
|
||||
for chunk in encoder.push_event(event["type"].as_str(), event)? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
}
|
||||
for chunk in encoder.finish()? {
|
||||
let mut encoder = ChatStreamEncoder::new(identity, true);
|
||||
let mut accumulator = ChatAccumulator::default();
|
||||
let mut collect = || {
|
||||
for event in events {
|
||||
for chunk in encoder.push_event(event["type"].as_str(), event)? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
Ok::<_, ChatError>(())
|
||||
};
|
||||
collect().and_then(|()| accumulator.finish())
|
||||
}
|
||||
for chunk in encoder.finish()? {
|
||||
accumulator.push(&chunk)?;
|
||||
}
|
||||
Ok::<_, ChatError>(())
|
||||
};
|
||||
match projected {
|
||||
Ok(value) => result.json = Some(value),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
collect().and_then(|()| accumulator.finish())
|
||||
};
|
||||
match projected {
|
||||
Ok(value) => result.json = Some(value),
|
||||
Err(error) => result.error = Some(error),
|
||||
}
|
||||
result
|
||||
}
|
||||
result
|
||||
}
|
||||
fn json_body(response: Projection) -> Value {
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
response.json.unwrap()
|
||||
}
|
||||
fn sse_body(response: Projection) -> (String, Vec<Value>) {
|
||||
fn stream_chunks(response: Projection) -> (String, Vec<Value>) {
|
||||
assert!(response.error.is_none(), "{:?}", response.error);
|
||||
(
|
||||
serde_json::to_string(&response.chunks).unwrap(),
|
||||
@@ -100,9 +81,6 @@ fn chat_identity() -> ChatIdentity {
|
||||
model: "model-a".to_owned(),
|
||||
}
|
||||
}
|
||||
fn chat_request(stream: bool) -> Value {
|
||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||
}
|
||||
fn wire(kind: &str, mut value: Value) -> Value {
|
||||
value["type"] = json!(kind);
|
||||
value
|
||||
@@ -135,8 +113,8 @@ fn tool(id: &str, call_id: &str, name: &str, arguments: &str) -> Value {
|
||||
|
||||
#[test]
|
||||
fn json_projects_public_identity_text_and_actual_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(json!([message("你好 🌍")]))]));
|
||||
let response = fixture.post(chat_request(false));
|
||||
let events = vec![completed(json!([message("你好 🌍")]))];
|
||||
let response = project_events(&events, false, false);
|
||||
let body = json_body(response);
|
||||
assert_eq!(body["object"], "chat.completion");
|
||||
assert!(body["id"].as_str().unwrap().starts_with("chatcmpl-"));
|
||||
@@ -164,7 +142,7 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
|
||||
let mut answer = message(&text);
|
||||
answer["content"][0]["annotations"] = json!([citation]);
|
||||
for stream in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.done",
|
||||
@@ -189,13 +167,11 @@ fn web_search_projects_citations_in_json_and_streams_the_original_links() {
|
||||
json!({"output_index":2,"item":answer}),
|
||||
),
|
||||
completed(json!([])),
|
||||
]));
|
||||
let mut request = chat_request(stream);
|
||||
request["web_search_options"] = json!({});
|
||||
let response = fixture.post(request);
|
||||
];
|
||||
let response = project_events(&events, stream, false);
|
||||
let expected = format!("🌍 {text}");
|
||||
if stream {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
assert_eq!(combined(&chunks, "content"), expected);
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
@@ -223,8 +199,8 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
{"type":"message","id":"refusal1","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]}]),
|
||||
] {
|
||||
let fixture = Fixture::new(Session::new(vec![completed(output.clone())]));
|
||||
let response = fixture.post(chat_request(false));
|
||||
let events = vec![completed(output.clone())];
|
||||
let response = project_events(&events, false, false);
|
||||
let body = json_body(response);
|
||||
let choice = &body["choices"][0];
|
||||
assert_eq!(choice["message"]["content"], Value::Null);
|
||||
@@ -245,7 +221,7 @@ fn json_tool_arguments_and_refusal_do_not_become_assistant_text() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
fn stream_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
for include_usage in [false, true] {
|
||||
let terminal = completed(json!([message("你好 🌍")]));
|
||||
let events = [
|
||||
@@ -316,7 +292,7 @@ fn sse_deduplicates_text_snapshots_and_emits_usage_only_when_requested() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
fn stream_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
let first = tool(
|
||||
"fc_first",
|
||||
"call_first",
|
||||
@@ -324,7 +300,7 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
"{ \"city\": \"北京\" }",
|
||||
);
|
||||
let second = tool("fc_second", "call_second", "search", "{\"query\":\"Rust\"}");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -355,8 +331,8 @@ fn sse_preserves_interleaved_tools_and_reordered_terminal_snapshots() {
|
||||
json!({"output_index":2,"item":first}),
|
||||
),
|
||||
completed(json!([second, first])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
let mut tools = BTreeMap::<u64, (String, String, String)>::new();
|
||||
for chunk in &chunks {
|
||||
if let Some(calls) = chunk["choices"][0]["delta"]["tool_calls"].as_array() {
|
||||
@@ -406,7 +382,7 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
|
||||
let mut text = message("preserved");
|
||||
text["future_optional"] = json!({"opaque":true});
|
||||
text["content"][0]["future_attribute"] = json!([1, 2, 3]);
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
wire("response.future_auxiliary", json!({"future":true})),
|
||||
wire(
|
||||
"response.future_reasoning.delta",
|
||||
@@ -414,8 +390,8 @@ fn extra_attributes_and_auxiliary_events_preserve_existing_chat_results() {
|
||||
),
|
||||
created(),
|
||||
completed(json!([text])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
assert_eq!(combined(&chunks, "content"), "preserved");
|
||||
assert!(
|
||||
!chunks
|
||||
@@ -430,7 +406,7 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
for streaming in [false, true] {
|
||||
let state =
|
||||
json!({"type":kind,"id":"ctx_1","encrypted_content":"opaque-private-state"});
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -441,10 +417,10 @@ fn compaction_state_preserves_chat_answer_without_exposing_ciphertext() {
|
||||
json!({"output_index":0,"item":state}),
|
||||
),
|
||||
completed(json!([state, message("preserved")])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (text, chunks) = sse_body(response);
|
||||
let (text, chunks) = stream_chunks(response);
|
||||
assert_eq!(combined(&chunks, "content"), "preserved");
|
||||
assert!(!text.contains("opaque-private-state"));
|
||||
assert_eq!(
|
||||
@@ -474,10 +450,10 @@ fn incomplete_projects_only_supported_finish_reasons() {
|
||||
"id":"resp_chat_test","status":"incomplete","output":[message("partial")],
|
||||
"incomplete_details":{"reason":reason}}}),
|
||||
);
|
||||
let fixture = Fixture::new(Session::new(vec![created(), event]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
let events = vec![created(), event];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
assert_eq!(
|
||||
chunks.last().unwrap()["choices"][0]["finish_reason"],
|
||||
expected
|
||||
@@ -497,7 +473,7 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
|
||||
"encrypted_content":"OPAQUE_ENCRYPTED_REASONING_MARKER"
|
||||
});
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -525,14 +501,10 @@ fn encrypted_reasoning_stays_private_while_public_text_and_usage_are_projected()
|
||||
"output_tokens_details":{"reasoning_tokens":2,"accepted_prediction_tokens":1}}
|
||||
}}),
|
||||
),
|
||||
]));
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request);
|
||||
];
|
||||
let response = project_events(&events, streaming, true);
|
||||
let (body, content, usage) = if streaming {
|
||||
let (body, chunks) = sse_body(response);
|
||||
let (body, chunks) = stream_chunks(response);
|
||||
let usage = chunks
|
||||
.iter()
|
||||
.find(|chunk| chunk["choices"] == json!([]))
|
||||
@@ -572,12 +544,8 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
|
||||
json!({"id":"action_native","type":"computer_call","status":"completed","call_id":"call_action","action":{"type":"click","x":1,"y":2}}),
|
||||
] {
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![created(), completed(json!([output]))]));
|
||||
let mut request = chat_request(streaming);
|
||||
if streaming {
|
||||
request["stream_options"] = json!({"include_usage":true});
|
||||
}
|
||||
let response = fixture.post(request);
|
||||
let events = vec![created(), completed(json!([output]))];
|
||||
let response = project_events(&events, streaming, true);
|
||||
assert_eq!(response.error, Some(ChatError::InvalidResponse));
|
||||
assert!(
|
||||
!response
|
||||
@@ -592,16 +560,15 @@ fn unrepresentable_business_output_fails_without_successful_chat_completion() {
|
||||
|
||||
#[test]
|
||||
fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"partial"}),
|
||||
),
|
||||
]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let response = fixture.post(body);
|
||||
];
|
||||
|
||||
let response = project_events(&events, true, true);
|
||||
assert_eq!(response.error, Some(ChatError::IncompleteStream));
|
||||
assert!(
|
||||
!response
|
||||
@@ -618,16 +585,15 @@ fn stream_without_terminal_does_not_emit_a_successful_finish_or_usage() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
let fixture = Fixture::new(Session::new(vec![wire(
|
||||
fn completed_event_without_usage_does_not_invent_usage() {
|
||||
let events = vec![wire(
|
||||
"response.completed",
|
||||
json!({"response":{
|
||||
"id":"resp_chat_test","status":"completed","output":[message("done only")]
|
||||
}}),
|
||||
)]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
)];
|
||||
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, true));
|
||||
assert_eq!(combined(&chunks, "content"), "done only");
|
||||
assert_eq!(
|
||||
chunks
|
||||
@@ -643,7 +609,7 @@ fn first_batch_terminal_can_finish_without_creating_usage_facts() {
|
||||
fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
let output = json!({"id":"msg_refusal","type":"message","role":"assistant","status":"completed",
|
||||
"content":[{"type":"refusal","refusal":"cannot help"}]});
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.refusal.delta",
|
||||
@@ -654,8 +620,8 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
json!({"item_id":"msg_refusal","output_index":0,"content_index":0,"refusal":"cannot help"}),
|
||||
),
|
||||
completed(json!([output])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
assert_eq!(combined(&chunks, "refusal"), "cannot help");
|
||||
assert_eq!(combined(&chunks, "content"), "");
|
||||
assert_eq!(
|
||||
@@ -667,23 +633,20 @@ fn refusal_deltas_and_done_snapshots_produce_only_standard_refusal() {
|
||||
#[test]
|
||||
fn auxiliary_events_after_completed_preserve_exactly_one_finish_and_usage() {
|
||||
for with_created in [false, true] {
|
||||
// 终态与辅助事件同属一批 Core 交付 不构造已终结会话继续产出事件的另一种异常
|
||||
let session = Session::new(if with_created {
|
||||
let mut events = if with_created {
|
||||
vec![created()]
|
||||
} else {
|
||||
Vec::new()
|
||||
})
|
||||
.with_batch(vec![
|
||||
};
|
||||
events.extend([
|
||||
completed(json!([message("completed text")])),
|
||||
wire(
|
||||
"response.future_metadata",
|
||||
json!({"response_id":"resp_chat_test","future":{"kept":true}}),
|
||||
),
|
||||
]);
|
||||
let fixture = Fixture::new(session);
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, true));
|
||||
assert_eq!(combined(&chunks, "content"), "completed text");
|
||||
assert_eq!(
|
||||
chunks
|
||||
@@ -727,10 +690,9 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
|
||||
failure
|
||||
}
|
||||
};
|
||||
let fixture = Fixture::new(Session::new(vec![created(), failure]));
|
||||
let mut body = chat_request(true);
|
||||
body["stream_options"] = json!({"include_usage":true});
|
||||
let (_, chunks) = sse_body(fixture.post(body));
|
||||
let events = vec![created(), failure];
|
||||
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, true));
|
||||
let errors = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk.get("error"))
|
||||
@@ -749,15 +711,15 @@ fn wire_failures_preserve_existing_recovery_fields_without_success_chunks() {
|
||||
|
||||
#[test]
|
||||
fn conflicting_text_snapshot_fails_instead_of_appending_replacement_content() {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
json!({"item_id":"msg_chat_test","output_index":0,"content_index":0,"delta":"already sent"}),
|
||||
),
|
||||
completed(json!([message("different result")])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(true));
|
||||
];
|
||||
let response = project_events(&events, true, false);
|
||||
assert_eq!(response.error, Some(ChatError::InvalidResponse));
|
||||
assert_eq!(combined(&response.chunks, "content"), "already sent");
|
||||
assert!(
|
||||
@@ -795,7 +757,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
|
||||
initial_custom["input"] = json!("");
|
||||
let mut initial_function = function.clone();
|
||||
initial_function["arguments"] = json!("");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_item.added",
|
||||
@@ -818,10 +780,10 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
|
||||
json!({"output_index":0,"item_id":"ct_1","input":"first\nsecond"}),
|
||||
),
|
||||
completed(output.clone()),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (body, chunks) = sse_body(response);
|
||||
let (body, chunks) = stream_chunks(response);
|
||||
assert_eq!(combined(&chunks, "refusal"), "no");
|
||||
assert_eq!(combined(&chunks, "reasoning_content"), "thought");
|
||||
assert!(!body.contains("PRIVATE_REASONING"));
|
||||
@@ -870,7 +832,7 @@ fn custom_and_function_calls_keep_distinct_shapes_in_json_and_interleaved_stream
|
||||
fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
|
||||
let image = json!({"id":"ig_one","type":"image_generation_call","status":"completed","result":"ZmluYWw=","output_format":"webp"});
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.image_generation_call.partial_image",
|
||||
@@ -881,10 +843,10 @@ fn image_previews_and_final_images_are_projected_once_per_distinct_snapshot() {
|
||||
json!({"output_index":0,"item":image}),
|
||||
),
|
||||
completed(json!([image, message("created")])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
let images = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk["choices"][0]["delta"]["images"].as_array())
|
||||
@@ -913,7 +875,7 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
|
||||
let mut output = message("hello");
|
||||
output["content"][0]["logprobs"] = probabilities.clone();
|
||||
for streaming in [false, true] {
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
@@ -924,10 +886,10 @@ fn output_logprobs_survive_json_projection_and_stream_snapshot_deduplication() {
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","text":"hello","logprobs":probabilities}),
|
||||
),
|
||||
completed(json!([output])),
|
||||
]));
|
||||
let response = fixture.post(chat_request(streaming));
|
||||
];
|
||||
let response = project_events(&events, streaming, false);
|
||||
if streaming {
|
||||
let (_, chunks) = sse_body(response);
|
||||
let (_, chunks) = stream_chunks(response);
|
||||
let values = chunks
|
||||
.iter()
|
||||
.filter_map(|chunk| chunk["choices"][0]["logprobs"]["content"].as_array())
|
||||
@@ -951,7 +913,7 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
|
||||
first["content"][0]["annotations"] = json!([citation]);
|
||||
let mut second = message("xy");
|
||||
second["id"] = json!("msg_second");
|
||||
let fixture = Fixture::new(Session::new(vec![
|
||||
let events = vec![
|
||||
created(),
|
||||
wire(
|
||||
"response.output_text.delta",
|
||||
@@ -970,8 +932,8 @@ fn streaming_citation_offsets_follow_delivered_text_when_messages_interleave() {
|
||||
json!({"output_index":0,"content_index":0,"item_id":"msg_chat_test","annotation_index":0,"annotation":citation}),
|
||||
),
|
||||
completed(json!([first, second])),
|
||||
]));
|
||||
let (_, chunks) = sse_body(fixture.post(chat_request(true)));
|
||||
];
|
||||
let (_, chunks) = stream_chunks(project_events(&events, true, false));
|
||||
assert_eq!(combined(&chunks, "content"), "abxycd");
|
||||
let annotations = chunks
|
||||
.iter()
|
||||
|
||||
@@ -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(¤t.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)
|
||||
|
||||
@@ -458,6 +458,8 @@ pub(super) const IMAGE_MODELS: &[&str] = &[
|
||||
"gpt-image-2.5-sunburst-2026-09-08",
|
||||
"gpt-image-2.5-flare",
|
||||
"gpt-image-2.5-flare-2026-09-08",
|
||||
"gpt-image-2.6-sunburst",
|
||||
"gpt-image-2.6-flare",
|
||||
];
|
||||
pub(super) const IMAGE_TEXT_RATES: TokenRates = TokenRates::new(50_000, 0, 12_500);
|
||||
pub(super) const IMAGE_TOKEN_RATES: TokenRates = TokenRates::new(80_000, 300_000, 20_000);
|
||||
|
||||
@@ -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(¤t.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(¤t.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(¤t).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(¤t, 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(¤t, 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(
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
//! 物理 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,
|
||||
};
|
||||
|
||||
use super::history::{HistoryItem, fingerprint};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct WebSocketContinuationState {
|
||||
latest_response_id: Option<String>,
|
||||
@@ -58,9 +54,9 @@ impl WebSocketContinuationState {
|
||||
.history
|
||||
.as_ref()
|
||||
.map_or(0, |last| last.total.count.min(items.len()));
|
||||
input.extend(&items[..cut]);
|
||||
input.extend(items[..cut].iter().map(HistoryItem::Input));
|
||||
let reuse = self.history.is_some_and(|last| last.total == input);
|
||||
input.extend(&items[cut..]);
|
||||
input.extend(items[cut..].iter().map(HistoryItem::Input));
|
||||
if reuse && let Some(id) = self.latest_response_id.filter(|id| !id.is_empty()) {
|
||||
items.drain(..cut);
|
||||
request.set_previous_response_id(Some(id));
|
||||
@@ -84,7 +80,7 @@ impl WebSocketContinuationState {
|
||||
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);
|
||||
history.total.push(HistoryItem::Output(item));
|
||||
} else {
|
||||
self.history = None;
|
||||
}
|
||||
@@ -100,7 +96,7 @@ impl WebSocketContinuationState {
|
||||
self.history = None;
|
||||
} else {
|
||||
history.total = history.input;
|
||||
history.total.extend(output);
|
||||
history.total.extend(output.iter().map(HistoryItem::Output));
|
||||
}
|
||||
} else if history.total.count - history.input.count < history.added {
|
||||
self.history = None;
|
||||
@@ -122,45 +118,6 @@ struct HttpHistory {
|
||||
added: usize,
|
||||
}
|
||||
|
||||
// 对齐 Codex 的历史项比较,保留工具结果及其调用绑定,只借用正文计算摘要
|
||||
fn history_digest(previous: [u8; 32], item: &Value) -> [u8; 32] {
|
||||
let Some(fields) = item.as_object() else {
|
||||
return fingerprint((previous, 0_u8, item));
|
||||
};
|
||||
let kind = item["type"].as_str();
|
||||
let sampled = matches!(
|
||||
kind,
|
||||
Some("reasoning" | "function_call" | "custom_tool_call")
|
||||
) || (kind == Some("message") && item["role"] == "assistant");
|
||||
let content: BTreeMap<_, _> = fields
|
||||
.iter()
|
||||
.filter(|(key, value)| match key.as_str() {
|
||||
"internal_chat_message_metadata_passthrough" => false,
|
||||
"metadata" if sampled => false,
|
||||
// Codex 回传空推理内容时可省略 content
|
||||
"content" if kind == Some("reasoning") => {
|
||||
!(value.is_null() || value.as_array().is_some_and(Vec::is_empty))
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
.collect();
|
||||
let results: Vec<_> = item["internal_chat_message_metadata_passthrough"]["executed_tool_calls"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter_map(|(index, call)| {
|
||||
Some((
|
||||
index,
|
||||
call.get("name"),
|
||||
call.get("arguments"),
|
||||
call.get("tool_result_metadata")?,
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
fingerprint((previous, 1_u8, content, results))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
struct Prefix {
|
||||
count: usize,
|
||||
@@ -168,33 +125,14 @@ struct Prefix {
|
||||
}
|
||||
|
||||
impl Prefix {
|
||||
fn extend(&mut self, items: &[Value]) {
|
||||
fn extend<'a>(&mut self, items: impl IntoIterator<Item = HistoryItem<'a>>) {
|
||||
for item in items {
|
||||
self.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, item: &Value) {
|
||||
self.digest = history_digest(self.digest, item);
|
||||
fn push(&mut self, item: HistoryItem<'_>) {
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Codex 历史项回传形状的只读摘要投影,不改写或留存业务正文
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
// 基准:openai/codex rust-v0.174.0,models.rs 的 ResponseItem 及嵌套线协议
|
||||
// https://github.com/openai/codex/blob/2d42293d1d32079068f1e4ed8aa70fdbf146ec01/codex-rs/protocol/src/models.rs
|
||||
// 官方先解析类型再回传,不能直接比较上游 JSON 中未被客户端保留的字段
|
||||
#[derive(Clone, Copy)]
|
||||
enum Shape {
|
||||
Item,
|
||||
Content,
|
||||
AgentContent,
|
||||
ToolOutput,
|
||||
Summary,
|
||||
ReasoningContent,
|
||||
WebSearchAction,
|
||||
ShellAction,
|
||||
ConfigurationReasoning,
|
||||
}
|
||||
|
||||
pub(super) enum HistoryItem<'a> {
|
||||
Input(&'a Value),
|
||||
Output(&'a Value),
|
||||
}
|
||||
|
||||
impl Hash for HistoryItem<'_> {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
let (Self::Input(value) | Self::Output(value)) = self;
|
||||
hash_value(value, Shape::Item, state);
|
||||
let kind = value["type"].as_str().unwrap_or_default();
|
||||
if fields(Shape::Item, kind, value).is_some()
|
||||
&& !matches!(
|
||||
kind,
|
||||
"additional_tools" | "configuration_update" | "compaction_trigger"
|
||||
)
|
||||
{
|
||||
// 上游 JSON 的结果元数据被官方 skip_deserializing,客户端回传的宿主结果则必须比较
|
||||
if matches!(self, Self::Input(_)) {
|
||||
hash_tool_results(value, state);
|
||||
} else {
|
||||
false.hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hash_value<H: Hasher>(value: &Value, shape: Shape, state: &mut H) {
|
||||
if let Some(items) = value.as_array()
|
||||
&& !matches!(shape, Shape::Item)
|
||||
{
|
||||
0_u8.hash(state);
|
||||
items.len().hash(state);
|
||||
for item in items {
|
||||
hash_value(item, shape, state);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let kind = value
|
||||
.get("type")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let kind = match (shape, kind) {
|
||||
(Shape::Item, "compaction_summary") => "compaction",
|
||||
(Shape::ConfigurationReasoning, _) => "",
|
||||
_ => kind,
|
||||
};
|
||||
let Some(fields) = value.as_object().and_then(|_| fields(shape, kind, value)) else {
|
||||
// 未知类型和非对象值仍按原值比较,不能像客户端 Other 一样合并不同正文
|
||||
1_u8.hash(state);
|
||||
value.hash(state);
|
||||
return;
|
||||
};
|
||||
2_u8.hash(state);
|
||||
kind.hash(state);
|
||||
for field in fields {
|
||||
let child = &value[*field];
|
||||
match (shape, kind, *field) {
|
||||
// 空 reasoning.content 在官方序列化时省略,其他空数组仍是有意义的值
|
||||
(Shape::Item, "reasoning", "content") if child.is_null() => {
|
||||
hash_value(&Value::Array(Vec::new()), Shape::ReasoningContent, state);
|
||||
}
|
||||
(Shape::Item, "message", "content") => hash_value(child, Shape::Content, state),
|
||||
(Shape::Item, "agent_message", "content") => {
|
||||
hash_value(child, Shape::AgentContent, state);
|
||||
}
|
||||
(Shape::Item, "reasoning", "summary") => hash_value(child, Shape::Summary, state),
|
||||
(Shape::Item, "reasoning", "content") => {
|
||||
hash_value(child, Shape::ReasoningContent, state);
|
||||
}
|
||||
(Shape::Item, "function_call_output" | "custom_tool_call_output", "output") => {
|
||||
hash_value(child, Shape::ToolOutput, state);
|
||||
}
|
||||
(Shape::Item, "web_search_call", "action") => {
|
||||
hash_value(child, Shape::WebSearchAction, state);
|
||||
}
|
||||
(Shape::Item, "local_shell_call", "action") => {
|
||||
hash_value(child, Shape::ShellAction, state);
|
||||
}
|
||||
(Shape::Item, "configuration_update", "reasoning") => {
|
||||
hash_value(child, Shape::ConfigurationReasoning, state);
|
||||
}
|
||||
// arguments、工具定义、schema、annotations 和 logprobs 都保留完整 JSON
|
||||
_ => child.hash(state),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(shape: Shape, kind: &str, value: &Value) -> Option<&'static [&'static str]> {
|
||||
Some(match (shape, kind) {
|
||||
(Shape::Item, "additional_tools") => &["id", "role", "tools"],
|
||||
(Shape::Item, "message") => &[
|
||||
"encrypted_content",
|
||||
"status",
|
||||
"id",
|
||||
"role",
|
||||
"content",
|
||||
"phase",
|
||||
],
|
||||
(Shape::Item, "agent_message") => &["id", "author", "recipient", "content"],
|
||||
(Shape::Item, "reasoning") => &["id", "summary", "content", "encrypted_content"],
|
||||
(Shape::Item, "local_shell_call") => {
|
||||
&["encrypted_content", "id", "call_id", "status", "action"]
|
||||
}
|
||||
(Shape::Item, "function_call") => &[
|
||||
"encrypted_content",
|
||||
"status",
|
||||
"id",
|
||||
"name",
|
||||
"namespace",
|
||||
"arguments",
|
||||
"encrypted_function_args",
|
||||
"call_id",
|
||||
],
|
||||
(Shape::Item, "tool_search_call") => &[
|
||||
"encrypted_content",
|
||||
"id",
|
||||
"call_id",
|
||||
"status",
|
||||
"execution",
|
||||
"arguments",
|
||||
],
|
||||
(Shape::Item, "function_call_output") => &["id", "call_id", "name", "namespace", "output"],
|
||||
(Shape::Item, "custom_tool_call") => &[
|
||||
"encrypted_content",
|
||||
"id",
|
||||
"status",
|
||||
"call_id",
|
||||
"name",
|
||||
"namespace",
|
||||
"input",
|
||||
],
|
||||
(Shape::Item, "custom_tool_call_output") => &["id", "call_id", "name", "output"],
|
||||
(Shape::Item, "tool_search_output") => &["id", "call_id", "status", "execution", "tools"],
|
||||
(Shape::Item, "web_search_call") => &["encrypted_content", "id", "status", "action"],
|
||||
(Shape::Item, "image_generation_call") => &[
|
||||
"encrypted_content",
|
||||
"id",
|
||||
"status",
|
||||
"revised_prompt",
|
||||
"result",
|
||||
],
|
||||
(Shape::Item, "compaction" | "compaction_summary" | "context_compaction") => {
|
||||
&["id", "encrypted_content"]
|
||||
}
|
||||
(Shape::Item, "configuration_update") => &["reasoning"],
|
||||
(Shape::Item, "compaction_trigger") => &[],
|
||||
(Shape::Content | Shape::AgentContent | Shape::ToolOutput, "input_text")
|
||||
| (Shape::Summary, "summary_text")
|
||||
| (Shape::ReasoningContent, "reasoning_text" | "text") => &["text"],
|
||||
(Shape::Content, "output_text") => &["text", "annotations", "logprobs"],
|
||||
(Shape::AgentContent | Shape::ToolOutput, "encrypted_content") => &["encrypted_content"],
|
||||
(Shape::Content | Shape::ToolOutput, "input_image") => {
|
||||
if value.get("image_url").is_some_and(Value::is_string) {
|
||||
&["image_url", "detail"]
|
||||
} else {
|
||||
&["file_id", "detail"]
|
||||
}
|
||||
}
|
||||
(Shape::Content | Shape::ToolOutput, "input_audio") => {
|
||||
if value.get("audio_url").is_some_and(Value::is_string) {
|
||||
&["audio_url"]
|
||||
} else {
|
||||
&["file_id"]
|
||||
}
|
||||
}
|
||||
(Shape::WebSearchAction, "search") => &["query", "queries"],
|
||||
(Shape::WebSearchAction, "open_page") => &["url"],
|
||||
(Shape::WebSearchAction, "find_in_page") => &["url", "pattern"],
|
||||
(Shape::ShellAction, "exec") => {
|
||||
&["command", "timeout_ms", "working_directory", "env", "user"]
|
||||
}
|
||||
(Shape::ConfigurationReasoning, "") => &["effort"],
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn hash_tool_results<H: Hasher>(item: &Value, state: &mut H) {
|
||||
// 官方比较宿主已记录的结果及调用绑定;反序列化会丢掉这些可信字段,不能借此忽略更新
|
||||
// result ID 只存在于客户端内存,线上可比较的事实是原始 metadata、调用位置、名称和参数
|
||||
for (index, call) in item["internal_chat_message_metadata_passthrough"]["executed_tool_calls"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
{
|
||||
if let Some(result) = call.get("tool_result_metadata") {
|
||||
true.hash(state);
|
||||
(index, call.get("name"), call.get("arguments"), result).hash(state);
|
||||
}
|
||||
}
|
||||
false.hash(state);
|
||||
}
|
||||
|
||||
// Value 的 Hash 忽略对象键顺序、保留数组顺序;摘要只在当前进程的连接租约内比较
|
||||
pub(super) 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()
|
||||
}
|
||||
@@ -8,6 +8,7 @@ mod coordinator;
|
||||
mod error;
|
||||
mod exchange;
|
||||
mod handshake;
|
||||
mod history;
|
||||
mod live;
|
||||
mod model;
|
||||
mod pool;
|
||||
|
||||
@@ -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(¤t)
|
||||
.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(
|
||||
¤t,
|
||||
secret("concurrent-refresh"),
|
||||
current.access_token_expires_at(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
Ok(if self.busy {
|
||||
ProviderLeaseAcquisition::Busy { retry_after: None }
|
||||
} else {
|
||||
|
||||
@@ -603,7 +603,7 @@ async fn openai_admin_provider_exposes_live_wire_profile_and_validated_billing()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn openai_legacy_billing_should_not_infer_long_context_flag() {
|
||||
async fn openai_billing_reconstruction_does_not_infer_long_context_flag() {
|
||||
let config = valid_config();
|
||||
let bundle = provider_openai::initialize(
|
||||
config.config.clone(),
|
||||
@@ -626,7 +626,7 @@ async fn openai_legacy_billing_should_not_infer_long_context_flag() {
|
||||
amount: "1.5".parse().expect("stored total"),
|
||||
},
|
||||
})
|
||||
.expect("legacy billing")
|
||||
.expect("reconstructed billing")
|
||||
.expect("matching billing breakdown");
|
||||
|
||||
assert_eq!(billing.total_amount.amount.as_str(), "1.5");
|
||||
|
||||
@@ -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(
|
||||
¤t(),
|
||||
secret(access_token),
|
||||
Some(SystemTime::now() + Duration::from_secs(3600)),
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
};
|
||||
reject(¤t(), "initial");
|
||||
rotate("renewed");
|
||||
let block_path = |token: &str| {
|
||||
block_on(selector.record_failure(
|
||||
¤t(),
|
||||
&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(¤t(), 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(
|
||||
¤t(),
|
||||
&oauth_auth(token),
|
||||
CodexAccountFailure::CredentialExpired,
|
||||
None,
|
||||
))
|
||||
.unwrap();
|
||||
};
|
||||
reject("original");
|
||||
block_on(store.repository().rotate_refreshed_oauth_secret(
|
||||
¤t(),
|
||||
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(
|
||||
¤t,
|
||||
&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(¤t));
|
||||
block_on(selector.record_success(¤t, 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(
|
||||
¤t(),
|
||||
&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(
|
||||
¤t(),
|
||||
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(¤t, CodexAccountFailure::QuotaExhausted, None))
|
||||
.expect("record failure with current revision");
|
||||
block_on(selector.record_failure(
|
||||
¤t,
|
||||
&oauth_auth("at-primary"),
|
||||
CodexAccountFailure::QuotaExhausted,
|
||||
None,
|
||||
))
|
||||
.expect("record failure with current revision");
|
||||
assert_eq!(
|
||||
store
|
||||
.account("acct_primary")
|
||||
|
||||
@@ -112,7 +112,7 @@ async fn mount_warmup(server: &MockServer, expected: u64) {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart() {
|
||||
async fn second_precision_progress_waits_five_minutes_and_claim_survives_restart() {
|
||||
let (store, server, now, reset) = setup().await;
|
||||
let quota = service(&store, &server);
|
||||
mount_usage(&server, reset + 604800, 0, 1).await;
|
||||
@@ -128,13 +128,13 @@ async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart()
|
||||
);
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
let account = store.account("acct_bucket_warmup").unwrap();
|
||||
let mut legacy = store
|
||||
let mut stored = store
|
||||
.load_quota_warmup_state(&account)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
// 升级前的进度以整秒持久化,新读取器仍须沿用该边界与并发领取约束。
|
||||
legacy.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset);
|
||||
// 整秒时间戳沿用同一预热边界与并发领取约束
|
||||
stored.data.get_mut("buckets").unwrap()["codex:604800s"]["reset_at"] = json!(reset);
|
||||
let observed_at = store
|
||||
.get_quotas(std::slice::from_ref(account.id()))
|
||||
.await
|
||||
@@ -144,9 +144,9 @@ async fn legacy_progress_waits_five_minutes_and_claim_survives_service_restart()
|
||||
store
|
||||
.compare_and_swap_quota_warmup_state(QuotaWarmupStateUpdate {
|
||||
account: &account,
|
||||
expected_version: legacy.version,
|
||||
expected_version: stored.version,
|
||||
expected_quota_observed_at: Some(observed_at),
|
||||
data: legacy.data,
|
||||
data: stored.data,
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
|
||||
@@ -486,13 +486,13 @@ async fn a_new_exhaustion_cannot_reuse_partial_recovery_from_the_previous_failur
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() {
|
||||
async fn stored_weekly_exhaustion_uses_window_evidence_over_account_reset() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_old_weekly").await;
|
||||
let account = store.account("acct_old_weekly").expect("account");
|
||||
create_account(&store, "acct_weekly_reset").await;
|
||||
let account = store.account("acct_weekly_reset").expect("account");
|
||||
let observed_at = SystemTime::now();
|
||||
let mut old = usage((88, SHORT_RESET), (100, WEEK_RESET));
|
||||
old["rate_limit"]["allowed"] = json!(false);
|
||||
let mut stored = usage((88, SHORT_RESET), (100, WEEK_RESET));
|
||||
stored["rate_limit"]["allowed"] = json!(false);
|
||||
store
|
||||
.compare_and_swap_quota(gateway_core::account::QuotaObservation {
|
||||
quota_pause: None,
|
||||
@@ -501,7 +501,7 @@ async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() {
|
||||
account_id: account.id().clone(),
|
||||
expected_revision: account.revision(),
|
||||
quota: gateway_core::account::OpaqueProviderData::new(
|
||||
old.as_object().expect("document").clone(),
|
||||
stored.as_object().expect("document").clone(),
|
||||
),
|
||||
observed_at,
|
||||
state: QuotaState::exhausted(
|
||||
@@ -511,7 +511,7 @@ async fn stored_weekly_exhaustion_ignores_the_old_primary_only_account_reset() {
|
||||
),
|
||||
})
|
||||
.await
|
||||
.expect("seed old persisted quota");
|
||||
.expect("seed stored quota");
|
||||
let server = MockServer::start().await;
|
||||
let service = quota_service_with_base_url(&store, reqwest::Client::new(), server.uri());
|
||||
mount_usage(&server, usage((88, SHORT_RESET), (0, WEEK_RESET + 604_800))).await;
|
||||
@@ -565,7 +565,7 @@ async fn an_unknown_slot_establishes_a_baseline_before_it_can_recover() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn legacy_exhaustion_recovers_after_two_nonfull_observations_despite_reset_drift() {
|
||||
async fn exhaustion_without_reset_recovers_after_two_nonfull_observations_despite_reset_drift() {
|
||||
for (first, second) in [(0, 1), (1, 1), (2, 2), (2, 60), (3600, 7200)] {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
let id = "acct_drifting_reset";
|
||||
@@ -579,7 +579,7 @@ async fn legacy_exhaustion_recovers_after_two_nonfull_observations_despite_reset
|
||||
old["rate_limit"]["allowed"] = json!(true);
|
||||
mount_usage(&server, old).await;
|
||||
service.refresh_account(account.id()).await.unwrap();
|
||||
// 旧版流内拒绝保留最近的用量,但未记录错误 reset,两个窗口都需复核
|
||||
// 拒绝状态缺少重置时间时,两个窗口都需复核
|
||||
persist_quota_state(&store, &account, exhausted_quota(None)).await;
|
||||
for (offset, exhausted) in [(first, true), (second, false)] {
|
||||
let mut fresh = usage((0, now + 18_000), (16, week + offset));
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -3218,6 +3218,8 @@ async fn image_prices_should_use_modality_rates_and_precede_delivery() {
|
||||
(ImageRequestKind::Edit, "gpt-image-2.5-sunburst-2026-09-08"),
|
||||
(ImageRequestKind::Generation, "gpt-image-2.5-flare"),
|
||||
(ImageRequestKind::Edit, "gpt-image-2.5-flare-2026-09-08"),
|
||||
(ImageRequestKind::Generation, "gpt-image-2.6-sunburst"),
|
||||
(ImageRequestKind::Edit, "gpt-image-2.6-flare"),
|
||||
] {
|
||||
let events = image_metering_events(kind, &response, model).await;
|
||||
let costs = events
|
||||
@@ -3272,6 +3274,8 @@ async fn image_prices_should_remain_unknown_when_modality_or_model_is_uncertain(
|
||||
("gpt-image-2.5", valid.clone()),
|
||||
("gpt-image-2.5-sunburst-future", valid.clone()),
|
||||
("gpt-image-2.5-flare-future", valid.clone()),
|
||||
("gpt-image-2.6", valid.clone()),
|
||||
("gpt-image-2.6-flare-future", valid.clone()),
|
||||
("gpt-image-2", json!(null)),
|
||||
(
|
||||
"gpt-image-2",
|
||||
|
||||
@@ -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");
|
||||
};
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
//! 官方历史项回传、业务变更与可信工具结果的多轮出站验证
|
||||
|
||||
use super::*;
|
||||
|
||||
struct Exchange {
|
||||
name: String,
|
||||
input: Vec<Value>,
|
||||
output: Vec<Value>,
|
||||
previous: Option<usize>,
|
||||
expected: Vec<Value>,
|
||||
request_fields: Map<String, Value>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
fn full(name: String, input: Vec<Value>, output: Vec<Value>) -> Self {
|
||||
Self {
|
||||
name,
|
||||
expected: input.clone(),
|
||||
input,
|
||||
output,
|
||||
previous: None,
|
||||
request_fields: Map::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_history_matches_official_item_replay_and_preserves_business_changes() {
|
||||
// replay 由固定官方源码的 serde 声明独立生成,不调用网关投影生成预期
|
||||
let fixture: Value = serde_json::from_str(include_str!("history_items.json")).unwrap();
|
||||
let mut exchanges = Vec::new();
|
||||
for case in fixture["cases"].as_array().unwrap() {
|
||||
let name = case["name"].as_str().unwrap();
|
||||
let upstream = &case["upstream"];
|
||||
let replay = &case["replay"];
|
||||
let is_output = case["output"].as_bool().unwrap();
|
||||
// 同一基线分别验证等价回传及每个业务字段变化,错误信息直接给出类型和字段
|
||||
for (field, change) in std::iter::once(("", &Value::Null)).chain(
|
||||
case["changes"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(field, value)| (field.as_str(), value)),
|
||||
) {
|
||||
let user = json!({"type":"message","role":"user","content":[{"type":"input_text","text":format!("{name}:{field}")}]});
|
||||
let next = json!({"type":"message","role":"user","content":[{"type":"input_text","text":"next"}]});
|
||||
let first = exchanges.len();
|
||||
let input = if is_output {
|
||||
vec![user.clone()]
|
||||
} else {
|
||||
vec![user.clone(), upstream.clone()]
|
||||
};
|
||||
let output = if is_output {
|
||||
vec![upstream.clone()]
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
exchanges.push(Exchange::full(
|
||||
format!("{name}:{field}:baseline"),
|
||||
input,
|
||||
output,
|
||||
));
|
||||
let mut replay = replay.clone();
|
||||
if !field.is_empty() {
|
||||
let (parent, key) = field.rsplit_once('/').unwrap();
|
||||
let target = replay.pointer_mut(parent).unwrap();
|
||||
if let Some(object) = target.as_object_mut() {
|
||||
object.insert(key.to_owned(), change.clone());
|
||||
} else {
|
||||
target[key.parse::<usize>().unwrap()] = change.clone();
|
||||
}
|
||||
}
|
||||
let input = vec![user, replay, next.clone()];
|
||||
let expected = if field.is_empty() {
|
||||
vec![next]
|
||||
} else {
|
||||
input.clone()
|
||||
};
|
||||
exchanges.push(Exchange {
|
||||
name: format!("{name}:{field}:replay"),
|
||||
input,
|
||||
output: vec![],
|
||||
previous: field.is_empty().then_some(first),
|
||||
expected,
|
||||
request_fields: Map::new(),
|
||||
});
|
||||
}
|
||||
}
|
||||
assert_exchanges(exchanges).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_history_keeps_unknown_items_and_late_tool_results_distinct() {
|
||||
let result = json!({"type":"function_call_output","call_id":"call","output":"result",
|
||||
"internal_chat_message_metadata_passthrough":{"turn_id":"one","executed_tool_calls":[
|
||||
{"name":"lookup","arguments":{"q":1},"tool_result_metadata":{"revision":1}}
|
||||
]}});
|
||||
let mut metadata_only = result.clone();
|
||||
metadata_only["internal_chat_message_metadata_passthrough"]["turn_id"] = json!("two");
|
||||
metadata_only["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]["tool_result_sources"] =
|
||||
json!([{"type":"mcp","id":"source"}]);
|
||||
let mut cases = vec![("analytics", result.clone(), metadata_only, true)];
|
||||
for (field, value) in [
|
||||
("tool_result_metadata", json!({"revision":2})),
|
||||
("tool_result_metadata", Value::Null),
|
||||
(
|
||||
"tool_result_metadata",
|
||||
json!("omitted_due_to_size_limit (overage_bytes=128)"),
|
||||
),
|
||||
("name", json!("other")),
|
||||
("arguments", json!({"q":2})),
|
||||
] {
|
||||
let mut changed = result.clone();
|
||||
changed["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0][field] =
|
||||
value;
|
||||
cases.push((field, result.clone(), changed, false));
|
||||
}
|
||||
let mut removed = result.clone();
|
||||
removed["internal_chat_message_metadata_passthrough"]["executed_tool_calls"][0]
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.shift_remove("tool_result_metadata");
|
||||
cases.push(("removed_result", result.clone(), removed, false));
|
||||
let mut reordered = result.clone();
|
||||
reordered["internal_chat_message_metadata_passthrough"]["executed_tool_calls"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.insert(0, json!({"name":"unobserved","arguments":{}}));
|
||||
cases.push(("call_order", result, reordered, false));
|
||||
cases.push((
|
||||
"unknown_item",
|
||||
json!({"type":"future_item","content":"one"}),
|
||||
json!({"type":"future_item","content":"two"}),
|
||||
false,
|
||||
));
|
||||
cases.push((
|
||||
"unknown_metadata",
|
||||
json!({"type":"future_item","metadata":1}),
|
||||
json!({"type":"future_item","metadata":2}),
|
||||
false,
|
||||
));
|
||||
cases.push((
|
||||
"unknown_content",
|
||||
json!({"type":"message","role":"assistant","content":[{"type":"future_content","data":1}]}),
|
||||
json!({"type":"message","role":"assistant","content":[{"type":"future_content","data":2}]}),
|
||||
false,
|
||||
));
|
||||
let mut exchanges = Vec::new();
|
||||
for (index, (name, previous, current, reuse)) in cases.into_iter().enumerate() {
|
||||
let user = json!({"role":"user","content":format!("case {index}")});
|
||||
let next = json!({"role":"user","content":"next"});
|
||||
let first = exchanges.len();
|
||||
exchanges.push(Exchange::full(
|
||||
name.to_owned(),
|
||||
vec![user.clone(), previous],
|
||||
vec![],
|
||||
));
|
||||
let input = vec![user, current, next.clone()];
|
||||
exchanges.push(Exchange {
|
||||
name: name.to_owned(),
|
||||
expected: if reuse { vec![next] } else { input.clone() },
|
||||
input,
|
||||
output: vec![],
|
||||
previous: reuse.then_some(first),
|
||||
request_fields: Map::new(),
|
||||
});
|
||||
}
|
||||
assert_exchanges(exchanges).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_history_compares_codex_properties_and_forwards_per_response_fields() {
|
||||
// core/src/client.rs::responses_request_properties_mismatch 的全部字段
|
||||
let baseline = json!({
|
||||
"model":"model", "tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}],
|
||||
"tool_choice":"auto", "parallel_tool_calls":true,
|
||||
"reasoning":{"effort":"high","summary":"auto"}, "store":false,"stream":true,
|
||||
"include":["reasoning.encrypted_content"], "service_tier":"auto", "prompt_cache_key":"cache",
|
||||
"prompt_cache_options":{"ttl":"30m"}, "text":{"verbosity":"medium"}
|
||||
});
|
||||
let changes = [
|
||||
("model", json!("other"), false),
|
||||
("tools", json!([{"type":"function","name":"other"}]), false),
|
||||
("tool_choice", json!("required"), false),
|
||||
("parallel_tool_calls", json!(false), false),
|
||||
("reasoning", json!({"effort":"low","summary":"auto"}), false),
|
||||
("store", json!(true), false),
|
||||
("stream", json!(false), false),
|
||||
("include", json!([]), false),
|
||||
("service_tier", json!("priority"), false),
|
||||
("prompt_cache_key", json!("other"), false),
|
||||
("prompt_cache_options", json!({"ttl":"12h"}), false),
|
||||
("text", json!({"verbosity":"high"}), false),
|
||||
("generate", json!(false), false),
|
||||
("client_metadata", json!({"turn_id":"next"}), true),
|
||||
(
|
||||
"stream_options",
|
||||
json!({"reasoning_summary_delivery":"sequential_cutoff"}),
|
||||
true,
|
||||
),
|
||||
("access_programs", json!({"cyber":"standard"}), true),
|
||||
("request_country", json!("US"), true),
|
||||
("instructions", json!("current instructions"), true),
|
||||
("client_extension", json!({"turn":2}), true),
|
||||
];
|
||||
let mut exchanges = Vec::new();
|
||||
for (field, value, reuse) in changes {
|
||||
let user = json!({"role":"user","content":field});
|
||||
let next = json!({"role":"user","content":"next"});
|
||||
let first = exchanges.len();
|
||||
let mut initial = Exchange::full(field.to_owned(), vec![user.clone()], vec![]);
|
||||
initial.request_fields = baseline.as_object().unwrap().clone();
|
||||
exchanges.push(initial);
|
||||
let input = vec![user, next.clone()];
|
||||
let mut request_fields = baseline.as_object().unwrap().clone();
|
||||
request_fields.insert(field.to_owned(), value);
|
||||
exchanges.push(Exchange {
|
||||
name: field.to_owned(),
|
||||
expected: if reuse { vec![next] } else { input.clone() },
|
||||
input,
|
||||
output: vec![],
|
||||
previous: reuse.then_some(first),
|
||||
request_fields,
|
||||
});
|
||||
}
|
||||
assert_exchanges(exchanges).await;
|
||||
}
|
||||
|
||||
async fn assert_exchanges(exchanges: Vec<Exchange>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let outputs: Vec<_> = exchanges
|
||||
.iter()
|
||||
.map(|exchange| exchange.output.clone())
|
||||
.collect();
|
||||
let (frames, mut seen) = tokio::sync::mpsc::unbounded_channel();
|
||||
let server = tokio::spawn(async move {
|
||||
let (socket, _) = listener.accept().await.unwrap();
|
||||
let mut ws = accept_codex_test_websocket(socket).await;
|
||||
for (turn, output) in outputs.into_iter().enumerate() {
|
||||
let frame = ws.next().await.unwrap().unwrap().into_text().unwrap();
|
||||
frames
|
||||
.send(serde_json::from_str::<Value>(&frame).unwrap())
|
||||
.unwrap();
|
||||
for (index, item) in output.iter().enumerate() {
|
||||
for event in ["response.output_item.added", "response.output_item.done"] {
|
||||
ws.send(Message::Text(
|
||||
json!({"type":event,"output_index":index,"item":item})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
// 分别覆盖只提供流式完成项和终态同时携带完整 output 的上游
|
||||
let output = if turn % 4 == 0 { output } else { vec![] };
|
||||
ws.send(Message::Text(json!({"type":"response.completed","response":{"id":format!("resp_{turn}"),"output":output}}).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()));
|
||||
for exchange in exchanges {
|
||||
let mut body = codex_request_body("model", "instructions", exchange.input);
|
||||
body.extend(exchange.request_fields.clone());
|
||||
let mut request = CodexResponsesRequest::from_body(body);
|
||||
request.client_api_key_id = Some("key".into());
|
||||
request.local_conversation_id = Some("session".into());
|
||||
timeout(
|
||||
Duration::from_secs(10),
|
||||
backend.create_response(&request, request_context("req", Some("acct"))),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let sent = seen.recv().await.unwrap();
|
||||
assert_eq!(
|
||||
sent.get("previous_response_id"),
|
||||
exchange
|
||||
.previous
|
||||
.map(|turn| json!(format!("resp_{turn}")))
|
||||
.as_ref(),
|
||||
"{}",
|
||||
exchange.name
|
||||
);
|
||||
assert_eq!(sent["input"], json!(exchange.expected), "{}", exchange.name);
|
||||
for (field, value) in exchange.request_fields {
|
||||
let mut actual = sent[&field].clone();
|
||||
if field == "client_metadata" {
|
||||
// 每轮出站补入请求时间戳,客户端提供的其余字段仍须原样保留
|
||||
actual
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("x-codex-ws-stream-request-start-ms")
|
||||
.expect("upstream request timestamp");
|
||||
}
|
||||
// 非流式客户端由网关聚合,WS 上游始终流式;客户端 stream 变化仍须使本轮完整重放
|
||||
let expected = if field == "stream" {
|
||||
Value::Bool(true)
|
||||
} else {
|
||||
value
|
||||
};
|
||||
assert_eq!(actual, expected, "{}:{field}", exchange.name);
|
||||
}
|
||||
}
|
||||
server.await.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,818 @@
|
||||
{
|
||||
"source": "openai/codex rust-v0.174.0 (2d42293d1d32079068f1e4ed8aa70fdbf146ec01), protocol/src/models.rs serde wire replay; internal analytics removed; host tool results tested separately",
|
||||
"cases": [
|
||||
{
|
||||
"changes": {
|
||||
"/content/0/annotations": [
|
||||
{
|
||||
"url": "https://example.com"
|
||||
}
|
||||
],
|
||||
"/content/0/logprobs": [
|
||||
{
|
||||
"logprob": -1,
|
||||
"token": "hello"
|
||||
}
|
||||
],
|
||||
"/content/0/text": "changed",
|
||||
"/id": "other",
|
||||
"/phase": "final_answer",
|
||||
"/status": "incomplete"
|
||||
},
|
||||
"name": "message",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"content": [
|
||||
{
|
||||
"annotations": [],
|
||||
"logprobs": [],
|
||||
"text": "hello",
|
||||
"type": "output_text"
|
||||
}
|
||||
],
|
||||
"id": "msg",
|
||||
"phase": "commentary",
|
||||
"role": "assistant",
|
||||
"status": "completed",
|
||||
"type": "message"
|
||||
},
|
||||
"upstream": {
|
||||
"content": [
|
||||
{
|
||||
"annotations": [],
|
||||
"logprobs": [],
|
||||
"text": "hello",
|
||||
"type": "output_text"
|
||||
}
|
||||
],
|
||||
"encrypted_content": null,
|
||||
"id": "msg",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"phase": "commentary",
|
||||
"role": "assistant",
|
||||
"status": "completed",
|
||||
"type": "message"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/encrypted_content": "different",
|
||||
"/summary/0/text": "changed"
|
||||
},
|
||||
"name": "reasoning_empty_content",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"encrypted_content": "cipher",
|
||||
"id": "rs",
|
||||
"summary": [
|
||||
{
|
||||
"text": "thinking",
|
||||
"type": "summary_text"
|
||||
}
|
||||
],
|
||||
"type": "reasoning"
|
||||
},
|
||||
"upstream": {
|
||||
"content": [],
|
||||
"encrypted_content": "cipher",
|
||||
"id": "rs",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"summary": [
|
||||
{
|
||||
"text": "thinking",
|
||||
"type": "summary_text"
|
||||
}
|
||||
],
|
||||
"type": "reasoning"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/content/0/text": "changed",
|
||||
"/content/1/text": "changed"
|
||||
},
|
||||
"name": "reasoning_content",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"content": [
|
||||
{
|
||||
"text": "first",
|
||||
"type": "reasoning_text"
|
||||
},
|
||||
{
|
||||
"text": "second",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"encrypted_content": null,
|
||||
"id": "rs",
|
||||
"summary": [],
|
||||
"type": "reasoning"
|
||||
},
|
||||
"upstream": {
|
||||
"content": [
|
||||
{
|
||||
"text": "first",
|
||||
"type": "reasoning_text"
|
||||
},
|
||||
{
|
||||
"text": "second",
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"id": "rs",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"summary": [],
|
||||
"type": "reasoning"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/arguments": "{\"q\":1}",
|
||||
"/call_id": "other",
|
||||
"/encrypted_function_args": [
|
||||
"cipher"
|
||||
],
|
||||
"/name": "other",
|
||||
"/namespace": "namespace"
|
||||
},
|
||||
"name": "function_call",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"arguments": "{}",
|
||||
"call_id": "call",
|
||||
"id": "fc",
|
||||
"name": "lookup",
|
||||
"status": "completed",
|
||||
"type": "function_call"
|
||||
},
|
||||
"upstream": {
|
||||
"arguments": "{}",
|
||||
"call_id": "call",
|
||||
"encrypted_content": null,
|
||||
"encrypted_function_args": null,
|
||||
"id": "fc",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"executed_tool_calls": [
|
||||
{
|
||||
"arguments": {},
|
||||
"name": "lookup",
|
||||
"tool_result_metadata": {
|
||||
"untrusted_server_value": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"name": "lookup",
|
||||
"namespace": null,
|
||||
"status": "completed",
|
||||
"type": "function_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/call_id": "other",
|
||||
"/input": "echo changed",
|
||||
"/name": "other",
|
||||
"/namespace": "namespace"
|
||||
},
|
||||
"name": "custom_tool_call",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"call_id": "call",
|
||||
"id": "ct",
|
||||
"input": "echo test",
|
||||
"name": "exec",
|
||||
"status": "completed",
|
||||
"type": "custom_tool_call"
|
||||
},
|
||||
"upstream": {
|
||||
"call_id": "call",
|
||||
"encrypted_content": null,
|
||||
"id": "ct",
|
||||
"input": "echo test",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"name": "exec",
|
||||
"namespace": null,
|
||||
"status": "completed",
|
||||
"type": "custom_tool_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/action/queries": [
|
||||
"other"
|
||||
],
|
||||
"/action/query": "changed",
|
||||
"/id": "changed"
|
||||
},
|
||||
"name": "web_search_search",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"action": {
|
||||
"query": "test",
|
||||
"type": "search"
|
||||
},
|
||||
"id": "ws",
|
||||
"status": "completed",
|
||||
"type": "web_search_call"
|
||||
},
|
||||
"upstream": {
|
||||
"action": {
|
||||
"queries": null,
|
||||
"query": "test",
|
||||
"type": "search"
|
||||
},
|
||||
"encrypted_content": null,
|
||||
"id": "ws",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"status": "completed",
|
||||
"type": "web_search_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/action/url": "https://example.org"
|
||||
},
|
||||
"name": "web_search_open_page",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"action": {
|
||||
"type": "open_page",
|
||||
"url": "https://example.com"
|
||||
},
|
||||
"id": "ws",
|
||||
"status": "completed",
|
||||
"type": "web_search_call"
|
||||
},
|
||||
"upstream": {
|
||||
"action": {
|
||||
"type": "open_page",
|
||||
"url": "https://example.com"
|
||||
},
|
||||
"id": "ws",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"status": "completed",
|
||||
"type": "web_search_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/action/pattern": "other",
|
||||
"/action/url": "https://example.org"
|
||||
},
|
||||
"name": "web_search_find",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"action": {
|
||||
"pattern": "test",
|
||||
"type": "find_in_page",
|
||||
"url": "https://example.com"
|
||||
},
|
||||
"id": "ws",
|
||||
"status": "completed",
|
||||
"type": "web_search_call"
|
||||
},
|
||||
"upstream": {
|
||||
"action": {
|
||||
"pattern": "test",
|
||||
"type": "find_in_page",
|
||||
"url": "https://example.com"
|
||||
},
|
||||
"id": "ws",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"status": "completed",
|
||||
"type": "web_search_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/action/command": [
|
||||
"echo",
|
||||
"changed"
|
||||
],
|
||||
"/action/env": {
|
||||
"X": "one"
|
||||
},
|
||||
"/action/timeout_ms": 5,
|
||||
"/action/user": "example",
|
||||
"/action/working_directory": "/example"
|
||||
},
|
||||
"name": "local_shell_call",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"action": {
|
||||
"command": [
|
||||
"echo",
|
||||
"test"
|
||||
],
|
||||
"env": null,
|
||||
"timeout_ms": null,
|
||||
"type": "exec",
|
||||
"user": null,
|
||||
"working_directory": null
|
||||
},
|
||||
"call_id": null,
|
||||
"id": "shell",
|
||||
"status": "completed",
|
||||
"type": "local_shell_call"
|
||||
},
|
||||
"upstream": {
|
||||
"action": {
|
||||
"command": [
|
||||
"echo",
|
||||
"test"
|
||||
],
|
||||
"type": "exec"
|
||||
},
|
||||
"id": "shell",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"status": "completed",
|
||||
"type": "local_shell_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/arguments/query": "changed",
|
||||
"/call_id": "other",
|
||||
"/execution": "client"
|
||||
},
|
||||
"name": "tool_search_call",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"arguments": {
|
||||
"query": "test"
|
||||
},
|
||||
"call_id": null,
|
||||
"execution": "server",
|
||||
"id": "ts",
|
||||
"status": "completed",
|
||||
"type": "tool_search_call"
|
||||
},
|
||||
"upstream": {
|
||||
"arguments": {
|
||||
"query": "test"
|
||||
},
|
||||
"execution": "server",
|
||||
"id": "ts",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"status": "completed",
|
||||
"type": "tool_search_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/result": "different",
|
||||
"/revised_prompt": "changed"
|
||||
},
|
||||
"name": "image_generation_call",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"id": "ig",
|
||||
"result": "image-data",
|
||||
"status": "completed",
|
||||
"type": "image_generation_call"
|
||||
},
|
||||
"upstream": {
|
||||
"encrypted_content": null,
|
||||
"id": "ig",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"result": "image-data",
|
||||
"revised_prompt": null,
|
||||
"status": "completed",
|
||||
"type": "image_generation_call"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/encrypted_content": "cipher"
|
||||
},
|
||||
"name": "context_compaction",
|
||||
"output": true,
|
||||
"replay": {
|
||||
"id": "ctx",
|
||||
"type": "context_compaction"
|
||||
},
|
||||
"upstream": {
|
||||
"encrypted_content": null,
|
||||
"id": "ctx",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"metadata": {
|
||||
"turn_id": "sampled-turn"
|
||||
},
|
||||
"type": "context_compaction"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/tools/0/name": "other",
|
||||
"/tools/0/parameters": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"name": "additional_tools",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"role": "developer",
|
||||
"tools": [
|
||||
{
|
||||
"name": "test",
|
||||
"parameters": {
|
||||
"type": "object"
|
||||
},
|
||||
"type": "function"
|
||||
}
|
||||
],
|
||||
"type": "additional_tools"
|
||||
},
|
||||
"upstream": {
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"role": "developer",
|
||||
"tools": [
|
||||
{
|
||||
"name": "test",
|
||||
"parameters": {
|
||||
"type": "object"
|
||||
},
|
||||
"type": "function"
|
||||
}
|
||||
],
|
||||
"type": "additional_tools"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/author": "other",
|
||||
"/content/0/text": "changed",
|
||||
"/content/1/encrypted_content": "changed",
|
||||
"/recipient": "other"
|
||||
},
|
||||
"name": "agent_message",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"author": "worker",
|
||||
"content": [
|
||||
{
|
||||
"text": "hello",
|
||||
"type": "input_text"
|
||||
},
|
||||
{
|
||||
"encrypted_content": "cipher",
|
||||
"type": "encrypted_content"
|
||||
}
|
||||
],
|
||||
"recipient": "parent",
|
||||
"type": "agent_message"
|
||||
},
|
||||
"upstream": {
|
||||
"author": "worker",
|
||||
"content": [
|
||||
{
|
||||
"text": "hello",
|
||||
"type": "input_text"
|
||||
},
|
||||
{
|
||||
"encrypted_content": "cipher",
|
||||
"type": "encrypted_content"
|
||||
}
|
||||
],
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"recipient": "parent",
|
||||
"type": "agent_message"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/call_id": "other",
|
||||
"/name": "other",
|
||||
"/namespace": "other",
|
||||
"/output": "changed"
|
||||
},
|
||||
"name": "function_call_output_text",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"call_id": "call",
|
||||
"output": "result",
|
||||
"type": "function_call_output"
|
||||
},
|
||||
"upstream": {
|
||||
"call_id": "call",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"name": null,
|
||||
"namespace": null,
|
||||
"output": "result",
|
||||
"type": "function_call_output"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/output/0/text": "changed",
|
||||
"/output/1/detail": "high",
|
||||
"/output/1/image_url": "different",
|
||||
"/output/2/file_id": "other",
|
||||
"/output/3/audio_url": "other",
|
||||
"/output/4/file_id": "other",
|
||||
"/output/5/encrypted_content": "other"
|
||||
},
|
||||
"name": "function_call_output_content",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"call_id": "call",
|
||||
"output": [
|
||||
{
|
||||
"text": "result",
|
||||
"type": "input_text"
|
||||
},
|
||||
{
|
||||
"image_url": "data:image/png;base64,dGVzdA==",
|
||||
"type": "input_image"
|
||||
},
|
||||
{
|
||||
"detail": "original",
|
||||
"file_id": "image-file",
|
||||
"type": "input_image"
|
||||
},
|
||||
{
|
||||
"audio_url": "data:audio/wav;base64,dGVzdA==",
|
||||
"type": "input_audio"
|
||||
},
|
||||
{
|
||||
"file_id": "audio-file",
|
||||
"type": "input_audio"
|
||||
},
|
||||
{
|
||||
"encrypted_content": "cipher",
|
||||
"type": "encrypted_content"
|
||||
}
|
||||
],
|
||||
"type": "function_call_output"
|
||||
},
|
||||
"upstream": {
|
||||
"call_id": "call",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"output": [
|
||||
{
|
||||
"text": "result",
|
||||
"type": "input_text"
|
||||
},
|
||||
{
|
||||
"detail": null,
|
||||
"image_url": "data:image/png;base64,dGVzdA==",
|
||||
"type": "input_image"
|
||||
},
|
||||
{
|
||||
"detail": "original",
|
||||
"file_id": "image-file",
|
||||
"type": "input_image"
|
||||
},
|
||||
{
|
||||
"audio_url": "data:audio/wav;base64,dGVzdA==",
|
||||
"type": "input_audio"
|
||||
},
|
||||
{
|
||||
"file_id": "audio-file",
|
||||
"type": "input_audio"
|
||||
},
|
||||
{
|
||||
"encrypted_content": "cipher",
|
||||
"type": "encrypted_content"
|
||||
}
|
||||
],
|
||||
"type": "function_call_output"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/call_id": "other",
|
||||
"/name": "other",
|
||||
"/output": "changed"
|
||||
},
|
||||
"name": "custom_tool_call_output",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"call_id": "call",
|
||||
"output": "result",
|
||||
"type": "custom_tool_call_output"
|
||||
},
|
||||
"upstream": {
|
||||
"call_id": "call",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"name": null,
|
||||
"output": "result",
|
||||
"type": "custom_tool_call_output"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/call_id": "other",
|
||||
"/execution": "client",
|
||||
"/status": "in_progress",
|
||||
"/tools/0/name": "other"
|
||||
},
|
||||
"name": "tool_search_output",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"call_id": "call",
|
||||
"execution": "server",
|
||||
"status": "completed",
|
||||
"tools": [
|
||||
{
|
||||
"name": "test",
|
||||
"type": "function"
|
||||
}
|
||||
],
|
||||
"type": "tool_search_output"
|
||||
},
|
||||
"upstream": {
|
||||
"call_id": "call",
|
||||
"execution": "server",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"status": "completed",
|
||||
"tools": [
|
||||
{
|
||||
"name": "test",
|
||||
"type": "function"
|
||||
}
|
||||
],
|
||||
"type": "tool_search_output"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/encrypted_content": "changed"
|
||||
},
|
||||
"name": "compaction_alias",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"encrypted_content": "cipher",
|
||||
"id": "compact",
|
||||
"type": "compaction"
|
||||
},
|
||||
"upstream": {
|
||||
"encrypted_content": "cipher",
|
||||
"id": "compact",
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"type": "compaction_summary"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/reasoning/effort": "low"
|
||||
},
|
||||
"name": "configuration_update",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"reasoning": {
|
||||
"effort": "high"
|
||||
},
|
||||
"type": "configuration_update"
|
||||
},
|
||||
"upstream": {
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"reasoning": {
|
||||
"effort": "high"
|
||||
},
|
||||
"type": "configuration_update"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/type": "context_compaction"
|
||||
},
|
||||
"name": "compaction_trigger",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"type": "compaction_trigger"
|
||||
},
|
||||
"upstream": {
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"type": "compaction_trigger"
|
||||
}
|
||||
},
|
||||
{
|
||||
"changes": {
|
||||
"/content/0/text": "other",
|
||||
"/content/1/detail": "low",
|
||||
"/content/1/file_id": "other",
|
||||
"/content/2/audio_url": "other"
|
||||
},
|
||||
"name": "message_multimodal",
|
||||
"output": false,
|
||||
"replay": {
|
||||
"content": [
|
||||
{
|
||||
"text": "test",
|
||||
"type": "input_text"
|
||||
},
|
||||
{
|
||||
"detail": "high",
|
||||
"file_id": "image-file",
|
||||
"type": "input_image"
|
||||
},
|
||||
{
|
||||
"audio_url": "audio-data",
|
||||
"type": "input_audio"
|
||||
}
|
||||
],
|
||||
"role": "user",
|
||||
"type": "message"
|
||||
},
|
||||
"upstream": {
|
||||
"content": [
|
||||
{
|
||||
"text": "test",
|
||||
"type": "input_text"
|
||||
},
|
||||
{
|
||||
"detail": "high",
|
||||
"file_id": "image-file",
|
||||
"type": "input_image"
|
||||
},
|
||||
{
|
||||
"audio_url": "audio-data",
|
||||
"type": "input_audio"
|
||||
}
|
||||
],
|
||||
"internal_chat_message_metadata_passthrough": {
|
||||
"turn_id": "old-turn"
|
||||
},
|
||||
"role": "user",
|
||||
"type": "message"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -11,6 +11,7 @@ mod cleanup;
|
||||
mod continuation;
|
||||
mod diagnostics;
|
||||
mod fingerprint;
|
||||
mod history;
|
||||
mod metadata;
|
||||
mod pool;
|
||||
|
||||
|
||||
@@ -261,7 +261,7 @@ async fn xai_admin_provider_validates_known_billing_breakdown() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn xai_legacy_billing_should_not_infer_long_context_flag() {
|
||||
async fn xai_billing_reconstruction_does_not_infer_long_context_flag() {
|
||||
let bundle = provider_xai::initialize(provider_ports())
|
||||
.await
|
||||
.expect("xAI bundle");
|
||||
@@ -279,7 +279,7 @@ async fn xai_legacy_billing_should_not_infer_long_context_flag() {
|
||||
amount: "0.8".parse().expect("stored total"),
|
||||
},
|
||||
})
|
||||
.expect("legacy billing")
|
||||
.expect("reconstructed billing")
|
||||
.expect("matching billing breakdown");
|
||||
|
||||
assert_eq!(billing.total_amount.amount.as_str(), "0.8");
|
||||
|
||||
@@ -32,20 +32,27 @@ sha256sum --check --strict .frozen-sha256
|
||||
|
||||
## 本地测试库
|
||||
|
||||
`gateway-store` 的 PostgreSQL/Redis 集成测试使用以下环境变量;所需测试服务未配置时,本地相关测试跳过,CI 直接失败:
|
||||
为集成测试准备专用 PostgreSQL 与 Redis 实例,服务启动方式见[开发指南](../../docs/development.md#启动宿主)。测试会创建随机 schema、Redis key 和临时认证用户,不能连接生产实例
|
||||
|
||||
- PostgreSQL 测试用户需要创建、删除 schema 和角色的权限
|
||||
- Redis 测试用户需要读写测试键、执行脚本及创建、删除 ACL 用户的权限
|
||||
- 备份恢复测试需要在测试进程的 `PATH` 中提供与 PostgreSQL 服务端版本匹配的 `pg_dump` 和 `psql`
|
||||
|
||||
在运行测试的终端设置连接信息,两条 URL 都须包含符合 [Store 密码要求](../../deploy/README.md#手动安装)的密码。测试凭据可使用 `openssl rand -hex 24` 生成的十六进制值,避免 URL 转义
|
||||
|
||||
```bash
|
||||
export CPR_TEST_DATABASE_URL='postgres://<user>:<password>@127.0.0.1:5432/<db>'
|
||||
export CPR_TEST_REDIS_URL='redis://:<password>@127.0.0.1:6379'
|
||||
unset CPR_DATABASE_URL CPR_REDIS_URL CPR_DATABASE_PASSWORD CPR_REDIS_PASSWORD
|
||||
```
|
||||
|
||||
插件 Runtime 的真实子进程与持久化测试可使用专用的 `CPR_PLUGIN_TEST_DATABASE_URL`,此时须同时设置 `CPR_PLUGIN_TEST_REDIS_URL`。省略插件数据库 URL 时使用上面的测试服务
|
||||
将占位值替换为测试服务的实际用户、密码和数据库名。测试 URL 携带密码;部署配置仍将 URL 与密码分开,清除上述部署环境变量可避免它们覆盖测试配置
|
||||
|
||||
使用专用开发或测试实例,测试通过随机 schema 和 Redis key 前缀隔离数据。凭据取自部署配置或 CI Secret,不要分享未脱敏的 `docker inspect` 输出
|
||||
插件 Runtime 的真实子进程与持久化测试默认复用这组服务。需要单独实例时,同时设置 `CPR_PLUGIN_TEST_DATABASE_URL` 与 `CPR_PLUGIN_TEST_REDIS_URL`,密码要求相同
|
||||
|
||||
PostgreSQL 的临时 schema 测试连接使用异步提交,保留事务可见性、回滚和完整迁移检查
|
||||
需要验证数据库崩溃后的持久性时,使用独立数据库与生产连接配置,不复用这类 fixture
|
||||
按[后端验证命令](../../docs/architecture.md#验证命令)运行测试。Store 用例在所需 URL 缺失时本地提前返回;插件 Runtime 用例在两组数据库 URL 均未设置时本地提前返回,选定数据库后缺少对应 Redis URL 会失败。CI 要求配置测试服务
|
||||
|
||||
运行包含 `StoreBundle` 初始化的完整集成测试时,两条测试 URL 都须包含密码,原始密码须满足
|
||||
[Store 密码要求](../../deploy/README.md#手动安装),在测试 URL 中按 URL 规则编码。
|
||||
在测试进程中清除 `CPR_DATABASE_URL`、`CPR_REDIS_URL`、`CPR_DATABASE_PASSWORD` 和 `CPR_REDIS_PASSWORD`,避免部署环境覆盖测试配置
|
||||
提前返回的用例可能仍显示通过,不能据此认定 PostgreSQL / Redis 行为已验证。URL 已设置但连接失败时,用例会失败,不按未配置处理
|
||||
|
||||
Store 的 PostgreSQL 临时 schema 夹具执行完整迁移集,并为这些测试连接设置异步提交,验证现行读写、事务可见性与回滚。
|
||||
验证数据库崩溃后的持久性须使用独立数据库与生产连接配置,不复用这类夹具
|
||||
+45
-23
@@ -1278,7 +1278,7 @@ call 与账号的绑定保存在网关进程内,未连接时一小时过期;
|
||||
| `GET` | `/api/key-usage/overview` | `period?`、`asOf?` 或 `startTime?`、`endTime?`,另含 `model?` | 用量汇总、趋势、当前额度和锚点所在日期的健康时间线 |
|
||||
| `GET` | `/api/key-usage/records` | 同上,另含 `kind?`、`currentPage?`、`pageSize?` | 当前 Key 的请求记录 |
|
||||
| `GET` | `/api/key-usage/config` | 无 | 当前 Key 的客户端配置凭据 |
|
||||
| `GET` | `/api/key-usage/version` | 无 | “关于”弹窗使用的当前版本号和提交号 |
|
||||
| `GET` | `/api/key-usage/version` | 无 | 当前版本号和提交号 |
|
||||
|
||||
用量查询支持[页面时间合同](#页面时间合同),默认 `period=7d`,一次最多 31 天。模型按字面量包含匹配,区分大小写,通配符按普通字符处理
|
||||
不接受 Key ID、账号、Provider 等范围参数或其他未知字段。页码默认 1,每页默认 20,允许 1–100 条;
|
||||
@@ -1512,11 +1512,7 @@ Key 预算及其访问状态随互联默认公开,不要求开启 `shareQuota`
|
||||
|
||||
最多 256 项,每个 ID 最多 256 字节;重复 ID 去重,不接受空白、控制字符、`__` 前缀或 `*` 通配符。
|
||||
允许保存当前上游目录尚未返回的 ID。限制按全局模型映射后的上游 ID 判断,不扩大账号本身的上游权限。
|
||||
管理端刷新目录只更新目录,不修改模型限制。全选与取消全选只作用于上游目录中符合当前搜索条件的模型。
|
||||
账号和分组白名单均可一键勾选 `gpt-image-2` 和 `gpt-image-1.5`。
|
||||
自定义模型取消勾选后在本次编辑期间保留,可再次勾选。保存时以最终选中项更新限制,关闭或取消编辑会丢弃草稿。
|
||||
白名单的清理按钮列出当前目录未返回的已选 ID,默认不选中任何项,
|
||||
由管理员确认后从当前表单移除,保存账号后生效。目录未就绪、刷新失败或返回空目录时不能清理,清理也不能将白名单置空。
|
||||
刷新模型目录不修改已保存的模型限制。
|
||||
图像、搜索、插件适配模型和映射目标可能不在目录中,目录缺失本身不代表模型失效。
|
||||
例如 Plus 设置 `allowlist` 并选中 luna 的实际 ID,Pro 设置 `denylist` 并选中同一 ID,即可严格分流;
|
||||
Pro 使用 `all` 时也能参与 luna 调度。套餐名称不自动生成或修改规则
|
||||
@@ -2018,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`,缺失时为未知。
|
||||
预付余额保留上游账本符号,非零余额及剩余按量额度可独立证明可用;窗口已过期或缺少可用证据时,
|
||||
不凭旧快照恢复账号
|
||||
@@ -2271,12 +2269,51 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c
|
||||
| `POST` | `/api/admin/client-keys/disable` | `{ id }` | 禁用 |
|
||||
| `POST` | `/api/admin/client-keys/delete` | `{ id }` | 删除 |
|
||||
|
||||
### 列表查询
|
||||
|
||||
`GET /api/admin/client-keys` 接受以下可选参数:
|
||||
|
||||
| 参数 | 默认值 | 约束 |
|
||||
| --- | --- | --- |
|
||||
| `limit` | `50` | 每页数量,整数 `1`–`65535` |
|
||||
| `search` | 不筛选 | 去除首尾空白后最多 256 字节,不能包含控制字符;空字符串等同于未提供 |
|
||||
| `sortBy` | `createdAt` | `name`、`enabled`、`createdAt` 或 `lastUsedAt` |
|
||||
| `sortDirection` | `desc` | `asc` 或 `desc` |
|
||||
| `cursor` | 从第一页开始 | 原样传入上次返回的 `nextCursor`;非空且最多 512 字节,不自行构造或解析 |
|
||||
|
||||
响应 `data` 为 `{ items, nextCursor, total }`。`total` 为满足搜索条件的总数,`nextCursor: null` 表示已到末尾。
|
||||
翻页时保持搜索和排序条件,`limit` 可调整;切换搜索或排序时省略 `cursor`,重新读取第一页。
|
||||
游标绑定排序字段和方向;非法参数、未知查询字段、无效游标或排序不匹配均返回 `400` / `40001`
|
||||
|
||||
搜索仅匹配名称和标签,不匹配密钥值或可见前缀;不区分大小写,使用字面量包含匹配,`%`、`_` 和 `\` 按普通字符处理。
|
||||
名称排序不区分大小写,`lastUsedAt` 为空的记录始终排在最后;排序值相同时按 Key ID 同方向排序
|
||||
|
||||
### 统计与窗口对齐
|
||||
|
||||
两个统计接口按部署时区和请求开始时间统计近 7 天(`7d`,默认)或 30 天(`30d`)。概览返回截止时间 `asOf`(Unix 毫秒),切换指标与读取明细时可用其固定统计区间。趋势按 `metric`(`costUsd`、`tokens`、`requests`)返回周期排名前五的模型,其余合为一条曲线(`model: null`)。模型优先取上游实际模型,缺失时回退到请求模型,两者都缺失时为空字符串
|
||||
|
||||
模型和周期合计包含请求数、已知 Token、已知 USD 费用,以及费用是否含本地估算或存在缺失。无已知数值时对应金额或 Token 为 `null`,费用占比以该 Key 周期内的已知 USD 总额为分母
|
||||
|
||||
手动对齐使用密钥可访问分组内账号的当前整账号 24 小时或七天窗口。确认时复核预览边界和密钥窗口版本,按完成时间重算本期消费。窗口到期后密钥恢复原生日历规则。已失效的预览或不足以重算的费用历史返回冲突
|
||||
|
||||
### 创建与更新密钥
|
||||
|
||||
创建字段为 `name`、可选 `label`、`groupIds`、`maxConcurrency`、`requestsPerMinute`、可选
|
||||
`dailyLimitUsd`、`weeklyLimitUsd`、`customKey`、`providerRequestProfileOverrides`、`peerSharing` 和 `validity`。更新请求携带 `id`,不接受 `customKey`。
|
||||
`groupIds` 必须显式提交:空数组派生 `routingScope: "all"`,非空数组派生
|
||||
`routingScope: "groups"`。列表项返回分组引用 `groups`,以及从当前有效账号池派生、仅供展示的 `providerKinds`
|
||||
|
||||
创建成功返回 `201`,`data` 为 `{ id, prefix, plaintextKey }`;reveal 返回 `{ id, plaintextKey }`。
|
||||
这两个响应包含完整明文 Key,调用方须安全保存。单个 Key 的更新、启用、禁用和删除返回 `{ id }`,完整配置通过列表查询读取
|
||||
|
||||
`peerSharing` 为 `{ enabled, sharePool, shareQuota, sharePlans }`,各项均为布尔值且默认 `false`。
|
||||
创建时省略保持关闭;更新时省略或 `null` 保留整个配置,提交对象时替换完整配置,对象内省略项为 `false`。
|
||||
列表项返回完整对象。`sharePlans` 需要 `sharePool`;开启 `enabled` 必须提交非空 `groupIds`,
|
||||
推理允许使用这些组内的 OAuth 和 API Key 账号,[CPR 互联导出](#cpr-互联只读协议) 仅公开本地直连账号的观测。
|
||||
账号池、原生额度窗口、套餐分布分别按对应开关公开;关闭共享不改变已保存的其他开关值
|
||||
|
||||
### 批量更新
|
||||
|
||||
批量更新只提交要修改的字段,各密钥保留其余配置。任一密钥或分组不存在、任一密钥的最终配置无效时,整批回滚
|
||||
|
||||
- `enabled` 设置启用状态。`groupIds` 替换全部分组,显式传空数组授权全部当前及未来账号
|
||||
@@ -2284,19 +2321,6 @@ HTTP 返回 `403` 和 `image_generation_disabled`,WebSocket 每个 `response.c
|
||||
- `peerSharing` 可单独修改 `enabled`、`sharePool`、`shareQuota`、`sharePlans`。开启互联需要绑定分组,共享套餐构成需要开启账号池概览
|
||||
- `providerRequestProfileOverrides` 按 Provider 更新,显式传入某个 Provider 为 `null` 时恢复其全局配置。`installationSeed` 单独接受 UUID;仅修改身份配置时保留各密钥原有种子,仅修改种子时保留各自的身份配置
|
||||
|
||||
创建字段为 `name`、可选 `label`、`groupIds`、`maxConcurrency`、`requestsPerMinute`、可选
|
||||
`dailyLimitUsd`、`weeklyLimitUsd`、`customKey`、`providerRequestProfileOverrides` 和 `peerSharing`。更新请求携带 `id`,不接受 `customKey`。
|
||||
`groupIds` 必须显式提交:空数组派生 `routingScope: "all"`,非空数组派生
|
||||
`routingScope: "groups"`。响应同时返回分组引用 `groups`,以及从当前有效账号池派生、仅供展示的
|
||||
`providerKinds`。创建和 reveal 响应会返回完整明文 Key,调用方
|
||||
必须立即安全保存
|
||||
|
||||
`peerSharing` 为 `{ enabled, sharePool, shareQuota, sharePlans }`,各项均为布尔值且默认 `false`。
|
||||
创建时省略保持关闭;更新时省略或 `null` 保留整个配置,提交对象时替换完整配置,对象内省略项为 `false`。
|
||||
列表、创建及更新响应均返回完整对象。`sharePlans` 需要 `sharePool`;开启 `enabled` 必须提交非空 `groupIds`,
|
||||
推理允许使用这些组内的 OAuth 和 API Key 账号,[CPR 互联导出](#cpr-互联只读协议) 仅公开本地直连账号的观测。
|
||||
账号池、原生额度窗口、套餐分布分别按对应开关公开;关闭共享不改变已保存的其他开关值
|
||||
|
||||
### Key 客户端身份
|
||||
|
||||
`providerRequestProfileOverrides` 按 Provider ID 保存身份选择,列表返回同名对象。创建时各项为完整配置对象,
|
||||
@@ -2313,7 +2337,6 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
|
||||
|
||||
### 名称与密钥值
|
||||
|
||||
密钥列表的 `search` 仅匹配名称和标签,不匹配密钥值或可见前缀;搜索不区分大小写,使用字面量包含匹配,`%`、`_` 和 `\` 按普通字符处理。
|
||||
创建和更新时去除名称首尾空白,并按忽略大小写、首尾空格的名称查重,重复返回 `409`。
|
||||
更新排除当前记录,并发写入同样执行查重;失败不会留下审计或配置版本变更。
|
||||
已有同名 Key 的凭据有效,编辑时须使用未被其他 Key 占用的名称
|
||||
@@ -2324,7 +2347,7 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
|
||||
应用不另设 Key 长度上限;创建请求和 `Authorization` 头仍受 Web 服务器及反向代理的通用大小限制。
|
||||
更新接口不接受 `customKey`,防止修改策略时意外替换正在使用的凭据。
|
||||
列表仅展示最多前 10 个字符,且至少隐藏一半字符;单字符 Key 的可见前缀为空。
|
||||
完整值仍只通过创建和显式 reveal 返回,不进入普通 Debug 或审计
|
||||
完整密钥不进入普通 Debug 或审计
|
||||
|
||||
自定义 Key 创建示例:
|
||||
|
||||
@@ -2340,7 +2363,6 @@ OpenAI Key 的 `installationSeed` 接受带连字符的 UUID,保存时规范
|
||||
|
||||
创建、更新可传 `validity`,其中 `startsAt`、`expiresAt` 为带时区的 RFC3339 时间点。起点包含在有效期内,到达终点即失效。起止时间须成对填写,终点须晚于起点。
|
||||
创建时默认立即生效且长期有效;更新时省略整个对象保留原有效期,传入对象会替换两个边界,两者同时为空可恢复长期有效。
|
||||
管理页面使用浏览器本地时间选择起止日期和时分秒。新建默认留空,选择日期时默认 00:00:00;7 天和 30 天从今天零点起按日历日计算。
|
||||
列表提供 `validity`、查询时的 `validityStatus`(`scheduled`、`active`、`expired`)和按部署时区格式化的 `startsAtDisplay`、`expiresAtDisplay`。手动重置额度保留密钥有效期
|
||||
|
||||
自定义 Key 的分组权限、日/周限额和并发规则按本平台配置执行,不导入其他平台的历史用量
|
||||
|
||||
+48
-28
@@ -347,7 +347,7 @@ Provider 可为模型提供来源账号集合;Core 在公开目录查询时结
|
||||
客户端原生模型目录同样由 Provider 拥有,通过 `ExecutionService` 和现有 Registry 的只读调用传递。
|
||||
`routing::catalog` 的原生条目只包含模型 ID 与不透明协议正文,Core 负责冻结账号范围和整对象模型映射,
|
||||
不解析上游字段;API 负责协议输出,不直接依赖具体 Provider。原生目录失败不会退回通用画像,只有不提供
|
||||
该协议原生目录的 Provider才走画像转换。目录读取不创建计量请求或推理 attempt。
|
||||
该协议原生目录的 Provider 才走画像转换。目录读取不创建计量请求或推理 attempt
|
||||
|
||||
请求位置、隐私、Fast 和生图的跨层策略见[请求策略与事实](#请求策略与事实),Provider 目录的刷新与凭据隔离见[账号模型目录](#账号模型目录)
|
||||
|
||||
@@ -508,23 +508,7 @@ Client Key 鉴权完成后,API adapter 从有界请求头识别客户端,Cor
|
||||
生成请求按模型目录编译候选;全局模型映射是精确映射,未命中时模型名原样交给候选 Provider。
|
||||
Responses、Messages、GenAI 和 Chat 保留各自的正文与协议事实进入共用 Generate 执行链。
|
||||
HTTP、request 与 attempt 中间件处理当前入站协议,endpoint 保留客户端路由。
|
||||
原生请求只匹配声明同协议能力的候选;Chat 由 Provider 选定账号后直接转换到目标协议,`outbound` 处理实际发送的请求
|
||||
|
||||
Core 独占路由、重试、交付事实与结算;Provider 独占上游身份、账号相关适配、隐私策略及账号隔离。
|
||||
`gateway-protocol` 的 `openai/`、`anthropic/`、`genai/` 保留原生解析;
|
||||
`chat_completions/{responses,messages,genai}/` 分别直接映射请求、完整响应和流事件,不借另一平台协议中转。
|
||||
转换器只保留本次响应身份、增量状态及工具名称映射,不持有输入历史、账号、连接或调度状态。
|
||||
API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。
|
||||
Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果
|
||||
|
||||
运行设置快照编译并共享提示词改写匹配器,支持字面前缀和正则,按配置顺序索引全局规则和各上游规则。路由计划冻结快照,每次尝试只取所选平台的适用规则。attempt 中间件提交后,协议层定位系统文本,Core 匹配开头;管理端预览复用同一匹配器。生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串。计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则
|
||||
|
||||
原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。
|
||||
内置转换只能从 Chat 来源调用;显式插件仍按现有能力声明与中间件合同运行。
|
||||
字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
|
||||
|
||||
Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。
|
||||
Core 按原始协议提取搜索能力要求,Chat 的 `web_search_options` 同样参与候选筛选;Provider 校验实际目标是否支持声明的搜索选项
|
||||
Provider 选定账号后完成适配,`outbound` 处理实际发送的请求;原生协议和 Chat 转换的职责见[生成协议与转换](#生成协议与转换)
|
||||
|
||||
Images 与 standalone Search 是 OpenAI Provider 自有端点:两者都不参与文本模型映射,只在 Client Key
|
||||
的账号范围确实包含 Codex 账号时生成单一 OpenAI 候选。Images 的图片模型由 Provider 从正文旁路
|
||||
@@ -543,6 +527,14 @@ API 暂存的下一轮请求和连接泵接收队列共用容量名额,控制
|
||||
`GenerateRequest` 在构造或替换正文时重算事实,仅改上下文不重复扫描正文;跨协议转换保留来源请求的能力约束和生图事实。
|
||||
Core 将这些事实转为路由能力要求与生图权限判断,协议解析不决定是否允许请求
|
||||
|
||||
Responses 搜索的强制执行判定、声明选择与联网模式解析由 `gateway-protocol::openai::web_search` 统一提供。
|
||||
Core 按原始协议提取搜索能力要求,Chat 的 `web_search_options` 同样参与候选筛选;Provider 校验实际目标是否支持声明的搜索选项
|
||||
|
||||
运行设置快照编译并共享提示词改写匹配器,按配置顺序索引全局规则和各上游规则,路由计划冻结快照,每次尝试只取所选平台的适用规则。
|
||||
attempt 中间件提交后,协议层定位系统文本,Core 匹配开头;管理端预览复用同一匹配器。
|
||||
生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串;计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则。
|
||||
规则格式与匹配行为见[提示词改写](api.md#提示词改写)
|
||||
|
||||
全局请求位置及开关由运行设置持久化,快照仅在开关开启时生成全局覆盖,并随
|
||||
`RuntimeSnapshot → RoutingPlan → AttemptContext` 冻结传递。Provider 在选定账号后优先应用代理位置,
|
||||
出站字段遵循[请求位置合同](api.md#独立代理管理--managed-proxies)。请求期间不额外查询全局设置,配置发布不改变已开始请求的全局值
|
||||
@@ -573,10 +565,11 @@ WS 路由提示属于握手,连接复用时不重发;档位变化不重建
|
||||
|
||||
## 5. Provider 与协议边界
|
||||
|
||||
Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 canonical event,不读取 Provider SDK
|
||||
类型。Provider 独占 credential schema、OAuth、账号选择、模型目录、额度投影和上游 transport
|
||||
Core 独占路由、重试、交付事实与结算,只理解 `Operation`、能力要求、Provider 候选、稳定错误和 canonical event,
|
||||
不读取 Provider SDK 类型。Provider 独占 credential schema、OAuth、账号选择、模型目录、额度投影、上游身份与 transport,
|
||||
负责选中账号的协议适配、隐私规则解释与执行,以及账号隔离
|
||||
|
||||
三个内置 Provider 在各自的 `lib.rs` 返回同一个 `ProviderBundle`。组合根从这一组 Bundle 注册执行器、管理端口和后台任务。共同职责使用一致目录:
|
||||
三个内置 Provider 分别在各自的 `lib.rs` 构造 `ProviderBundle`。组合根从这一组 Bundle 注册执行器、管理端口和后台任务。共同职责使用一致目录:
|
||||
|
||||
| 目录 | 职责 |
|
||||
| --- | --- |
|
||||
@@ -587,8 +580,6 @@ Core 只理解 `Operation`、能力要求、Provider 候选、稳定错误和 ca
|
||||
| `provider/` | 推理执行和 worker 装配 |
|
||||
| `transport/` | 出站协议与上游响应采集 |
|
||||
|
||||
Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号;OAuth 使用该账号的授权项目,API Key 直接请求配置的 GenAI 地址,停用账号仍可接受探测
|
||||
|
||||
数据面入口位于 `gateway-api/src/data_plane`,按协议、客户端扩展和平台专属端点划分职责:
|
||||
|
||||
- `responses`、`chat_completions`、`messages`、`genai` 拥有各自协议入口,生成与计数共用 `generation` 的执行交付、取消传播和连接生命周期
|
||||
@@ -597,11 +588,38 @@ Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模
|
||||
- `openai` 聚合当前绑定 OpenAI Provider 的 Images、独立 Search 与 Live 入口,通过 Core 端口调用上游能力;账号认证和上游传输仍由 Provider 拥有
|
||||
- `headers` 拥有数据面入站业务头与响应头边界,各协议直接使用公共头处理;跨协议 HTTP 规则和重试时间解析归 `gateway-protocol/http`,OpenAI/Codex 私有响应头分类归 `gateway-protocol/openai/headers`,API 出口组合两者
|
||||
|
||||
### 生成协议与转换
|
||||
|
||||
`gateway-protocol` 的 `openai/`、`anthropic/`、`genai/` 保留原生解析;
|
||||
`chat_completions/{responses,messages,genai}/` 分别直接映射请求、完整响应和流事件,不借另一平台协议中转。
|
||||
原生请求只匹配声明同协议能力的候选,Chat 由 Provider 选定账号后直接转换到目标协议
|
||||
|
||||
原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。
|
||||
内置转换只能从 Chat 来源调用;显式插件仍按其能力声明与中间件合同运行
|
||||
|
||||
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。
|
||||
选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段
|
||||
|
||||
Chat 响应在 Core 的响应中间件阶段之间直接转换。转换器只保留本次响应身份、增量状态及工具名称映射,
|
||||
不持有输入历史、账号、连接或调度状态,也不增加账号级签名缓存或对话副本。
|
||||
正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态,转换状态随单次流释放
|
||||
|
||||
API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。
|
||||
Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果。
|
||||
字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
|
||||
|
||||
### GenAI 目录与原生传输
|
||||
|
||||
Antigravity 的 `credential/catalog` 持有与凭据版本绑定的项目与模型观测,`credential/quota` 管理额度快照。凭据续期后的目录修复由 `provider/workers` 编排。管理端连接测试固定账号;OAuth 使用该账号的授权项目,API Key 直接请求配置的 GenAI 地址,停用账号仍可接受探测
|
||||
|
||||
GenAI 从 URL 解码模型和生成方法,要求候选模型在原生目录中声明对应协议。Core 在 Key 的账号范围内匹配能力,Antigravity OAuth 将选中的 GenAI 请求封装为 Cloud Code 上游请求,API Key 直接请求公开 GenAI 路径
|
||||
|
||||
Chat 的角色、公共字段结构与交付选项由 `gateway-protocol/chat_completions/request` 统一校验,目标转换器只补充可表达性与映射规则。选路事实只读取协议声明位置,不递归解释 schema、工具参数或扩展字段。
|
||||
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。
|
||||
API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录
|
||||
|
||||
GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigravity 提供完整的上游模型对象,Core 处理账号权限、来源选择和别名。API 通过原生操作能力筛选可执行条目,适配 GenAI 外层协议;AGY 列表按上游聊天和生图声明筛选、排序,详情和直接调用仍使用完整的授权目录。Antigravity 声明生成与输入计数能力,API Key 目录按 `supportedGenerationMethods` 区分生成与计数,选号再次核对所选账号的声明。计数复用选号、中间件及资源释放流程;OAuth 调用 Cloud Code `countTokens`,API Key 调用原生模型的 `countTokens`。计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
||||
Antigravity 声明生成与输入计数能力,API Key 目录按 `supportedGenerationMethods` 区分生成与计数,选号再次核对所选账号的声明。
|
||||
计数复用选号、中间件及资源释放流程;OAuth 调用 Cloud Code `countTokens`,API Key 调用原生模型的 `countTokens`。
|
||||
计数响应不产生生成用量或费用事实,失败不切换为本地估算
|
||||
|
||||
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
|
||||
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
||||
@@ -617,8 +635,6 @@ Antigravity 的 Cloud Code 传输按下游生成模式选择普通 JSON 或 SSE
|
||||
|
||||
Cloud Code 连接使用 rustls 与 HTTP/1.1,gzip 协商和流式解压由本 Provider 持有,不启用会影响其他 Provider 的 reqwest 全局压缩特性。解压后的流继续遵循控制面和推理消费方的大小限制、取消及截止时间
|
||||
|
||||
Chat 响应在 Core 的响应中间件阶段之间直接转换。转换器在正常 EOF 时刷新最后内容块并发出终态,尾部用量先于完成事件交付;错误和取消不合成成功终态。转换状态随单次流释放,不增加账号级签名缓存或对话副本
|
||||
|
||||
### 连接与上游身份
|
||||
|
||||
Responses 下游连接的心跳和退出由 API 拥有,每条 WS 使用独立取消信号,沿 Core 的 `ResponseControl` 传到 Provider 请求上下文。
|
||||
@@ -813,7 +829,7 @@ Continuation 受原请求的 Client Key、账号范围、Provider 和发送/交
|
||||
- OpenAI Provider 在发送前按上游握手声明的消息大小上限检查最终出站帧,新链可选择 HTTP;超限的 connection-local
|
||||
续接和已标记为需要重放的 HTTP/WS 增量返回 `ClientReplayRequired`,由客户端重发
|
||||
完整历史。预检拒绝先释放连接及租约,不消耗 WS 故障预算;Provider session state 只携带元数据,不保存 transcript
|
||||
- Codex OAuth 的 HTTP 全量历史由独占租用的上游 WS 比较。连接只持有上一轮的响应 ID、项数和绑定 Client Key 与请求属性的前缀摘要,随连接回收。请求属性采用 Codex 的续接字段集。历史项按顺序比较,忽略 Codex 回传省略的采样和内部元数据,工具结果及其调用绑定仍参与比较。增量只改写出站帧,本次完整请求仍可用于安全回退
|
||||
- Codex OAuth 的 HTTP 全量历史由独占租用的上游 WS 比较。连接只持有上一轮的响应 ID、项数和绑定 Client Key 与请求属性的前缀摘要,随连接回收。请求属性采用 Codex 的续接字段集。历史项按 Codex `ResponseItem` 及嵌套内容的回传形状计算只读摘要,统一缺省值和别名,未知类型按原值比较。上游采样元数据和客户端内部分析字段不参与比较;客户端回传的工具结果元数据及其调用绑定必须保留,正文、工具参数、工具定义和输出标注不合并。增量只改写出站帧,本次完整请求仍可用于安全回退
|
||||
- OpenAI 在有效输出交付前收到可安全重放的明确额度拒绝时,先隔离账号,再投影 `ClientReplayRequired`;
|
||||
丢弃未交付的原错误帧,由客户端提交完整历史开启新链,不把原增量输入交给其他账号。
|
||||
真实错误分类、状态码、发送状态和上游诊断保持不变,客户端合同见 [Responses API](api.md#3-模型数据面与模型目录)
|
||||
@@ -1134,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,订阅查询失败不影响额度观测
|
||||
|
||||
+10
-11
@@ -6,6 +6,7 @@
|
||||
| --- | --- |
|
||||
| 修改宿主前后端 | [环境与依赖](#环境与依赖) → [启动宿主](#启动宿主) |
|
||||
| 定位模块与共享实现 | [源码入口](#源码入口) |
|
||||
| 验证后端改动 | [测试环境](../backend/migrations/README.md#本地测试库) → [验证命令](architecture.md#验证命令) |
|
||||
| 同时修改 UI 或插件 | [源码联调](#源码联调) → [启动与检查](#启动与检查) |
|
||||
| 验证本地 SDK | [本地 SDK 验证](#本地-sdk-验证) |
|
||||
| 提交跨仓库改动 | [编辑与提交](#编辑与提交) |
|
||||
@@ -31,10 +32,10 @@ pnpm --dir frontend install --frozen-lockfile
|
||||
|
||||
使用源码仓库自带的 Compose 与配置模板,按[手动安装](../deploy/README.md#手动安装)中的配置与权限要求准备 `deploy/config.yaml` 和 `.runtime/` 目录
|
||||
|
||||
数据库及 Redis 可由 Compose 启动:
|
||||
启动数据库与 Redis,等待健康检查通过后运行后端:
|
||||
|
||||
```bash
|
||||
docker compose -f deploy/compose.yaml up -d postgres redis
|
||||
docker compose -f deploy/compose.yaml up -d --wait postgres redis
|
||||
cargo +1.99.1 run --manifest-path backend/Cargo.toml -p codex-proxy-rs --locked
|
||||
```
|
||||
|
||||
@@ -48,7 +49,7 @@ cargo +1.99.1 run --manifest-path backend/Cargo.toml -p codex-proxy-rs --locked
|
||||
pnpm --dir frontend dev
|
||||
```
|
||||
|
||||
后端代理由 `frontend/vite.config.ts` 配置,验证 WebSocket 时直接连接后端
|
||||
访问管理端开发服务输出的地址。HTTP 请求由 `frontend/vite.config.ts` 代理至后端,验证 WebSocket 时直接连接后端
|
||||
|
||||
前后端检查见 [贡献与审查](../CONTRIBUTING.md#验证),数据库集成测试使用[专用测试库](../backend/migrations/README.md#本地测试库)
|
||||
|
||||
@@ -56,15 +57,13 @@ pnpm --dir frontend dev
|
||||
|
||||
[后端 Workspace 边界](architecture.md#3-workspace-边界) · [前端模块职责](architecture.md#34-前端模块职责) · [共享 UI 组件架构](https://github.com/zyycn/codex-proxy-ui/blob/main/playground/guide/architecture.md)
|
||||
|
||||
Chat Completions 到 Responses、Messages、GenAI 的纯协议转换位于 `backend/crates/gateway-protocol/src/chat_completions/`,
|
||||
Chat HTTP 入口位于 `backend/crates/gateway-api/src/data_plane/chat_completions/`,各 Provider 的 `provider/chat/` 或 `provider/chat.rs` 负责调用获准的转换。
|
||||
Messages 原生类型位于 `backend/crates/gateway-protocol/src/anthropic/`,账号协议分派、HTTP 执行和计数位于 `backend/crates/providers/openai/src/provider/messages/`。
|
||||
模块职责见 [Provider 与协议边界](architecture.md#5-provider-与协议边界)
|
||||
协议转换、原生类型和 Provider 执行入口见 [Provider 与协议边界](architecture.md#5-provider-与协议边界),请求格式与支持范围见 [模型数据面](api.md#3-模型数据面与模型目录)
|
||||
|
||||
联调协议时为各 Provider 准备对应的原生账号,并通过账号分组与 Client Key 固定上游范围;OpenAI 的 Responses 与 Messages API Key 账号应分组验证。
|
||||
分别检查各账号的原生入口与 Chat 入口的 JSON、SSE、工具往返、取消和错误;支持计数的账号另测原生计数入口,并确认其他原生协议入口不会触发内置转换。
|
||||
请求格式与支持范围见 [模型数据面](api.md#3-模型数据面与模型目录)。
|
||||
Messages 账号只配置 HTTP;本地计数估算不能替代上游计费核对
|
||||
联调协议时:
|
||||
|
||||
1. 为各 Provider 准备对应的原生账号,通过账号分组与 Client Key 固定上游范围;OpenAI 的 Responses 与 Messages API Key 账号分组验证
|
||||
2. 分别检查原生入口与 Chat 入口的 JSON、SSE、工具往返、取消和错误,确认其他原生协议入口不会触发内置转换
|
||||
3. 支持计数的账号另测原生计数入口;本地计数估算不能替代上游计费核对
|
||||
|
||||
OpenAI 的 `transport::tls::` 测试在本机回环地址采集 ClientHello,覆盖默认 HTTP、自定义 CA 的 HTTP 和 WebSocket。运行方式见[后端验证命令](architecture.md#验证命令)
|
||||
|
||||
|
||||
+28
-3
@@ -1,6 +1,31 @@
|
||||
# v3.61.1-rc.6
|
||||
# v3.62.1-rc.1
|
||||
|
||||
## 问题修复
|
||||
|
||||
- OpenAI 请求显式指定 `reasoning.effort: none` 时,若所选账号的模型目录支持 `low` 但不支持 `none`,自动改用 `low`,并同步处理历史中的推理配置更新
|
||||
- Antigravity 调用 Claude 时,同名并行工具的调用与结果数量一致且均缺失 ID,可按出现顺序补齐配对,修复下一轮请求因缺少工具 ID 失败的问题(#848)
|
||||
- OpenAI OAuth 账号的访问令牌在到期前收到模型请求 401 时,有刷新令牌的账号会先自动续期。新令牌在首次成功请求前再次被拒时,才将凭据标记为过期(#853)
|
||||
- 手动和后台续期遇到并发 Cookie 写入时,可正确保存新令牌,并避免重复使用已轮换的刷新令牌
|
||||
- 并发模型请求返回时,较早请求的成功响应会保留核对期间新收到的 401 和风控失败记录
|
||||
|
||||
<!-- cpr-release:generated -->
|
||||
## Linux 一键安装(Docker Compose)
|
||||
|
||||
```bash
|
||||
curl -fsSLO https://raw.githubusercontent.com/zyycn/codex-proxy-rs/v3.62.1-rc.1/deploy/install.sh && CPR_RELEASE_TAG=v3.62.1-rc.1 bash install.sh
|
||||
```
|
||||
|
||||
## 📚 文档
|
||||
|
||||
- [GitHub 仓库](https://github.com/zyycn/codex-proxy-rs)
|
||||
- [部署指南](https://github.com/zyycn/codex-proxy-rs/blob/v3.62.1-rc.1/deploy/README.md)
|
||||
|
||||
## What's Changed
|
||||
* fix(openai): preserve OAuth recovery and token rotation by @think-back in https://github.com/zyycn/codex-proxy-rs/pull/853
|
||||
|
||||
|
||||
**Full Changelog**: https://github.com/zyycn/codex-proxy-rs/compare/v3.62.0...v3.62.1-rc.1
|
||||
|
||||
## 其他提交
|
||||
* fix(release): freeze complete notes and expose backend validation ([b20b0e201](https://github.com/zyycn/codex-proxy-rs/commit/b20b0e2013f1238cc1290e826ff8332e9bfbf2c7))
|
||||
* fix(openai): clear only recovery feedback observed before success ([72e82c565](https://github.com/zyycn/codex-proxy-rs/commit/72e82c565e15d35e0ca7b1a39f74e4295bb292e3))
|
||||
* docs(release): base stable version bumps on changes since the last stable release ([b987cca4a](https://github.com/zyycn/codex-proxy-rs/commit/b987cca4aa0fe663132fc9d082e4712a0d00d4f2))
|
||||
<!-- /cpr-release:generated -->
|
||||
+7
-2
@@ -21,7 +21,8 @@ Example:
|
||||
Before publishing, replace release/notes.md with the new version's notes,
|
||||
starting with "# v<version>". Leave the notes uncommitted; this command commits
|
||||
them together with release/version.yaml. Commit other tracked changes first.
|
||||
Use --check to validate without changing files, Git refs, or remote state.
|
||||
Use --check to preview the complete release notes and validate without changing
|
||||
files, Git refs, or remote state. Publishing commits the generated notes too.
|
||||
USAGE
|
||||
}
|
||||
|
||||
@@ -131,7 +132,7 @@ if git rev-parse --quiet --verify "refs/tags/$tag" >/dev/null; then
|
||||
fi
|
||||
|
||||
if [[ "$check_only" == false ]]; then
|
||||
git fetch "$remote"
|
||||
git fetch --tags "$remote"
|
||||
fi
|
||||
|
||||
upstream="$remote/$remote_branch"
|
||||
@@ -152,6 +153,9 @@ if [[ "$local_head" != "$upstream_head" && "$merge_base" != "$upstream_head" ]];
|
||||
die "branch has diverged from $upstream"
|
||||
fi
|
||||
|
||||
prepared_notes="$(ruby .github/scripts/release-notes.rb prepare "$version" "$repository" "$upstream_head")"
|
||||
printf '%s\n' "$prepared_notes"
|
||||
|
||||
if [[ "$check_only" == true ]]; then
|
||||
# 预检调用与正式更新相同的纯函数,不写回兼容窗口
|
||||
ruby -r './backend/crates/gateway-plugin/runtime/plugin-api-lifecycle' -e '
|
||||
@@ -165,6 +169,7 @@ fi
|
||||
|
||||
ruby backend/crates/gateway-plugin/runtime/plugin-api-lifecycle.rb "$PLUGIN_DEPRECATIONS_FILE" "$PLUGIN_COMPATIBILITY_FILE" "$version"
|
||||
update_version_file "$version"
|
||||
printf '%s\n' "$prepared_notes" > "$NOTES_FILE"
|
||||
|
||||
git add -- "$VERSION_FILE" "$NOTES_FILE" "$PLUGIN_DEPRECATIONS_FILE"
|
||||
git commit \
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.61.1-rc.6
|
||||
version: 3.62.1-rc.1
|
||||
published:
|
||||
'3':
|
||||
stable: 3.61.0
|
||||
rc: 3.61.1-rc.5
|
||||
beta: 3.61.1-rc.5
|
||||
alpha: 3.61.1-rc.5
|
||||
stable: 3.62.0
|
||||
rc: 3.62.0
|
||||
beta: 3.62.0
|
||||
alpha: 3.62.0
|
||||
Reference in new issue
Block a user