Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
229b636
feat: 为账号请求分散代理并约束授权维护出口
luotao21 Nov 16, 2026
17073f0
feat: 整合单多代理入口并增加批量选择和连接测试
luotao21 Nov 16, 2026
d4c2645
docs: 说明账号代理配置兼容和升级回退边界
luotao21 Nov 16, 2026
0f5313e
merge: 同步上游采集测试与认证修复以补齐CI基线
luotao21 Nov 16, 2026
6a87a47
修复BPS刷新与生成出口不一致并记录实际代理
luotao21 Nov 16, 2026
da931dd
隔离历史RED依赖并强制验证真实代理与Redis
luotao21 Nov 16, 2026
3a33096
补充多IP账号风险提示并明确876未覆盖范围
luotao21 Nov 16, 2026
41e39e5
同步上游最新验收脚本与待续接修复以匹配CI基线
luotao21 Nov 16, 2026
ffdcfe6
修复上游新增守卫测试导致历史回放准备失败
luotao21 Nov 16, 2026
0b08e01
修复代理路由测试的依赖边界和资源清理检查
luotao21 Nov 16, 2026
1ee33f8
修复历史回放脚本重复处理测试夹具导致失败
luotao21 Nov 16, 2026
b9fd2eb
修复历史回放遗漏测试辅助代码的编译依赖
luotao21 Nov 16, 2026
017d54c
合并上游模型更新并保留历史回放校验
luotao21 Nov 16, 2026
282af97
修复账号切换单代理时刷新绕过请求出口
luotao21 Nov 16, 2026
d7fb497
补充配置切换八场景的严格红绿回归门禁
luotao21 Nov 16, 2026
9429462
修复历史WS红灯回放编译到新代理夹具
luotao21 Nov 16, 2026
1a5fbd1
修复历史WS回放的预热测试API版本不匹配
luotao21 Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions .github/scripts/assert-account-proxy-config-switch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Require all eight real config-switch cases; reject setup failures as RED."""

import json
import sys
from collections import Counter
from pathlib import Path

PACKAGE = "github.com/Wei-Shaw/sub2api/internal/service"
ROOTS = {"TestExcelBPSRequestProxyConfigSwitch" + path for path in ("Forward", "Images", "SIWC", "OAuth")}
LEAVES = {root + "/" + mode for root in ROOTS for mode in ("single_B", "single_empty")}
NODES = ROOTS | LEAVES
ESCAPED = "CONFIG_SWITCH_REFRESH_EGRESS_ESCAPED"
REACHED = ("CONFIG_SWITCH_ROUTE_READY", "CONFIG_SWITCH_SINGLE_SAVED")


def validate(phase, code, text):
if phase not in {"RED", "GREEN"} or code != (1 if phase == "RED" else 0):
raise ValueError("wrong phase or Go exit status")
try:
events = [json.loads(line) for line in text.splitlines() if line.strip()]
except (ValueError, TypeError) as exc:
raise ValueError("non-JSON build/runtime output") from exc
if not events or any(not isinstance(event, dict) for event in events):
raise ValueError("missing JSON events")
if any(event.get("Package") != PACKAGE for event in events):
raise ValueError("wrong package")
output = "".join(event.get("Output", "") for event in events)
poison = ("[no tests to run]", "DATA RACE", "panic:", "fatal error:", "signal: killed", "undefined:", "build failed", "no required module provides package", "--- SKIP:")
if any(marker in output for marker in poison) or any(event.get("Action") in {"skip", "build-fail", "build-output"} or event.get("FailedBuild") for event in events):
raise ValueError("build/runtime/skip contamination")
named = [event for event in events if event.get("Test")]
if any(event["Test"] not in NODES for event in named):
raise ValueError("unexpected test")
runs = Counter(event["Test"] for event in named if event.get("Action") == "run")
terminal = "fail" if phase == "RED" else "pass"
ends = Counter(event["Test"] for event in named if event.get("Action") in {"pass", "fail", "skip"})
if runs != Counter({name: 1 for name in NODES}) or ends != runs:
raise ValueError("missing or repeated test nodes")
if any(event.get("Action") != terminal for event in named if event.get("Action") in {"pass", "fail", "skip"}):
raise ValueError("wrong test verdict")
packages = [event["Action"] for event in events if not event.get("Test") and event.get("Action") in {"pass", "fail", "skip"}]
if packages != [terminal]:
raise ValueError("wrong package verdict")
for leaf in LEAVES:
own = "".join(event.get("Output", "") for event in named if event["Test"] == leaf)
if not all(marker in own for marker in REACHED):
raise ValueError("route barrier or real admin save not reached: " + leaf)
if (ESCAPED in own) != (phase == "RED"):
raise ValueError("wrong business failure: " + leaf)
return {"phase": phase, "go_exit": code, "roots": len(ROOTS), "leaves": len(LEAVES), "nodes": len(NODES)}


if __name__ == "__main__":
print(json.dumps(validate(sys.argv[1], int(sys.argv[2]), Path(sys.argv[3]).read_text()), sort_keys=True))
176 changes: 176 additions & 0 deletions .github/scripts/prepare-request-proxy-historical-tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
"""Isolate twelve PR885 fixtures and restore one existing historical WS fixture."""

import json
import os
import re
import subprocess
import sys
from pathlib import Path


BASELINE_SHA = "94bb4a53e9e5057990cd851ab0620d99b116ad41"
CONTRACT = "backend/internal/service/openai_proxy_routing.go"
REDIS_HELPER = "backend/internal/testutil/redissession/store.go"
FIXTURES = (
"backend/internal/service/admin_account_request_proxy_upstream_merge_test.go",
"backend/internal/service/openai_codex_models_request_proxy_test.go",
"backend/internal/service/openai_excel_bps_proxy_config_test.go",
"backend/internal/service/openai_excel_bps_request_proxy_test.go",
"backend/internal/service/openai_maintenance_remaining_proxy_test.go",
"backend/internal/service/openai_maintenance_task_request_proxy_test.go",
"backend/internal/service/openai_oauth_create_request_proxy_test.go",
"backend/internal/service/openai_oauth_reauth_request_proxy_test.go",
"backend/internal/service/openai_oauth_request_proxy_test.go",
"backend/internal/service/openai_proxy_routing_test.go",
"backend/internal/service/openai_quota_request_proxy_test.go",
"backend/internal/service/openai_request_proxy_test.go",
)
ORACLES = (
"backend/internal/service/openai_409_ws_ticket_test.go",
"backend/internal/handler/openai_409_ws_rebuild_test.go",
"backend/internal/handler/openai_409_ws_oracle_test.go",
)
ADAPTED_FIXTURES = {
"backend/internal/service/openai_excel_bps_warm_test.go": "9dc2054fd0ab61d0465e1eb12ac060360bc80166",
}


def git(tree, *args):
return subprocess.run(
["git", "-C", str(tree), *args], check=True, capture_output=True, text=True, timeout=30
).stdout.strip()


def entry(tree, revision, relative):
raw = git(tree, "ls-tree", revision, "--", relative)
if not raw:
return None
metadata, path = raw.split("\t", 1)
mode, kind, blob = metadata.split()
if path != relative or mode != "100644" or kind != "blob":
raise ValueError("unexpected git entry: " + relative)
return blob


def safe_path(root, relative):
path = root
for part in Path(relative).parts:
if part in {"..", "."}:
raise ValueError("unexpected relative path")
path = path / part
if path.is_symlink():
raise ValueError("symlink refused: " + str(path))
return path


def candidate_file(tree, candidate, relative):
blob = entry(tree, candidate, relative)
path = safe_path(tree, relative)
if not blob or not path.is_file() or git(tree, "hash-object", "--", str(path)) != blob:
raise ValueError("missing or dirty candidate file: " + relative)
return blob, path


def prepare(baseline, root, candidate, destination):
# No CLI baseline override: the helper owns exactly this historical boundary.
if baseline != BASELINE_SHA:
raise ValueError("unsupported historical baseline")
if not re.fullmatch(r"[0-9a-f]{40}", candidate):
raise ValueError("candidate must be an exact commit SHA")
tree = Path(os.path.abspath(root))
if tree.is_symlink() or not tree.is_dir():
raise ValueError("invalid or symlinked worktree")
tree = tree.resolve()
if Path(git(tree, "rev-parse", "--show-toplevel")).resolve() != tree:
raise ValueError("expected the worktree root")
if git(tree, "rev-parse", "HEAD") != candidate:
raise ValueError("worktree HEAD is not candidate")
if git(tree, "rev-parse", baseline + "^{commit}") != baseline:
raise ValueError("baseline is not an exact commit")

manifest = Path(os.path.abspath(destination))
safe_path(Path(manifest.anchor), str(manifest.relative_to(manifest.anchor)))
if os.path.lexists(manifest) or not manifest.parent.is_dir() or manifest.is_relative_to(tree):
raise ValueError("manifest must be a new external evidence file")

# The baseline lacks the actual production contract, not just a test name.
contract_path = safe_path(tree, CONTRACT)
contract_blob = entry(tree, candidate, CONTRACT)
if entry(tree, baseline, CONTRACT) or not contract_blob or os.path.lexists(contract_path):
raise ValueError("request proxy contract must be absent in historical production")
contract_source = git(tree, "show", candidate + ":" + CONTRACT)
if "OpenAIProxyModeKey" not in contract_source or "OpenAIRequestProxyEnabled" not in contract_source:
raise ValueError("candidate request proxy contract is unexpected")

# Preserve the previously proved production baseline plus its sole explicit
# Redis test-support exception. Do not restore candidate production APIs.
if entry(tree, baseline, REDIS_HELPER):
raise ValueError("unexpected historical Redis test helper")
helper_blob, _ = candidate_file(tree, candidate, REDIS_HELPER)
production = git(tree, "diff", "--name-only", baseline, "--", "backend/**/*.go", ":!backend/**/*_test.go")
if production.splitlines() != [REDIS_HELPER]:
raise ValueError("unexpected production changes")
if git(tree, "ls-files", "--others", "--", "backend/**/*.go"):
raise ValueError("unexpected untracked backend Go files")

oracles = {}
for relative in ORACLES:
blob, _ = candidate_file(tree, candidate, relative)
oracles[relative] = blob

pending = []
for relative in FIXTURES:
if entry(tree, baseline, relative):
raise ValueError("fixture is not candidate-only: " + relative)
blob, path = candidate_file(tree, candidate, relative)
pending.append((relative, blob, path))

adaptations = []
for relative, expected_baseline_blob in ADAPTED_FIXTURES.items():
baseline_blob = entry(tree, baseline, relative)
if baseline_blob != expected_baseline_blob:
raise ValueError("unexpected adapted fixture baseline blob: " + relative)
candidate_blob, path = candidate_file(tree, candidate, relative)
historical = subprocess.run(
["git", "-C", str(tree), "show", baseline + ":" + relative],
check=True, capture_output=True, timeout=30,
).stdout
adaptations.append((relative, candidate_blob, baseline_blob, path, historical))

# Preflight every path and blob before the first mutation. A later dirty
# fixture cannot leave an earlier fixture removed on a rejected preparation.
records = []
for relative, blob, path in pending:
path.unlink()
records.append({"path": relative, "candidate_blob": blob, "baseline_blob": "absent", "actual": "absent"})
adapted_records = []
for relative, candidate_blob, baseline_blob, path, historical in adaptations:
path.write_bytes(historical)
actual_blob = git(tree, "hash-object", "--", str(path))
if actual_blob != baseline_blob:
raise ValueError("adapted fixture restoration mismatch: " + relative)
adapted_records.append({"path": relative, "candidate_blob": candidate_blob,
"baseline_blob": baseline_blob, "actual_blob": actual_blob})
result = {
"baseline": baseline,
"candidate": candidate,
"contract": {"path": CONTRACT, "baseline_blob": "absent", "candidate_blob": contract_blob, "actual": "absent"},
"production_exception": {"path": REDIS_HELPER, "candidate_blob": helper_blob},
"unchanged_oracles": oracles,
"fixtures": records,
"adapted_fixtures": adapted_records,
}
with manifest.open("x") as stream:
json.dump(result, stream, sort_keys=True, indent=2)
stream.write("\n")
return result


if __name__ == "__main__":
if len(sys.argv) != 5:
raise SystemExit("usage: prepare-request-proxy-historical-tests.py BASELINE TREE CANDIDATE MANIFEST")
try:
result = prepare(*sys.argv[1:])
except (ValueError, OSError, subprocess.SubprocessError) as exc:
raise SystemExit("historical request-proxy preparation refused: " + str(exc)) from exc
print("historical request-proxy fixtures isolated: " + str(len(result["fixtures"])))
39 changes: 27 additions & 12 deletions .github/scripts/prepare-ws-inherited-model-red.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@
BASELINE = "da526bfbab47efd40549cab98f1069f9b2b45b9f"
FIXTURE = "backend/internal/handler/openai_ws_inherited_model_test.go"
GUARDS = "backend/internal/service/openai_ws_owner_conflict_test.go"
# This upstream commit only prepends the independent pending-deadline fixture.
# Keep its full blob pinned; arbitrary changes to the candidate guards still fail.
GUARD_EXTENSION = "9dc66846a16609fb75b59a643563fae3284944cf"
GUARD_SOURCE_START = b"// Calls are learned only from the real response observer and successful write\n"


def git(*args, **kwargs):
Expand Down Expand Up @@ -47,26 +51,37 @@ def prepare(destination, evidence):
raise ValueError("baseline backend blob mismatch")
if (destination / FIXTURE).exists():
raise ValueError("fixture unexpectedly exists in pinned baseline")
# Guard files may acquire independent tests after the pinned baseline.
# Overlay the committed candidate tests in both cases, just as for the
# handler oracle. Every production/dependency blob above remains historical;
# the selected guard assertions and the evidence validator remain intact.
fixture_blobs = {}
for path in (FIXTURE, GUARDS):
blob = git("rev-parse", f"{candidate}:{path}").decode().strip()
if git("hash-object", path).decode().strip() != blob:
raise ValueError("dirty candidate fixture: " + path)
fixture_blob = git("rev-parse", f"{candidate}:{FIXTURE}").decode().strip()
if git("hash-object", FIXTURE).decode().strip() != fixture_blob:
raise ValueError("dirty candidate fixture")
guard_blob = git("rev-parse", f"{candidate}:{GUARDS}").decode().strip()
if git("hash-object", GUARDS).decode().strip() != guard_blob:
raise ValueError("dirty candidate guard fixture")
baseline_guards = (destination / GUARDS).read_bytes()
candidate_guards = Path(GUARDS).read_bytes()
if candidate_guards != baseline_guards:
approved_guards = git("show", f"{GUARD_EXTENSION}:{GUARDS}")
if candidate_guards != approved_guards:
raise ValueError("guard fixture changed outside the pinned upstream extension")
if (baseline_guards.count(GUARD_SOURCE_START) != 1
or candidate_guards.count(GUARD_SOURCE_START) != 1
or baseline_guards.split(GUARD_SOURCE_START, 1)[1]
!= candidate_guards.split(GUARD_SOURCE_START, 1)[1]):
raise ValueError("guard fixture changed; identical baseline/candidate guard tests required")
# Overlay both committed candidate fixtures so RED and GREEN run identical
# selected handler/guard assertions. Guard approval above remains pinned.
for path, blob in ((FIXTURE, fixture_blob), (GUARDS, guard_blob)):
shutil.copyfile(path, destination / path)
if git("hash-object", str(destination / path)).decode().strip() != blob:
raise ValueError("candidate test copy mismatch: " + path)
fixture_blobs[path] = blob
manifest = {
"baseline": BASELINE, "candidate": candidate,
"baseline_tree": git("rev-parse", f"{BASELINE}^{{tree}}").decode().strip(),
"baseline_backend_tree": git("rev-parse", f"{BASELINE}:backend").decode().strip(),
"candidate_fixture_blob": fixture_blobs[FIXTURE], "fixture": FIXTURE,
"guard_fixture_blob": fixture_blobs[GUARDS],
"candidate_fixture_blob": fixture_blob, "fixture": FIXTURE,
"guard_fixture_blob": guard_blob,
"baseline_guard_fixture_blob": git("rev-parse", f"{BASELINE}:{GUARDS}").decode().strip(),
"approved_guard_extension": GUARD_EXTENSION if candidate_guards != baseline_guards else None,
"verified_baseline_backend_blobs": len(entries),
"production_changes_in_red": [], "candidate_test_overlays": [FIXTURE, GUARDS],
}
Expand Down
83 changes: 83 additions & 0 deletions .github/scripts/test_account_proxy_config_switch_evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""Validator self-tests; synthetic events are never business evidence."""

import importlib.util
import json
import unittest
from pathlib import Path

SPEC = importlib.util.spec_from_file_location("gate", Path(__file__).with_name("assert-account-proxy-config-switch.py"))
GATE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(GATE)


def evidence(phase):
terminal = "fail" if phase == "RED" else "pass"
events = [{"Action": "start"}]
for root in sorted(GATE.ROOTS):
events.append({"Action": "run", "Test": root})
for leaf in sorted(name for name in GATE.LEAVES if name.startswith(root + "/")):
events.extend([{"Action": "run", "Test": leaf}, {"Action": "output", "Test": leaf, "Output": " ".join(GATE.REACHED) + (" " + GATE.ESCAPED if phase == "RED" else "")}, {"Action": terminal, "Test": leaf}])
events.append({"Action": terminal, "Test": root})
events.append({"Action": terminal})
return [dict(event, Package=GATE.PACKAGE) for event in events]


def raw(events):
return "\n".join(json.dumps(event) for event in events)


class ConfigSwitchEvidenceTests(unittest.TestCase):
def test_complete_red_and_green(self):
for phase, code in (("RED", 1), ("GREEN", 0)):
self.assertEqual(8, GATE.validate(phase, code, raw(evidence(phase)))["leaves"])

def test_each_run_terminal_and_business_marker_required(self):
for phase, code in (("RED", 1), ("GREEN", 0)):
events = evidence(phase)
for index, event in enumerate(events):
if event["Action"] in {"run", "pass", "fail", "output"}:
with self.assertRaises(ValueError):
GATE.validate(phase, code, raw(events[:index] + events[index + 1:]))
if event["Action"] in {"run", "pass", "fail"}:
with self.assertRaises(ValueError):
GATE.validate(phase, code, raw(events + [event]))
if event["Action"] == "output":
for marker in (*GATE.REACHED, GATE.ESCAPED) if phase == "RED" else GATE.REACHED:
changed = [dict(value) for value in events]
changed[index]["Output"] = changed[index]["Output"].replace(marker, "unrelated")
with self.assertRaises(ValueError):
GATE.validate(phase, code, raw(changed))

def test_exit_verdict_scope_and_contamination_rejected(self):
for phase, code in (("RED", 1), ("GREEN", 0)):
events = evidence(phase)
for wrong in (0, 1, 2, 137):
if wrong != code:
with self.assertRaises(ValueError):
GATE.validate(phase, wrong, raw(events))
for action in ("pass", "fail", "run", "skip", "build-fail"):
with self.assertRaises(ValueError):
GATE.validate(phase, code, raw(events + [{"Action": action, "Test": "Unrelated", "Package": GATE.PACKAGE}]))
for poison in ("[no tests to run]", "DATA RACE", "panic: bad", "undefined: fixture", "no required module provides package", "--- SKIP: fixture"):
with self.assertRaises(ValueError):
GATE.validate(phase, code, raw(events + [{"Action": "output", "Package": GATE.PACKAGE, "Output": poison}]))
for bad in ("", "not JSON", "[]", raw([dict(events[0], Package="other")]) + "\n" + raw(events)):
with self.assertRaises(ValueError):
GATE.validate(phase, code, bad)

def test_mixed_verdict_and_wrong_phase_rejected(self):
for phase, code in (("RED", 1), ("GREEN", 0)):
events = evidence(phase)
for index, event in enumerate(events):
if event["Action"] not in {"pass", "fail"}:
continue
changed = [dict(value) for value in events]
changed[index]["Action"] = "pass" if phase == "RED" else "fail"
with self.assertRaises(ValueError):
GATE.validate(phase, code, raw(changed))
with self.assertRaises(ValueError):
GATE.validate("OTHER", 1, raw(evidence("RED")))


if __name__ == "__main__":
unittest.main()
Loading
Loading