diff --git a/.github/scripts/issue854-evidence.py b/.github/scripts/issue854-evidence.py
new file mode 100644
index 000000000000..d51c6410b5f0
--- /dev/null
+++ b/.github/scripts/issue854-evidence.py
@@ -0,0 +1,100 @@
+"""Accept named business failures only; shared validator rejects dirty logs."""
+import importlib.util
+import json
+import sys
+from collections import Counter
+from pathlib import Path
+
+spec = importlib.util.spec_from_file_location("common", Path(__file__).with_name("assert-readable-continuation.py"))
+common = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(common)
+ROOT = "TestIssue854OwnerContinuation"
+MODES = ("http_bridge", "ctx_pool", "shared", "dedicated", "passthrough")
+LEAVES = {f"{ROOT}/{mode}/{case}" for mode in MODES for case in ("original", "fresh", "guard_live")}
+PARENTS = {ROOT}
+
+
+def inventory(suite):
+ if suite == "lifecycle":
+ return LEAVES, PARENTS, {n for n in LEAVES if n.endswith("/guard_live")}, ("WS_READABLE_B_DISPATCH_MISSING", "The proven encrypted agent owner is currently unavailable")
+ if suite == "persistence":
+ root = "TestIssue854OwnerFailurePersistence"
+ leaves = {f"{root}/{mode}/{connection}" for mode in MODES for connection in ("guard", "fresh")}
+ return leaves, {root}, leaves, ("ISSUE854_FAILURE_NOT_PERSISTED",)
+ if suite == "r1":
+ root = "TestIssue854FreshOwnerSelection"
+ leaves = {f"{root}/{mode}/{case}" for mode in MODES for case in ("disabled", "cooldown", "off", "pending", "failed", "conflict", "unfinished")}
+ return leaves, {root}, {n for n in leaves if n.endswith(("/disabled", "/cooldown"))}, ("ISSUE854_R1_INITIAL_OWNER_REFUSED", "encrypted_agent_recovery_owner_")
+ if suite == "http-empty-image":
+ root = "TestIssue854HTTPTransformMatrix"
+ leaves = {f"{root}/{account}/stream={stream}/empty_image" for account in ("apikey", "oauth") for stream in ("false", "true")}
+ return leaves, {root}, leaves, ("HTTP_REBUILD_B_DISPATCH_MISSING", "encrypted_agent_recovery_wire_changed")
+ if suite == "http-transform":
+ root = "TestIssue854HTTPTransformMatrix"
+ cases = ("metadata", "message_namespace", "tool_namespace", "empty_image", "reasoning_summary", "compaction_order", "timezone_manual", "timezone_auto", "lite", "reserved_alias", "namespace_declaration", "namespace_flatten", "schema_null", "new_task")
+ leaves = {f"{root}/{account}/stream={stream}/{case}" for account in ("apikey", "oauth") for stream in ("false", "true") for case in cases}
+ return leaves, {root}, set(), ()
+ if suite == "http-route":
+ root = "TestIssue854HTTPRouteAdmission"
+ leaves = {f"{root}/stream={stream}/native_available={available}" for stream in ("false", "true") for available in ("false", "true")}
+ return leaves, {root}, set(), ()
+ if suite == "postgres":
+ root = "TestIssue854PostgresRoundtrip"
+ return {f"{root}/{name}" for name in ("ws_guard", "ws_fresh", "sse")}, {root}, set(), ()
+ if suite == "ws-upstream":
+ root = "TestIssue854WSOwnerRateLimit"
+ leaves = {f"{root}/{mode}/encrypted_agent_recovery_{code}" for mode in MODES for code in ("owner_rate_limited", "untrusted_fixture")}
+ return leaves, {root}, {n for n in leaves if n.endswith("owner_rate_limited")}, ("ISSUE854_WS_OWNER_LIMIT_CODE_LOST",)
+ if suite == "upstream":
+ root = "TestIssue854UpstreamOwnerRateLimit"
+ parents = {root}
+ leaves = {f"{root}/stream={stream}/encrypted_agent_recovery_{code}" for stream in ("false", "true") for code in ("owner_rate_limited", "untrusted_fixture")}
+ return leaves, parents, {n for n in leaves if n.endswith("owner_rate_limited")}, ("ISSUE854_OWNER_LIMIT_CODE_LOST",)
+ raise ValueError("invalid suite")
+
+
+def validate(phase, status, raw, suite="lifecycle"):
+ leaves, parents, red_failures, markers = inventory(suite)
+ if phase not in ("RED", "GREEN"):
+ raise ValueError("invalid phase")
+ if phase == "RED" and suite in ("http-transform", "http-route"):
+ raise ValueError("updated policy matrix is a GREEN gate; use the named empty-image RED and archived original matrix")
+ common.check_clean(raw)
+ if "requires real redis-server in CI" in raw:
+ raise ValueError("fixture setup failure")
+ events = []
+ for line in raw.splitlines():
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if not isinstance(event, dict):
+ raise ValueError("invalid event")
+ events.append(event)
+ counts = Counter((e.get("Action"), e.get("Test")) for e in events if e.get("Package") == common.PACKAGE)
+ failures = red_failures if phase == "RED" else set()
+ failed_parents = {p for p in parents if any(n.startswith(p + "/") for n in failures)}
+ expected = {n: "fail" if n in failures | failed_parents else "pass" for n in leaves | parents}
+ expected[None] = "fail" if failures else "pass"
+ if status != (1 if failures else 0):
+ raise ValueError("wrong exit status")
+ for name, terminal in expected.items():
+ if name and counts["run", name] != 1:
+ raise ValueError(f"missing/repeated run: {name}")
+ if counts[terminal, name] != 1 or counts["pass", name] + counts["fail", name] != 1:
+ raise ValueError(f"wrong terminal: {name}")
+ for e in events:
+ if e.get("Action") in ("run", "pass", "fail") and (e.get("Package") != common.PACKAGE or e.get("Test") not in expected):
+ raise ValueError("unrelated test")
+ for name in failures:
+ output = "".join(e.get("Output", "") for e in events if e.get("Test") == name)
+ for marker in markers:
+ if marker not in output:
+ raise ValueError(f"missing business assertion: {name}: {marker}")
+
+
+if __name__ == "__main__":
+ phase, status, filename, *extra = sys.argv[1:]
+ suite = extra[0] if extra else "lifecycle"
+ validate(phase, int(status), Path(filename).read_text(), suite)
+ print(f"{phase}: all {len(inventory(suite)[0])} named {suite} leaves verified")
diff --git a/.github/scripts/prepare-mature-red-fixtures.sh b/.github/scripts/prepare-mature-red-fixtures.sh
index 97ef87be0a09..529fb1796ba0 100644
--- a/.github/scripts/prepare-mature-red-fixtures.sh
+++ b/.github/scripts/prepare-mature-red-fixtures.sh
@@ -2,6 +2,7 @@
# Only historical full-production overlays without the provider/QQ/coupon
# implementation omit its later independent test files. The newly merged BPS
# account-search fixture also requires absent historical service symbols.
+# Independent BPS settings and provider-team tests also require later APIs.
# GREEN keeps all tests.
# Never remove the selected gateway/moderation/recovery oracle or its fixtures.
set -euo pipefail
@@ -41,6 +42,9 @@ done < <(git -C "$tree" ls-files \
'backend/internal/service/mature_*_test.go' \
'backend/internal/service/repair_f2_coupon_recovery_test.go' \
'backend/internal/service/openai_excel_bps_search_test.go' \
+ 'backend/internal/service/bps_search_settings_test.go' \
+ 'backend/internal/service/account_ops_providers_test.go' \
+ 'backend/internal/service/account_ops_team_test.go' \
'backend/internal/server/routes/mature_*_test.go' \
'backend/internal/server/routes/repair_r1_payment_review_test.go' \
'backend/internal/server/routes/repair_provider_session_budget_test.go' \
diff --git a/.github/scripts/prepare-moderation-red-fixtures.sh b/.github/scripts/prepare-moderation-red-fixtures.sh
index 7fb254a40b80..e8363320774a 100644
--- a/.github/scripts/prepare-moderation-red-fixtures.sh
+++ b/.github/scripts/prepare-moderation-red-fixtures.sh
@@ -29,17 +29,22 @@ while IFS= read -r target; do
test ! -e "$tree/$target"
done < <(git -C "$tree" ls-files 'backend/internal/handler/moderation_upstream*_test.go' 'backend/internal/handler/admin/moderation_upstream_scope_test.go' 'backend/internal/service/content_moderation_upstream_scope_test.go' 'backend/internal/repository/moderation_upstream_scope*_test.go' 'backend/internal/handler/openai_409_ws_audit_test.go')
-# This pre-PR848 fixture retains PR834's actual error observer and all existing
-# recovery harness entry points, with the historical eight-argument constructor.
-fixture_base=afa7dbd6fccffef950febadc666b9243bba2454d
+# Preserve current harness entry points needed by independently compiled newer
+# tests. Only adapt the known constructor arity in this disposable RED tree.
+# Production stays byte-for-byte historical; selected behavior tests stay intact.
target=backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go
-if ! git -C "$tree" cat-file -e "$fixture_base^{commit}" 2>/dev/null; then
- git -C "$tree" fetch --no-tags --depth=1 origin "$fixture_base"
-fi
candidate_blob=$(git -C "$tree" rev-parse "$candidate:$target")
test "$(git -C "$tree" hash-object "$target")" = "$candidate_blob"
-expected=$(git -C "$tree" rev-parse "$fixture_base:$target")
-git -C "$tree" show "$fixture_base:$target" > "$tree/$target"
+python3 - "$tree/$target" <<'PY_FIXTURE'
+from pathlib import Path
+import sys
+path = Path(sys.argv[1])
+source = path.read_text()
+new = "service.NewContentModerationService(settingRepo, moderationRepo, nil, nil, nil, nil, nil, nil, accountRepo)"
+old = "service.NewContentModerationService(settingRepo, moderationRepo, nil, nil, nil, nil, nil, nil)"
+if source.count(new) != 1:
+ raise SystemExit("unexpected moderation fixture constructor")
+path.write_text(source.replace(new, old, 1))
+PY_FIXTURE
actual=$(git -C "$tree" hash-object "$target")
-test "$actual" = "$expected"
-printf 'compatible path=%s fixture_base=%s candidate=%s expected=%s actual=%s\n' "$target" "$fixture_base" "$candidate_blob" "$expected" "$actual"
+printf 'compatible test-only constructor path=%s candidate=%s adapted=%s\n' "$target" "$candidate_blob" "$actual"
diff --git a/.github/scripts/prepare-replay-red-fixtures.sh b/.github/scripts/prepare-replay-red-fixtures.sh
new file mode 100644
index 000000000000..b3373ac01d3d
--- /dev/null
+++ b/.github/scripts/prepare-replay-red-fixtures.sh
@@ -0,0 +1,57 @@
+#!/usr/bin/env bash
+# Disposable historical overlays only. Keep all candidate GREEN fixtures and
+# all selected historical RED assertions; never backport production behavior.
+set -euo pipefail
+tree="${2:-.}"
+baseline=$(git -C "$tree" rev-parse "$1^{commit}")
+candidate=$(git -C "$tree" rev-parse "${3:-HEAD}^{commit}")
+
+exclude_absent_fixture() {
+ local target="$1" contract="$2"
+ if git -C "$tree" cat-file -e "$baseline:$target" 2>/dev/null; then
+ printf 'refusing to exclude baseline replay fixture: %s\n' "$target" >&2
+ exit 1
+ fi
+ local expected actual expected_contract actual_contract
+ expected_contract=$(git -C "$tree" rev-parse "$baseline:$contract")
+ actual_contract=$(git -C "$tree" hash-object "$contract")
+ test "$actual_contract" = "$expected_contract"
+ expected=$(git -C "$tree" rev-parse "$candidate:$target")
+ # The mature full-source overlay also owns this independent BPS fixture.
+ # Both helpers retain their baseline/contract checks; accept only its exact
+ # already-recorded deletion, never a missing selected replay oracle.
+ if test "$target" = backend/internal/service/openai_excel_bps_search_test.go && ! test -e "$tree/$target"; then
+ test "$(git -C "$tree" diff --name-only --diff-filter=D "$candidate" -- "$target")" = "$target"
+ printf 'shared BPS fixture already excluded baseline=%s candidate=%s path=%s candidate_blob=%s contract_blob=%s\n' "$baseline" "$candidate" "$target" "$expected" "$actual_contract"
+ return
+ fi
+ actual=$(git -C "$tree" hash-object "$target")
+ test "$actual" = "$expected"
+ printf 'unrelated replay fixture baseline=%s candidate=%s path=%s baseline_blob=absent expected=%s actual=%s contract=%s contract_blob=%s\n' "$baseline" "$candidate" "$target" "$expected" "$actual" "$contract" "$actual_contract"
+ rm -- "$tree/$target"
+ test ! -e "$tree/$target"
+}
+
+# Full old-source overlays remove the unit-only OAuth dial seam alongside
+# later production files. This separate, later Issue842 matrix is not selected
+# by the historical 409/805/shadow regressions. Its own focused RED retains it.
+seam=backend/internal/service/issue842_gateway_test_support.go
+if ! test -f "$tree/$seam"; then
+ if git -C "$tree" cat-file -e "$baseline:$seam" 2>/dev/null; then
+ printf 'historical replay seam unexpectedly missing: %s\n' "$seam" >&2
+ exit 1
+ fi
+ exclude_absent_fixture backend/internal/handler/openai_issue842_oauth_repair_test.go backend/internal/service/openai_ws_agent_recovery.go
+fi
+
+# Older Account/search contracts cannot compile the unrelated new search
+# fixture in a service-package RED. Preserve the exact historical Account leaf;
+# only exclude the test when its baseline absence and candidate blob are proven.
+contract=backend/internal/service/account_excel_bps_tools.go
+if ! git -C "$tree" grep -q 'func (a \*Account) IsExcelBPSSearchEnabled' "$baseline" -- "$contract"; then
+ if ! test -f "$tree/$contract"; then
+ printf 'missing historical BPS account contract: %s\n' "$contract" >&2
+ exit 1
+ fi
+ exclude_absent_fixture backend/internal/service/openai_excel_bps_search_test.go "$contract"
+fi
diff --git a/.github/scripts/test_issue854_evidence.py b/.github/scripts/test_issue854_evidence.py
new file mode 100644
index 000000000000..d2e58647b76f
--- /dev/null
+++ b/.github/scripts/test_issue854_evidence.py
@@ -0,0 +1,64 @@
+import importlib.util
+import json
+import unittest
+from pathlib import Path
+
+spec = importlib.util.spec_from_file_location("gate", Path(__file__).with_name("issue854-evidence.py"))
+gate = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(gate)
+
+
+def transcript(phase, suite="lifecycle"):
+ leaves, parents, failures, markers = gate.inventory(suite)
+ events = []
+ for name in sorted(leaves | parents):
+ events.append(dict(Action="run", Test=name, Package=gate.common.PACKAGE))
+ failed = phase == "RED" and (name in failures or (name in parents and any(n.startswith(name + "/") for n in failures)))
+ if failed:
+ events.append(dict(Action="output", Test=name, Package=gate.common.PACKAGE, Output=" ".join(markers)))
+ events.append(dict(Action="fail" if failed else "pass", Test=name, Package=gate.common.PACKAGE))
+ events.append(dict(Action="fail" if phase == "RED" else "pass", Package=gate.common.PACKAGE))
+ return "\n".join(json.dumps(e) for e in events)
+
+
+class EvidenceTest(unittest.TestCase):
+ def test_other_suites(self):
+ for suite in ("persistence", "upstream", "ws-upstream", "r1", "http-empty-image"):
+ for phase, code in (("RED", 1), ("GREEN", 0)):
+ raw = transcript(phase, suite)
+ gate.validate(phase, code, raw, suite)
+ for pollution in ("build failed", "setup failed", "requires real redis-server in CI", "no tests to run", "panic", "DATA RACE", "--- SKIP: fixture", "crash"):
+ with self.assertRaises(ValueError):
+ gate.validate(phase, code, raw + "\n" + pollution, suite)
+ with self.assertRaises(ValueError):
+ gate.validate(phase, code, raw.replace('"Action": "run"', '"Action": "skip"', 1), suite)
+
+ def test_updated_policy_matrix_green(self):
+ for suite in ("http-transform", "http-route"):
+ raw = transcript("GREEN", suite)
+ gate.validate("GREEN", 0, raw, suite)
+ for polluted in (raw + "\npanic: fixture", raw + "\n" + raw, ""):
+ with self.assertRaises(ValueError):
+ gate.validate("GREEN", 0, polluted, suite)
+ with self.assertRaises(ValueError):
+ gate.validate("RED", 1, raw, suite)
+
+ def test_valid_and_polluted(self):
+ for phase, code in (("RED", 1), ("GREEN", 0)):
+ raw = transcript(phase)
+ gate.validate(phase, code, raw)
+ for pollution in ("panic: fixture", "DATA RACE", "build failed", "setup failed", "requires real redis-server in CI", "no tests to run", "--- SKIP: x", "signal: killed", "fatal error", "test timed out", "crash"):
+ with self.subTest(phase=phase, pollution=pollution), self.assertRaises(ValueError):
+ gate.validate(phase, code, raw + "\n" + pollution)
+ with self.assertRaises(ValueError):
+ gate.validate(phase, code, raw.replace('"Action": "run"', '"Action": "skip"', 1))
+ with self.assertRaises(ValueError):
+ gate.validate(phase, code, raw + "\n" + raw)
+ with self.assertRaises(ValueError):
+ gate.validate(phase, code, "")
+ with self.assertRaises(ValueError):
+ gate.validate("RED", 1, transcript("RED").replace("WS_READABLE_B_DISPATCH_MISSING", "unrelated error"))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml
index c99365638d6a..bd13605a2650 100644
--- a/.github/workflows/backend-ci.yml
+++ b/.github/workflows/backend-ci.yml
@@ -11,6 +11,136 @@ env:
EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
jobs:
+ issue854-behavior:
+ if: github.event_name == 'pull_request' && github.head_ref == 'fix/issue854-ws-owner-continuation'
+ runs-on: macos-15-intel
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ fetch-depth: 0
+ - name: Assert exact candidate
+ run: |
+ test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA"
+ git diff --exit-code
+ mkdir -p "$RUNNER_TEMP/issue854-evidence"
+ git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue854-evidence/candidate.txt"
+ - uses: actions/setup-go@v6
+ with:
+ go-version-file: backend/go.mod
+ cache-dependency-path: backend/go.sum
+ - name: Install isolated Redis fixture dependency
+ env:
+ HOMEBREW_NO_AUTO_UPDATE: '1'
+ HOMEBREW_NO_INSTALL_CLEANUP: '1'
+ run: |
+ if ! command -v redis-server >/dev/null; then
+ brew install redis
+ fi
+ redis-server --version
+ - name: Validate evidence parser mutations
+ run: python3 -m unittest discover -s .github/scripts -p 'test_issue854_evidence.py'
+ - name: RED exact baseline production blobs with candidate tests
+ shell: bash
+ run: |
+ set -euo pipefail
+ baseline=aa8e596e6d6f3e4648d6beba73b39b240dd5357a
+ git worktree add --detach "$RUNNER_TEMP/issue854-red" "$EXPECTED_HEAD_SHA"
+ git rev-parse "$baseline" "$baseline^{tree}" > "$RUNNER_TEMP/issue854-evidence/baseline.txt"
+ git diff --name-only "$baseline" "$EXPECTED_HEAD_SHA" -- backend | while IFS= read -r target; do
+ case "$target" in
+ *_test.go) continue ;;
+ *.go)
+ if git cat-file -e "$baseline:$target" 2>/dev/null; then
+ printf '%s %s\n' "$(git rev-parse "$baseline:$target")" "$target" >> "$RUNNER_TEMP/issue854-evidence/baseline-blobs.txt"
+ git show "$baseline:$target" > "$RUNNER_TEMP/issue854-red/$target"
+ test "$(git hash-object "$RUNNER_TEMP/issue854-red/$target")" = "$(git rev-parse "$baseline:$target")"
+ else
+ rm -- "$RUNNER_TEMP/issue854-red/$target"
+ fi ;;
+ esac
+ done
+ cd "$RUNNER_TEMP/issue854-red"
+ bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue854-evidence/independent-fixtures.txt"
+ bash "$GITHUB_WORKSPACE/.github/scripts/prepare-replay-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue854-evidence/replay-fixtures.txt"
+ git diff --stat > "$RUNNER_TEMP/issue854-evidence/red-diff.txt"
+ for suite in lifecycle persistence upstream ws-upstream r1 http-empty-image; do
+ case "$suite" in
+ lifecycle) test_name=TestIssue854OwnerContinuation ;;
+ persistence) test_name=TestIssue854OwnerFailurePersistence ;;
+ upstream) test_name=TestIssue854UpstreamOwnerRateLimit ;;
+ ws-upstream) test_name=TestIssue854WSOwnerRateLimit ;;
+ r1) test_name=TestIssue854FreshOwnerSelection ;;
+ http-empty-image) test_name='TestIssue854HTTPTransformMatrix$/.*/.*/empty_image' ;;
+ http-transform) test_name=TestIssue854HTTPTransformMatrix ;;
+ http-route) test_name=TestIssue854HTTPRouteAdmission ;;
+ esac
+ set +e
+ (cd backend && go test -tags=unit,issue854matrix ./internal/handler -run "^${test_name}$" -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/red-$suite.jsonl" 2>&1
+ status=$?
+ set -e
+ cat "$RUNNER_TEMP/issue854-evidence/red-$suite.jsonl"
+ python3 .github/scripts/issue854-evidence.py RED "$status" "$RUNNER_TEMP/issue854-evidence/red-$suite.jsonl" "$suite"
+ done
+ - name: GREEN clean candidate and lifecycle race checks
+ shell: bash
+ run: |
+ set -euo pipefail
+ test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA"
+ git diff --exit-code
+ for suite in lifecycle persistence upstream ws-upstream r1 http-transform http-route; do
+ case "$suite" in
+ lifecycle) test_name=TestIssue854OwnerContinuation ;;
+ persistence) test_name=TestIssue854OwnerFailurePersistence ;;
+ upstream) test_name=TestIssue854UpstreamOwnerRateLimit ;;
+ ws-upstream) test_name=TestIssue854WSOwnerRateLimit ;;
+ r1) test_name=TestIssue854FreshOwnerSelection ;;
+ http-transform) test_name=TestIssue854HTTPTransformMatrix ;;
+ http-route) test_name=TestIssue854HTTPRouteAdmission ;;
+ esac
+ set +e
+ (cd backend && go test -race -tags=unit,issue854matrix ./internal/handler -run "^${test_name}$" -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/green-$suite.jsonl" 2>&1
+ status=$?
+ set -e
+ cat "$RUNNER_TEMP/issue854-evidence/green-$suite.jsonl"
+ python3 .github/scripts/issue854-evidence.py GREEN "$status" "$RUNNER_TEMP/issue854-evidence/green-$suite.jsonl" "$suite"
+ done
+ - name: Contract and safety regressions
+ shell: bash
+ run: |
+ set -euo pipefail
+ (cd backend && go test -race -tags=unit ./internal/handler -run '^Test(OpenAI409(WSReadableBoundaries|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|HTTPTaskRebuild|HTTPRebuildBoundaries|HTTPToolDefinitionOracle)|OpenAI409HTTPProjectionAndPassthrough|OpenAI409WSInitialWithoutPointer|Issue854HTTPContinuation|Issue854LostOwnerEvidence|Issue805|Issue758WS)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" 2>&1
+ python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/issue854-evidence/contracts.jsonl"
+ python3 .github/scripts/assert-ws-readable.py GREEN 0 "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" ws-boundaries
+ (cd backend && go test -race -tags=unit,issue854matrix ./internal/service -run '^Test(OpenAI409PhysicalTimezonePreservesReadableTask|OpenAI409NamespaceProjectionPreservesNumbers|Issue854HTTPProjectionIntegrity|Issue854BeforeSendRecoveryGuards|OpenAI409WSUnsentTurnBoundary|Issue715WS|OpenAI409WS|OpenAIWS.*(Agent|Replay))' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/service-contracts.jsonl" 2>&1
+ python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/issue854-evidence/service-contracts.jsonl"
+ - name: PostgreSQL terminal failure roundtrip
+ env:
+ HOMEBREW_NO_AUTO_UPDATE: '1'
+ HOMEBREW_NO_INSTALL_CLEANUP: '1'
+ ISSUE854_TEST_POSTGRES_DSN: postgres://fixture@127.0.0.1:15439/issue854_fixture?sslmode=disable
+ shell: bash
+ run: |
+ set -euo pipefail
+ brew install postgresql@16
+ pg_bin="$(brew --prefix postgresql@16)/bin"
+ "$pg_bin/initdb" -D "$RUNNER_TEMP/issue854-pg" -U fixture -A trust
+ "$pg_bin/pg_ctl" -D "$RUNNER_TEMP/issue854-pg" -l "$RUNNER_TEMP/issue854-evidence/postgres.log" -o '-h 127.0.0.1 -p 15439' start
+ trap '"$pg_bin/pg_ctl" -D "$RUNNER_TEMP/issue854-pg" stop -m fast' EXIT
+ "$pg_bin/createdb" -h 127.0.0.1 -p 15439 -U fixture issue854_fixture
+ set +e
+ (cd backend && go test -race -tags=unit,issue854pg ./internal/handler -run '^TestIssue854PostgresRoundtrip$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/postgres.jsonl" 2>&1
+ status=$?
+ set -e
+ cat "$RUNNER_TEMP/issue854-evidence/postgres.jsonl"
+ python3 .github/scripts/issue854-evidence.py GREEN "$status" "$RUNNER_TEMP/issue854-evidence/postgres.jsonl" postgres
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: issue854-evidence-${{ github.event.pull_request.head.sha }}
+ path: ${{ runner.temp }}/issue854-evidence/
+
pelican-round-evidence:
if: github.event_name == 'pull_request' && github.head_ref == 'fix/issue795-round-evidence-followup-20261112'
runs-on: ubuntu-latest
@@ -193,7 +323,7 @@ jobs:
run: make test-integration
frontend:
- runs-on: ${{ vars.SUB2API_SUPPLEMENTARY_RUNNER || 'ubuntu-latest' }}
+ runs-on: ${{ (github.head_ref == 'fix/issue854-ws-owner-continuation' || github.ref_name == 'fix/issue854-ws-owner-continuation') && 'macos-15-intel' || vars.SUB2API_SUPPLEMENTARY_RUNNER || 'ubuntu-latest' }}
steps:
- uses: actions/checkout@v6
with:
@@ -214,7 +344,12 @@ jobs:
working-directory: frontend
run: pnpm install --frozen-lockfile
- name: Frontend typecheck and critical vitest
+ env:
+ NODE_OPTIONS: ${{ (github.head_ref == 'fix/issue854-ws-owner-continuation' || github.ref_name == 'fix/issue854-ws-owner-continuation') && '--max-old-space-size=4096' || '' }}
run: make test-frontend
+ - name: Issue854 transport failure presentation
+ if: github.head_ref == 'fix/issue854-ws-owner-continuation' || github.ref_name == 'fix/issue854-ws-owner-continuation'
+ run: pnpm --dir frontend exec vitest run src/views/admin/ops/components/__tests__/OpsErrorLogTable.spec.ts src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts
golangci-lint:
runs-on: ubuntu-latest
diff --git a/.github/workflows/encrypted-history-409.yml b/.github/workflows/encrypted-history-409.yml
index 93d6e66b26f9..62b47b9f38cf 100644
--- a/.github/workflows/encrypted-history-409.yml
+++ b/.github/workflows/encrypted-history-409.yml
@@ -51,7 +51,7 @@ jobs:
cd "$RUNNER_TEMP/omit-metadata-red"
# Keep the pre-rebuild callers coherent with the old omission API.
# The historical metadata regression itself remains the candidate's.
- for target in backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_agent_message_recovery_error.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_codex_transform.go backend/internal/handler/openai_gateway_handler.go; do
+ for target in backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_agent_message_recovery_error.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_codex_transform.go backend/internal/handler/openai_gateway_handler.go backend/internal/handler/openai_agent_message_recovery.go; do
git show "$callers:$target" > "$target"
test "$(git hash-object "$target")" = "$(git rev-parse "$callers:$target")"
done
@@ -59,12 +59,26 @@ jobs:
git show "$callers:$target" > "$target"
test "$(git hash-object "$target")" = "$(git rev-parse "$callers:$target")"
done
- ! git cat-file -e "$callers:backend/internal/service/openai_ws_readable_continuation.go" 2>/dev/null
+ if git cat-file -e "$callers:backend/internal/service/openai_ws_readable_continuation.go" 2>/dev/null; then exit 1; fi
rm -- backend/internal/service/openai_ws_readable_continuation.go
for target in backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go; do
- ! git cat-file -e "$callers:$target" 2>/dev/null
+ if git cat-file -e "$callers:$target" 2>/dev/null; then exit 1; fi
rm -- "$target"
done
+ # This later helper is not part of the pinned recovery defect. Its
+ # pre-OAuth-projection API is compatible with the restored struct;
+ # preserve every selected defect/caller blob and behavioral assertion.
+ compatibility=00d2e9be01404c6e85c0560fa196e4650ef5d0fb
+ target=backend/internal/service/openai_agent_replay_metadata.go
+ if git cat-file -e "$callers:$target" 2>/dev/null; then exit 1; fi
+ git fetch --no-tags --depth=1 origin "$compatibility"
+ candidate_blob=$(git rev-parse "HEAD:$target")
+ test "$(git hash-object "$target")" = "$candidate_blob"
+ expected=$(git rev-parse "$compatibility:$target")
+ git show "$compatibility:$target" > "$target"
+ actual=$(git hash-object "$target")
+ test "$actual" = "$expected"
+ echo "$target defect_source=$callers defect_blob=absent compatibility=$compatibility candidate=$candidate_blob expected=$expected actual=$actual" >> "$RUNNER_TEMP/omit-history-red-compat.txt"
target=backend/internal/service/openai_409_omit_history.go
git show "$baseline:$target" > "$target"
test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")"
@@ -74,7 +88,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/omit-history-red.log"
test "$result" -ne 0
- ! grep -Eiq 'build failed|no tests to run|undefined:|panic|data race|--- SKIP:' "$RUNNER_TEMP/omit-history-red.log"
+ if grep -Eiq 'build failed|no tests to run|undefined:|panic|data race|--- SKIP:' "$RUNNER_TEMP/omit-history-red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestOpenAI409ReplayMetadataHTTP' "$RUNNER_TEMP/omit-history-red.log"
grep -q 'encrypted_agent_recovery_wire_changed' "$RUNNER_TEMP/omit-history-red.log"
- uses: actions/upload-artifact@v7
@@ -84,6 +98,7 @@ jobs:
path: |
${{ runner.temp }}/omit-history-protocol.log
${{ runner.temp }}/omit-history-red.log
+ ${{ runner.temp }}/omit-history-red-compat.txt
screenshots:
runs-on: ubuntu-latest
timeout-minutes: 15
diff --git a/.github/workflows/future-shadow.yml b/.github/workflows/future-shadow.yml
index ed89efc17d9b..a95928ff2a51 100644
--- a/.github/workflows/future-shadow.yml
+++ b/.github/workflows/future-shadow.yml
@@ -20,6 +20,7 @@ on:
- '.github/scripts/test_assert_future_shadow.py'
- '.github/scripts/mutate-future-shadow.py'
- '.github/scripts/prepare-moderation-red-fixtures.sh'
+ - '.github/scripts/prepare-replay-red-fixtures.sh'
- '.github/workflows/future-shadow.yml'
permissions:
contents: read
@@ -101,6 +102,7 @@ jobs:
if [ "$PHASE" = RED ]; then
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA"
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA"
+ bash "$GITHUB_WORKSPACE/.github/scripts/prepare-replay-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-evidence/replay-fixtures.txt"
bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-evidence/moderation-fixtures.txt"
fi
for target in backend/internal/handler/openai_409_shadow_http_test.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_409_omit_history.go; do
diff --git a/.github/workflows/http-task-rebuild.yml b/.github/workflows/http-task-rebuild.yml
index f6cdd164f1d7..909da77756a0 100644
--- a/.github/workflows/http-task-rebuild.yml
+++ b/.github/workflows/http-task-rebuild.yml
@@ -24,6 +24,7 @@ on:
- '.github/scripts/mutate-http-rebuild-owner-scan.py'
- '.github/scripts/assert-readable-continuation.py'
- '.github/scripts/prepare-moderation-red-fixtures.sh'
+ - '.github/scripts/prepare-replay-red-fixtures.sh'
- '.github/workflows/http-task-rebuild.yml'
permissions:
@@ -117,6 +118,7 @@ jobs:
if [ "$PHASE" = RED ]; then
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA"
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA"
+ bash "$GITHUB_WORKSPACE/.github/scripts/prepare-replay-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/http-task-evidence/replay-fixtures.txt"
bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/http-task-evidence/moderation-fixtures.txt"
fi
for target in backend/internal/handler/openai_409_http_rebuild_test.go backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_responses_failover_cancel_test.go; do
@@ -218,6 +220,7 @@ jobs:
git diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go'
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$REVIEW_BASELINE"
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$REVIEW_BASELINE"
+ bash "$GITHUB_WORKSPACE/.github/scripts/prepare-replay-red-fixtures.sh" "$REVIEW_BASELINE" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/http-review-red-evidence/replay-fixtures.txt"
bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$REVIEW_BASELINE" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/http-review-red-evidence/moderation-fixtures.txt"
for suite in pointer-waiver normalization; do
test_name=TestOpenAI409HTTPUnownedPointerMustDetach
diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml
index e587a3d3a3f4..7b79fcee5d22 100644
--- a/.github/workflows/issue715-agent-recovery.yml
+++ b/.github/workflows/issue715-agent-recovery.yml
@@ -73,7 +73,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestIssue715BridgeDoesNotAdvertiseEncryptedAgent' "$RUNNER_TEMP/issue715-red.log"
grep -q 'bridge must not create unreadable encrypted tasks' "$RUNNER_TEMP/issue715-red.log"
grep -q -- '--- FAIL: TestIssue715FetchedAndPinnedBridgeCapabilities' "$RUNNER_TEMP/issue715-red.log"
@@ -102,9 +102,15 @@ jobs:
targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_gateway_response_handling.go backend/internal/service/openai_gateway_service.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go)
added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_agent_message_recovery_wait.go backend/internal/service/openai_ws_search_activation.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go)
# The exact original gateway struct predates analysis admission state.
- added+=(backend/internal/service/openai_ws_readable_continuation.go)
+ added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_replay_metadata.go)
+ handler_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a
+ handler_leaf=backend/internal/handler/openai_agent_message_recovery.go
# Pin this unrelated leaf to its pre-admission version, preserving all
# Issue715 business-chain blobs and the retained handler regressions.
+ # Issue842 compatibility-body callers depend on the later recovery
+ # helper. Keep its exact pre-Issue842 blob in this historical assembly.
+ metadata_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a
+ metadata_leaf=backend/internal/service/openai_gateway_request_body.go
analysis_compat=e395038e98fbc5a0c44944f0edcfbfe714570f71
analysis_leaf=backend/internal/service/priority_analysis.go
# The restored usage struct also predates the 30m/12h counters.
@@ -117,10 +123,14 @@ jobs:
weekly_compat=f895ea743f34a4c4ab6c9d01c01e13c931625a6e
weekly_leaves=(backend/internal/service/openai_disable_scheduling_429.go backend/internal/service/openai_gateway_passthrough.go backend/internal/service/openai_plugin_transport.go backend/internal/service/openai_quota_service.go backend/internal/service/openai_quota_usage_snapshot.go backend/internal/service/openai_ws_forwarder_support.go backend/internal/service/openai_ws_forwarder_v2.go)
git fetch --no-tags --depth=1 origin "$original"
+ git fetch --no-tags --depth=1 origin "$metadata_compat"
git fetch --no-tags --depth=1 origin "$analysis_compat"
git fetch --no-tags --depth=1 origin "$billing_compat"
- trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT
+ trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}" "$handler_leaf" "$metadata_leaf" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT
git restore --source="$original" -- "${targets[@]}"
+ git restore --source="$metadata_compat" -- "$metadata_leaf"
+ test "$(git hash-object "$metadata_leaf")" = "$(git rev-parse "$metadata_compat:$metadata_leaf")"
+ echo "compatibility_leaf_baseline=$metadata_compat path=$metadata_leaf blob=$(git hash-object "$metadata_leaf")"
git restore --source="$analysis_compat" -- "$analysis_leaf"
git restore --source="$billing_compat" -- "$billing_leaf"
git fetch --no-tags --depth=1 origin "$weekly_compat"
@@ -139,6 +149,10 @@ jobs:
actual=$(git hash-object "$analysis_leaf")
echo "compatibility_leaf_baseline=$analysis_compat path=$analysis_leaf expected_blob=$expected tested_blob=$actual"
test "$expected" = "$actual"
+ git fetch --no-tags --depth=1 origin "$handler_compat"
+ git restore --source="$handler_compat" -- "$handler_leaf"
+ test "$(git hash-object "$handler_leaf")" = "$(git rev-parse "$handler_compat:$handler_leaf")"
+ echo "handler_compatibility_baseline=$handler_compat path=$handler_leaf"
rm -- "${added[@]}"
for target in "${targets[@]}"; do
expected=$(git rev-parse "$original:$target")
@@ -153,7 +167,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-recovery-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-recovery-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-recovery-red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestIssue715HTTPResumesSameTaskAcrossTwoTurns/false' "$RUNNER_TEMP/issue715-recovery-red.log"
grep -q -- '--- FAIL: TestIssue715HTTPResumesSameTaskAcrossTwoTurns/true' "$RUNNER_TEMP/issue715-recovery-red.log"
grep -q 'same task and tool context must survive route drift' "$RUNNER_TEMP/issue715-recovery-red.log"
@@ -190,7 +204,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-delivery-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-delivery-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-delivery-red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestIssue715HTTPFailedDeliveryNeverGrantsOwner/json/error' "$RUNNER_TEMP/issue715-delivery-red.log"
grep -q -- '--- FAIL: TestIssue715HTTPFailedDeliveryNeverGrantsOwner/aggregate/error' "$RUNNER_TEMP/issue715-delivery-red.log"
grep -q 'failed downstream delivery must not grant a successful owner' "$RUNNER_TEMP/issue715-delivery-red.log"
@@ -227,7 +241,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-generated-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-generated-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:' "$RUNNER_TEMP/issue715-generated-red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestIssue715HTTPGeneratedTaskReturnsToItsProducer/generated-json' "$RUNNER_TEMP/issue715-generated-red.log"
grep -q -- '--- FAIL: TestIssue715HTTPGeneratedTaskReturnsToItsProducer/generated-stream-items' "$RUNNER_TEMP/issue715-generated-red.log"
grep -q 'newly generated task must return to its producer before any prior successful input' "$RUNNER_TEMP/issue715-generated-red.log"
@@ -257,6 +271,8 @@ jobs:
# Neither helper exists on the restored historical socket structure.
ws_added=(backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_search_activation.go)
ws_added+=(backend/internal/service/openai_ws_readable_continuation.go)
+ handler_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a
+ handler_leaf=backend/internal/handler/openai_agent_message_recovery.go
# The historical recovery request predates Issue758 cooldown state.
# Keep the exact delivery-defect blobs above, and pin only this
# scheduling compatibility leaf to the pre-Issue758 production base.
@@ -265,17 +281,28 @@ jobs:
wait_added=backend/internal/service/openai_agent_message_recovery_wait.go
# The Beta helper depends on fields absent in this historical recovery struct.
omission_added=(backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go)
+ omission_added+=(backend/internal/service/openai_agent_replay_metadata.go)
+ metadata_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a
+ metadata_leaf=backend/internal/service/openai_gateway_request_body.go
git fetch --no-tags --depth=1 origin "$original"
git fetch --no-tags --depth=1 origin "$ws_original"
git fetch --no-tags --depth=1 origin "$scheduler_compat"
- trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "${omission_added[@]}" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT
+ git fetch --no-tags --depth=1 origin "$metadata_compat"
+ trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "${omission_added[@]}" "$handler_leaf" "$metadata_leaf" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT
git restore --source="$original" -- "${targets[@]}"
git restore --source="$ws_original" -- "${ws_targets[@]}"
+ git restore --source="$metadata_compat" -- "$metadata_leaf"
+ test "$(git hash-object "$metadata_leaf")" = "$(git rev-parse "$metadata_compat:$metadata_leaf")"
+ echo "compatibility_leaf_baseline=$metadata_compat path=$metadata_leaf blob=$(git hash-object "$metadata_leaf")"
git restore --source="$scheduler_compat" -- "$scheduler_leaf"
expected=$(git rev-parse "$scheduler_compat:$scheduler_leaf")
actual=$(git hash-object "$scheduler_leaf")
echo "compatibility_leaf_baseline=$scheduler_compat path=$scheduler_leaf expected_blob=$expected tested_blob=$actual"
test "$expected" = "$actual"
+ git fetch --no-tags --depth=1 origin "$handler_compat"
+ git restore --source="$handler_compat" -- "$handler_leaf"
+ test "$(git hash-object "$handler_leaf")" = "$(git rev-parse "$handler_compat:$handler_leaf")"
+ echo "handler_compatibility_baseline=$handler_compat path=$handler_leaf"
rm -- "$added" "${ws_added[@]}" "$wait_added" "${omission_added[@]}"
for target in "${omission_added[@]}"; do
test ! -e "$target"
@@ -294,7 +321,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-first-delivery-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:|DATA RACE|fixture barrier not reached' "$RUNNER_TEMP/issue715-first-delivery-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:|DATA RACE|fixture barrier not reached' "$RUNNER_TEMP/issue715-first-delivery-red.log"; then exit 1; fi
for format in generated-json generated-stream generated-stream-items; do
grep -q -- "--- FAIL: TestIssue715HTTPFirstDeliveryCrossNodeBarrier/$format" "$RUNNER_TEMP/issue715-first-delivery-red.log"
done
@@ -332,9 +359,15 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:|DATA RACE|--- SKIP:' "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:|DATA RACE|--- SKIP:' "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestIssue715WSGeneratedTaskContinuation/http_bridge/cross-node=false' "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"
- grep -q 'generated WS task must continue without rebuilding the session' "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"
+ # PR855 returns the safe structured refusal before the close. The
+ # unchanged oracle now reaches its content assertion (instead of the
+ # socket-read assertion). Require that exact business failure after
+ # the first continuation completed; do not accept arbitrary errors.
+ grep -q 'generated opaque WS task and tool result must return to producer' "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"
+ grep -q 'encrypted_agent_recovery_wire_changed' "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"
+ grep -q 'ingress_ws_http_bridge_turn_completed.*turn=2' "$RUNNER_TEMP/issue715-ws-bridge-sequence-red.log"
red-ws-wire:
runs-on: ubuntu-latest
@@ -382,7 +415,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-ws-wire-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:|--- SKIP:' "$RUNNER_TEMP/issue715-ws-wire-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:|--- SKIP:' "$RUNNER_TEMP/issue715-ws-wire-red.log"; then exit 1; fi
grep -q -- '--- FAIL: TestIssue715WSBridgeValidatesBuiltPayload' "$RUNNER_TEMP/issue715-ws-wire-red.log"
grep -q 'bridge must validate actual built HTTP body before granting opaque task admission' "$RUNNER_TEMP/issue715-ws-wire-red.log"
@@ -459,7 +492,7 @@ jobs:
set -e
cat "$RUNNER_TEMP/issue715-ws-red.log"
test "$result" -ne 0
- ! grep -Eq 'build failed|no tests to run|undefined:|panic:|DATA RACE|--- SKIP:' "$RUNNER_TEMP/issue715-ws-red.log"
+ if grep -Eq 'build failed|no tests to run|undefined:|panic:|DATA RACE|--- SKIP:' "$RUNNER_TEMP/issue715-ws-red.log"; then exit 1; fi
for mode in ctx_pool passthrough http_bridge; do
grep -q -- "--- FAIL: TestIssue715WSGeneratedTaskContinuation/$mode/cross-node=true" "$RUNNER_TEMP/issue715-ws-red.log"
done
@@ -525,7 +558,7 @@ jobs:
test "$issue715_diag_samples" -gt 0
test "$(grep -c '^=== RUN TestOpsOutputTPSQueryDeadline$' "$issue715_diag_dir/test.log")" -eq 20
test "$(grep -c '^--- PASS: TestOpsOutputTPSQueryDeadline ' "$issue715_diag_dir/test.log")" -eq 20
- ! grep -En '^--- (FAIL|SKIP):|panic:|\[build failed\]|\[no tests to run\]|skipping integration tests' "$issue715_diag_dir/test.log"
+ if grep -En '^--- (FAIL|SKIP):|panic:|\[build failed\]|\[no tests to run\]|skipping integration tests' "$issue715_diag_dir/test.log"; then exit 1; fi
- uses: actions/upload-artifact@v6
if: always()
with:
diff --git a/.github/workflows/issue805-owner-policy.yml b/.github/workflows/issue805-owner-policy.yml
index 8157ca045e6a..ff4c97a81152 100644
--- a/.github/workflows/issue805-owner-policy.yml
+++ b/.github/workflows/issue805-owner-policy.yml
@@ -6,6 +6,7 @@ on:
paths:
- 'backend/**'
- '.github/scripts/prepare-moderation-red-fixtures.sh'
+ - '.github/scripts/prepare-replay-red-fixtures.sh'
- '.github/workflows/issue805-owner-policy.yml'
workflow_dispatch:
@@ -87,7 +88,7 @@ jobs:
# baseline. The readable/task-rebuild fixtures import its settings and
# usage helpers. Exclude this exact dependency set only in the old
# Issue805 RED; GREEN and each feature's own TDD job retain them.
- for omission_test in backend/internal/handler/openai_409_omit_history_test.go backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_409_http_rebuild_test.go backend/internal/handler/openai_409_shadow_http_test.go backend/internal/handler/openai_409_shadow_race_test.go backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/handler/openai_400_omit_history_test.go; do
+ for omission_test in backend/internal/handler/openai_409_omit_history_test.go backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_409_http_rebuild_test.go backend/internal/handler/openai_409_shadow_http_test.go backend/internal/handler/openai_409_shadow_race_test.go backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/handler/openai_400_omit_history_test.go backend/internal/handler/openai_issue854_continuation_test.go backend/internal/handler/openai_issue854_upstream_test.go backend/internal/handler/openai_issue854_postgres_test.go; do
git cat-file -e "$EXPECTED_HEAD_SHA:$omission_test"
rm -- "$omission_test"
test ! -e "$omission_test"
@@ -95,6 +96,7 @@ jobs:
done
# The pinned HTTP2 exclusion helper above already handles the handler
# fixture absent from this baseline; do not remove it a second time.
+ bash "$GITHUB_WORKSPACE/.github/scripts/prepare-replay-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue805-evidence/replay-fixtures.txt"
bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue805-evidence/moderation-fixtures.txt"
# The selected regression and its shared harness must remain exact
# candidate blobs. The clean GREEN checkout retains all new tests.
diff --git a/.github/workflows/issue842-replay-metadata.yml b/.github/workflows/issue842-replay-metadata.yml
new file mode 100644
index 000000000000..1fe5347ec12f
--- /dev/null
+++ b/.github/workflows/issue842-replay-metadata.yml
@@ -0,0 +1,162 @@
+name: Issue842 protected replay metadata
+
+on:
+ pull_request:
+ branches: [production]
+ paths: ['backend/**', '.github/workflows/issue842-replay-metadata.yml']
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: issue842-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+env:
+ EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
+
+jobs:
+ evidence:
+ runs-on: ubuntu-latest
+ timeout-minutes: 35
+ services:
+ postgres:
+ image: postgres:16-alpine
+ env:
+ POSTGRES_USER: fixture
+ POSTGRES_PASSWORD: fixture
+ POSTGRES_DB: issue842
+ ports: ['15432:5432']
+ options: >-
+ --health-cmd "pg_isready -U fixture -d issue842"
+ --health-interval 5s --health-timeout 5s --health-retries 10
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ - uses: actions/setup-go@v6
+ with:
+ go-version-file: backend/go.mod
+ cache-dependency-path: backend/go.sum
+ - name: Install isolated Redis fixture
+ run: |
+ bash .github/scripts/ci-ubuntu-mirrors.sh
+ if ! command -v redis-server >/dev/null; then
+ sudo apt-get update
+ sudo apt-get install -y --no-install-recommends redis-server
+ fi
+ - name: Candidate GREEN at exact head
+ shell: bash
+ run: |
+ set -euo pipefail
+ test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA"
+ test -z "$(git status --porcelain)"
+ mkdir -p "$RUNNER_TEMP/issue842"
+ git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue842/candidate.txt"
+ # Formatting is verified remotely as well; no local toolchain runs.
+ gofmt -d backend/internal/handler/openai_issue842*_test.go backend/internal/service/openai_issue842_replay_test.go backend/internal/service/issue842_gateway_test_support.go backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_ws_agent_recovery.go > "$RUNNER_TEMP/issue842/format.patch"
+ cat "$RUNNER_TEMP/issue842/format.patch"
+ cd backend
+ go test -race -json -tags=unit ./internal/handler ./internal/service -run '^Test(Issue(842|805)|OpenAIAgentRecoveryCompaction|WithoutOpenAIRemoteCompaction)' -count=1 -timeout=10m 2>&1 | tee "$RUNNER_TEMP/issue842/green.jsonl"
+ if grep -Eiq '"Action":"skip"|no tests to run|panic:|WARNING: DATA RACE' "$RUNNER_TEMP/issue842/green.jsonl"; then exit 1; fi
+ - name: Isolated pinned defect RED with candidate fixtures
+ shell: bash
+ run: |
+ set -euo pipefail
+ baseline=aa8e596e6d6f3e4648d6beba73b39b240dd5357a
+ git fetch --no-tags --depth=1 origin "$baseline"
+ git worktree add --detach "$RUNNER_TEMP/issue842-red" "$EXPECTED_HEAD_SHA"
+ cd "$RUNNER_TEMP/issue842-red"
+ # Only the production paths of this repair are restored. Candidate
+ # fixtures stay exact, and the original GREEN tree stays untouched.
+ for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_gateway_request_body.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_agent_message_recovery.go; do
+ git show "$baseline:$target" > "$target"
+ expected=$(git rev-parse "$baseline:$target")
+ actual=$(git hash-object "$target")
+ echo "$target expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue842/red-blobs.txt"
+ test "$expected" = "$actual"
+ done
+ target=backend/internal/service/openai_agent_replay_metadata.go
+ if git cat-file -e "$baseline:$target" 2>/dev/null; then exit 1; fi
+ rm -- "$target"
+ test ! -e "$target"
+ echo "$target baseline=absent actual=absent" >> "$RUNNER_TEMP/issue842/red-blobs.txt"
+ target=backend/internal/handler/openai_issue842_replay_test.go
+ test "$(git hash-object "$target")" = "$(git rev-parse "$EXPECTED_HEAD_SHA:$target")"
+ git diff --stat > "$RUNNER_TEMP/issue842/red-diff.txt"
+ set +e
+ (cd backend && go test -json -tags=unit ./internal/handler -run '^TestIssue842(HTTP|WS)ReplayMetadata$' -count=1 -timeout=5m) > "$RUNNER_TEMP/issue842/red.jsonl" 2>&1
+ result=$?
+ set -e
+ cat "$RUNNER_TEMP/issue842/red.jsonl"
+ test "$result" -ne 0
+ if grep -Eiq 'build failed|no tests to run|undefined:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|"Action":"skip"' "$RUNNER_TEMP/issue842/red.jsonl"; then exit 1; fi
+ python3 - "$RUNNER_TEMP/issue842/red.jsonl" <<'PY'
+ import itertools, json, sys
+ events = [json.loads(line) for line in open(sys.argv[1])]
+ failed = {e.get('Test') for e in events if e.get('Action') == 'fail'}
+ variants = ('reasoning_status', 'reasoning_content', 'plaintext_reasoning', 'reasoning_id', 'invalid_replay_id', 'message_call_id')
+ for kind, stream, variant, known in itertools.product(('apikey', 'oauth'), ('false', 'true'), variants, ('true', 'false')):
+ name = f'TestIssue842HTTPReplayMetadata/{kind}/stream={stream}/{variant}/known={known}'
+ assert name in failed, f'missing business RED: {name}'
+ output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name)
+ assert 'Issue842 benign replay metadata must reach B once' in output, name
+ assert 'encrypted_agent_recovery_wire_changed' in output, name
+ for mode, variant, known in itertools.product(('ctx_pool', 'passthrough', 'http_bridge'), variants, ('true', 'false')):
+ name = f'TestIssue842WSReplayMetadata/{mode}/{variant}/known={known}'
+ assert name in failed, f'missing WS business RED: {name}'
+ output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name)
+ assert 'Issue842 WS benign metadata must reach the actual adapter once' in output, name
+ assert 'encrypted_agent_recovery_wire_changed' in output or 'Issue842 metadata policy refusal before frame' in output, name
+ PY
+ - name: OAuth store and summary repair RED on pinned prior candidate
+ shell: bash
+ run: |
+ set -euo pipefail
+ baseline=af0328aec4a47c6c81a9b81d9a65c66ac660aea0
+ git fetch --no-tags --depth=1 origin "$baseline"
+ git worktree add --detach "$RUNNER_TEMP/issue842-oauth-red" "$EXPECTED_HEAD_SHA"
+ cd "$RUNNER_TEMP/issue842-oauth-red"
+ # Preserve the live production/BPS merge and the exact candidate
+ # fixture. Restore only the four production paths of this repair.
+ for target in backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_ws_agent_recovery.go; do
+ git show "$baseline:$target" > "$target"
+ expected=$(git rev-parse "$baseline:$target")
+ actual=$(git hash-object "$target")
+ echo "$target expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue842/oauth-red-blobs.txt"
+ test "$expected" = "$actual"
+ done
+ for target in backend/internal/handler/openai_issue842_oauth_repair_test.go backend/internal/service/issue842_gateway_test_support.go; do
+ test "$(git hash-object "$target")" = "$(git rev-parse "$EXPECTED_HEAD_SHA:$target")"
+ done
+ set +e
+ (cd backend && go test -json -tags=unit ./internal/handler -run '^TestIssue842OAuthStateless(HTTP|WS)$' -count=1 -timeout=5m) > "$RUNNER_TEMP/issue842/oauth-red.jsonl" 2>&1
+ result=$?
+ set -e
+ cat "$RUNNER_TEMP/issue842/oauth-red.jsonl"
+ test "$result" -ne 0
+ if grep -Eiq 'build failed|no tests to run|undefined:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|"Action":"skip"' "$RUNNER_TEMP/issue842/oauth-red.jsonl"; then exit 1; fi
+ python3 - "$RUNNER_TEMP/issue842/oauth-red.jsonl" <<'PY'
+ import itertools, json, sys
+ events = [json.loads(line) for line in open(sys.argv[1])]
+ failed = {e.get('Test') for e in events if e.get('Action') == 'fail'}
+ for stream, store, summary in itertools.product(('false', 'true'), ('omitted', 'true'), ('omitted', 'null', 'nonempty')):
+ name = f'TestIssue842OAuthStatelessHTTP/oauth/stream={stream}/store={store}/summary={summary}'
+ assert name in failed, f'missing OAuth HTTP business RED: {name}'
+ output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name)
+ assert 'Issue842 OAuth stateless input must match immutable-source metadata projection' in output, name
+ for mode, store, summary in itertools.product(('ctx_pool', 'passthrough', 'http_bridge'), ('omitted', 'true'), ('omitted', 'null', 'nonempty')):
+ name = f'TestIssue842OAuthStatelessWS/{mode}/store={store}/summary={summary}'
+ assert name in failed, f'missing OAuth WS business RED: {name}'
+ output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name)
+ assert 'Issue842 OAuth WS stateless input must match immutable-source metadata projection' in output, name
+ PY
+ - name: Remote formatting gate
+ run: test ! -s "$RUNNER_TEMP/issue842/format.patch"
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: issue842-${{ env.EXPECTED_HEAD_SHA }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/issue842/
+ if-no-files-found: error
diff --git a/.github/workflows/readable-continuation-409.yml b/.github/workflows/readable-continuation-409.yml
index f1e841787221..faa9d9c2f6e7 100644
--- a/.github/workflows/readable-continuation-409.yml
+++ b/.github/workflows/readable-continuation-409.yml
@@ -86,7 +86,7 @@ jobs:
baseline=dbed7697aa56e76c6eb48c4914fa441496b67bdd
# Restore the matching production callers too: later HTTP rebuild
# APIs must not turn the original reasoning RED into a compile error.
- for target in backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_agent_message_recovery_error.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_codex_transform.go backend/internal/handler/openai_gateway_handler.go; do
+ for target in backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_agent_message_recovery_error.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_codex_transform.go backend/internal/handler/openai_gateway_handler.go backend/internal/handler/openai_agent_message_recovery.go; do
git show "$baseline:$target" > "$target"
test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")"
git rev-parse "$baseline:$target" >> "$RUNNER_TEMP/readable-RED-provenance.txt"
@@ -96,13 +96,27 @@ jobs:
git show "$baseline:$target" > "$target"
test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")"
done
- ! git cat-file -e "$baseline:backend/internal/service/openai_ws_readable_continuation.go" 2>/dev/null
+ if git cat-file -e "$baseline:backend/internal/service/openai_ws_readable_continuation.go" 2>/dev/null; then exit 1; fi
rm -- backend/internal/service/openai_ws_readable_continuation.go
# Keep the selected HTTP tests intact and remove only new production.
for target in backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go; do
- ! git cat-file -e "$baseline:$target" 2>/dev/null
+ if git cat-file -e "$baseline:$target" 2>/dev/null; then exit 1; fi
rm -- "$target"
done
+ # This later helper is not part of the pinned recovery defect. Its
+ # pre-OAuth-projection API is compatible with the restored struct;
+ # preserve every selected defect/caller blob and behavioral assertion.
+ compatibility=00d2e9be01404c6e85c0560fa196e4650ef5d0fb
+ target=backend/internal/service/openai_agent_replay_metadata.go
+ if git cat-file -e "$baseline:$target" 2>/dev/null; then exit 1; fi
+ git fetch --no-tags --depth=1 origin "$compatibility"
+ candidate_blob=$(git rev-parse "HEAD:$target")
+ test "$(git hash-object "$target")" = "$candidate_blob"
+ expected=$(git rev-parse "$compatibility:$target")
+ git show "$compatibility:$target" > "$target"
+ actual=$(git hash-object "$target")
+ test "$actual" = "$expected"
+ echo "$target defect_source=$baseline defect_blob=absent compatibility=$compatibility candidate=$candidate_blob expected=$expected actual=$actual" >> "$RUNNER_TEMP/readable-RED-provenance.txt"
- name: Same HTTP JSON and SSE behavior in both checkouts
env:
PHASE: ${{ matrix.phase }}
diff --git a/.github/workflows/rebuilt-request-dispatch.yml b/.github/workflows/rebuilt-request-dispatch.yml
index ababa5388856..fea90ca68342 100644
--- a/.github/workflows/rebuilt-request-dispatch.yml
+++ b/.github/workflows/rebuilt-request-dispatch.yml
@@ -44,6 +44,25 @@ jobs:
for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go backend/internal/service/openai_responses_namespace.go; do
git show "$baseline:$target" > "$target"
done
+ # Keep unrelated replay callers compatible with the frozen recovery
+ # struct. These pinned blobs predate PR853's OAuth projection; none
+ # of the selected dispatch defect blobs above are replaced.
+ compatibility=00d2e9be01404c6e85c0560fa196e4650ef5d0fb
+ callers="$baseline"
+ # PR855 adds typed WS route refusals; preserve that pre-PR853 caller
+ # only when the candidate actually contains the corresponding types.
+ if git grep -q 'type openAIWSOwnerRouteError struct' HEAD -- backend/internal/service/openai_ws_readable_continuation.go; then
+ callers=d1bd861bcfa34443a629db98de9121a4e15d1d0b
+ fi
+ for source in "$compatibility" "$callers"; do git fetch --no-tags --depth=1 origin "$source"; done
+ for target in backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_gateway_request_body.go backend/internal/service/openai_ws_agent_recovery.go; do
+ source="$callers"
+ if [ "$target" = backend/internal/service/openai_agent_replay_metadata.go ]; then source="$compatibility"; fi
+ expected=$(git rev-parse "$source:$target")
+ git show "$source:$target" > "$target"
+ test "$(git hash-object "$target")" = "$expected"
+ echo "$target compatibility=$source blob=$expected" >> "$RUNNER_TEMP/dispatch-compatibility.txt"
+ done
- name: Same network and tool-loop regressions
env:
PHASE: ${{ matrix.phase }}
diff --git a/.github/workflows/shadow-review-repair.yml b/.github/workflows/shadow-review-repair.yml
index f2a0c26d79d0..cfc637b0b53b 100644
--- a/.github/workflows/shadow-review-repair.yml
+++ b/.github/workflows/shadow-review-repair.yml
@@ -17,6 +17,7 @@ on:
- '.github/scripts/assert-ws-readable.py'
- '.github/scripts/test_assert_ws_readable.py'
- '.github/scripts/prepare-moderation-red-fixtures.sh'
+ - '.github/scripts/prepare-replay-red-fixtures.sh'
- '.github/workflows/shadow-review-repair.yml'
permissions:
contents: read
@@ -92,6 +93,7 @@ jobs:
if [ "$PHASE" = RED ]; then
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA"
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA"
+ bash "$GITHUB_WORKSPACE/.github/scripts/prepare-replay-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-repair-evidence/replay-fixtures.txt"
bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-repair-evidence/moderation-fixtures.txt"
fi
for target in backend/internal/handler/openai_409_shadow_race_test.go backend/internal/handler/openai_409_shadow_http_test.go backend/internal/securityaudit/prompt_recovered_context_test.go backend/internal/service/openai_409_readable_shadow.go; do
@@ -163,6 +165,7 @@ jobs:
git -C "$tested_tree" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go'
if [ "$PHASE" = RED ]; then
bash .github/scripts/exclude-later-http2-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA"
+ bash .github/scripts/prepare-replay-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-repair-evidence/async-replay-fixtures.txt"
bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-repair-evidence/async-moderation-fixtures.txt"
fi
for target in backend/internal/securityaudit/prompt_service.go backend/internal/securityaudit/prompt_repository.go backend/internal/securityaudit/prompt_recovered_context_test.go; do
diff --git a/.github/workflows/ws-readable-continuation.yml b/.github/workflows/ws-readable-continuation.yml
index d75a77490877..2cb2ae454dc7 100644
--- a/.github/workflows/ws-readable-continuation.yml
+++ b/.github/workflows/ws-readable-continuation.yml
@@ -21,6 +21,7 @@ on:
- '.github/scripts/exclude-later-http2-red-fixtures.sh'
- 'backend/internal/service/openai_gateway_passthrough.go'
- '.github/scripts/prepare-moderation-red-fixtures.sh'
+ - '.github/scripts/prepare-replay-red-fixtures.sh'
- '.github/workflows/ws-readable-continuation.yml'
permissions:
contents: read
@@ -99,6 +100,7 @@ jobs:
if [ "$PHASE" = RED ]; then
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/transport-400-exclusions.txt"
bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA"
+ bash "$GITHUB_WORKSPACE/.github/scripts/prepare-replay-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/transport-replay-fixtures.txt"
bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/transport-moderation-fixtures.txt"
fi
for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/handler/openai_gateway_handler.go; do
@@ -165,6 +167,7 @@ jobs:
if [ "$PHASE" = RED ]; then
bash .github/scripts/exclude-later-400-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/review-400-exclusions.txt"
bash .github/scripts/exclude-later-http2-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA"
+ bash .github/scripts/prepare-replay-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/review-replay-fixtures.txt"
bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/review-moderation-fixtures.txt"
fi
for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_forwarder_payload.go; do
@@ -201,11 +204,17 @@ jobs:
if [ "$PHASE" = RED ]; then
bash .github/scripts/exclude-later-400-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/residual-400-exclusions.txt"
bash .github/scripts/exclude-later-http2-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA"
+ bash .github/scripts/prepare-replay-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/residual-replay-fixtures.txt"
bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/residual-moderation-fixtures.txt"
# The service test package also compiles unrelated fixtures added by
# newer production. Match their historical APIs in this disposable
# RED only; keep every selected 409/ticket test and all GREEN tests.
- for target in backend/internal/service/temp_unsched_pending_test.go backend/internal/service/temp_unsched_stream_timing_test.go backend/internal/service/temp_unsched_ws_forward_test.go backend/internal/service/openai_auth_connection_status_test.go backend/internal/service/openai_auth_connections_account_type_test.go backend/internal/service/account_ops_balance_test.go backend/internal/service/openai_excel_bps_bridge_failure_test.go backend/internal/service/quality_5xx_immediate_test.go; do
+ # PR855 route-evidence types and later production BPS search APIs
+ # are absent in this baseline. Their unselected tests follow the
+ # pinned historical APIs too; the selected ticket oracle stays current.
+ # BPS search is already excluded with blob/contract proofs by the
+ # shared helpers above, so do not inspect/remove it a second time.
+ for target in backend/internal/service/temp_unsched_pending_test.go backend/internal/service/temp_unsched_stream_timing_test.go backend/internal/service/temp_unsched_ws_forward_test.go backend/internal/service/openai_auth_connection_status_test.go backend/internal/service/openai_auth_connections_account_type_test.go backend/internal/service/account_ops_balance_test.go backend/internal/service/openai_excel_bps_bridge_failure_test.go backend/internal/service/quality_5xx_immediate_test.go backend/internal/service/openai_ws_agent_recovery_test.go; do
candidate_blob=$(git rev-parse "$CANDIDATE_SHA:$target")
test "$(git hash-object "$tested_tree/$target")" = "$candidate_blob"
if git cat-file -e "$baseline:$target" 2>/dev/null; then
@@ -264,6 +273,7 @@ jobs:
if [ "$PHASE" = RED ]; then
bash .github/scripts/exclude-later-400-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/namespace-400-exclusions.txt"
bash .github/scripts/prepare-mature-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/namespace-mature-fixtures.txt"
+ bash .github/scripts/prepare-replay-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/namespace-replay-fixtures.txt"
bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/namespace-moderation-fixtures.txt"
fi
for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/service/openai_ws_agent_recovery.go; do
diff --git a/backend/internal/handler/openai_409_http_rebuild_test.go b/backend/internal/handler/openai_409_http_rebuild_test.go
index c9b60eb97896..2b273f8d2e7b 100644
--- a/backend/internal/handler/openai_409_http_rebuild_test.go
+++ b/backend/internal/handler/openai_409_http_rebuild_test.go
@@ -478,8 +478,30 @@ func httpRebuildOwnerKey(t *testing.T, h *OpenAIGatewayHandler, agent string) st
return "openai_agent_owner:v1:" + hex.EncodeToString(key[:])
}
-func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointer, outcome, boundary, mutation string) {
+type httpRebuildFixtureOptions struct {
+ extraAccounts []service.Account
+ afterFirst func([]service.Account)
+ refuseCode string
+ physicalBody func(*testing.T, []byte, int) []byte
+ headers func(*http.Request)
+ toolsAvailable func([]byte) bool
+ request func(map[string]any, bool)
+ provider func(*testing.T, []byte, http.Header, int)
+ accounts func([]service.Account)
+ gateway func(*OpenAIGatewayHandler, []service.Account, service.HTTPUpstream, service.GatewayCache, *service.SettingService, service.UsageLogRepository)
+ settings service.SettingRepository
+}
+
+func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointer, outcome, boundary, mutation string, options ...httpRebuildFixtureOptions) {
t.Helper()
+ var option httpRebuildFixtureOptions
+ if len(options) > 0 {
+ option = options[0]
+ }
+ authenticated := boundary == "issue854_auth"
+ if authenticated {
+ boundary = ""
+ }
noOpaque := strings.HasSuffix(pointer, "_no_opaque")
pointer = strings.TrimSuffix(pointer, "_no_opaque")
mixed := strings.HasPrefix(boundary, "mixed/")
@@ -503,8 +525,15 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
providerHeaders = append(providerHeaders, r.Header.Clone())
n := len(providerBodies)
mu.Unlock()
+ if option.provider != nil {
+ option.provider(t, body, r.Header, n)
+ }
noToolsFinal := pointer == "no_tools_parallel" && n == 3
- if (!noToolsFinal && !httpRebuildToolsAvailable(body)) || (noToolsFinal && (gjson.GetBytes(body, "tools").Exists() || gjson.GetBytes(body, "parallel_tool_calls").Exists())) {
+ toolsAvailable := httpRebuildToolsAvailable
+ if option.toolsAvailable != nil {
+ toolsAvailable = option.toolsAvailable
+ }
+ if (!noToolsFinal && !toolsAvailable(body)) || (noToolsFinal && (gjson.GetBytes(body, "tools").Exists() || gjson.GetBytes(body, "parallel_tool_calls").Exists())) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
_, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","message":"fixture rejected missing or changed tool declarations"}}`)
@@ -585,21 +614,42 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
if pointer == "passthrough" {
accounts[1].Extra = map[string]any{"openai_passthrough": true, "openai_responses_mode": "force_responses"}
}
- settings := service.NewSettingService(&omit409SettingsRepo{enabled: boundary != "strict"}, cfg)
+ accounts = append(accounts, option.extraAccounts...)
+ if option.accounts != nil {
+ option.accounts(accounts)
+ }
+ var settingsRepo service.SettingRepository = &omit409SettingsRepo{enabled: boundary != "strict"}
+ if option.settings != nil {
+ settingsRepo = option.settings
+ }
+ settings := service.NewSettingService(settingsRepo, cfg)
usage := &readable409UsageRepo{}
h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, transport, repository.NewGatewayCache(clients()), settings, usage, accounts...)
h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ if option.gateway != nil {
+ option.gateway(h, accounts, transport, repository.NewGatewayCache(clients()), settings, usage)
+ }
template, _ := newIssue715Context(t, "{}")
done := make(chan struct{}, 1)
var sessions []string
pendingBeforeWrite := false
var observeErr error
router := gin.New()
+ if authenticated {
+ key := template.Keys[string(middleware.ContextKeyAPIKey)].(*service.APIKey)
+ key.Key, key.Status, key.UserID = "fixture-issue854-http", service.StatusActive, key.User.ID
+ key.User.Status = service.StatusActive
+ key.Group.Status, key.Group.Hydrated = service.StatusActive, true
+ h.apiKeyService = service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg)
+ router.Use(gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(h.apiKeyService, nil, cfg)))
+ }
router.POST("/v1/responses", func(c *gin.Context) {
defer func() { done <- struct{}{} }()
sessions = append(sessions, c.GetHeader("session_id"))
- for key, value := range template.Keys {
- c.Set(key, value)
+ if !authenticated {
+ for key, value := range template.Keys {
+ c.Set(key, value)
+ }
}
if c.GetHeader("X-Fixture-Foreign-User") == "true" {
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 101})
@@ -672,10 +722,19 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
if previous.Exists() && pointer == "conversation" {
body["conversation"] = map[string]any{"id": previous.Get("conversation.id").String()}
}
+ if option.request != nil {
+ option.request(body, previous.Exists())
+ }
req, err := http.NewRequest(http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(httpRebuildJSON(body)))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("session_id", httpRebuildSession)
+ if authenticated {
+ req.Header.Set("Authorization", "Bearer fixture-issue854-http")
+ }
+ if option.headers != nil {
+ option.headers(req)
+ }
if boundary == "foreign_user" && previous.Exists() {
req.Header.Set("X-Fixture-Foreign-User", "true")
}
@@ -726,6 +785,9 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
require.Len(t, ownersA, 1)
}
accounts[0].Schedulable = false
+ if option.afterFirst != nil {
+ option.afterFirst(accounts)
+ }
cooldownUntil := time.Now().Add(7 * 24 * time.Hour)
if ownerCooldown {
accounts[0].Schedulable = true
@@ -756,6 +818,15 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
accounts[1].Schedulable = false
}
status, answer = request(history, first)
+ if option.refuseCode != "" {
+ require.Contains(t, answer, option.refuseCode)
+ require.GreaterOrEqual(t, status, 400)
+ require.Len(t, transport.snapshot(), 1, "unsupported routes must not generate")
+ require.Equal(t, ownersA, issue805Owners(t, observer))
+ require.Equal(t, 1, tools.patches)
+ require.Zero(t, tools.verifications)
+ return
+ }
if boundary != "" && !mixed && !ownerCooldown {
if boundary == "strict" {
require.Len(t, transport.snapshot(), 1, "HTTP_POINTER_STRICT_A_STATE_LEAK: disabled A pointer must never reach B under default strict policy; response=%s", answer)
@@ -906,7 +977,11 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe
defer mu.Unlock()
require.Len(t, providerBodies, 3)
for i, wire := range wires {
- require.JSONEq(t, string(wire.body), string(providerBodies[i]), "provider must receive the final builder payload unchanged")
+ expected := wire.body
+ if option.physicalBody != nil {
+ expected = option.physicalBody(t, expected, i)
+ }
+ require.JSONEq(t, string(expected), string(providerBodies[i]), "provider must receive exactly the declared physical projection")
require.Equal(t, wire.header.Get("Authorization"), providerHeaders[i].Get("Authorization"))
}
}
diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go
index 3a0b5c5cf473..b6de9cf11223 100644
--- a/backend/internal/handler/openai_409_ws_oracle_test.go
+++ b/backend/internal/handler/openai_409_ws_oracle_test.go
@@ -52,6 +52,13 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt
u.validationFailures++
return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_native_namespace_changed"}}}`)
}
+ if strings.HasPrefix(u.scenario, "issue854_guard_") && n == 2 {
+ if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-B" || !strings.Contains(string(body), "issue854-warm-B") {
+ u.validationFailures++
+ return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_bad_B_warmup"}}}`)
+ }
+ return []byte(`{"type":"response.completed","response":{"id":"resp_issue854_warm","status":"completed","model":"gpt-5.1","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"issue854-warm-B-complete"}]}],"usage":{"input_tokens":2,"output_tokens":1}}}`)
+ }
if u.scenario == "bridge_model" && n == 2 {
if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-A" || gjson.GetBytes(body, "model").String() != "gpt-5.4" || !strings.Contains(string(body), "model-switch-warmup") {
u.validationFailures++
@@ -60,7 +67,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt
return []byte(`{"type":"response.completed","response":{"id":"resp_model_warmup","status":"completed","model":"gpt-5.4","error":null,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"model-switch-complete"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`)
}
logicalTurn := n
- if u.scenario == "bridge_model" && n > 2 {
+ if (u.scenario == "bridge_model" || strings.HasPrefix(u.scenario, "issue854_guard_")) && n > 2 {
logicalTurn--
}
output := []json.RawMessage{json.RawMessage(httpRebuildAgentA), json.RawMessage(httpRebuildCall("apply_patch", "call_ws_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))}
diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go
index 9b455f0b4ba3..709875042ec0 100644
--- a/backend/internal/handler/openai_409_ws_rebuild_test.go
+++ b/backend/internal/handler/openai_409_ws_rebuild_test.go
@@ -147,8 +147,10 @@ func logReadableWSDispatchFailure(t *testing.T, h *openAIWSPassthroughHandlerHar
var peerClose coderws.CloseError
require.ErrorAs(t, clientErr, &peerClose)
require.Equal(t, coderws.StatusPolicyViolation, peerClose.Code)
+ require.Eventually(t, func() bool {
+ return h.requestLogs.FilterMessage("openai.websocket_proxy_failed").Len() == 1
+ }, 3*time.Second, 5*time.Millisecond, "expected one actual failed B dispatch")
entries := h.requestLogs.FilterMessage("openai.websocket_proxy_failed").All()
- require.Len(t, entries, 1, "expected one actual failed B dispatch")
require.Equal(t, int64(2), entries[0].ContextMap()["account_id"])
var reported error
for _, field := range entries[0].Context {
@@ -174,7 +176,7 @@ func TestOpenAI409WSInitialWithoutPointer(t *testing.T) {
}
}
-func runReadableWSContinuation(t *testing.T, mode, scenario string) {
+func runReadableWSContinuation(t *testing.T, mode, scenario string, persistent ...service.OpsRepository) {
t.Helper()
clients := issue805Redis(t)
probe := clients()
@@ -183,7 +185,47 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
defer provider.Close()
headers := http.Header{"Session_id": {"fixture-readable-ws-session"}, "Thread-Id": {"fixture-readable-ws-thread"}}
settings := map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: fmt.Sprint(scenario != "off")}
+ r1 := strings.HasPrefix(scenario, "issue854_r1_")
+ r1Case := strings.TrimPrefix(scenario, "issue854_r1_")
+ r1Reject := r1 && r1Case != "disabled" && r1Case != "cooldown"
+ issue854 := strings.HasPrefix(scenario, "issue854_")
+ if r1Case == "off" {
+ settings[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled] = "false"
+ }
+ issue854Failure := scenario == "issue854_guard_refusal" || scenario == "issue854_fresh_refusal"
+ var failureRepo *ingressRejectOpsRepo
+ var configureHandler func(*OpenAIGatewayHandler)
+ if issue854Failure {
+ setupOpsErrorLogTestQueue(t, 4)
+ failureRepo = &ingressRejectOpsRepo{}
+ settings[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled] = "false"
+ configureHandler = func(h *OpenAIGatewayHandler) {
+ var opsRepo service.OpsRepository = failureRepo
+ if len(persistent) > 0 {
+ opsRepo = persistent[0]
+ }
+ h.opsService = service.NewOpsService(opsRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ }
+ if len(persistent) > 0 {
+ name := "ws_guard"
+ if scenario == "issue854_fresh_refusal" {
+ name = "ws_fresh"
+ }
+ headers.Set("X-Request-ID", "fixture-issue854-pg-"+name)
+ }
+ }
+ var authSetup func(*service.APIKey, *config.Config) *service.APIKeyService
+ if issue854 {
+ headers.Set("Authorization", "Bearer sk-handler-cyber-test")
+ authSetup = func(key *service.APIKey, cfg *config.Config) *service.APIKeyService {
+ key.Status = service.StatusActive
+ key.User.Concurrency = 1
+ key.Group = &service.Group{ID: *key.GroupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, Hydrated: true}
+ return service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg)
+ }
+ }
initialNoPointer := strings.HasPrefix(scenario, "initial_no_pointer_")
+ var initialUnavailableUntil time.Time
identityCase, modelCase := scenario == "identity" || strings.HasPrefix(scenario, "header_"), scenario == "bridge_model"
customTools := strings.HasPrefix(scenario, "tools_")
nativeNamespace := scenario == "native_namespace"
@@ -202,9 +244,9 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
settings[service.SettingKeyCyberSessionIdentityStrictEnabled] = "true"
}
var accounts *readableWSAccounts
- h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, provider.URL, headers,
+ h := newOpenAIWSPassthroughHandlerHarnessWithAuth(t, provider.URL, headers,
settings,
- repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true },
+ repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, configureHandler, authSetup,
func(a *service.Account, cfg *config.Config, upstream *service.HTTPUpstream, repo *service.AccountRepository) {
a.ID, a.Priority = 1, 0
a.Credentials["api_key"] = "fixture-readable-ws-A"
@@ -296,19 +338,38 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
require.Equal(t, 1, customCalls, "A must actually deliver the completed custom tool")
omitTools = scenario == "tools_omitted"
}
- require.Eventually(t, func() bool {
- owners := issue805Owners(t, probe)
- if len(owners) != 1 {
- return false
+ // Poll in the test goroutine: testify.Eventually runs its predicate in a
+ // detached goroutine, so a slow Redis read can outlive the deadline and
+ // assert against a closed client after this test's cleanup. A race-enabled
+ // hosted runner may also finish A's delivery after the old one-second limit.
+ // Keep the same committed-owner predicate and bound all reads by one budget.
+ ownerCtx, cancelOwnerWait := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancelOwnerWait()
+ ownerTick := time.NewTicker(5 * time.Millisecond)
+ defer ownerTick.Stop()
+ var owners map[string]string
+ for {
+ keys, err := probe.Keys(ownerCtx, "openai_agent_owner:*").Result()
+ require.NoError(t, err, "read A's committed owner before changing its availability")
+ owners = make(map[string]string, len(keys))
+ committed := len(keys) == 1
+ for _, key := range keys {
+ raw, err := probe.Get(ownerCtx, key).Result()
+ require.NoError(t, err, "read A's delivery record")
+ owners[key] = raw
+ committed = committed && json.Valid([]byte(raw)) && gjson.Parse(raw).IsArray() && gjson.Get(raw, "1").Int() == 1
}
- for _, raw := range owners {
- if !json.Valid([]byte(raw)) || !gjson.Parse(raw).IsArray() || gjson.Get(raw, "1").Int() != 1 {
- return false
- }
+ if committed {
+ break
+ }
+ select {
+ case <-ownerCtx.Done():
+ t.Fatal("A must commit exactly one delivered owner before this continuation scenario")
+ case <-ownerTick.C:
}
- return true
- }, time.Second, 5*time.Millisecond)
- owners := issue805Owners(t, probe)
+ }
+ cancelOwnerWait()
+ ownerTick.Stop()
previous := first.Get("id").String()
extraSends := 0
if modelCase {
@@ -325,13 +386,26 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
accounts.mu.Lock()
accounts.disableAdmission = 2
accounts.mu.Unlock()
- } else {
+ } else if scenario != "issue854_lost_owner" {
accounts.disable(1)
}
+ if scenario == "issue854_lost_owner" {
+ for key := range owners {
+ require.NoError(t, probe.Del(context.Background(), key).Err())
+ }
+ }
+ if r1 && r1Case == "cooldown" {
+ accounts.mu.Lock()
+ until := time.Now().Add(time.Hour)
+ accounts.accounts[0].Schedulable = true
+ accounts.accounts[0].RateLimitResetAt = &until
+ accounts.mu.Unlock()
+ }
if initialNoPointer {
if scenario != "initial_no_pointer_paused" {
accounts.mu.Lock()
reset := time.Now().Add(7 * 24 * time.Hour)
+ initialUnavailableUntil = reset
accounts.accounts[0].Schedulable = true
if scenario == "initial_no_pointer_rate_limited" {
accounts.accounts[0].RateLimitResetAt = &reset
@@ -340,6 +414,9 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
}
accounts.mu.Unlock()
}
+ previous = ""
+ }
+ if initialNoPointer || r1 || strings.HasPrefix(scenario, "issue854_fresh") || strings.HasPrefix(scenario, "issue854_guard_") {
issue600Finish(t, h, headers)
dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
conn, _, err := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers})
@@ -347,7 +424,44 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
require.NoError(t, err)
h.clientConn = conn
t.Cleanup(func() { _ = conn.CloseNow() })
+ if strings.HasPrefix(scenario, "issue854_guard_") {
+ issue715WSSend(t, conn, create([]string{httpRebuildMessage("user", "issue854-warm-B")}, ""))
+ warm := issue715WSRead(t, conn)
+ require.Contains(t, string(warm), "issue854-warm-B-complete")
+ extraSends = 1
+ }
+ }
+ if r1 {
+ // Remove only this isolated fixture's readable shadow after A's actual
+ // delivery. Keep its proven owner; neither a pointer nor shadow can hide R1.
+ keys, err := probe.Keys(context.Background(), "openai_readable_shadow:*").Result()
+ require.NoError(t, err)
+ for _, key := range keys {
+ require.NoError(t, probe.Del(context.Background(), key).Err())
+ }
+ keys, err = probe.Keys(context.Background(), "openai_readable_shadow:*").Result()
+ require.NoError(t, err)
+ require.Empty(t, keys)
previous = ""
+ for key, raw := range owners {
+ switch r1Case {
+ case "pending":
+ raw = "pending:fixture-r1:" + raw
+ case "failed":
+ raw = "failed"
+ case "conflict":
+ raw = "conflict"
+ case "unknown":
+ require.NoError(t, probe.Del(context.Background(), key).Err())
+ continue
+ }
+ if r1Case == "pending" || r1Case == "failed" || r1Case == "conflict" {
+ require.NoError(t, probe.Set(context.Background(), key, raw, time.Minute).Err())
+ }
+ }
+ if r1Case == "unfinished" {
+ history = history[:len(history)-1]
+ }
}
if scenario == "b_disabled" {
accounts.disable(2)
@@ -384,7 +498,69 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
oracle.mu.Lock()
sends := len(oracle.frames)
oracle.mu.Unlock()
- if scenario != "completed" && !initialNoPointer && !identityCase && !modelCase && !nativeNamespace && smartMode == "" {
+ if r1Reject {
+ require.NoError(t, readErr, "R1 refusal must be a structured business error")
+ require.Equal(t, "error", gjson.GetBytes(secondRaw, "type").String())
+ require.Equal(t, 1, sends, "R1 unsafe/disabled recovery must never generate on B")
+ require.Equal(t, 1, tools.patches)
+ require.Zero(t, tools.verifications)
+ return
+ }
+ if r1 {
+ require.Equal(t, 2, sends, "ISSUE854_R1_INITIAL_OWNER_REFUSED: valid no-pointer/no-shadow task must reach B; terminal=%s close=%v", secondRaw, readErr)
+ }
+ if scenario == "issue854_lost_owner" {
+ require.NoError(t, readErr)
+ require.Equal(t, "encrypted_agent_recovery_owner_unavailable", gjson.GetBytes(secondRaw, "error.code").String())
+ require.Equal(t, 1, sends, "loss of previously observed owner evidence must refuse before any generation")
+ require.Equal(t, 1, tools.patches)
+ require.Zero(t, tools.verifications)
+ a, err := accounts.GetByID(context.Background(), 1)
+ require.NoError(t, err)
+ require.True(t, a.Schedulable, "this refusal must come from owner evidence, not account admission")
+ return
+ }
+ if issue854Failure {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ for readErr == nil {
+ _, _, readErr = h.clientConn.Read(ctx)
+ }
+ require.Equal(t, coderws.StatusPolicyViolation, coderws.CloseStatus(readErr))
+ select {
+ case <-h.handlerDone:
+ case <-ctx.Done():
+ t.Fatal("owner refusal did not finish")
+ }
+ finished = true
+ for len(opsErrorLogQueue) > 0 {
+ flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue})
+ }
+ if len(persistent) > 0 {
+ require.Equal(t, "encrypted_agent_recovery_owner_unavailable", gjson.GetBytes(secondRaw, "error.code").String())
+ return // The PostgreSQL fixture queries committed rows with the real repository.
+ }
+ require.Len(t, failureRepo.entries, 1, "ISSUE854_FAILURE_NOT_PERSISTED: WS101 must not hide the failed turn")
+ entry := failureRepo.entries[0]
+ require.Equal(t, 409, entry.StatusCode)
+ require.Equal(t, "internal", entry.ErrorPhase)
+ require.Equal(t, "platform", entry.ErrorOwner)
+ require.Equal(t, int16(service.RequestTypeWSV2), *entry.RequestType)
+ require.Equal(t, "encrypted_agent_recovery_owner_unavailable", gjson.Get(entry.ErrorBody, "error.code").String())
+ require.Equal(t, "websocket", gjson.Get(entry.ErrorBody, "error.protocol").String())
+ wantTurn, wantSends, wantPhase := 2, 2, "before_upstream_write"
+ if scenario == "issue854_fresh_refusal" {
+ wantTurn, wantSends, wantPhase = 1, 1, "before_dispatch"
+ }
+ require.EqualValues(t, wantTurn, gjson.Get(entry.ErrorBody, "error.turn").Int())
+ require.Equal(t, wantPhase, gjson.Get(entry.ErrorBody, "error.phase").String())
+ require.Equal(t, gjson.False, gjson.Get(entry.ErrorBody, "error.request_written").Type)
+ require.NotContains(t, entry.ErrorBody, "fixture-opaque-A")
+ require.Equal(t, "encrypted_agent_recovery_owner_unavailable", gjson.GetBytes(secondRaw, "error.code").String())
+ require.Equal(t, wantSends, sends, "failed turn cannot reach either upstream")
+ return
+ }
+ if scenario != "completed" && !issue854 && !initialNoPointer && !identityCase && !modelCase && !nativeNamespace && smartMode == "" {
require.NotErrorIs(t, readErr, context.DeadlineExceeded)
closeCtx, cancelClose := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelClose()
@@ -441,6 +617,10 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
} else if smartMode != "" {
require.Equal(t, 2, sends, "WS_REVIEW_SMART_SESSION_STALE: close=%v terminal=%s", readErr, secondRaw)
}
+ if scenario == "issue854_guard_live" && sends != 3 {
+ require.Equal(t, 2, sends)
+ logReadableWSDispatchFailure(t, h, readErr)
+ }
require.Equal(t, 2+extraSends, sends, "WS_READABLE_B_DISPATCH_MISSING: same client must automatically replace disabled A before any next generation; close=%v terminal=%s", readErr, secondRaw)
if modelCase {
accounts.mu.Lock()
@@ -487,10 +667,29 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) {
require.Equal(t, 1, tools.verifications)
a, err := accounts.GetByID(context.Background(), 1)
require.NoError(t, err)
+ if r1 && r1Case == "cooldown" {
+ require.True(t, a.Schedulable)
+ require.NotNil(t, a.RateLimitResetAt)
+ require.True(t, a.RateLimitResetAt.After(time.Now()))
+ } else if initialNoPointer && scenario != "initial_no_pointer_paused" {
+ require.True(t, a.Schedulable)
+ if scenario == "initial_no_pointer_rate_limited" {
+ require.NotNil(t, a.RateLimitResetAt)
+ require.Equal(t, initialUnavailableUntil, *a.RateLimitResetAt)
+ } else {
+ require.NotNil(t, a.OverloadUntil)
+ require.Equal(t, initialUnavailableUntil, *a.OverloadUntil)
+ }
+ } else {
+ require.False(t, a.Schedulable)
+ }
require.False(t, a.IsSchedulable())
oracle.mu.Lock()
defer oracle.mu.Unlock()
expectedIdentities := []string{"Bearer fixture-readable-ws-A", "Bearer fixture-readable-ws-B", "Bearer fixture-readable-ws-B"}
+ if scenario == "issue854_guard_live" {
+ expectedIdentities = append(expectedIdentities, "Bearer fixture-readable-ws-B")
+ }
if modelCase {
expectedIdentities = append([]string{"Bearer fixture-readable-ws-A"}, expectedIdentities...)
require.Equal(t, "gpt-5.4", gjson.GetBytes(oracle.frames[1], "model").String(), "A actually accepted M2 before the later omission")
diff --git a/backend/internal/handler/openai_agent_message_recovery.go b/backend/internal/handler/openai_agent_message_recovery.go
index 49cad7c167b2..f503daff5f43 100644
--- a/backend/internal/handler/openai_agent_message_recovery.go
+++ b/backend/internal/handler/openai_agent_message_recovery.go
@@ -17,6 +17,17 @@ func (h *OpenAIGatewayHandler) handleOpenAIAgentRecoveryError(c *gin.Context, er
if !errors.As(err, &recovery) {
return false
}
+ protocol := "http"
+ if streamStarted || c.GetBool(opsStreamKey) {
+ protocol = "sse"
+ }
+ // HTTP forwarders can return a compatibility error after a provider read;
+ // the HTTP handler alone cannot prove an unsent generation.
+ phase := "before_response"
+ if streamStarted || c.Writer.Written() {
+ phase = "forwarding"
+ }
+ markOpenAIRecoveryFailure(c, recovery, protocol, phase, nil)
committed := streamStarted || c.Writer.Written()
if !committed && !recovery.RetryAt.IsZero() {
seconds := max(int64(1), int64((time.Until(recovery.RetryAt)+time.Second-1)/time.Second))
@@ -28,11 +39,22 @@ func (h *OpenAIGatewayHandler) handleOpenAIAgentRecoveryError(c *gin.Context, er
// The socket has already upgraded when initial scheduling runs. Send the full
// recovery guidance as an error event; close reasons alone are length limited.
-func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Context, conn *coderws.Conn, err error) bool {
+func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Context, conn *coderws.Conn, err error, contexts ...*gin.Context) bool {
var recovery *service.OpenAIAgentRecoveryError
if !errors.As(err, &recovery) {
return false
}
+ if len(contexts) > 0 && contexts[0] != nil {
+ phase, written := "before_dispatch", boolPointer(false)
+ var closeErr *service.OpenAIWSClientCloseError
+ if errors.As(err, &closeErr) {
+ phase, written = "forwarding", nil
+ }
+ if service.OpenAIWSAgentRecoveryBeforeSend(err) {
+ phase, written = "before_upstream_write", boolPointer(false)
+ }
+ markOpenAIRecoveryFailure(contexts[0], recovery, "websocket", phase, written)
+ }
payload, _ := json.Marshal(map[string]any{
"type": "error", "status": recovery.HTTPStatus(),
"error": map[string]string{"type": recovery.ClientType(), "code": recovery.ClientCode(), "message": recovery.ClientMessage()},
@@ -48,3 +70,13 @@ func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Cont
closeOpenAIClientWS(conn, status, reason)
return true
}
+
+func boolPointer(value bool) *bool { return &value }
+
+func markOpenAIRecoveryFailure(c *gin.Context, recovery *service.OpenAIAgentRecoveryError, protocol, phase string, written *bool) {
+ service.MarkOpsStreamErrorValue(c, service.OpsStreamError{
+ ErrType: recovery.ClientType(), Code: recovery.ClientCode(), Message: recovery.ClientMessage(),
+ IntendedStatus: recovery.HTTPStatus(), CountTowardsSLA: true, NonStream: protocol == "http",
+ RecoveryFailure: &service.OpsRecoveryFailure{Protocol: protocol, Phase: phase, RequestWritten: written},
+ })
+}
diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go
index b361d2689eb8..18134373390f 100644
--- a/backend/internal/handler/openai_gateway_handler.go
+++ b/backend/internal/handler/openai_gateway_handler.go
@@ -894,6 +894,15 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
}
}
+ // Normalize the finite replay metadata before either immutable body copy or
+ // the recovery digest is frozen. Each attempt derives from these same bytes.
+ if prepared, err := h.gatewayService.PrepareOpenAIAgentReplayBody(body); err != nil {
+ h.handleOpenAIAgentRecoveryError(c, err, streamStarted)
+ return
+ } else {
+ body = prepared
+ }
+
// 解析渠道级模型映射
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody)
@@ -1208,6 +1217,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
// 从不可变的 canonical forwardBody 派生本次尝试 body 并整块剔除上游私有的加密
// reasoning item(含耦合的 id/summary),避免非透传上游 400 拒绝 Kiro reasoning 形态。
attemptBody := h.deriveOpenAIForwardAttemptBody(reqLog, forwardBody, account, &passthroughFailoverState)
+ if h.cfg != nil && h.cfg.Gateway.DisableEncryptedAgentOwnerBinding {
+ // Account-specific builders/retries never own the frozen source slice.
+ attemptBody = append([]byte(nil), attemptBody...)
+ }
result, err := func() (*service.OpenAIForwardResult, error) {
defer func() {
if accountReleaseFunc != nil {
@@ -3184,6 +3197,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
bindOpenAIPriorityObservation(c, apiKey.GroupID, reqModel, firstMessage)
ctx = c.Request.Context()
setOpsEndpointContext(c, "", int16(service.RequestTypeWSV2))
+ service.BeginOpsStreamTurn(c, 1)
// Connection-wide audit identity survives proxy restarts/failover, whose
// transport-local turn counters restart at 1. Replays keep the current
@@ -3350,7 +3364,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
ctx = h.gatewayService.WithOpenAIWSAgentRecovery(ctx, c, firstMessage, sessionHash, wsForwardModel)
ctx = service.WithOpenAIGuardianParentAffinity(ctx, c, firstMessage, reqModel)
if next, clean, changed, rebuildErr := h.gatewayService.PrepareOpenAI409ReadableContinuation(ctx, c, firstMessage, sessionHash, wsForwardModel); rebuildErr != nil {
- h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr)
+ h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr, c)
return
} else if changed {
ctx, firstMessage, previousResponseID = next, clean, ""
@@ -3359,6 +3373,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
maxAccountSwitches := h.maxAccountSwitches
switchCount := 0
+ opsTurnOffset := 0
var forbiddenBudget grokForbiddenFailoverBudget
profitVetoCount := 0
failedAccountIDs := make(map[int64]struct{})
@@ -3367,7 +3382,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
var rpmAdmission openAIRPMAdmission
var oauth429FailoverState service.OpenAIOAuth429FailoverState
wsAttemptMessage := append([]byte(nil), firstMessage...)
- initialSelectionCanRebuild := true
+ initialDispatchStarted := false
waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool {
if !service.OpenAIWSAgentRecoveryCanRetry(ctx) {
return false
@@ -3479,24 +3494,47 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
requestPlatform,
)
if err != nil {
- // No transport has been invoked on this path. A known owner's
- // unavailability may only be discovered by initial selection, after
- // the eager rebuild skipped a single-owner frame without pointers.
- if initialSelectionCanRebuild && switchCount < maxAccountSwitches && requestPlatform == service.PlatformOpenAI {
- initialSelectionCanRebuild = false
- if next, clean, changed, rebuildErr := h.gatewayService.TryRebuildOpenAI409History(ctx, c, wsAttemptMessage, sessionHash, wsForwardModel, err); rebuildErr != nil {
- err = rebuildErr
- } else if changed {
- ctx, wsAttemptMessage, previousResponseID = next, clean, ""
- previousResponseCanMove = true
- ctx = service.ResetOpenAIWSReadableProviderSession(ctx, c)
+ if !initialDispatchStarted && requestPlatform == service.PlatformOpenAI &&
+ switchCount < maxAccountSwitches && service.OpenAIWSInitialOwnerCanRebuild(err) {
+ next, clean, changed, rebuildErr := h.gatewayService.RebuildOpenAIWSUnsentTurn(ctx, c, wsAttemptMessage, sessionHash, wsForwardModel)
+ if rebuildErr != nil {
+ h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr, c)
+ return
+ }
+ if changed {
+ c.Request = c.Request.WithContext(next)
+ permissions := openAIWSQueueTurnPermissions(reqModel, clean)
+ permissions.Models = service.APIKeyModelCandidates(apiKey, permissions.Models)
+ next = service.WithAPIKeyQueueRequestPermissions(next, permissions)
+ if authErr := h.concurrencyHelper.RevalidateTurnAuth(next); authErr != nil {
+ closeOpenAIWSAdmissionError(wsConn, reqLog, "openai.websocket_rebuild_auth_rejected", authErr)
+ return
+ }
+ if billingErr := h.checkRegionalBillingEligibility(next, apiKey, subscription); billingErr != nil {
+ closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed")
+ return
+ }
+ if contextErr := h.gatewayService.CheckAPIKeyLongContext(next, apiKey, clean, reqModel, wsRouteModel, wsForwardModel); contextErr != nil {
+ rejectAPIKeyLongContextWS(wsConn, contextErr)
+ return
+ }
+ if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, reqModel, clean, "first_turn"); decision != nil && !decision.AllowNextStage {
+ writeSecurityAuditWSError(next, wsConn, decision)
+ closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision))
+ return
+ }
+ // Existing first-turn hooks still enforce client identity, selected
+ // account moderation, permissions, slots and final payload checks.
+ setCyberTurnBody(1, clean, firstIdentityDecision.effective)
+ ctx = service.ResetOpenAIWSReadableProviderSession(next, c)
c.Request = c.Request.WithContext(ctx)
+ wsAttemptMessage, previousResponseID, previousResponseCanMove = clean, "", true
+ firstTurnQueuePermissions = permissions
switchCount++
- reqLog.Info("openai.websocket_initial_readable_continuation", zap.Bool("context_loss", true))
continue
}
}
- if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err) {
+ if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) {
return
}
if errors.Is(err, service.ErrPriorityLatencyUnavailable) {
@@ -3755,7 +3793,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
moderationLogicalTurn++
}
c.Set(securityAuditWSTurnContextKey, moderationLogicalTurn)
- service.BeginOpsStreamTurn(c, turn)
+ service.BeginOpsStreamTurn(c, opsTurnOffset+turn)
// 连接级 cyber session gate 也在 BeforeRequest 先执行,使 native 与
// passthrough ingress 都能在 BeforeTurn 及上游写入前无副作用地拒绝。
// BeforeTurn 中保留同一检查作为防御式兜底。
@@ -4055,7 +4093,6 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
},
}
- initialSelectionCanRebuild = false
wsFirstMessage := wsAttemptMessage
// 切组/会话失配防护:previous_response_id 未在当前分组命中粘连账号(StickyPreviousHit=false),
// 说明该会话链不属于本次调度到的账号,原样转发会触发上游会话链鉴权失败(“鉴权失败,请检查 API Key”)。
@@ -4084,6 +4121,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// Carry that frame's timestamps into the new ingress attempt too.
hooks.InitialTurnStartedAt = firstTurnStartedAt
hooks.InitialFrameArrivedAt = firstFrameArrivedAt
+ initialDispatchStarted = true
err := h.gatewayService.ProxyResponsesWebSocketFromClient(ctx, c, wsConn, account, token, wsFirstMessage, hooks)
if err == nil {
reqLog.Info("openai.websocket_ingress_closed", zap.Int64("account_id", account.ID))
@@ -4094,6 +4132,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// transport, never the connection's warmup or a failed generation.
releaseTurnSlots()
if switchCount >= maxAccountSwitches || !service.OpenAIWSIngressCanFailover(ctx, c) {
+ if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) {
+ return
+ }
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account eligibility changed; continuation budget exhausted")
return
}
@@ -4124,10 +4165,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
next, clean, changed, rebuildErr := h.gatewayService.RebuildOpenAIWSUnsentTurn(ctx, c, raw, sessionHash, currentForwardModel)
if rebuildErr != nil {
- h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr)
+ h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr, c)
return
}
if !changed {
+ if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) {
+ return
+ }
closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account eligibility changed; reconnect with complete context")
return
}
@@ -4178,8 +4222,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
}
reqModel, wsRouteModel, wsForwardModel = currentModel, currentRouteModel, currentForwardModel
channelMappingWS = mapping
+ opsTurnOffset += turn - 1
wsAttemptMessage, previousResponseID, previousResponseCanMove = clean, "", true
- failedAccountIDs[account.ID] = struct{}{}
+ if !service.OpenAIWSUnsentTurnKeepsAccount(err) {
+ failedAccountIDs[account.ID] = struct{}{}
+ }
switchCount++
h.gatewayService.RecordOpenAIAccountSwitch()
if !ensureUserSlotHeld() {
@@ -4188,6 +4235,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
reqLog.Info("openai.websocket_readable_continuation", zap.Bool("context_loss", true), zap.Int("switch_count", switchCount))
break
}
+ if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) {
+ releaseTurnSlots()
+ return
+ }
if isOpenAIRPMError(err) {
releaseTurnSlots()
reason := "OpenAI OAuth RPM protection is temporarily unavailable; retry later"
@@ -4652,6 +4703,11 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
upstreamMsg := service.ExtractUpstreamErrorMessage(responseBody)
service.SetOpsUpstreamError(c, statusCode, upstreamMsg, "")
+ if code, message, ok := service.OpenAIUpstreamRecoveryRateLimit(statusCode, responseBody); ok {
+ service.SetOpsUpstreamError(c, statusCode, message, "")
+ h.handleStreamingAwareErrorWithCode(c, statusCode, "rate_limit_error", code, message, streamStarted, false)
+ return
+ }
// 使用默认的错误映射
status, errType, errMsg := h.mapUpstreamError(statusCode)
h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted)
@@ -5097,6 +5153,16 @@ func closeOpenAIWSFailoverExhausted(c *gin.Context, conn *coderws.Conn, failover
}
}
+ if failoverErr != nil {
+ if code, safeMessage, ok := service.OpenAIUpstreamRecoveryRateLimit(failoverErr.StatusCode, failoverErr.ResponseBody); ok {
+ errorCode, message = code, safeMessage
+ payload, _ := json.Marshal(gin.H{"type": "error", "status": intendedStatus,
+ "error": gin.H{"type": errorType, "code": errorCode, "message": message}})
+ writeCtx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
+ _ = service.WriteCapturedWSClient(writeCtx, conn, coderws.MessageText, payload)
+ cancel()
+ }
+ }
service.MarkOpsStreamFailure(c, errorType, errorCode, message, intendedStatus)
closeOpenAIClientWS(conn, closeStatus, message)
}
diff --git a/backend/internal/handler/openai_issue805_ws_test.go b/backend/internal/handler/openai_issue805_ws_test.go
index fc61397ce89d..10366da3a0bf 100644
--- a/backend/internal/handler/openai_issue805_ws_test.go
+++ b/backend/internal/handler/openai_issue805_ws_test.go
@@ -387,6 +387,16 @@ func TestIssue805WSNewBOutputWaitsForCrossNodeCommit(t *testing.T) {
release := func() { releaseOnce.Do(func() { close(barrier.release) }) }
defer release()
producer := issue805WSNode(t, mode, srv.URL, barrier, true, true)
+ // Establish the consumer socket before holding the producer commit.
+ // TLS/dial setup under -race must not consume the production 3s
+ // persistence deadline while the fixture deliberately blocks it.
+ readerBase := newCache()
+ readerDelivery, ok := readerBase.(issue715WSDeliveryCache)
+ require.True(t, ok)
+ observed := make(chan struct{})
+ var observeOnce sync.Once
+ reader := &issue805ReadObserver{GatewayCache: readerBase, issue715WSDeliveryCache: readerDelivery, seen: observed, once: &observeOnce}
+ consumer := issue805WSNode(t, mode, srv.URL, reader, true, true)
issue715WSSend(t, producer.clientConn, issue715WSCreate("", true))
answer := issue715WSRead(t, producer.clientConn)
require.Contains(t, string(answer), "fixture-task-produced-by-B")
@@ -401,13 +411,6 @@ func TestIssue805WSNewBOutputWaitsForCrossNodeCommit(t *testing.T) {
require.Contains(t, raw, `[1,2,`)
}
}
- readerBase := newCache()
- readerDelivery, ok := readerBase.(issue715WSDeliveryCache)
- require.True(t, ok)
- observed := make(chan struct{})
- var observeOnce sync.Once
- reader := &issue805ReadObserver{GatewayCache: readerBase, issue715WSDeliveryCache: readerDelivery, seen: observed, once: &observeOnce}
- consumer := issue805WSNode(t, mode, srv.URL, reader, true, true)
mixed := strings.Replace(issue715WSCreate("", true), issue715Agent, issue715Agent+","+issue805AgentB, 1)
issue715WSSend(t, consumer.clientConn, mixed)
issue715Await(t, observed)
@@ -416,7 +419,8 @@ func TestIssue805WSNewBOutputWaitsForCrossNodeCommit(t *testing.T) {
u.mu.Unlock()
require.Equal(t, 2, before, "client-visible B output cannot be consumed on another node before commit")
release()
- require.Equal(t, "response.completed", gjson.GetBytes(issue715WSRead(t, consumer.clientConn), "type").String())
+ completed := issue715WSRead(t, consumer.clientConn)
+ require.Equal(t, "response.completed", gjson.GetBytes(completed, "type").String(), "continuation after committed B output: %s", completed)
for _, node := range []*openAIWSPassthroughHandlerHarness{consumer, producer, originalNode} {
issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
}
diff --git a/backend/internal/handler/openai_issue842_boundaries_test.go b/backend/internal/handler/openai_issue842_boundaries_test.go
new file mode 100644
index 000000000000..de65f7decfa7
--- /dev/null
+++ b/backend/internal/handler/openai_issue842_boundaries_test.go
@@ -0,0 +1,188 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/Wei-Shaw/sub2api/internal/testutil"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+type issue842FaultCache struct {
+ service.GatewayCache
+ issue715WSDeliveryCache
+ fault string
+ reads atomic.Int64
+ client *redis.Client
+}
+
+// Exercise actual account builders after the handler has frozen the complete
+// input. These rewrites have semantics and are outside the metadata allowlist.
+func TestIssue842HTTPBuilderChangesStopBeforeNetwork(t *testing.T) {
+ for _, kind := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} {
+ for _, change := range []string{"namespace", "timezone", "system_promotion"} {
+ if kind == service.AccountTypeAPIKey && change == "system_promotion" {
+ continue
+ }
+ t.Run(kind+"/"+change, func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ target, err := url.Parse(srv.URL)
+ require.NoError(t, err)
+ accounts := issue715Accounts()
+ for i := range accounts {
+ accounts[i].Type = kind
+ accounts[i].Credentials = map[string]any{"api_key": "fixture842", "access_token": "fixture842", "base_url": srv.URL}
+ }
+ body, _ := issue842History(t, false, "reasoning_status")
+ settingsRepo := &issue842Settings{values: map[string]string{}}
+ switch change {
+ case "namespace":
+ body, err = sjson.Set(body, "input.1.namespace", "semantic-namespace842")
+ case "system_promotion":
+ body, err = sjson.Set(body, "input.1.role", "system")
+ case "timezone":
+ body, err = sjson.Set(body, "input.1.content", "\nUTC\n")
+ settingsRepo.values["openai_request_timezone_enabled"] = "true"
+ settingsRepo.values["openai_request_timezone_auto"] = "false"
+ }
+ require.NoError(t, err)
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, repository.NewGatewayCache(clients()), service.NewSettingService(settingsRepo, cfg), accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ issue805Policy(t, h.cfg, true)
+ answer := issue758Request(t, h, body)
+ require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String())
+ require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_wire_changed")
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ require.Empty(t, u.frames, "a gateway builder cannot rebase trust onto its changed input")
+ require.Empty(t, issue805Owners(t, clients()))
+ })
+ }
+ }
+}
+
+func (c *issue842FaultCache) GetOpenAIAgentRecovery(ctx context.Context, key string) (string, error) {
+ reads := c.reads.Add(1)
+ if c.fault == "redis_error" {
+ _ = c.client.Close()
+ return c.issue715WSDeliveryCache.GetOpenAIAgentRecovery(ctx, key)
+ }
+ if c.fault == "lost_after_snapshot" && reads > 1 {
+ if err := c.client.Del(ctx, "openai_agent_owner:v1:"+key).Err(); err != nil {
+ return "", err
+ }
+ }
+ return c.issue715WSDeliveryCache.GetOpenAIAgentRecovery(ctx, key)
+}
+
+func TestIssue842HTTPPolicyAndDeliveryBoundaries(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ for _, state := range []string{"complete", "pending", "failed", "conflict", "redis_error", "lost_after_snapshot", "canceled", "pointer"} {
+ for _, disabled := range []bool{false, true} {
+ for _, beta := range []bool{false, true} {
+ t.Run(fmt.Sprintf("stream=%t/%s/optout=%t/beta=%t", stream, state, disabled, beta), func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ accounts := issue715AccountsOfType(service.AccountTypeAPIKey)
+ for i := range accounts {
+ accounts[i].Credentials = map[string]any{"api_key": []string{"fixture-ws-one", "fixture-ws-two"}[i], "base_url": srv.URL}
+ }
+ newNode := func(relaxed, lossy bool, fault string) *OpenAIGatewayHandler {
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ client := clients()
+ cache := repository.NewGatewayCache(client)
+ if fault != "" {
+ cache = &issue842FaultCache{GatewayCache: cache, issue715WSDeliveryCache: cache.(issue715WSDeliveryCache), fault: fault, client: client}
+ }
+ settings := service.NewSettingService(&issue842Settings{beta: lossy}, cfg)
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, testutil.NewRealHTTPUpstream(cfg), cache, settings, accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ issue805Policy(t, h.cfg, relaxed)
+ return h
+ }
+ first := issue758Request(t, newNode(false, false, ""), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1))
+ require.Equal(t, http.StatusOK, first.Code, first.Body.String())
+ original := issue805Owners(t, clients())
+ require.Len(t, original, 1)
+ probe := clients()
+ if state == "pending" || state == "failed" || state == "conflict" {
+ for key, raw := range original {
+ value := state
+ if state == "pending" {
+ value = "pending:fixture842:" + raw
+ }
+ require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err())
+ }
+ }
+ before := issue805Owners(t, clients())
+ accounts[0].Schedulable = false
+ body, want := issue842History(t, stream, "reasoning_status")
+ if state == "pointer" {
+ body = strings.TrimSuffix(body, "}") + fmt.Sprintf(`,"previous_response_id":%q}`, issue758CompletedResponse(t, first.Body.String(), stream).Get("id").String())
+ }
+ fault := ""
+ if state == "redis_error" || state == "lost_after_snapshot" {
+ fault = state
+ }
+ h := newNode(disabled, beta, fault)
+ var code int
+ var response string
+ if state == "canceled" {
+ code, response = issue715Request(t, h, body, 715, "fixture-758-thread", true)
+ } else {
+ answer := issue758Request(t, h, body)
+ code, response = answer.Code, answer.Body.String()
+ }
+ allowed := state == "complete" && (disabled || beta)
+ // Beta explicitly detaches an old provider pointer before any
+ // send; ordinary opt-out cannot grant this lossy behavior.
+ allowed = allowed || (state == "pointer" && beta)
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if allowed {
+ require.Equal(t, http.StatusOK, code, response)
+ require.Len(t, u.frames, 2)
+ if disabled && state == "complete" {
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw)
+ }
+ } else {
+ require.Len(t, u.frames, 1, "unsafe history must stop before B, regardless of metadata or Beta: %s", response)
+ if state != "canceled" {
+ require.GreaterOrEqual(t, code, http.StatusBadRequest, response)
+ }
+ }
+ for key, raw := range before {
+ if state == "lost_after_snapshot" {
+ current := issue805Owners(t, clients())[key]
+ require.True(t, current == "" || current == raw, "lost records cannot be republished")
+ continue
+ }
+ require.Equal(t, raw, issue805Owners(t, clients())[key])
+ }
+ })
+ }
+ }
+ }
+ }
+}
diff --git a/backend/internal/handler/openai_issue842_oauth_repair_test.go b/backend/internal/handler/openai_issue842_oauth_repair_test.go
new file mode 100644
index 000000000000..f89947b709ed
--- /dev/null
+++ b/backend/internal/handler/openai_issue842_oauth_repair_test.go
@@ -0,0 +1,281 @@
+//go:build unit
+
+package handler
+
+import (
+ "fmt"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/Wei-Shaw/sub2api/internal/testutil"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+// Independent oracle: OAuth stateless metadata is expected even when incoming
+// store is omitted/true; API-key store:true must keep its provider reasoning ID.
+func issue842StatelessHistory(t *testing.T, kind, store, summary string, stream bool) (string, string) {
+ t.Helper()
+ body, _ := issue842History(t, stream, "reasoning_id")
+ var err error
+ if store == "omitted" {
+ body, err = sjson.Delete(body, "store")
+ } else {
+ body, err = sjson.SetRaw(body, "store", store)
+ }
+ require.NoError(t, err)
+ body, err = sjson.SetRaw(body, "input.5.content", `[{"type":"reasoning_text","text":"Retain readable OAuth reasoning842"}]`)
+ require.NoError(t, err)
+ switch summary {
+ case "omitted":
+ body, err = sjson.Delete(body, "input.5.summary")
+ case "null":
+ body, err = sjson.SetRaw(body, "input.5.summary", "null")
+ case "nonempty":
+ body, err = sjson.SetRaw(body, "input.5.summary", `[{"type":"summary_text","text":"Retain nonempty summary842"}]`)
+ }
+ require.NoError(t, err)
+ body, err = sjson.SetRaw(body, "input.-1", `{"type":"reasoning","id":"rs_plaintext842","summary":null,"content":[{"type":"reasoning_text","text":"Retain plaintext reasoning842"}]}`)
+ require.NoError(t, err)
+ want := body
+ if kind == service.AccountTypeOAuth || store == "false" {
+ want, err = sjson.Delete(want, "input.5.id")
+ require.NoError(t, err)
+ if summary != "nonempty" {
+ want, err = sjson.SetRaw(want, "input.5.summary", "[]")
+ require.NoError(t, err)
+ }
+ }
+ if kind == service.AccountTypeOAuth {
+ want, err = sjson.Delete(want, "input.6.id")
+ require.NoError(t, err)
+ want, err = sjson.SetRaw(want, "input.6.summary", "[]")
+ require.NoError(t, err)
+ }
+ return body, want
+}
+
+type issue842RepairTransport struct {
+ service.HTTPUpstream
+ target *url.URL
+ mu sync.Mutex
+ paths []string
+}
+
+func (u *issue842RepairTransport) Do(req *http.Request, proxy string, account int64, concurrency int) (*http.Response, error) {
+ u.mu.Lock()
+ u.paths = append(u.paths, req.URL.Path)
+ u.mu.Unlock()
+ if proxy != "" || (req.URL.Host != "chatgpt.com" && req.URL.Host != "bps.openai.com" && req.URL.Host != u.target.Host) {
+ return nil, fmt.Errorf("Issue842 refuses unexpected fixture route")
+ }
+ local := req.Clone(req.Context())
+ address := *req.URL
+ address.Scheme, address.Host = u.target.Scheme, u.target.Host
+ local.URL = &address
+ return u.HTTPUpstream.Do(local, "", account, concurrency)
+}
+
+func (u *issue842RepairTransport) DoWithTLS(req *http.Request, proxy string, account int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return u.Do(req, proxy, account, concurrency)
+}
+
+func TestIssue842OAuthStatelessHTTP(t *testing.T) {
+ for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} {
+ for _, stream := range []bool{false, true} {
+ for _, store := range []string{"omitted", "true", "false"} {
+ for _, summary := range []string{"omitted", "null", "nonempty"} {
+ t.Run(fmt.Sprintf("%s/stream=%t/store=%s/summary=%s", kind, stream, store, summary), func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ target, err := url.Parse(srv.URL)
+ require.NoError(t, err)
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ transport := &issue842RepairTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ accounts := issue715AccountsOfType(kind)
+ for i := range accounts {
+ accounts[i].Credentials = map[string]any{"api_key": []string{"fixture-ws-one", "fixture-ws-two"}[i], "access_token": []string{"fixture-ws-one", "fixture-ws-two"}[i], "base_url": srv.URL}
+ }
+ newNode := func(disabled bool) *OpenAIGatewayHandler {
+ settings := service.NewSettingService(&issue842Settings{}, cfg)
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, transport, repository.NewGatewayCache(clients()), settings, accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ issue805Policy(t, h.cfg, disabled)
+ return h
+ }
+ first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1))
+ require.Equal(t, http.StatusOK, first.Code, first.Body.String())
+ issue758CompletedResponse(t, first.Body.String(), stream)
+ original := issue805Owners(t, clients())
+ require.Len(t, original, 1)
+ accounts[0].Schedulable = false
+ body, want := issue842StatelessHistory(t, kind, store, summary, stream)
+ answer := issue758Request(t, newNode(true), body)
+ require.Equal(t, http.StatusOK, answer.Code, answer.Body.String())
+ issue758CompletedResponse(t, answer.Body.String(), stream)
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two"}, u.ids, "exactly one admitted B generation")
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw, "Issue842 OAuth stateless input must match immutable-source metadata projection")
+ if kind == service.AccountTypeOAuth {
+ require.Equal(t, gjson.False, gjson.GetBytes(u.frames[1], "store").Type)
+ }
+ for key, raw := range original {
+ require.Equal(t, raw, issue805Owners(t, clients())[key], "A ownership must stay unchanged")
+ }
+ })
+ }
+ }
+ }
+ }
+}
+
+func issue842OAuthWSNode(t *testing.T, mode, upstream string, cache service.GatewayCache, disabled, limited bool) *openAIWSPassthroughHandlerHarness {
+ t.Helper()
+ target, err := url.Parse(upstream)
+ require.NoError(t, err)
+ h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, upstream,
+ http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}},
+ map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false"}, cache,
+ func(key *service.APIKey) { key.AllowLongContext = true },
+ func(a *service.Account, cfg *config.Config, httpUpstream *service.HTTPUpstream, repo *service.AccountRepository) {
+ a.ID, a.Priority, a.Type = 1, 0, service.AccountTypeOAuth
+ a.Credentials = map[string]any{"access_token": "fixture-ws-one", "chatgpt_account_id": "fixture842-A"}
+ a.Extra["openai_oauth_responses_websockets_v2_enabled"] = true
+ a.Extra["openai_oauth_responses_websockets_v2_mode"] = mode
+ a.Extra["codex_fingerprint_mode"] = "off"
+ cfg.Gateway.OpenAIWS.OAuthEnabled = true
+ cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 15
+ issue805Policy(t, cfg, disabled)
+ require.Equal(t, mode, a.ResolveOpenAIResponsesWebSocketV2Mode(cfg.Gateway.OpenAIWS.IngressModeDefault))
+ other := *a
+ other.ID, other.Priority = 2, 1
+ other.Credentials = map[string]any{"access_token": "fixture-ws-two", "chatgpt_account_id": "fixture842-B"}
+ if limited {
+ reset := time.Now().Add(time.Hour)
+ a.RateLimitResetAt = &reset
+ }
+ *httpUpstream = &issue842RepairTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ *repo = &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, other}}}
+ })
+ require.NoError(t, service.RouteIssue842OAuthSocketsToLoopbackForTest(h.handler.gatewayService, upstream))
+ return h
+}
+
+func TestIssue842OAuthStatelessWS(t *testing.T) {
+ for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} {
+ for _, store := range []string{"omitted", "true", "false"} {
+ for _, summary := range []string{"omitted", "null", "nonempty"} {
+ t.Run(fmt.Sprintf("%s/store=%s/summary=%s", mode, store, summary), func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ producer := issue842OAuthWSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), false, false)
+ issue715WSSend(t, producer.clientConn, issue715WSCreate("", false))
+ require.Contains(t, string(issue715WSRead(t, producer.clientConn)), "fixture-task-reference-715")
+ probe := clients()
+ require.Eventually(t, func() bool {
+ owners := issue805Owners(t, probe)
+ if len(owners) != 1 {
+ return false
+ }
+ for _, raw := range owners {
+ if !issue805CompletedOwner(raw, 1) {
+ return false
+ }
+ }
+ return true
+ }, time.Second, 5*time.Millisecond)
+ original := issue805Owners(t, probe)
+ consumer := issue842OAuthWSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), true, true)
+ body, want := issue842StatelessHistory(t, service.AccountTypeOAuth, store, summary, true)
+ body, err := sjson.Set(body, "type", "response.create")
+ require.NoError(t, err)
+ body, err = sjson.Set(body, "client_metadata.thread_id", "fixture-ws715-thread")
+ require.NoError(t, err)
+ for turn := 0; turn < 2; turn++ {
+ issue715WSSend(t, consumer.clientConn, body)
+ answer := issue715WSRead(t, consumer.clientConn)
+ require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), string(answer))
+ }
+ for _, node := range []*openAIWSPassthroughHandlerHarness{consumer, producer} {
+ issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
+ }
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two", "Bearer fixture-ws-two"}, u.ids)
+ for _, frame := range u.frames[1:] {
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(frame, "input").Raw, "Issue842 OAuth WS stateless input must match immutable-source metadata projection")
+ }
+ if mode == service.OpenAIWSIngressModeHTTPBridge {
+ require.Equal(t, 3, u.http)
+ require.Zero(t, u.ws)
+ } else {
+ require.Equal(t, 3, u.ws, "native OAuth first/later frames must use real sockets")
+ require.Zero(t, u.http)
+ }
+ for key, raw := range original {
+ require.Equal(t, raw, issue805Owners(t, probe)[key])
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestIssue842BPSSearchRefusesBeforeAnySend(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ t.Run(fmt.Sprint(stream), func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ target, err := url.Parse(srv.URL)
+ require.NoError(t, err)
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ transport := &issue842RepairTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ accounts := issue715Accounts()
+ for i := range accounts {
+ accounts[i].Credentials = map[string]any{"access_token": []string{"fixture-ws-one", "fixture-ws-two"}[i]}
+ }
+ newNode := func(disabled bool) *OpenAIGatewayHandler {
+ settings := service.NewSettingService(&issue842Settings{values: map[string]string{"excel_bps_enabled": "true"}}, cfg)
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, transport, repository.NewGatewayCache(clients()), settings, accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ issue805Policy(t, h.cfg, disabled)
+ return h
+ }
+ first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1))
+ require.Equal(t, http.StatusOK, first.Code, first.Body.String())
+ original := issue805Owners(t, clients())
+ require.Len(t, original, 1)
+ accounts[0].Schedulable = false
+ accounts[1].Extra = map[string]any{"openai_excel_bps": true, "openai_excel_bps_web_search": true, "openai_excel_bps_web_search_auto": true}
+ body, _ := issue842StatelessHistory(t, service.AccountTypeOAuth, "omitted", "null", stream)
+ body, err = sjson.SetRaw(body, "tools", `[{"type":"web_search","external_web_access":true}]`)
+ require.NoError(t, err)
+ require.True(t, accounts[1].IsExcelBPSEnabledForModel(gjson.Get(body, "model").String()))
+ answer := issue758Request(t, newNode(true), body)
+ require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String())
+ require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_route_changed")
+ transport.mu.Lock()
+ defer transport.mu.Unlock()
+ require.Len(t, transport.paths, 1, "BPS generation/search/continuation must all have zero sends after A delivery")
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ require.Len(t, u.frames, 1)
+ require.Equal(t, original, issue805Owners(t, clients()))
+ })
+ }
+}
diff --git a/backend/internal/handler/openai_issue842_replay_test.go b/backend/internal/handler/openai_issue842_replay_test.go
new file mode 100644
index 000000000000..9daaacd76b08
--- /dev/null
+++ b/backend/internal/handler/openai_issue842_replay_test.go
@@ -0,0 +1,197 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/Wei-Shaw/sub2api/internal/testutil"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+// The real native OAuth builder has a fixed URL. Redirect only its final
+// transport to loopback; never dial a provider or change its body/credentials.
+type issue842Transport struct {
+ service.HTTPUpstream
+ target *url.URL
+}
+
+func (u *issue842Transport) Do(req *http.Request, proxy string, account int64, concurrency int) (*http.Response, error) {
+ if proxy != "" || (req.URL.String() != "https://chatgpt.com/backend-api/codex/responses" && req.URL.String() != u.target.String()+"/v1/responses") {
+ return nil, fmt.Errorf("Issue842 refuses non-fixture transport")
+ }
+ local := req.Clone(req.Context())
+ address := *req.URL
+ address.Scheme, address.Host = u.target.Scheme, u.target.Host
+ local.URL = &address
+ return u.HTTPUpstream.Do(local, "", account, concurrency)
+}
+
+func (u *issue842Transport) DoWithTLS(req *http.Request, proxy string, account int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return u.Do(req, proxy, account, concurrency)
+}
+
+// This uses the existing setting's literal key so historical RED assemblies
+// predating Beta can still compile these otherwise independent fixtures.
+type issue842Settings struct {
+ service.SettingRepository
+ beta bool
+ values map[string]string
+}
+
+func (s *issue842Settings) GetValue(_ context.Context, key string) (string, error) {
+ if value, ok := s.values[key]; ok {
+ return value, nil
+ }
+ if key == "openai_409_omit_encrypted_history_enabled" {
+ return fmt.Sprint(s.beta), nil
+ }
+ return "", service.ErrSettingNotFound
+}
+
+func (s *issue842Settings) GetMultiple(context.Context, []string) (map[string]string, error) {
+ return map[string]string{"openai_409_omit_encrypted_history_enabled": fmt.Sprint(s.beta)}, nil
+}
+
+func issue842History(t *testing.T, stream bool, variant string) (string, string) {
+ t.Helper()
+ body := issue715Body(true, stream)
+ var err error
+ body, err = sjson.Set(body, "store", false)
+ require.NoError(t, err)
+ body, err = sjson.SetRaw(body, "input.1.sequence", "9007199254740993")
+ require.NoError(t, err)
+ reasoning := `{"type":"reasoning","encrypted_content":"fixture-842-reasoning-cipher","summary":[]}`
+ switch variant {
+ case "reasoning_status":
+ reasoning, err = sjson.Set(reasoning, "status", "completed")
+ case "reasoning_content":
+ reasoning, err = sjson.SetRaw(reasoning, "content", `[{"type":"reasoning_text","text":"Retain this readable reasoning exactly"}]`)
+ case "plaintext_reasoning":
+ reasoning = `{"type":"reasoning","summary":[{"type":"summary_text","text":"retain plaintext summary"}],"content":[{"type":"reasoning_text","text":"Retain this readable reasoning exactly"}]}`
+ case "reasoning_id":
+ reasoning, err = sjson.Set(reasoning, "id", "rs_fixture842")
+ case "invalid_replay_id":
+ body, err = sjson.Set(body, "input.1.id", "invalid-provider-item842")
+ case "message_call_id":
+ body, err = sjson.Set(body, "input.1.call_id", "unpaired-output-metadata842")
+ }
+ require.NoError(t, err)
+ body, err = sjson.SetRaw(body, "input.-1", reasoning)
+ require.NoError(t, err)
+ // Independent expected representation: exactly the metadata permitted by
+ // the pre-freeze contract; no production normalizer is used as the oracle.
+ want := body
+ for _, path := range []string{"input.5.status", "input.5.id", "input.1.id", "input.1.call_id"} {
+ want, err = sjson.Delete(want, path)
+ require.NoError(t, err)
+ }
+ return body, want
+}
+
+func TestIssue842HTTPReplayMetadata(t *testing.T) {
+ for _, kind := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} {
+ for _, stream := range []bool{false, true} {
+ for _, variant := range []string{"reasoning_status", "reasoning_content", "plaintext_reasoning", "reasoning_id", "invalid_replay_id", "message_call_id"} {
+ for _, known := range []bool{true, false} {
+ t.Run(fmt.Sprintf("%s/stream=%t/%s/known=%t", kind, stream, variant, known), func(t *testing.T) {
+ clients := issue805Redis(t)
+ var mu sync.Mutex
+ var bodies [][]byte
+ var identities []string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ require.Empty(t, r.Header.Get("Upgrade"), "count the actual HTTP adapter, including configured SSE acceleration")
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ mu.Lock()
+ bodies = append(bodies, body)
+ identities = append(identities, r.Header.Get("Authorization"))
+ n := len(bodies)
+ mu.Unlock()
+ output := "[" + issue715Agent + "]"
+ if n > 1 || gjson.GetBytes(body, "input.#(type==function_call_output)").Exists() {
+ output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"recorded result retained once"}]}]`
+ }
+ response := fmt.Sprintf(`{"id":"resp_842_%d","status":"completed","error":null,"model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, n, output)
+ if gjson.GetBytes(body, "stream").Bool() {
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response)
+ } else {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, response)
+ }
+ }))
+ defer srv.Close()
+ target, err := url.Parse(srv.URL)
+ require.NoError(t, err)
+ accounts := issue715Accounts()
+ for i := range accounts {
+ accounts[i].Type = kind
+ accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture842-%d", i+1), "access_token": fmt.Sprintf("fixture842-%d", i+1), "base_url": srv.URL}
+ }
+ newNode := func(disabled bool) *OpenAIGatewayHandler {
+ if disabled && kind == service.AccountTypeOAuth {
+ accounts[1].Extra = map[string]any{"openai_oauth_responses_websockets_v2_enabled": true, "openai_oauth_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool, "openai_oauth_ws_sse_acceleration": true}
+ }
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ settings := service.NewSettingService(&issue842Settings{}, cfg)
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, repository.NewGatewayCache(clients()), settings, accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ h.cfg.Gateway.OpenAIWS.Enabled = disabled
+ h.cfg.Gateway.OpenAIWS.OAuthEnabled = disabled
+ h.cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = disabled
+ issue805Policy(t, h.cfg, disabled)
+ return h
+ }
+ if known {
+ first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1))
+ require.Equal(t, http.StatusOK, first.Code, first.Body.String())
+ require.JSONEq(t, issue715Agent, issue758CompletedResponse(t, first.Body.String(), stream).Get("output.0").Raw)
+ }
+ original := issue805Owners(t, clients())
+ offset := 0
+ if known {
+ offset = 1
+ }
+ require.Len(t, original, offset, "A must actually complete delivery")
+ accounts[0].Schedulable = false
+ body, want := issue842History(t, stream, variant)
+ answer := issue758Request(t, newNode(true), body)
+ require.Equal(t, http.StatusOK, answer.Code, "Issue842 benign replay metadata must reach B once: %s", answer.Body.String())
+ issue758CompletedResponse(t, answer.Body.String(), stream)
+ mu.Lock()
+ defer mu.Unlock()
+ expectedIDs := []string{"Bearer fixture842-2"}
+ if known {
+ expectedIDs = append([]string{"Bearer fixture842-1"}, expectedIDs...)
+ }
+ require.Equal(t, expectedIDs, identities)
+ require.Len(t, bodies, offset+1, "one A generation and one intact B continuation")
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(bodies[offset], "input").Raw)
+ require.Equal(t, "9007199254740993", gjson.GetBytes(bodies[offset], "input.1.sequence").Raw)
+ require.Equal(t, original, issue805Owners(t, clients()), "consuming A on B must not republish its owner")
+ })
+ }
+ }
+ }
+ }
+}
diff --git a/backend/internal/handler/openai_issue842_ws_test.go b/backend/internal/handler/openai_issue842_ws_test.go
new file mode 100644
index 000000000000..0a38979f3699
--- /dev/null
+++ b/backend/internal/handler/openai_issue842_ws_test.go
@@ -0,0 +1,179 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ coderws "github.com/coder/websocket"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+func issue842WSHistory(t *testing.T, variant string) (string, string) {
+ t.Helper()
+ body, want := issue842History(t, true, variant)
+ var err error
+ body, err = sjson.Set(body, "type", "response.create")
+ require.NoError(t, err)
+ body, err = sjson.Set(body, "client_metadata.thread_id", "fixture-ws715-thread")
+ require.NoError(t, err)
+ return body, want
+}
+
+func TestIssue842WSDeliveryAndUnknownOutcome(t *testing.T) {
+ for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} {
+ for _, state := range []string{"pending", "failed", "conflict", "foreign_pointer", "unknown"} {
+ t.Run(mode+"/"+state, func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ producer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), false, false)
+ issue715WSSend(t, producer.clientConn, issue715WSCreate("", false))
+ require.Contains(t, string(issue715WSRead(t, producer.clientConn)), "fixture-task-reference-715")
+ probe := clients()
+ require.Eventually(t, func() bool {
+ owners := issue805Owners(t, probe)
+ if len(owners) != 1 {
+ return false
+ }
+ for _, raw := range owners {
+ if !issue805CompletedOwner(raw, 1) {
+ return false
+ }
+ }
+ return true
+ }, time.Second, 5*time.Millisecond)
+ original := issue805Owners(t, probe)
+ body, want := issue842WSHistory(t, "reasoning_status")
+ if state == "foreign_pointer" {
+ body, _ = sjson.Set(body, "previous_response_id", "resp_fixture_foreign842")
+ require.NoError(t, service.NewOpenAIWSStateStore(repository.NewGatewayCache(clients())).BindResponseAccount(context.Background(), 4301, "resp_fixture_foreign842", 1, time.Minute))
+ } else if state != "unknown" {
+ for key, raw := range original {
+ value := state
+ if state == "pending" {
+ value = "pending:fixture842:" + raw
+ }
+ require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err())
+ }
+ }
+ if state == "unknown" {
+ u.mu.Lock()
+ u.disconnect = true
+ u.mu.Unlock()
+ }
+ consumer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), true, true)
+ issue715WSSend(t, consumer.clientConn, body)
+ if state == "unknown" {
+ issue805WSAmbiguousTermination(t, consumer.clientConn)
+ } else {
+ code := "encrypted_agent_recovery_owner_unavailable"
+ if state == "pending" {
+ code = "encrypted_agent_recovery_delivery_pending"
+ } else if state == "conflict" {
+ code = "encrypted_agent_recovery_owner_conflict"
+ }
+ issue805WSRefusal(t, consumer.clientConn, code)
+ }
+ for _, node := range []*openAIWSPassthroughHandlerHarness{consumer, producer} {
+ issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
+ }
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if state == "unknown" {
+ require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two"}, u.ids, "unknown B write cannot replay warmup, generation or tool results")
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw)
+ require.Equal(t, original, issue805Owners(t, probe))
+ } else {
+ require.Len(t, u.frames, 1, "unsafe metadata-bearing history never reaches B")
+ }
+ })
+ }
+ }
+}
+
+func TestIssue842WSReplayMetadata(t *testing.T) {
+ for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} {
+ for _, variant := range []string{"reasoning_status", "reasoning_content", "plaintext_reasoning", "reasoning_id", "invalid_replay_id", "message_call_id"} {
+ for _, known := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/%s/known=%t", mode, variant, known), func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ original := map[string]string{}
+ if known {
+ producer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), false, false)
+ issue715WSSend(t, producer.clientConn, issue715WSCreate("", false))
+ require.Contains(t, string(issue715WSRead(t, producer.clientConn)), "fixture-task-reference-715")
+ probe := clients()
+ require.Eventually(t, func() bool {
+ owners := issue805Owners(t, probe)
+ if len(owners) != 1 {
+ return false
+ }
+ for _, raw := range owners {
+ if !issue805CompletedOwner(raw, 1) {
+ return false
+ }
+ }
+ return true
+ }, time.Second, 5*time.Millisecond)
+ original = issue805Owners(t, probe)
+ issue600Finish(t, producer, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
+ }
+ consumer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), true, true)
+ body, want := issue842WSHistory(t, variant)
+ for turn := 0; turn < 2; turn++ {
+ issue715WSSend(t, consumer.clientConn, body)
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ _, answer, err := consumer.clientConn.Read(ctx)
+ cancel()
+ if err != nil {
+ require.NotErrorIs(t, err, context.DeadlineExceeded)
+ if coderws.CloseStatus(err) == coderws.StatusPolicyViolation {
+ t.Log("Issue842 metadata policy refusal before frame")
+ }
+ }
+ require.NoError(t, err, "Issue842 WS benign metadata must reach the actual adapter once")
+ require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), "Issue842 WS benign metadata must reach the actual adapter once: %s", answer)
+ require.Contains(t, string(answer), "existing ledger balance 18")
+ }
+ issue600Finish(t, consumer, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ offset := 0
+ if known {
+ offset = 1
+ }
+ ids := []string{"Bearer fixture-ws-two", "Bearer fixture-ws-two"}
+ if known {
+ ids = append([]string{"Bearer fixture-ws-one"}, ids...)
+ }
+ require.Equal(t, ids, u.ids, "no warmup or executed tool replay")
+ for _, frame := range u.frames[offset:] {
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(frame, "input").Raw)
+ require.Equal(t, "9007199254740993", gjson.GetBytes(frame, "input.1.sequence").Raw)
+ }
+ if mode == service.OpenAIWSIngressModeHTTPBridge {
+ require.Equal(t, len(ids), u.http)
+ require.Zero(t, u.ws)
+ } else {
+ require.Equal(t, len(ids), u.ws)
+ require.Zero(t, u.http)
+ }
+ for key, raw := range original {
+ require.Equal(t, raw, issue805Owners(t, clients())[key], "A remains the original producer")
+ }
+ })
+ }
+ }
+ }
+}
diff --git a/backend/internal/handler/openai_issue854_continuation_test.go b/backend/internal/handler/openai_issue854_continuation_test.go
new file mode 100644
index 000000000000..48944f5ac9f1
--- /dev/null
+++ b/backend/internal/handler/openai_issue854_continuation_test.go
@@ -0,0 +1,54 @@
+//go:build unit
+
+package handler
+
+import (
+ "fmt"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "testing"
+)
+
+// Real authentication, scheduler and forwarders; only repositories and paid
+// providers are fixtures. B must validate tools, completed results and absence
+// of A's ciphertext/pointers before completing the remaining tool loop.
+func TestIssue854OwnerContinuation(t *testing.T) {
+ for _, mode := range readableWSModes {
+ for _, connection := range []string{"original", "fresh", "guard_live"} {
+ t.Run(mode+"/"+connection, func(t *testing.T) {
+ runReadableWSContinuation(t, mode, "issue854_"+connection)
+ })
+ }
+ }
+}
+
+func TestIssue854OwnerFailurePersistence(t *testing.T) {
+ for _, mode := range readableWSModes {
+ for _, connection := range []string{"guard", "fresh"} {
+ t.Run(mode+"/"+connection, func(t *testing.T) {
+ runReadableWSContinuation(t, mode, "issue854_"+connection+"_refusal")
+ })
+ }
+ }
+}
+
+func TestIssue854HTTPContinuation(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) {
+ runHTTPRebuildFixture(t, service.AccountTypeAPIKey, stream, "previous", "completed", "issue854_auth", "")
+ })
+ }
+}
+
+func TestIssue854LostOwnerEvidence(t *testing.T) {
+ for _, mode := range readableWSModes {
+ t.Run(mode, func(t *testing.T) { runReadableWSContinuation(t, mode, "issue854_lost_owner") })
+ }
+}
+
+func TestIssue854FreshOwnerSelection(t *testing.T) {
+ for _, mode := range readableWSModes {
+ for _, state := range []string{"disabled", "cooldown", "off", "pending", "failed", "conflict", "unfinished"} {
+ t.Run(mode+"/"+state, func(t *testing.T) { runReadableWSContinuation(t, mode, "issue854_r1_"+state) })
+ }
+ }
+}
diff --git a/backend/internal/handler/openai_issue854_http_transform_test.go b/backend/internal/handler/openai_issue854_http_transform_test.go
new file mode 100644
index 000000000000..ebaf9b9994c0
--- /dev/null
+++ b/backend/internal/handler/openai_issue854_http_transform_test.go
@@ -0,0 +1,270 @@
+//go:build unit && issue854matrix
+
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+// The same authenticated A -> completed patch -> B -> verification -> final
+// fixture exercises the real HTTP repository and a loopback provider. These
+// cases add only the missing transformations identified in comment6882215071.
+func TestIssue854HTTPTransformMatrix(t *testing.T) {
+ for _, account := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} {
+ for _, stream := range []bool{false, true} {
+ for _, transform := range []string{"metadata", "message_namespace", "tool_namespace", "empty_image", "reasoning_summary", "compaction_order", "timezone_manual", "timezone_auto", "lite", "reserved_alias", "namespace_declaration", "namespace_flatten", "schema_null", "new_task"} {
+ t.Run(fmt.Sprintf("%s/stream=%t/%s", account, stream, transform), func(t *testing.T) {
+ option := httpRebuildFixtureOptions{
+ request: func(body map[string]any, continuation bool) {
+ if transform == "reserved_alias" || transform == "namespace_declaration" || transform == "namespace_flatten" {
+ extra := map[string]any{"type": "function", "name": "python", "parameters": map[string]any{"type": "object", "properties": map[string]any{"code": map[string]any{"type": "string"}}, "required": []any{"code"}, "additionalProperties": false}}
+ if strings.HasPrefix(transform, "namespace_") {
+ extra = map[string]any{"type": "namespace", "name": "fixture_tools", "tools": []any{extra}}
+ }
+ body["tools"] = append(body["tools"].([]any), extra)
+ }
+ if !continuation && !strings.HasPrefix(transform, "timezone_") {
+ return
+ }
+ if transform == "schema_null" {
+ body["tools"].([]any)[0].(map[string]any)["parameters"].(map[string]any)["type"] = nil
+ }
+ var input []map[string]any
+ require.NoError(t, json.Unmarshal(body["input"].(json.RawMessage), &input))
+ for _, item := range input {
+ switch transform {
+ case "metadata":
+ if item["role"] == "user" {
+ item["internal_chat_message_metadata_passthrough"] = map[string]any{"fixture": true}
+ }
+ case "message_namespace":
+ if item["role"] == "user" {
+ item["namespace"] = "fixture_messages"
+ }
+ case "tool_namespace":
+ if item["type"] == "function_call" {
+ item["namespace"] = "functions"
+ }
+ case "empty_image":
+ if item["role"] == "user" {
+ if text, ok := item["content"].(string); ok {
+ item["content"] = []any{map[string]any{"type": "input_text", "text": text}}
+ }
+ if content, ok := item["content"].([]any); ok {
+ item["content"] = append(content, map[string]any{"type": "input_image", "image_url": "data:image/png;base64,"})
+ }
+ }
+ }
+ }
+ if transform == "reasoning_summary" {
+ input = append(input, map[string]any{"type": "reasoning", "encrypted_content": "fixture-reasoning-old", "summary": []any{map[string]any{"type": "summary_text", "text": "fixture-readable-summary"}}})
+ }
+ if transform == "compaction_order" {
+ input = append(input, map[string]any{"type": "compaction", "encrypted_content": "fixture-compaction-old"}, map[string]any{"type": "message", "role": "user", "content": "fixture-after-compaction: reuse the recorded result"})
+ }
+ if strings.HasPrefix(transform, "timezone_") {
+ input = append(input, map[string]any{"type": "message", "role": "user", "content": "Asia/Shanghai"})
+ }
+ if transform == "new_task" {
+ input = append(input, map[string]any{"type": "message", "role": "user", "content": "fixture-new-task: document the completed fix without repeating it"})
+ }
+ body["input"] = input
+ },
+ provider: func(t *testing.T, body []byte, header http.Header, n int) {
+ if n < 2 && !strings.HasPrefix(transform, "timezone_") {
+ return
+ }
+ switch transform {
+ case "timezone_manual", "timezone_auto":
+ // JSON escaping of XML is irrelevant; inspect decoded physical input.
+ var wire map[string]any
+ require.NoError(t, json.Unmarshal(body, &wire))
+ text := fmt.Sprint(wire["input"])
+ want, absent := "Asia/Tokyo", "Asia/Shanghai"
+ if transform == "timezone_auto" && n > 1 {
+ want, absent = absent, want
+ }
+ require.Contains(t, text, ""+want+"", "ISSUE854_HTTP_TIMEZONE_LAST_BYTES")
+ require.NotContains(t, text, ""+absent+"")
+ require.Equal(t, "Asia/Tokyo", header.Get("X-Timezone"), "header still follows the configured egress")
+ case "lite":
+ if account == service.AccountTypeOAuth {
+ require.Equal(t, "all_turns", gjson.GetBytes(body, "reasoning.context").String())
+ } else {
+ require.False(t, gjson.GetBytes(body, "reasoning.context").Exists())
+ }
+ require.Equal(t, gjson.False, gjson.GetBytes(body, "parallel_tool_calls").Type)
+ case "new_task":
+ require.Contains(t, string(body), "fixture-new-task")
+ case "metadata":
+ if account == service.AccountTypeOAuth {
+ require.NotContains(t, string(body), "internal_chat_message_metadata_passthrough", "ISSUE854_HTTP_METADATA_PHYSICAL_WIRE")
+ }
+ case "message_namespace":
+ require.NotContains(t, string(body), "fixture_messages", "ISSUE854_HTTP_MESSAGE_NAMESPACE_PHYSICAL_WIRE")
+ case "tool_namespace":
+ for _, item := range gjson.GetBytes(body, "input").Array() {
+ if item.Get("type").String() == "function_call" {
+ if account == service.AccountTypeOAuth {
+ require.Equal(t, "functions", item.Get("namespace").String())
+ } else {
+ require.False(t, item.Get("namespace").Exists())
+ }
+ }
+ }
+ case "empty_image":
+ require.NotContains(t, string(body), "data:image/png;base64,", "ISSUE854_HTTP_EMPTY_IMAGE_PHYSICAL_WIRE")
+ case "reasoning_summary":
+ require.Contains(t, string(body), "fixture-readable-summary")
+ require.NotContains(t, string(body), "fixture-reasoning-old")
+ case "compaction_order":
+ require.NotContains(t, string(body), "fixture-compaction-old")
+ require.Greater(t, strings.Index(string(body), "fixture-after-compaction"), strings.Index(string(body), httpRebuildPatch))
+ }
+ },
+ }
+ if strings.HasPrefix(transform, "timezone_") {
+ if transform == "timezone_auto" {
+ option.physicalBody = func(t *testing.T, body []byte, index int) []byte {
+ if index > 0 {
+ return body
+ }
+ // Independent oracle for the only permitted repository-layer
+ // rewrite on ordinary A only. Rebuilt B bodies stay exact. Compare ALL
+ // other fields, tool declarations, arguments/results unchanged.
+ for i, item := range gjson.GetBytes(body, "input").Array() {
+ if item.Get("content").String() == "Asia/Shanghai" {
+ var err error
+ body, err = sjson.SetBytes(body, fmt.Sprintf("input.%d.content", i), "Asia/Tokyo")
+ require.NoError(t, err)
+ }
+ }
+ return body
+ }
+ }
+ option.headers = func(r *http.Request) { r.Header.Set("X-Timezone", "Asia/Shanghai") }
+ option.settings = &issue854TimezoneSettings{omit409SettingsRepo: omit409SettingsRepo{enabled: true}, auto: transform == "timezone_auto"}
+ option.accounts = func(accounts []service.Account) {
+ for i := range accounts {
+ if accounts[i].Extra == nil {
+ accounts[i].Extra = map[string]any{}
+ }
+ accounts[i].Extra["openai_request_timezone"] = "Asia/Tokyo"
+ }
+ }
+ option.gateway = func(h *OpenAIGatewayHandler, accounts []service.Account, upstream service.HTTPUpstream, cache service.GatewayCache, settings *service.SettingService, usage service.UsageLogRepository) {
+ h.gatewayService = service.ProvideOpenAIGatewayService(service.OpenAIGatewayDependencies{Accounts: openAIImagesFailoverAccountRepo{accounts: accounts}, Config: h.cfg, Upstream: upstream, Cache: cache, Settings: settings, UsageLogs: usage, Billing: service.NewBillingService(h.cfg, nil), Deferred: &service.DeferredService{}, TimezoneProber: issue854TimezoneProbe{}})
+ }
+ }
+ if transform == "namespace_flatten" {
+ option.accounts = func(accounts []service.Account) {
+ for i := range accounts {
+ if accounts[i].Extra == nil {
+ accounts[i].Extra = map[string]any{}
+ }
+ accounts[i].Extra["openai_responses_flatten_namespaces"] = true
+ }
+ }
+ }
+ if transform == "lite" {
+ option.headers = func(r *http.Request) { r.Header.Set("X-OpenAI-Internal-Codex-Responses-Lite", "true") }
+ }
+ if transform == "reserved_alias" || transform == "namespace_declaration" || transform == "namespace_flatten" {
+ option.toolsAvailable = func(body []byte) bool {
+ tools := gjson.GetBytes(body, "tools").Array()
+ if len(tools) != 3 {
+ return false
+ }
+ extra := tools[2]
+ name := "python"
+ if account == service.AccountTypeOAuth {
+ name = "python__sub2api"
+ }
+ if strings.HasPrefix(transform, "namespace_") && !(transform == "namespace_flatten" && account == service.AccountTypeOAuth) {
+ if extra.Get("type").String() != "namespace" || extra.Get("name").String() != "fixture_tools" {
+ return false
+ }
+ extra = extra.Get("tools.0")
+ }
+ if transform == "namespace_flatten" && account == service.AccountTypeOAuth {
+ name = "fixture_tools__python"
+ }
+ if extra.Get("name").String() != name || extra.Get("parameters.properties.code.type").String() != "string" {
+ return false
+ }
+ core, err := sjson.DeleteBytes(body, "tools.2")
+ return err == nil && httpRebuildToolsAvailable(core)
+ }
+ }
+ runHTTPRebuildFixture(t, account, stream, "previous", "completed", "issue854_auth", "", option)
+ })
+ }
+ }
+ }
+}
+
+// Only the geolocation fact is fake. Repository BindOpenAIRequestTimezone runs
+// on the actual loopback send after transport selection; provider reads bytes.
+type issue854TimezoneSettings struct {
+ omit409SettingsRepo
+ auto bool
+}
+
+func (s *issue854TimezoneSettings) GetValue(ctx context.Context, key string) (string, error) {
+ if key == service.SettingKeyOpenAIRequestTimezoneEnabled {
+ return "true", nil
+ }
+ if key == service.SettingKeyOpenAIRequestTimezoneAuto {
+ if s.auto {
+ return "true", nil
+ }
+ return "false", nil
+ }
+ return s.omit409SettingsRepo.GetValue(ctx, key)
+}
+
+type issue854TimezoneProbe struct{}
+
+func (issue854TimezoneProbe) ProbeProxy(context.Context, string) (*service.ProxyExitInfo, int64, error) {
+ return &service.ProxyExitInfo{IP: "192.0.2.1", Timezone: "Asia/Tokyo"}, 0, nil
+}
+
+func TestIssue854HTTPRouteAdmission(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ for _, fallback := range []bool{false, true} {
+ t.Run(fmt.Sprintf("stream=%t/native_available=%t", stream, fallback), func(t *testing.T) {
+ option := httpRebuildFixtureOptions{}
+ if fallback {
+ extra := issue715AccountsOfType(service.AccountTypeAPIKey)[1]
+ extra.ID, extra.Priority, extra.Schedulable = 3, -100, false
+ extra.Credentials = map[string]any{"api_key": "fixture-unsupported-never-send"}
+ extra.Extra = map[string]any{"openai_copilot_sdk": true}
+ option.extraAccounts = []service.Account{extra}
+ option.afterFirst = func(accounts []service.Account) {
+ accounts[2].Schedulable = true
+ accounts[2].Credentials["base_url"] = accounts[1].Credentials["base_url"]
+ }
+ } else {
+ option.afterFirst = func(accounts []service.Account) {
+ if accounts[1].Extra == nil {
+ accounts[1].Extra = map[string]any{}
+ }
+ accounts[1].Extra["openai_copilot_sdk"] = true
+ }
+ option.refuseCode = "Service temporarily unavailable"
+ }
+ runHTTPRebuildFixture(t, service.AccountTypeAPIKey, stream, "previous", "completed", "issue854_auth", "", option)
+ })
+ }
+ }
+}
diff --git a/backend/internal/handler/openai_issue854_postgres_test.go b/backend/internal/handler/openai_issue854_postgres_test.go
new file mode 100644
index 000000000000..f465962ce77a
--- /dev/null
+++ b/backend/internal/handler/openai_issue854_postgres_test.go
@@ -0,0 +1,125 @@
+//go:build unit && issue854pg
+
+package handler
+
+import (
+ "context"
+ "database/sql"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "github.com/Wei-Shaw/sub2api/internal/server/middleware"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/gin-gonic/gin"
+ _ "github.com/lib/pq"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// Explicit build tag and exact disposable database name prevent this fixture
+// from silently skipping or using an application/production DSN.
+func TestIssue854PostgresRoundtrip(t *testing.T) {
+ dsn := os.Getenv("ISSUE854_TEST_POSTGRES_DSN")
+ u, err := url.Parse(dsn)
+ require.NoError(t, err)
+ require.Contains(t, []string{"127.0.0.1", "localhost"}, u.Hostname())
+ require.Equal(t, "/issue854_fixture", u.Path)
+ db, err := sql.Open("postgres", dsn)
+ require.NoError(t, err)
+ defer func() { _ = db.Close() }()
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
+ defer cancel()
+ require.NoError(t, db.PingContext(ctx))
+ require.NoError(t, repository.ApplyMigrations(ctx, db))
+ repo := repository.NewOpsRepository(db)
+ for _, tc := range []struct {
+ name, scenario, protocol, phase string
+ turn, wire int
+ knownUnsent bool
+ }{
+ {"ws_guard", "issue854_guard_refusal", "websocket", "before_upstream_write", 2, 101, true},
+ {"ws_fresh", "issue854_fresh_refusal", "websocket", "before_dispatch", 1, 101, true},
+ {"sse", "", "sse", "forwarding", 0, 200, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ requestID := "fixture-issue854-pg-" + tc.name
+ _, err := db.ExecContext(ctx, "DELETE FROM ops_error_logs WHERE request_id=$1", requestID)
+ require.NoError(t, err)
+ t.Cleanup(func() {
+ _, _ = db.ExecContext(context.Background(), "DELETE FROM ops_error_logs WHERE request_id=$1", requestID)
+ })
+ if tc.scenario != "" {
+ runReadableWSContinuation(t, service.OpenAIWSIngressModePassthrough, tc.scenario, repo)
+ } else {
+ setupOpsErrorLogTestQueue(t, 4)
+ ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ router := gin.New()
+ done := make(chan struct{}, 1)
+ router.Use(func(c *gin.Context) { c.Next(); done <- struct{}{} })
+ router.Use(middleware.RequestLogger(), OpsErrorLoggerMiddleware(ops))
+ router.POST("/v1/responses", func(c *gin.Context) {
+ service.SetOpenAIClientTransport(c, service.OpenAIClientTransportHTTP)
+ setOpsRequestContext(c, "fixture-model", true)
+ c.Header("Content-Type", "text/event-stream")
+ c.Status(http.StatusOK)
+ c.Writer.Flush()
+ h := &OpenAIGatewayHandler{}
+ require.True(t, h.handleOpenAIAgentRecoveryError(c, &service.OpenAIAgentRecoveryError{Reason: "owner_unavailable"}, true))
+ })
+ server := httptest.NewServer(router)
+ defer server.Close()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, server.URL+"/v1/responses", nil)
+ require.NoError(t, err)
+ req.Header.Set("X-Request-ID", requestID)
+ response, err := server.Client().Do(req)
+ require.NoError(t, err)
+ body, err := io.ReadAll(response.Body)
+ _ = response.Body.Close()
+ require.NoError(t, err)
+ require.Equal(t, 200, response.StatusCode)
+ require.Contains(t, string(body), "encrypted_agent_recovery_owner_unavailable")
+ <-done
+ for len(opsErrorLogQueue) > 0 {
+ flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue})
+ }
+ }
+ // Real repository query, not the capture stub. Count and read back
+ // committed rows after OpsService -> INSERT through the real pool.
+ var count int
+ require.NoError(t, db.QueryRowContext(ctx, "SELECT COUNT(*) FROM ops_error_logs WHERE request_id=$1", requestID).Scan(&count))
+ require.Equal(t, 1, count, "one terminal failure must be committed")
+ listed, err := repo.ListErrorLogs(ctx, &service.OpsErrorLogFilter{RequestID: requestID, View: "all", Page: 1, PageSize: 10})
+ require.NoError(t, err)
+ require.Len(t, listed.Errors, 1, "wire101/200 failure must be searchable as an error")
+ row, err := repo.GetErrorLogByID(ctx, listed.Errors[0].ID)
+ require.NoError(t, err)
+ require.Equal(t, requestID, row.RequestID)
+ require.Equal(t, 409, row.StatusCode)
+ require.Nil(t, row.UpstreamStatusCode)
+ require.Equal(t, "internal", row.Phase)
+ require.Equal(t, "platform", row.Owner)
+ fields := gjson.Get(row.ErrorBody, "error")
+ require.Equal(t, "encrypted_agent_recovery_owner_unavailable", fields.Get("code").String())
+ require.Equal(t, tc.protocol, fields.Get("protocol").String())
+ require.EqualValues(t, tc.turn, fields.Get("turn").Int())
+ require.Equal(t, tc.phase, fields.Get("phase").String())
+ require.EqualValues(t, tc.wire, fields.Get("wire_status").Int())
+ require.EqualValues(t, 409, fields.Get("status").Int())
+ require.Equal(t, "failed", fields.Get("outcome").String())
+ if tc.knownUnsent {
+ require.Equal(t, gjson.False, fields.Get("request_written").Type)
+ } else {
+ require.False(t, fields.Get("request_written").Exists(), "unknown send state must not be fabricated")
+ }
+ require.NotContains(t, row.ErrorBody, "fixture-opaque")
+ t.Logf("PostgreSQL INSERT/readback: %s wire=%d logical=409 turn=%d rows=%d", tc.name, tc.wire, tc.turn, count)
+ require.Positive(t, row.ID)
+ })
+ }
+}
diff --git a/backend/internal/handler/openai_issue854_upstream_test.go b/backend/internal/handler/openai_issue854_upstream_test.go
new file mode 100644
index 000000000000..ddfced383970
--- /dev/null
+++ b/backend/internal/handler/openai_issue854_upstream_test.go
@@ -0,0 +1,197 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ "github.com/Wei-Shaw/sub2api/internal/server/middleware"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/Wei-Shaw/sub2api/internal/testutil"
+ coderws "github.com/coder/websocket"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+func TestIssue854UpstreamOwnerRateLimit(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ for _, code := range []string{"encrypted_agent_recovery_owner_rate_limited", "encrypted_agent_recovery_untrusted_fixture"} {
+ t.Run(fmt.Sprintf("stream=%v/%s", stream, code), func(t *testing.T) {
+ setupOpsErrorLogTestQueue(t, 4)
+ var sends atomic.Int32
+ provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ sends.Add(1)
+ body, err := io.ReadAll(r.Body)
+ if err != nil || gjson.GetBytes(body, "model").String() != "gpt-5.1" {
+ t.Error("invalid fixture provider request")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusTooManyRequests)
+ _, _ = fmt.Fprintf(w, `{"error":{"type":"rate_limit_error","code":%q,"message":"fixture-private-provider-diagnostic","param":"fixture-private-param"}}`, code)
+ }))
+ defer provider.Close()
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ accounts := issue715AccountsOfType(service.AccountTypeAPIKey)
+ for i := range accounts {
+ accounts[i].Credentials = map[string]any{"base_url": provider.URL, "api_key": "fixture-owner-limit"}
+ }
+ h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, testutil.NewRealHTTPUpstream(cfg), nil, nil, &readable409UsageRepo{}, accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ h.maxAccountSwitches = 1
+ key := &service.APIKey{ID: 99, UserID: 100, Key: "fixture-issue854-client", Status: service.StatusActive, AllowLongContext: true,
+ User: &service.User{ID: 100, Status: service.StatusActive},
+ Group: &service.Group{ID: 3132, Platform: service.PlatformOpenAI, Status: service.StatusActive, Hydrated: true}}
+ key.GroupID = &key.Group.ID
+ h.apiKeyService = service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg)
+ repo := &ingressRejectOpsRepo{}
+ ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ done := make(chan struct{}, 1)
+ router := gin.New()
+ router.Use(func(c *gin.Context) { c.Next(); done <- struct{}{} })
+ router.Use(OpsErrorLoggerMiddleware(ops))
+ router.Use(gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(h.apiKeyService, nil, cfg)))
+ router.POST("/v1/responses", h.Responses)
+ gateway := httptest.NewServer(router)
+ defer gateway.Close()
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(fmt.Sprintf(`{"model":"gpt-5.1","stream":%v,"input":"fixture continuation"}`, stream)))
+ require.NoError(t, err)
+ req.Header.Set("Authorization", "Bearer "+key.Key)
+ req.Header.Set("Content-Type", "application/json")
+ res, err := gateway.Client().Do(req)
+ require.NoError(t, err)
+ body, err := io.ReadAll(res.Body)
+ _ = res.Body.Close()
+ require.NoError(t, err)
+ select {
+ case <-done:
+ case <-ctx.Done():
+ t.Fatal("rate limit handler did not finish")
+ }
+ require.Equal(t, 429, res.StatusCode)
+ require.GreaterOrEqual(t, sends.Load(), int32(1))
+ require.LessOrEqual(t, sends.Load(), int32(2), "rejection recovery is bounded")
+ if code == "encrypted_agent_recovery_owner_rate_limited" {
+ require.Equal(t, code, gjson.GetBytes(body, "error.code").String(), "ISSUE854_OWNER_LIMIT_CODE_LOST")
+ } else {
+ require.NotContains(t, string(body), code, "arbitrary recovery-prefixed codes are not trusted")
+ }
+ require.NotContains(t, string(body), "fixture-private")
+ for len(opsErrorLogQueue) > 0 {
+ flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue})
+ }
+ require.Len(t, repo.entries, 1)
+ require.Equal(t, 429, repo.entries[0].StatusCode)
+ if code == "encrypted_agent_recovery_owner_rate_limited" {
+ require.Equal(t, code, gjson.Get(repo.entries[0].ErrorBody, "error.code").String())
+ }
+ })
+ }
+ }
+}
+
+func TestIssue854WSOwnerRateLimit(t *testing.T) {
+ for _, mode := range readableWSModes {
+ for _, code := range []string{"encrypted_agent_recovery_owner_rate_limited", "encrypted_agent_recovery_untrusted_fixture"} {
+ t.Run(mode+"/"+code, func(t *testing.T) {
+ setupOpsErrorLogTestQueue(t, 4)
+ var sends atomic.Int32
+ provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ answer := fmt.Sprintf(`{"error":{"type":"rate_limit_error","code":%q,"message":"fixture-private-owner-limit","param":"fixture-private-param"}}`, code)
+ if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
+ sends.Add(1)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusTooManyRequests)
+ _, _ = io.WriteString(w, answer)
+ return
+ }
+ conn, err := coderws.Accept(w, r, nil)
+ if err != nil {
+ return
+ }
+ defer func() { _ = conn.CloseNow() }()
+ if _, _, err := conn.Read(r.Context()); err != nil {
+ return
+ }
+ sends.Add(1)
+ answer = `{"type":"error","status":429,` + strings.TrimPrefix(answer, "{")
+ _ = conn.Write(r.Context(), coderws.MessageText, []byte(answer))
+ // Keep the provider alive until the gateway finishes its
+ // error decision, rather than racing an unrelated EOF.
+ _, _, _ = conn.Read(r.Context())
+ }))
+ defer provider.Close()
+ repo := &ingressRejectOpsRepo{}
+ headers := http.Header{"Session_id": {"fixture-ws-owner-limit"}, "Authorization": {"Bearer sk-handler-cyber-test"}}
+ h := newOpenAIWSPassthroughHandlerHarnessWithAuth(t, provider.URL, headers,
+ map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "false"},
+ repository.NewGatewayCache(issue805Redis(t)()), nil,
+ func(h *OpenAIGatewayHandler) {
+ h.opsService = service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ },
+ func(key *service.APIKey, cfg *config.Config) *service.APIKeyService {
+ key.Status, key.AllowLongContext = service.StatusActive, true
+ key.User.Concurrency = 1
+ key.Group = &service.Group{ID: *key.GroupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, Hydrated: true}
+ return service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg)
+ },
+ func(a *service.Account, cfg *config.Config, _ *service.HTTPUpstream, accountRepo *service.AccountRepository) {
+ a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode
+ cfg.Gateway.MaxAccountSwitches = 0
+ *accountRepo = &readableWSAccounts{issue600SwitchRepo: &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a}}}}
+ })
+ finished := false
+ defer func() {
+ if !finished {
+ issue600Finish(t, h, headers)
+ }
+ }()
+ issue715WSSend(t, h.clientConn, `{"type":"response.create","model":"gpt-5.1","input":"fixture owner limit"}`)
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ defer cancel()
+ var frames []byte
+ for {
+ _, raw, err := h.clientConn.Read(ctx)
+ frames = append(frames, raw...)
+ if err != nil {
+ require.Equal(t, coderws.StatusTryAgainLater, coderws.CloseStatus(err))
+ break
+ }
+ }
+ select {
+ case <-h.handlerDone:
+ case <-ctx.Done():
+ t.Fatal("WS owner limit handler did not finish")
+ }
+ finished = true
+ require.EqualValues(t, 1, sends.Load(), "exhausted owner limit must not replay the generation")
+ for len(opsErrorLogQueue) > 0 {
+ flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue})
+ }
+ require.Len(t, repo.entries, 1)
+ require.Equal(t, 429, repo.entries[0].StatusCode)
+ if code == "encrypted_agent_recovery_owner_rate_limited" {
+ require.Equal(t, code, gjson.GetBytes(frames, "error.code").String(), "ISSUE854_WS_OWNER_LIMIT_CODE_LOST")
+ require.Equal(t, code, gjson.Get(repo.entries[0].ErrorBody, "error.code").String())
+ } else {
+ require.NotContains(t, string(frames), code)
+ require.NotContains(t, repo.entries[0].ErrorBody, code)
+ }
+ require.NotContains(t, string(frames), "fixture-private")
+ })
+ }
+ }
+}
diff --git a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go
index 39a4f33bab4d..91ad9536b01b 100644
--- a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go
+++ b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go
@@ -60,6 +60,10 @@ func newOpenAIWSPassthroughHandlerHarnessWithKey(t *testing.T, upstreamURL strin
}
func newOpenAIWSPassthroughHandlerHarnessWithAudit(t *testing.T, upstreamURL string, clientHeaders http.Header, extraSettings map[string]string, gatewayCache service.GatewayCache, configureKey func(*service.APIKey), configureHandler func(*OpenAIGatewayHandler), configure ...func(*service.Account, *config.Config, *service.HTTPUpstream, *service.AccountRepository)) *openAIWSPassthroughHandlerHarness {
+ return newOpenAIWSPassthroughHandlerHarnessWithAuth(t, upstreamURL, clientHeaders, extraSettings, gatewayCache, configureKey, configureHandler, nil, configure...)
+}
+
+func newOpenAIWSPassthroughHandlerHarnessWithAuth(t *testing.T, upstreamURL string, clientHeaders http.Header, extraSettings map[string]string, gatewayCache service.GatewayCache, configureKey func(*service.APIKey), configureHandler func(*OpenAIGatewayHandler), authSetup func(*service.APIKey, *config.Config) *service.APIKeyService, configure ...func(*service.Account, *config.Config, *service.HTTPUpstream, *service.AccountRepository)) *openAIWSPassthroughHandlerHarness {
t.Helper()
if gatewayCache == nil {
gatewayCache = testutil.NewRedisGatewayCache(t)
@@ -166,23 +170,34 @@ func newOpenAIWSPassthroughHandlerHarnessWithAudit(t *testing.T, upstreamURL str
return zapcore.NewTee(core, requestCore)
}))
c.Request = c.Request.WithContext(logger.IntoContext(c.Request.Context(), observed))
- c.Set(string(middleware.ContextKeyAPIKey), apiKey)
- c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
+ if authSetup == nil {
+ c.Set(string(middleware.ContextKeyAPIKey), apiKey)
+ c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1})
+ }
c.Next()
})
- router.GET("/openai/v1/responses", func(c *gin.Context) {
- h.ResponsesWebSocket(c)
+ if authSetup != nil {
+ h.apiKeyService = authSetup(apiKey, cfg)
+ router.Use(gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(h.apiKeyService, nil, cfg)))
+ }
+ router.Use(func(c *gin.Context) {
+ c.Next()
finalHeaders <- c.Request.Header.Clone()
handlerDone <- struct{}{}
})
+ if h.opsService != nil {
+ router.Use(middleware.RequestLogger(), OpsErrorLoggerMiddleware(h.opsService))
+ }
+ router.GET("/openai/v1/responses", h.ResponsesWebSocket)
handlerServer := httptest.NewServer(router)
t.Cleanup(handlerServer.Close)
wsURL := "ws" + strings.TrimPrefix(handlerServer.URL, "http") + "/openai/v1/responses"
dialCtx, cancelDial := context.WithTimeout(context.Background(), 3*time.Second)
- clientConn, _, err := coderws.Dial(dialCtx, wsURL, &coderws.DialOptions{HTTPHeader: clientHeaders})
+ clientConn, response, err := coderws.Dial(dialCtx, wsURL, &coderws.DialOptions{HTTPHeader: clientHeaders})
cancelDial()
require.NoError(t, err)
+ require.Equal(t, http.StatusSwitchingProtocols, response.StatusCode)
t.Cleanup(func() { _ = clientConn.CloseNow() })
return &openAIWSPassthroughHandlerHarness{
diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go
index cd4cd929ac1c..76d784caaa90 100644
--- a/backend/internal/handler/ops_error_logger.go
+++ b/backend/internal/handler/ops_error_logger.go
@@ -1149,7 +1149,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
// Trust only the forwarding boundary's local marker. The captured SSE
// parser cannot distinguish a bridge failure from an upstream failure and
// otherwise overwrites real HTTP 200 evidence with a synthetic 502.
- if marked, ok := service.GetOpsStreamError(c); ok && (marked.BridgeFailure != nil || marked.TransportFailure != nil) {
+ if marked, ok := service.GetOpsStreamError(c); ok && (marked.BridgeFailure != nil || marked.TransportFailure != nil || marked.RecoveryFailure != nil) {
// A trusted final marker must not erase failures from earlier WS turns.
logOpsStreamError(c, ops, status)
return
@@ -1545,6 +1545,17 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus
errorBody = string(payload)
}
}
+ if failure := streamErr.RecoveryFailure; failure != nil {
+ fields := gin.H{"type": normalizedType, "code": streamErr.Code, "message": streamErr.Message,
+ "protocol": failure.Protocol, "turn": streamErr.Turn, "phase": failure.Phase, "outcome": "failed",
+ "wire_status": wireStatus, "status": streamErr.IntendedStatus}
+ if failure.RequestWritten != nil {
+ fields["request_written"] = *failure.RequestWritten
+ }
+ if payload, err := json.Marshal(gin.H{"error": fields}); err == nil {
+ errorBody = string(payload)
+ }
+ }
if streamErr.BridgeFailure != nil {
if payload, err := json.Marshal(gin.H{"error": streamErr.BridgeFailure.Details()}); err == nil {
errorBody = string(payload)
@@ -1654,6 +1665,12 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus
}
entry.UpstreamErrorMessage, entry.UpstreamErrorDetail = nil, nil
}
+ if streamErr.RecoveryFailure != nil {
+ entry.ErrorPhase, entry.ErrorOwner, entry.ErrorSource = "internal", "platform", "gateway"
+ entry.IsBusinessLimited = false
+ entry.UpstreamStatusCode, entry.UpstreamErrorMessage, entry.UpstreamErrorDetail = nil, nil, nil
+ entry.UpstreamErrors = nil
+ }
if streamErr.TransportFailure != nil {
entry.ErrorPhase, entry.ErrorType = "network", "transport_error"
entry.ErrorOwner, entry.ErrorSource, entry.Severity = "provider", "upstream_transport", "error"
diff --git a/backend/internal/handler/pr610_queue_wait_test.go b/backend/internal/handler/pr610_queue_wait_test.go
index 1fd421445a5a..398748b8bd43 100644
--- a/backend/internal/handler/pr610_queue_wait_test.go
+++ b/backend/internal/handler/pr610_queue_wait_test.go
@@ -55,6 +55,8 @@ type pr610TimingScenario struct {
longFirst bool
attempts atomic.Int32
mu sync.Mutex
+ frameSentAt map[int32]time.Time
+ providerWait map[int32]time.Duration
gated map[string]bool
barriers chan pr610Barrier
deltaRead chan struct{}
@@ -63,7 +65,7 @@ type pr610TimingScenario struct {
func newPR610Scenario(t *testing.T, mode string) *pr610TimingScenario {
t.Helper()
- s := &pr610TimingScenario{t: t, mode: mode, base: time.Now(), barriers: make(chan pr610Barrier), deltaRead: make(chan struct{}), gated: map[string]bool{}}
+ s := &pr610TimingScenario{t: t, mode: mode, base: time.Now(), barriers: make(chan pr610Barrier), deltaRead: make(chan struct{}), gated: map[string]bool{}, frameSentAt: map[int32]time.Time{}, providerWait: map[int32]time.Duration{}}
raw := testutil.NewRedisConcurrencyCache(t)
q, ok := raw.(service.APIKeySlotQueueCache)
require.True(t, ok)
@@ -141,6 +143,7 @@ func (s *pr610TimingScenario) prepareTurn() {
}
s.mu.Lock()
s.gated = map[string]bool{}
+ s.frameSentAt[turn] = time.Now()
s.mu.Unlock()
phases := []string{"user", "account"}
if s.failover && turn == 2 {
@@ -210,7 +213,17 @@ func (s *pr610TimingScenario) afterDelta() {
s.advance(80 * time.Second)
}
}
+
+// Capture the real client-send-to-provider boundary independently of the
+// production timing arithmetic. Hosted-runner scheduling can extend waits.
+func (s *pr610TimingScenario) observeProvider() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ turn := s.turn.Load()
+ s.providerWait[turn] = time.Since(s.frameSentAt[turn])
+}
func (s *pr610TimingScenario) writeWS(c *coderws.Conn, turn int, payload []byte) {
+ s.observeProvider()
s.advance(2 * time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
@@ -222,6 +235,7 @@ func (s *pr610TimingScenario) serveHTTP(w http.ResponseWriter, r *http.Request,
if s.mode != service.OpenAIWSIngressModeHTTPBridge {
return false
}
+ s.observeProvider()
payload, err := io.ReadAll(r.Body)
require.NoError(s.t, err)
if (s.failover || s.sameAccount) && s.turn.Load() == 2 && r.Header.Get("Authorization") == "Bearer fixture-account-a" && s.failedSwitch.CompareAndSwap(false, true) {
@@ -390,7 +404,11 @@ func TestPR610RealWaitNativeIngress(t *testing.T) {
}
require.NotNil(t, row.QueueWaitMs, "native authenticated turn must retain a measured wait")
require.GreaterOrEqual(t, *row.QueueWaitMs, want-10, "accepted frame must count real blocked acquisition before forward")
- require.Less(t, *row.QueueWaitMs, want+150, "each wait must be counted once, without previous-turn tail")
+ s.mu.Lock()
+ observed := s.providerWait[int32(i+1)]
+ s.mu.Unlock()
+ require.Positive(t, observed, "fixture must observe the actual provider receive")
+ require.LessOrEqual(t, int64(*row.QueueWaitMs), observed.Milliseconds()+2, "queue cannot exceed this turn's real client-to-provider interval or include the previous turn")
require.NotNil(t, row.QueueTiming, "measured source must survive authenticated production usage path")
require.InDelta(t, 20, *row.QueueTiming.ForwardFirstTokenMs, 100)
require.GreaterOrEqual(t, *row.QueueTiming.ServerFirstTokenMs, int64(want+10))
diff --git a/backend/internal/service/issue842_gateway_test_support.go b/backend/internal/service/issue842_gateway_test_support.go
new file mode 100644
index 000000000000..43ad7b1a87fa
--- /dev/null
+++ b/backend/internal/service/issue842_gateway_test_support.go
@@ -0,0 +1,38 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/url"
+)
+
+// RouteIssue842OAuthSocketsToLoopbackForTest retains the production OAuth
+// builder, admission and frame writer. Only its fixed external dial address is
+// replaced, by the real socket dialer, in a unit-only localhost fixture.
+func RouteIssue842OAuthSocketsToLoopbackForTest(s *OpenAIGatewayService, target string) error {
+ u, err := url.Parse(target)
+ if err != nil || u == nil || u.Hostname() != "127.0.0.1" || u.Scheme != "http" {
+ return fmt.Errorf("Issue842 socket fixture requires loopback HTTP")
+ }
+ u.Scheme = "ws"
+ u.Path = "/v1/responses"
+ dialer := &issue842LoopbackDialer{target: u.String(), delegate: newConfiguredOpenAIWSClientDialer(s.cfg)}
+ s.getOpenAIWSConnPool().setClientDialerForTest(dialer)
+ s.openaiWSPassthroughDialerOnce.Do(func() { s.openaiWSPassthroughDialer = dialer })
+ return nil
+}
+
+type issue842LoopbackDialer struct {
+ target string
+ delegate openAIWSClientDialer
+}
+
+func (d *issue842LoopbackDialer) Dial(ctx context.Context, address string, headers http.Header, proxy string) (openAIWSClientConn, int, http.Header, error) {
+ if address != "wss://chatgpt.com/backend-api/codex/responses" || proxy != "" {
+ return nil, 0, nil, fmt.Errorf("Issue842 refuses unexpected OAuth socket destination")
+ }
+ return d.delegate.Dial(ctx, d.target, headers, "")
+}
diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go
index a947ff64affb..d259eced63b3 100644
--- a/backend/internal/service/openai_409_omit_history.go
+++ b/backend/internal/service/openai_409_omit_history.go
@@ -409,7 +409,7 @@ func openAI409ReadableMetadata(value any) any {
}
func prepareOpenAI409KnownReadableReplay(raw []byte) ([]byte, error) {
- clean, _, err := sanitizeOpenAIResponsesInputItemIDs(raw)
+ clean, err := normalizeOpenAIReplayMetadata(raw)
if err != nil {
return nil, err
}
@@ -613,6 +613,21 @@ func (s *OpenAIGatewayService) prepareOpenAI409HTTPProjection(ctx context.Contex
if err != nil {
return ctx, body, err
}
+ // Match the existing native builder's empty-image sanitation before
+ // freezing this projected representation. Keep readable text, completed
+ // tool results, order and exact JSON numbers; do not rebase at final send.
+ if openAIRequestBodyMayContainEmptyBase64InputImage(clean) {
+ var decoded map[string]any
+ if err := decodeOpenAIJSONUseNumber(clean, &decoded); err != nil {
+ return ctx, body, err
+ }
+ if sanitizeEmptyBase64InputImagesInOpenAIRequestBodyMap(decoded) {
+ clean, err = json.Marshal(decoded)
+ if err != nil {
+ return ctx, body, err
+ }
+ }
+ }
snapshot := *r
snapshot.inputDigest = openAIAgentRecoveryInputDigest(clean)
snapshot.replayControlsDigest = openAI409ControlsDigest(clean)
diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go
index db80033374eb..36947164e9ce 100644
--- a/backend/internal/service/openai_agent_message_recovery.go
+++ b/backend/internal/service/openai_agent_message_recovery.go
@@ -51,6 +51,9 @@ type openAIAgentRecoveryRequest struct {
disableOwnerBinding bool
previousResponseID string
inputDigest [32]byte
+ replaySource []byte // immutable pre-builder source, never a retry's mutable wire
+ nativeOAuthInput [32]byte
+ nativeOAuthPrepared bool
replayControlsDigest [32]byte
apiControlsDigest [32]byte
apiInputDigest [32]byte
@@ -123,6 +126,7 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex
request.items = openAIAgentRecoveryItemDigests(body)
if request.preservesHistory() {
request.inputDigest = openAIAgentRecoveryInputDigest(body)
+ request.replaySource = append([]byte(nil), body...)
}
gjson.GetBytes(body, "input").ForEach(func(_, item gjson.Result) bool {
request.toolResult = request.toolResult || isCodexToolCallOutputItemType(item.Get("type").String())
@@ -295,7 +299,10 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryAccount(ctx context.Conte
// even on a pointer-only request with no known opaque item owner.
if request.previousResponseID != "" {
owner, err := s.getOpenAIWSStateStore().GetResponseAccount(ctx, request.groupID, request.previousResponseID)
- if err != nil || owner <= 0 || account == nil || owner != account.ID {
+ if err != nil {
+ return openAIAgentRecoveryError("store_unavailable")
+ }
+ if owner <= 0 || account == nil || owner != account.ID {
return openAIAgentRecoveryError("owner_unavailable")
}
if request.httpResponsePointer && !account.IsOpenAIApiKey() {
@@ -384,7 +391,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
if !account.IsOpenAI() || account.HasManagedOpenAIConnections() || account.AuthConnectionID != "" ||
(account.IsOpenAIPassthroughEnabled() && !openAI409UsesNativeAPIKey(ctx, account)) || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() {
if request.owner != nil || request.preservesHistory() {
- return noop, openAIAgentRecoveryError("wire_changed")
+ return noop, openAIAgentRecoveryRefusal(ctx, "unsupported_adapter")
}
return noop, nil
}
@@ -392,14 +399,14 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" {
return noop, nil
}
- return noop, openAIAgentRecoveryError("wire_changed")
+ return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable")
}
reader, err := req.GetBody()
if err != nil {
if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" {
return noop, nil
}
- return noop, openAIAgentRecoveryError("wire_changed")
+ return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable")
}
body, err := io.ReadAll(reader)
_ = reader.Close()
@@ -407,15 +414,18 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" {
return noop, nil
}
- return noop, openAIAgentRecoveryError("wire_changed")
+ return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable")
}
if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) {
if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" {
return noop, nil
}
- return noop, openAIAgentRecoveryError("wire_changed")
+ return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable")
}
expectedInput, expectedControls := request.inputDigest, request.replayControlsDigest
+ if request.nativeOAuthPrepared && account.UsesOpenAICodexProtocol() && !request.omittedHistory {
+ expectedInput = request.nativeOAuthInput
+ }
if request.omittedHistory && account.IsOpenAIApiKey() && request.apiReplayPrepared {
expectedInput, expectedControls = request.apiInputDigest, request.apiControlsDigest
}
@@ -429,7 +439,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
if request.omittedHistory {
logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", zap.String("stage", "input_integrity"))
}
- return noop, openAIAgentRecoveryError("wire_changed")
+ return noop, openAIAgentRecoveryRefusal(ctx, "input_integrity")
}
if request.omittedHistory && (gjson.GetBytes(body, "previous_response_id").Exists() || gjson.GetBytes(body, "conversation").Exists() ||
openAI409ControlsDigest(body) != expectedControls) {
@@ -459,7 +469,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
return noop, openAIAgentRecoveryError("wire_changed")
}
if request.ownerBindingRequired() && !sameOpenAIAgentRecoveryRoute(*request.owner, binding) {
- return noop, openAIAgentRecoveryError("wire_changed")
+ return noop, openAIAgentRecoveryRefusal(ctx, "route_identity")
}
if err := s.checkOpenAIAgentRecoveryRecords(ctx, request, binding); err != nil {
return noop, err
diff --git a/backend/internal/service/openai_agent_message_recovery_wait.go b/backend/internal/service/openai_agent_message_recovery_wait.go
index 3b993d0ee50d..c5c1a90324dc 100644
--- a/backend/internal/service/openai_agent_message_recovery_wait.go
+++ b/backend/internal/service/openai_agent_message_recovery_wait.go
@@ -3,9 +3,22 @@ package service
import (
"context"
"encoding/hex"
+ "errors"
"time"
)
+// Produced only by the scheduler after checking the proven owner's current
+// route/policy and completed delivery fences. No upstream response or generic
+// authentication/billing error can authorize this pre-dispatch rebuild.
+type openAIInitialOwnerUnavailableError struct{ cause error }
+
+func (e *openAIInitialOwnerUnavailableError) Error() string { return e.cause.Error() }
+func (e *openAIInitialOwnerUnavailableError) Unwrap() error { return e.cause }
+func OpenAIWSInitialOwnerCanRebuild(err error) bool {
+ var unavailable *openAIInitialOwnerUnavailableError
+ return errors.As(err, &unavailable)
+}
+
// A cooldown is not evidence of incompatible ciphertext. Preserve the existing
// evidence while waiting, without admitting a request or guessing another owner.
func (s *defaultOpenAIAccountScheduler) checkOpenAIAgentRecoveryCooldown(ctx context.Context, req OpenAIAccountScheduleRequest, recovery *openAIAgentRecoveryRequest) error {
@@ -33,12 +46,13 @@ func (s *defaultOpenAIAccountScheduler) checkOpenAIAgentRecoveryCooldown(ctx con
if account.OverloadUntil != nil && account.OverloadUntil.After(now) && account.OverloadUntil.After(retryAt) {
retryAt, reason = *account.OverloadUntil, "owner_overloaded"
}
- if retryAt.IsZero() {
+ pausedWSOwner := !account.Schedulable && req.RequiredTransport == OpenAIUpstreamTransportResponsesWebsocketV2Ingress
+ if retryAt.IsZero() && !pausedWSOwner {
return nil
}
// Revocation, manual pauses and credential/route changes still require
// intervention; a future quota reset must not disguise those conditions.
- if !account.IsActive() || !account.Schedulable || account.PerformancePaused ||
+ if !account.IsActive() || (!account.Schedulable && !pausedWSOwner) || account.PerformancePaused ||
(account.AutoPauseOnExpired && account.ExpiresAt != nil && !account.ExpiresAt.After(now)) ||
(account.TempUnschedulableUntil != nil && account.TempUnschedulableUntil.After(now)) ||
(account.SupportsAccountQuota() && account.IsQuotaExceeded()) ||
@@ -68,6 +82,12 @@ func (s *defaultOpenAIAccountScheduler) checkOpenAIAgentRecoveryCooldown(ctx con
if _, excluded := req.ExcludedIDs[account.ID]; excluded {
return openAIAgentRecoveryError("owner_unavailable")
}
+ if pausedWSOwner {
+ if err := s.service.retainOpenAIAgentRecovery(ctx, recovery, s.service.openAIWSSessionStickyTTL()); err != nil {
+ return err
+ }
+ return &openAIInitialOwnerUnavailableError{cause: openAIAgentRecoveryError("owner_unavailable")}
+ }
// Leave a full normal affinity window after reset, even if the client waits
// without polling. These are local observations, not provider-side leases.
ttl := time.Until(retryAt) + s.service.openAIWSSessionStickyTTL()
@@ -102,7 +122,11 @@ func (s *defaultOpenAIAccountScheduler) checkOpenAIAgentRecoveryCooldown(ctx con
if err := s.service.retainOpenAIAgentRecovery(storeCtx, recovery, ttl); err != nil {
return err
}
- return &OpenAIAgentRecoveryError{Reason: reason, RetryAt: retryAt}
+ refusal := &OpenAIAgentRecoveryError{Reason: reason, RetryAt: retryAt}
+ if req.RequiredTransport == OpenAIUpstreamTransportResponsesWebsocketV2Ingress {
+ return &openAIInitialOwnerUnavailableError{cause: refusal}
+ }
+ return refusal
}
func (s *OpenAIGatewayService) retainOpenAIAgentRecovery(ctx context.Context, request *openAIAgentRecoveryRequest, ttl time.Duration) error {
diff --git a/backend/internal/service/openai_agent_replay_metadata.go b/backend/internal/service/openai_agent_replay_metadata.go
new file mode 100644
index 000000000000..c30a6c97cef9
--- /dev/null
+++ b/backend/internal/service/openai_agent_replay_metadata.go
@@ -0,0 +1,153 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "unicode/utf8"
+
+ "github.com/Wei-Shaw/sub2api/internal/pkg/logger"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+ "go.uber.org/zap"
+)
+
+// PrepareOpenAIAgentReplayBody is a pre-snapshot stage, never a final-wire
+// exemption. Only output metadata is portable here. Readable reasoning,
+// ciphertext, tool relationships, array order and JSON numbers remain intact.
+// The caller must forward these bytes and freeze them before account builders.
+func (s *OpenAIGatewayService) PrepareOpenAIAgentReplayBody(body []byte) ([]byte, error) {
+ if !s.preserveOpenAIAgentHistory(body) {
+ return body, nil
+ }
+ if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) {
+ return nil, openAIAgentRecoveryError("wire_changed")
+ }
+ return normalizeOpenAIReplayMetadata(body)
+}
+
+// OAuth forces stateless reasoning even when the client omits store or sends
+// true. Derive only that account's finite metadata projection from the frozen
+// source, before timezone/namespace/OAuth builders. API-key store:true is intact.
+func (s *OpenAIGatewayService) prepareOpenAIAgentOAuthReplay(ctx context.Context, account *Account, body []byte) (context.Context, []byte, error) {
+ r := openAIAgentRecoveryFromContext(ctx)
+ if r == nil || !r.disableOwnerBinding || !r.preservesHistory() || r.omittedHistory || account == nil || !account.UsesOpenAICodexProtocol() {
+ return ctx, body, nil
+ }
+ if len(r.replaySource) == 0 || openAIAgentRecoveryInputDigest(body) != r.inputDigest ||
+ openAI409ControlsDigest(body) != openAI409ControlsDigest(r.replaySource) {
+ return ctx, nil, openAIAgentRecoveryRefusal(ctx, "input_integrity")
+ }
+ projected, err := projectOpenAIOAuthReasoningMetadata(r.replaySource)
+ if err != nil {
+ return ctx, nil, err
+ }
+ next, err := sjson.SetRawBytes(body, "input", []byte(gjson.GetBytes(projected, "input").Raw))
+ if err != nil {
+ return ctx, nil, err
+ }
+ private := *r
+ private.nativeOAuthInput = openAIAgentRecoveryInputDigest(projected)
+ private.nativeOAuthPrepared = true
+ return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &private), next, nil
+}
+
+// Match the existing OAuth stateless reasoning contract without its general
+// input filter: no readable content, ciphertext, item or tool relationship is
+// removed. Missing/null summary becomes []; a nonempty summary stays exact.
+func projectOpenAIOAuthReasoningMetadata(body []byte) ([]byte, error) {
+ var source map[string]any
+ if err := decodeOpenAIJSONUseNumber(body, &source); err != nil {
+ return nil, err
+ }
+ input, _ := source["input"].([]any)
+ for _, value := range input {
+ item, ok := value.(map[string]any)
+ if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "reasoning" {
+ continue
+ }
+ delete(item, "id")
+ if item["summary"] == nil {
+ item["summary"] = []any{}
+ }
+ }
+ encoded, err := json.Marshal(input)
+ if err != nil {
+ return nil, err
+ }
+ return sjson.SetRawBytes(body, "input", encoded)
+}
+
+func normalizeOpenAIResponsesReasoningContentReplayProtected(body []byte, protected bool) ([]byte, bool, error) {
+ if protected {
+ return body, false, nil
+ }
+ return normalizeOpenAIResponsesReasoningContentReplay(body)
+}
+
+func normalizeOpenAIAPIKeyStoreFalseReasoningReplayProtected(body []byte, knownStoreFalse, protected bool) ([]byte, bool, error) {
+ if protected {
+ return body, false, nil
+ }
+ return normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, knownStoreFalse)
+}
+
+// The allowlist is internal and fixed. Never attach bodies, ciphertext, item
+// digests, route URLs or credentials, including in unexpected-stage fallback.
+func openAIAgentRecoveryRefusal(ctx context.Context, stage string) error {
+ switch stage {
+ case "input_integrity", "body_unreadable", "unsupported_adapter", "route_identity":
+ default:
+ stage = "route_identity"
+ }
+ if r := openAIAgentRecoveryFromContext(ctx); r != nil && r.disableOwnerBinding {
+ logger.FromContext(ctx).Warn("openai.encrypted_agent_recovery_refused", zap.String("stage", stage))
+ }
+ return openAIAgentRecoveryError("wire_changed")
+}
+
+// Shared with readable Beta preparation. This deliberately excludes OAuth
+// system promotion, namespace flattening, timezone and call reconstruction.
+func normalizeOpenAIReplayMetadata(body []byte) ([]byte, error) {
+ clean, _, err := sanitizeOpenAIResponsesInputItemIDs(body)
+ if err != nil {
+ return nil, err
+ }
+ var source map[string]any
+ if err := decodeOpenAIJSONUseNumber(clean, &source); err != nil {
+ return nil, err
+ }
+ input, _ := source["input"].([]any)
+ storeFalse := gjson.GetBytes(clean, "store").Type == gjson.False
+ changed := false
+ for _, value := range input {
+ item, ok := value.(map[string]any)
+ if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "reasoning" {
+ continue
+ }
+ if _, exists := item["status"]; exists {
+ delete(item, "status")
+ changed = true
+ }
+ encrypted, _ := item["encrypted_content"].(string)
+ if !storeFalse || strings.TrimSpace(encrypted) == "" {
+ continue
+ }
+ if strings.HasPrefix(strings.TrimSpace(firstNonEmptyString(item["id"])), "rs_") {
+ delete(item, "id")
+ changed = true
+ }
+ if item["summary"] == nil {
+ item["summary"] = []any{}
+ changed = true
+ }
+ }
+ if !changed {
+ return clean, nil
+ }
+ encoded, err := json.Marshal(input)
+ if err != nil {
+ return nil, err
+ }
+ return sjson.SetRawBytes(clean, "input", encoded)
+}
diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go
index 3edf8bdedc4a..28b3a6868d77 100644
--- a/backend/internal/service/openai_gateway_forward.go
+++ b/backend/internal/service/openai_gateway_forward.go
@@ -91,6 +91,11 @@ func prismBrowserResponsesURL(baseURL string) string {
// Forward forwards request to OpenAI API
func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (result *OpenAIForwardResult, resultErr error) {
+ preparedCtx, preparedBody, prepareErr := s.prepareOpenAIAgentOAuthReplay(ctx, account, body)
+ if prepareErr != nil {
+ return nil, prepareErr
+ }
+ ctx, body = preparedCtx, preparedBody
defer func() {
if result != nil && c != nil {
@@ -390,7 +395,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
body = normalized
originalBody = normalized
}
- if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, isOpenAIResponsesCompactPath(c)); normalizeErr != nil {
+ if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplayProtected(body, isOpenAIResponsesCompactPath(c), s.preserveOpenAIAgentHistory(body)); normalizeErr != nil {
return nil, normalizeErr
} else if changed {
body = normalized
@@ -422,7 +427,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
}
SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint)
if account.IsOpenAI() && (account.IsOpenAIApiKey() || account.IsOpenAIOAuthLike()) {
- normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplay(body)
+ normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplayProtected(body, s.preserveOpenAIAgentHistory(body))
if reasoningErr != nil {
return nil, fmt.Errorf("normalize OpenAI Responses reasoning content replay: %w", reasoningErr)
}
@@ -744,7 +749,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
IsCompact: isCompactRequest,
SkipDefaultInstructions: true,
PreserveToolCallIDs: true,
- PreserveReadableReplay: readableReplay,
+ PreserveReadableReplay: readableReplay || openAIAgentRecoveryPreservesHistory(ctx),
OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages,
ResponsesLite: responsesLite,
})
@@ -755,7 +760,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco
IsCodexCLI: isCodexCLI,
IsCompact: isCompactRequest,
SkipDefaultInstructions: readableReplay,
- PreserveReadableReplay: readableReplay,
+ PreserveReadableReplay: readableReplay || openAIAgentRecoveryPreservesHistory(ctx),
OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages,
ResponsesLite: responsesLite,
})
diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go
index a62083f8eec6..10a55f79e051 100644
--- a/backend/internal/service/openai_gateway_request_body.go
+++ b/backend/internal/service/openai_gateway_request_body.go
@@ -1474,7 +1474,8 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac
}
func normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(cfg *config.Config, body []byte, account *Account, responsesLite bool) ([]byte, bool, error) {
- return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{Config: cfg, ResponsesLite: responsesLite})
+ protected := cfg != nil && cfg.Gateway.DisableEncryptedAgentOwnerBinding && len(openAIAgentRecoveryItemDigests(body)) > 0
+ return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{Config: cfg, ResponsesLite: responsesLite, PreserveInput: protected})
}
type openAIResponsesCompatibilityOptions struct {
@@ -1483,6 +1484,9 @@ type openAIResponsesCompatibilityOptions struct {
// Compact marks the /responses/compact wire shape, which is left as-is
// by request-shape compatibility rewrites such as web_search history.
Compact bool
+ // The pre-builder metadata stage already prepared this complete history.
+ // Never drop readable reasoning or whole items in ordinary opt-out mode.
+ PreserveInput bool
}
func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account *Account, opts openAIResponsesCompatibilityOptions) ([]byte, bool, error) {
@@ -1499,11 +1503,13 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account *
return body, false, err
}
}
- if next, normalizedReasoningContent, err := normalizeOpenAIResponsesReasoningContentReplay(normalized); err != nil {
- return body, false, err
- } else if normalizedReasoningContent {
- normalized = next
- changed = true
+ if !opts.PreserveInput {
+ if next, normalizedReasoningContent, err := normalizeOpenAIResponsesReasoningContentReplay(normalized); err != nil {
+ return body, false, err
+ } else if normalizedReasoningContent {
+ normalized = next
+ changed = true
+ }
}
if account.IsOpenAIApiKey() {
if next, normalizedParallel, err := normalizeOpenAIParallelToolCallsWithoutTools(normalized, responsesLite); err != nil {
@@ -1512,11 +1518,13 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account *
normalized = next
changed = true
}
- if next, normalizedReasoning, err := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(normalized, false); err != nil {
- return body, false, err
- } else if normalizedReasoning {
- normalized = next
- changed = true
+ if !opts.PreserveInput {
+ if next, normalizedReasoning, err := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(normalized, false); err != nil {
+ return body, false, err
+ } else if normalizedReasoning {
+ normalized = next
+ changed = true
+ }
}
}
if sanitized, idsChanged, err := sanitizeOpenAIResponsesInputItemIDs(normalized); err != nil {
diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go
index 16f3fa9c7172..024b851779e6 100644
--- a/backend/internal/service/openai_gateway_upstream_errors.go
+++ b/backend/internal/service/openai_gateway_upstream_errors.go
@@ -826,6 +826,11 @@ func (s *OpenAIGatewayService) handleErrorResponse(
return nil, fmt.Errorf("upstream error: %d message=%s", resp.StatusCode, upstreamMsg)
}
+ if code, message, ok := OpenAIUpstreamRecoveryRateLimit(resp.StatusCode, body); ok {
+ setOpsUpstreamError(c, resp.StatusCode, message, "")
+ c.JSON(resp.StatusCode, gin.H{"error": gin.H{"type": "rate_limit_error", "code": code, "message": message}})
+ return nil, fmt.Errorf("upstream owner rate limited: %d", resp.StatusCode)
+ }
// Return appropriate error response
var errType, errMsg string
var statusCode int
diff --git a/backend/internal/service/openai_issue842_replay_test.go b/backend/internal/service/openai_issue842_replay_test.go
new file mode 100644
index 000000000000..2715cbc4babb
--- /dev/null
+++ b/backend/internal/service/openai_issue842_replay_test.go
@@ -0,0 +1,163 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+const issue842Source = `{"model":"gpt-6-astra","store":false,"input":[{"type":"agent_message","author":"fixture-parent","recipient":"fixture-worker","encrypted_content":"fixture-agent842"},{"type":"reasoning","status":"completed","id":"rs_fixture842","summary":[],"content":[{"type":"reasoning_text","text":"readable reasoning842"}],"encrypted_content":"fixture-reasoning842"},{"type":"message","role":"user","content":"keep task842","sequence":9007199254740993},{"type":"function_call","name":"record","call_id":"fc_fixture842","arguments":"{\"n\":9007199254740993}"},{"type":"function_call_output","call_id":"fc_fixture842","output":"already recorded842"}]}`
+
+func TestIssue842FrozenWSInputRejectsSemanticMutation(t *testing.T) {
+ for _, mutation := range []string{"intact", "agent_cipher", "author", "reasoning_cipher", "readable_reasoning", "task", "arguments", "result", "pair", "order", "precision", "drop_reasoning", "inject_status", "mutate_source"} {
+ t.Run(mutation, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ manager, _, account := issue715WSManager(t, svc, context.Background())
+ defer manager.abort()
+ source := []byte(issue842Source)
+ original := append([]byte(nil), source...)
+ // Keep historical production-overlay assemblies compilable. The
+ // exact candidate must provide the pre-builder preparation method.
+ preparer, ok := any(manager).(interface {
+ prepareReadable(*Account, []byte) ([]byte, error)
+ })
+ require.True(t, ok)
+ payload, err := preparer.prepareReadable(account, source)
+ require.NoError(t, err)
+ require.Equal(t, original, source, "preparation must not mutate the original frame")
+ path, value := "", "changed842"
+ switch mutation {
+ case "agent_cipher":
+ path = "input.0.encrypted_content"
+ case "author":
+ path = "input.0.author"
+ case "reasoning_cipher":
+ path = "input.1.encrypted_content"
+ case "readable_reasoning":
+ path = "input.1.content.0.text"
+ case "task", "mutate_source":
+ path = "input.2.content"
+ case "arguments":
+ path = "input.3.arguments"
+ case "result":
+ path = "input.4.output"
+ case "pair":
+ path = "input.4.call_id"
+ case "inject_status":
+ path, value = "input.1.status", "completed"
+ case "precision":
+ payload, err = sjson.SetRawBytes(payload, "input.2.sequence", []byte("9007199254740992"))
+ case "drop_reasoning":
+ payload, err = sjson.DeleteBytes(payload, "input.1")
+ case "order":
+ items := gjson.GetBytes(payload, "input").Array()
+ items[0], items[2] = items[2], items[0]
+ var raw []string
+ for _, item := range items {
+ raw = append(raw, item.Raw)
+ }
+ payload, err = sjson.SetRawBytes(payload, "input", []byte("["+strings.Join(raw, ",")+"]"))
+ }
+ require.NoError(t, err)
+ if path != "" {
+ payload, err = sjson.SetBytes(payload, path, value)
+ require.NoError(t, err)
+ }
+ if mutation == "mutate_source" {
+ source = append([]byte(nil), payload...)
+ }
+ err = manager.beginSocket(account, source, payload, "wss://native.example/v1/responses", http.Header{"Authorization": {"Bearer fixture"}}, "ctx_pool")
+ if mutation == "intact" {
+ require.NoError(t, err)
+ require.Contains(t, string(payload), "readable reasoning842")
+ require.Contains(t, string(payload), "9007199254740993")
+ } else {
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal, "a frozen snapshot cannot trust later source or wire mutation")
+ require.Equal(t, "wire_changed", refusal.Reason)
+ }
+ })
+ }
+}
+
+func TestIssue842FrozenHTTPInputRejectsSemanticMutation(t *testing.T) {
+ for _, replacement := range []string{"fixture-agent842", "readable reasoning842", "keep task842", "9007199254740993", "already recorded842"} {
+ t.Run(replacement, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ c, _ := newTurnStateTestContext(t, 715, "fixture-session")
+ c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)})
+ // Explicit expected metadata normalization, independent of helper.
+ body := strings.ReplaceAll(strings.ReplaceAll(issue842Source, `,"status":"completed"`, ""), `,"id":"rs_fixture842"`, "")
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra")
+ mutated := strings.Replace(body, replacement, replacement+"-changed", 1)
+ if replacement == "9007199254740993" {
+ mutated = strings.Replace(body, replacement, "9007199254740992", 1)
+ }
+ req, err := http.NewRequest(http.MethodPost, "https://fixture.example/v1/responses", bytes.NewBufferString(mutated))
+ require.NoError(t, err)
+ _, err = svc.prepareOpenAIAgentRecoveryAttempt(ctx, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req)
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal)
+ require.Equal(t, "wire_changed", refusal.Reason)
+ })
+ }
+}
+
+func TestIssue842OAuthProjectionRejectsChangedSourceOrWire(t *testing.T) {
+ for _, mutation := range []string{"intact", "source_input", "source_controls", "final_input"} {
+ t.Run(mutation, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ c, _ := newTurnStateTestContext(t, 715, "fixture-session")
+ c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)})
+ body := []byte(strings.ReplaceAll(strings.ReplaceAll(issue842Source, `,"status":"completed"`, ""), `"store":false,`, ""))
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, body, "fixture-session", "gpt-6-astra")
+ switch mutation {
+ case "source_input":
+ body = bytes.Replace(body, []byte("keep task842"), []byte("changed task842"), 1)
+ case "source_controls":
+ var err error
+ body, err = sjson.SetBytes(body, "instructions", "unapproved instruction842")
+ require.NoError(t, err)
+ }
+ // Historical overlay compiles against its old service; this method is
+ // required only when this exact candidate regression actually runs.
+ preparer, ok := any(svc).(interface {
+ prepareOpenAIAgentOAuthReplay(context.Context, *Account, []byte) (context.Context, []byte, error)
+ })
+ require.True(t, ok)
+ account := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth}
+ preparedCtx, prepared, err := preparer.prepareOpenAIAgentOAuthReplay(ctx, account, body)
+ if strings.HasPrefix(mutation, "source_") {
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal)
+ require.Equal(t, "wire_changed", refusal.Reason)
+ return
+ }
+ require.NoError(t, err)
+ if mutation == "final_input" {
+ prepared = bytes.Replace(prepared, []byte("readable reasoning842"), []byte("changed reasoning842"), 1)
+ }
+ req, err := http.NewRequest(http.MethodPost, "https://fixture.example/v1/responses", bytes.NewReader(prepared))
+ require.NoError(t, err)
+ finish, err := svc.prepareOpenAIAgentRecoveryAttempt(preparedCtx, account, req)
+ if mutation == "intact" {
+ require.NoError(t, err)
+ finish(true)
+ } else {
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal)
+ require.Equal(t, "wire_changed", refusal.Reason)
+ }
+ })
+ }
+}
diff --git a/backend/internal/service/openai_issue854_http_projection_test.go b/backend/internal/service/openai_issue854_http_projection_test.go
new file mode 100644
index 000000000000..083d78d44e15
--- /dev/null
+++ b/backend/internal/service/openai_issue854_http_projection_test.go
@@ -0,0 +1,54 @@
+//go:build unit && issue854matrix
+
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/sjson"
+)
+
+func TestIssue854HTTPProjectionIntegrity(t *testing.T) {
+ for _, mutation := range []string{"none", "task_before", "tools_before", "task_after", "tools_after"} {
+ t.Run(mutation, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)}
+ body := []byte(`{"model":"gpt-5.1","input":[{"type":"message","role":"user","namespace":"client_metadata","content":"reuse the completed patch"}],"tools":[{"type":"function","name":"verify","parameters":{"type":"object"}}]}`)
+ r := &openAIAgentRecoveryRequest{omittedHistory: true, inputDigest: openAIAgentRecoveryInputDigest(body), replayControlsDigest: openAI409ControlsDigest(body)}
+ originalInput, originalControls := r.inputDigest, r.replayControlsDigest
+ ctx := context.WithValue(context.Background(), openAIAgentRecoveryContextKey{}, r)
+ c, _ := newTurnStateTestContext(t, 715, "fixture-session")
+ switch mutation {
+ case "task_before":
+ body, _ = sjson.SetBytes(body, "input.0.content", "repeat the patch")
+ case "tools_before":
+ body, _ = sjson.DeleteBytes(body, "tools")
+ }
+ projected, clean, err := svc.prepareOpenAI409HTTPProjection(ctx, c, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, body)
+ if mutation == "task_before" || mutation == "tools_before" {
+ require.Error(t, err)
+ require.Same(t, r, openAIAgentRecoveryFromContext(projected))
+ } else {
+ require.NoError(t, err)
+ require.NotSame(t, r, openAIAgentRecoveryFromContext(projected))
+ require.NotContains(t, string(clean), "client_metadata")
+ if mutation == "task_after" {
+ clean, _ = sjson.SetBytes(clean, "input.0.content", "repeat the patch")
+ }
+ if mutation == "tools_after" {
+ clean, _ = sjson.DeleteBytes(clean, "tools")
+ }
+ _, err = prepareOpenAI409APIKeyReplay(projected, clean, false)
+ if mutation == "none" {
+ require.NoError(t, err)
+ } else {
+ require.Error(t, err)
+ }
+ }
+ require.Equal(t, originalInput, r.inputDigest, "projection cannot overwrite the trusted input")
+ require.Equal(t, originalControls, r.replayControlsDigest, "projection cannot overwrite trusted controls")
+ })
+ }
+}
diff --git a/backend/internal/service/openai_upstream_client_error.go b/backend/internal/service/openai_upstream_client_error.go
index 431f5a7703fd..8a394a18215e 100644
--- a/backend/internal/service/openai_upstream_client_error.go
+++ b/backend/internal/service/openai_upstream_client_error.go
@@ -61,3 +61,14 @@ func writeOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte,
func WriteOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte, upstreamMsg string) {
writeOpenAIUpstreamClientError(c, statusCode, body, upstreamMsg)
}
+
+// OpenAIUpstreamRecoveryRateLimit preserves one explicitly safe provider code.
+// A matching prefix, arbitrary message/param, or contradictory HTTP status is
+// not trusted evidence and must retain the ordinary public error mapping.
+func OpenAIUpstreamRecoveryRateLimit(status int, body []byte) (code, message string, ok bool) {
+ const ownerRateLimit = "encrypted_agent_recovery_owner_rate_limited"
+ if status != http.StatusTooManyRequests || gjson.GetBytes(body, "error.code").String() != ownerRateLimit {
+ return "", "", false
+ }
+ return ownerRateLimit, "The upstream encrypted agent owner is temporarily rate limited. Resume this conversation after its limit resets.", true
+}
diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go
index d26560e52b10..e1a43bb8bfdc 100644
--- a/backend/internal/service/openai_ws_agent_recovery.go
+++ b/backend/internal/service/openai_ws_agent_recovery.go
@@ -52,6 +52,9 @@ type openAIWSAgentRecovery struct {
readable *openAIAgentRecoveryRequest
readableSource, readableControls [32]byte
bridgeSource []byte // verified pre-builder bytes, bounded by the current frame
+ protected *openAIAgentRecoveryRequest
+ protectedSource [32]byte
+ protectedControls [32]byte
}
func newOpenAIWSAgentRecovery(s *OpenAIGatewayService, ctx context.Context, c *gin.Context) *openAIWSAgentRecovery {
@@ -110,9 +113,32 @@ func (r *openAIWSAgentRecovery) prepareReadable(account *Account, source []byte)
defer r.mu.Unlock()
r.readable = nil
r.bridgeSource = nil
+ r.protected = nil
initial := openAIAgentRecoveryFromContext(r.ctx)
if initial == nil || !initial.omittedHistory {
- return source, nil
+ clean, err := r.service.PrepareOpenAIAgentReplayBody(source)
+ if err != nil {
+ return nil, err
+ }
+ if r.service.preserveOpenAIAgentHistory(source) {
+ if account.UsesOpenAICodexProtocol() {
+ clean, err = projectOpenAIOAuthReasoningMetadata(clean)
+ if err != nil {
+ return nil, err
+ }
+ }
+ // Freeze before compatibility, timezone, OAuth or tool builders.
+ // begin may refresh owner records, but cannot trust a new input.
+ model := gjson.GetBytes(source, "model").String()
+ if initial != nil {
+ model = initial.model
+ }
+ ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, clean, r.session, model)
+ r.protected = openAIAgentRecoveryFromContext(ctx)
+ r.protectedSource = openAIAgentRecoveryInputDigest(source)
+ r.protectedControls = openAI409ControlsDigest(source)
+ }
+ return append([]byte(nil), clean...), nil
}
ctx, clean := r.ctx, source
if openAIAgentRecoveryInputDigest(source) != initial.inputDigest || openAI409ControlsDigest(source) != initial.replayControlsDigest {
@@ -228,6 +254,25 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte,
model = initial.model
}
ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, source, r.session, model)
+ if r.protected != nil {
+ if openAIAgentRecoveryInputDigest(source) != r.protectedSource || openAI409ControlsDigest(source) != r.protectedControls {
+ return openAIAgentRecoveryRefusal(ctx, "input_integrity")
+ }
+ // Keep fresh authoritative lookup/fences; the trusted input remains
+ // the immutable pre-builder snapshot, never the final source/payload.
+ fresh := openAIAgentRecoveryFromContext(ctx)
+ fresh.inputDigest = r.protected.inputDigest
+ if fresh.known == nil {
+ fresh.known = make(map[[32]byte]bool)
+ }
+ for key := range r.protected.known {
+ fresh.known[key] = true
+ }
+ if r.protected.lookupErr != nil {
+ fresh.lookupErr = r.protected.lookupErr
+ }
+ fresh.conflict = fresh.conflict || r.protected.conflict
+ }
if r.readable != nil {
if openAIAgentRecoveryInputDigest(source) != r.readableSource || openAI409ControlsDigest(source) != r.readableControls {
return openAIAgentRecoveryError("wire_changed")
@@ -253,7 +298,7 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte,
}
for _, key := range r.request.keys {
if r.known[key] && !r.request.known[key] {
- return openAIAgentRecoveryError("owner_unavailable")
+ return &openAIWSLostOwnerEvidenceError{cause: openAIAgentRecoveryError("owner_unavailable")}
}
}
// These call sites have already selected a native Responses socket or
@@ -265,14 +310,21 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte,
if (r.request.owner != nil || r.request.preservesHistory()) && r.request.disallowLearning {
return openAIAgentRecoveryError("route_changed")
}
+ previous := gjson.GetBytes(source, "previous_response_id").String()
+ if !r.request.omittedHistory && previous != "" && (r.request.owner != nil || r.request.disableOwnerBinding || r.request.previousResponseID != "") &&
+ gjson.GetBytes(payload, "previous_response_id").String() != previous {
+ return openAIAgentRecoveryError("wire_changed")
+ }
if err := r.service.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil {
- return err
+ return &openAIWSOwnerRouteError{cause: err}
}
- previous := gjson.GetBytes(source, "previous_response_id").String()
if !r.request.omittedHistory && (r.request.owner != nil || r.request.disableOwnerBinding) && previous != "" {
owner, err := r.service.getOpenAIWSStateStore().GetResponseAccount(ctx, r.request.groupID, previous)
- if err != nil || owner != account.ID || gjson.GetBytes(payload, "previous_response_id").String() != previous {
- return openAIAgentRecoveryError("owner_unavailable")
+ if err != nil {
+ return openAIAgentRecoveryError("store_unavailable")
+ }
+ if owner != account.ID {
+ return &openAIWSOwnerRouteError{cause: openAIAgentRecoveryError("owner_unavailable")}
}
}
copyReq := req.Clone(ctx)
diff --git a/backend/internal/service/openai_ws_agent_recovery_test.go b/backend/internal/service/openai_ws_agent_recovery_test.go
index 664e120afeb3..6a20aae8d727 100644
--- a/backend/internal/service/openai_ws_agent_recovery_test.go
+++ b/backend/internal/service/openai_ws_agent_recovery_test.go
@@ -188,3 +188,37 @@ func TestIssue715WSBridgeValidatesBuiltPayload(t *testing.T) {
err := manager.begin(account, []byte(issue715OpaqueBody), []byte(issue715OpaqueBody), newRequest(built), "http_bridge")
require.Error(t, err, "bridge must validate actual built HTTP body before granting opaque task admission")
}
+
+func TestIssue854BeforeSendRecoveryGuards(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ cause error
+ recoverable bool
+ }{
+ {"owner_unavailable", &openAIWSOwnerRouteError{cause: openAIAgentRecoveryError("owner_unavailable")}, true},
+ {"route_changed", &openAIWSOwnerRouteError{cause: openAIAgentRecoveryError("route_changed")}, true},
+ {"late_owner_fence", openAIAgentRecoveryError("owner_unavailable"), false},
+ {"route_store_failure", &openAIWSOwnerRouteError{cause: openAIAgentRecoveryError("store_unavailable")}, false},
+ {"wire_integrity", openAIAgentRecoveryError("wire_changed"), false},
+ {"conflicting_owners", openAIAgentRecoveryError("owner_conflict"), false},
+ {"delivery_pending", openAIAgentRecoveryError("delivery_pending"), false},
+ {"store_unavailable", openAIAgentRecoveryError("store_unavailable"), false},
+ {"lost_known_owner", &openAIWSLostOwnerEvidenceError{cause: openAIAgentRecoveryError("owner_unavailable")}, false},
+ {"unknown_send", errors.New("upstream write outcome unknown"), false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ body := []byte(`{"type":"response.create","input":"private-current-task"}`)
+ result := openAIWSUnsentAgentTurn(tc.cause, body, "gpt-5.1", 2)
+ body[0] = '!'
+ payload, model, turn, ok := OpenAIWSUnsentTurnPayload(result)
+ require.Equal(t, tc.recoverable, ok)
+ require.Equal(t, tc.recoverable, OpenAIWSUnsentTurnKeepsAccount(result))
+ require.NotContains(t, result.Error(), "private-current-task")
+ if ok {
+ require.True(t, gjson.ValidBytes(payload))
+ require.Equal(t, "gpt-5.1", model)
+ require.Equal(t, 2, turn)
+ }
+ })
+ }
+}
diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go
index 740a43489077..454357b2645a 100644
--- a/backend/internal/service/openai_ws_forwarder_ingress.go
+++ b/backend/internal/service/openai_ws_forwarder_ingress.go
@@ -1884,11 +1884,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient(
if err := s.priorityLatencyBeforeSend(priorityLatencyCtx, account); err != nil {
return nil, err
}
- latencyGenerationStartedTurn = turn
}
if err := agentRecovery.beginSocket(latest, clientPayload, payload, wsURL, lease.conn.agentRecoveryHeaders, "ctx_pool"); err != nil {
+ if latencyGenerationStartedTurn != turn {
+ return nil, openAIWSUnsentAgentTurn(err, clientPayload, originalModel, turn)
+ }
return nil, openAIWSAgentRecoveryClose(err)
}
+ latencyGenerationStartedTurn = turn
if err := lease.WriteJSONWithContextTimeout(ctx, json.RawMessage(payload), s.openAIWSWriteTimeout()); err != nil {
return nil, wrapOpenAIWSIngressTurnError(
"write_upstream",
diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go
index 85e58e09fe2f..53430a54e2df 100644
--- a/backend/internal/service/openai_ws_http_bridge.go
+++ b/backend/internal/service/openai_ws_http_bridge.go
@@ -366,12 +366,16 @@ func buildOpenAIWSHTTPBridgeErrorEvent(statusCode int, message string, source ..
}
errorBody := map[string]any{"type": "upstream_error", "message": message}
if len(source) > 0 {
- // Preserve only the standard error identity fields, not an arbitrary
- // upstream envelope. The caller already sanitized the message.
- for _, field := range []string{"code", "type", "param"} {
- value := gjson.GetBytes(source[0], "error."+field)
- if value.Type == gjson.String && value.String() != "" {
- errorBody[field] = value.String()
+ if code, safeMessage, ok := OpenAIUpstreamRecoveryRateLimit(statusCode, source[0]); ok {
+ errorBody = map[string]any{"type": "rate_limit_error", "code": code, "message": safeMessage}
+ } else {
+ // Preserve only the standard error identity fields, not an arbitrary
+ // upstream envelope. The caller already sanitized the message.
+ for _, field := range []string{"code", "type", "param"} {
+ value := gjson.GetBytes(source[0], "error."+field)
+ if value.Type == gjson.String && value.String() != "" {
+ errorBody[field] = value.String()
+ }
}
}
}
@@ -620,17 +624,20 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
}
return nil, admissionErr
}
- // Freeze the first-send boundary. Rejected-field network attempts remain
- // in forwarding and in the compatible helper-entry legacy timer.
- if forwardStart.IsZero() {
- forwardStart = requesttiming.Now(ctx)
- }
if recovery := openAIWSAgentRecoveryFromContext(ctx); recovery != nil {
source, _ := ctx.Value(openAIWSAgentSourceKey{}).([]byte)
if err := recovery.begin(latest, source, body, upstreamReq, "http_bridge"); err != nil {
+ if forwardStart.IsZero() {
+ return nil, openAIWSUnsentAgentTurn(err, source, originalModel, turn)
+ }
return nil, openAIWSAgentRecoveryClose(err)
}
}
+ // Only crossing the physical send boundary makes this turn ineligible
+ // for unsent recovery, including any later rejected-field attempt.
+ if forwardStart.IsZero() {
+ forwardStart = requesttiming.Now(ctx)
+ }
resp, err = s.doOpenAIUpstream(upstreamReq, proxyURL, account)
if err != nil {
var phaseTimeout *openAIHTTPPhaseTimeout
@@ -710,7 +717,8 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
s.handleOpenAIAccountUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, actualModel)
}
clientError := buildOpenAIWSHTTPBridgeErrorEvent(resp.StatusCode, upstreamMsg)
- if preserveAgentHistory {
+ _, _, safeOwnerLimit := OpenAIUpstreamRecoveryRateLimit(resp.StatusCode, respBody)
+ if preserveAgentHistory || safeOwnerLimit {
clientError = buildOpenAIWSHTTPBridgeErrorEvent(resp.StatusCode, upstreamMsg, respBody)
}
if writeErr := writeClientMessage(clientError); writeErr == nil {
diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go
index 97f3e95f9208..9e57ed6050e9 100644
--- a/backend/internal/service/openai_ws_readable_continuation.go
+++ b/backend/internal/service/openai_ws_readable_continuation.go
@@ -16,10 +16,11 @@ import (
// Constructed only at transport boundaries before the CURRENT generation has
// been written. Neither a transport failure nor lack of output proves this.
type openAIWSUnsentTurnError struct {
- cause error
- body []byte
- model string
- turn int
+ cause error
+ body []byte
+ model string
+ turn int
+ keepAccount bool // an owner mismatch does not disqualify a healthy selected account
}
func (e *openAIWSUnsentTurnError) Error() string {
@@ -40,6 +41,59 @@ func openAIWSUnsentTurn(err error, body []byte, model string, turn int) error {
return &openAIWSUnsentTurnError{cause: err, body: append([]byte(nil), body...), model: model, turn: turn}
}
+// Retains send-boundary evidence even when the specific guard is terminal.
+type openAIWSRecoveryBeforeSendError struct{ cause error }
+
+func (e *openAIWSRecoveryBeforeSendError) Error() string { return e.cause.Error() }
+func (e *openAIWSRecoveryBeforeSendError) Unwrap() error { return e.cause }
+func OpenAIWSAgentRecoveryBeforeSend(err error) bool {
+ var before *openAIWSRecoveryBeforeSendError
+ return errors.As(err, &before)
+}
+
+// Losing ownership already observed on this socket is not ordinary account
+// unavailability. It must never become permission to discard that fence.
+type openAIWSLostOwnerEvidenceError struct{ cause error }
+
+func (e *openAIWSLostOwnerEvidenceError) Error() string { return e.cause.Error() }
+func (e *openAIWSLostOwnerEvidenceError) Unwrap() error { return e.cause }
+
+// Only the account/route compatibility check may grant this evidence. The same
+// public code from a later integrity or delivery fence stays terminal.
+type openAIWSOwnerRouteError struct{ cause error }
+
+func (e *openAIWSOwnerRouteError) Error() string { return e.cause.Error() }
+func (e *openAIWSOwnerRouteError) Unwrap() error { return e.cause }
+
+// Called only before the current generation's first physical write. A guard
+// refusal on an internal retry is not proof that earlier work was unsent.
+func openAIWSUnsentAgentTurn(err error, body []byte, model string, turn int) error {
+ closed := openAIWSAgentRecoveryClose(&openAIWSRecoveryBeforeSendError{cause: err})
+ var lost *openAIWSLostOwnerEvidenceError
+ if errors.As(err, &lost) {
+ return closed
+ }
+ var route *openAIWSOwnerRouteError
+ var recovery *OpenAIAgentRecoveryError
+ if turn < 1 || !errors.As(err, &route) || !errors.As(err, &recovery) || !gjson.ValidBytes(body) {
+ return closed
+ }
+ switch recovery.Reason {
+ case "owner_unavailable", "route_changed":
+ // Rebuild still checks completed ownership, delivery fences, readable
+ // intent, tool results and final payload integrity. Do not turn wire
+ // mutation, pending/failed/conflicting ownership or store errors into retries.
+ default:
+ return closed
+ }
+ return &openAIWSUnsentTurnError{cause: closed, body: append([]byte(nil), body...), model: model, turn: turn, keepAccount: true}
+}
+
+func OpenAIWSUnsentTurnKeepsAccount(err error) bool {
+ var unsent *openAIWSUnsentTurnError
+ return errors.As(err, &unsent) && unsent.keepAccount
+}
+
func OpenAIWSUnsentTurnPayload(err error) ([]byte, string, int, bool) {
var unsent *openAIWSUnsentTurnError
if !errors.As(err, &unsent) {
diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go
index 46bc5baf4994..59b7368c6a14 100644
--- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go
+++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go
@@ -1405,7 +1405,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
}
if err := agentRecovery.beginSocket(latest, pendingAgentSource, firstClientMessage, wsURL, headers, "passthrough"); err != nil {
cancelFirstWrite()
- return openAIWSAgentRecoveryClose(err)
+ return openAIWSUnsentAgentTurn(err, pendingAgentSource, gjson.GetBytes(firstClientMessage, "model").String(), 1)
}
firstWriteErr := relayUpstreamFrameConn.WriteFrame(firstWriteCtx, coderws.MessageText, firstClientMessage)
cancelFirstWrite()
@@ -1469,7 +1469,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
return err
}
if err := agentRecovery.beginSocket(latest, pendingAgentSource, payload, wsURL, headers, "passthrough"); err != nil {
- return openAIWSAgentRecoveryClose(err)
+ return openAIWSUnsentAgentTurn(err, pendingAgentSource, usageMeta.requestModelForFrame(pendingAgentSource), max(2, int(completedTurns.Load())+1))
}
return nil
},
@@ -1829,6 +1829,10 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough(
}
func openAIWSPassthroughRelayClientClose(exit openaiwsv2.RelayExit, completedTurns int) (coderws.StatusCode, string, bool) {
+ var recovery *OpenAIAgentRecoveryError
+ if errors.As(exit.Err, &recovery) {
+ return 0, "", false // Handler persists the outcome and writes the safe error before closing.
+ }
if _, _, _, unsent := OpenAIWSUnsentTurnPayload(exit.Err); unsent {
return 0, "", false // Handler owns bounded fresh admission on the same client.
}
diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go
index eff976900e39..c14f7d4fef65 100644
--- a/backend/internal/service/ops_upstream_context.go
+++ b/backend/internal/service/ops_upstream_context.go
@@ -180,12 +180,21 @@ func IsOpsRequestScopedError(c *gin.Context) bool {
return c != nil && c.GetBool(OpsRequestScopedErrorKey)
}
+// OpsRecoveryFailure is trusted local compatibility evidence, never populated
+// from an upstream error envelope or client metadata.
+type OpsRecoveryFailure struct {
+ Protocol string
+ Phase string
+ RequestWritten *bool // nil means no proof of whether the generation was sent
+}
+
// OpsStreamError 描述承载在 2xx 响应上的带内错误:网关在响应状态已固化为 200 之后
// 就地以 SSE error 帧返回的错误(并发限流回退、Wait 后二次计费校验失败、流开始后才无
// 可用账号等),以及上游 2xx 正文或事件里携带的错误结果(NonStream 标记非流式正文)。
// 由于 HTTP 状态码停留在 2xx,ops_error_logger 中间件在 status<400 分支消费该标记并
// 补记错误日志;标记方是 handler.handleStreamingAwareError 或各 service 的带内检测。
type OpsStreamError struct {
+ RecoveryFailure *OpsRecoveryFailure
TransportFailure *OpsTransportFailure
// BridgeFailure is set only by the local BPS conversion boundary. It keeps
// real upstream HTTP evidence while assigning failure ownership to gateway.
diff --git a/docs/encrypted-history-409-beta.md b/docs/encrypted-history-409-beta.md
index 679e1ce774e5..0ec8d1de6cfe 100644
--- a/docs/encrypted-history-409-beta.md
+++ b/docs/encrypted-history-409-beta.md
@@ -43,3 +43,12 @@ HTTP 重建请求会在原始可读快照验证通过后,按目标账号执行
API Key 账号开启普通透传时,重建请求使用原生 Responses 构造与交付流程;普通请求仍使用透传。其他尚不支持重建的账号路线在选号时排除,避免先选中再本地拒绝。WS 新连接首帧没有会话指针、但已有可读任务和原 owner 时,初次选号发现 owner 不可用也会进入一次有界重建。
重建或显式完整历史保护请求的正文在物理发送前不再按自动出口时区改写,以免验证后更改用户任务;HTTP 时区请求头仍可按出口更新,普通请求的自动时区行为不变。手动时区在 HTTP 重建投影中处理。缺少可读任务、未完成工具或交付不确定时继续停止,不以重新计算最终摘要掩盖变化。
+
+
+### Issue854 integrated continuation checks
+
+PR855 incorporates the fixed PR860 source (`591bb9b9b917c0df2ae8c59abed672c0cddf5c1c`) by an ordinary source merge. This does not imply a GitHub PR merge or a deployment. It retains the typed WS initial-owner availability check, fresh permission/billing/prompt checks, and terminal error persistence from PR855.
+
+Native HTTP projection also applies the existing empty-base64-image sanitizer before freezing the projected representation. Readable text, tool declarations, completed results, their order, and exact JSON numbers remain protected. Final dispatch does not overwrite the source snapshot or waive integrity checks.
+
+The synthetic acceptance matrix distinguishes configured manual timezone projection, automatic normalization on ordinary requests, and automatic egress headers with unchanged protected recovery bodies. API Key passthrough is a supported native recovery route; genuinely unsupported adapters are checked separately for refusal or selection of an eligible native account. The pre-coordination oracle and raw results are retained as historical evidence; they are not silently relabeled as current acceptance.
diff --git a/frontend/src/utils/errorCategory.ts b/frontend/src/utils/errorCategory.ts
index 7150c18265ac..e7c589d5441f 100644
--- a/frontend/src/utils/errorCategory.ts
+++ b/frontend/src/utils/errorCategory.ts
@@ -4,6 +4,7 @@
* 两处修改须同步。返回稳定分类码,展示文案走 i18n `usage.errors.categories.*`。
*/
export function mapErrorCategory(phase?: string | null, errType?: string | null): string {
+ if ((errType || '').toLowerCase() === 'transport_error') return 'transport_error'
switch ((phase || '').toLowerCase()) {
case 'auth':
return 'auth'
diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue
index 80ec0a067870..b1295f600d78 100644
--- a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue
+++ b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue
@@ -89,12 +89,15 @@
-
{{ t('admin.ops.errorDetail.status') }}
+
{{ t(detail.type === 'transport_error' ? 'usage.errors.detail.clientHttpStatus' : 'admin.ops.errorDetail.status') }}
{{ detail.status_code }}
+
+ {{ t('usage.errors.detail.streamFailedAfterHeaders') }}
+
diff --git a/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue b/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue
index 7d1eb7c0d097..a7fc7413638c 100644
--- a/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue
+++ b/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue
@@ -107,6 +107,9 @@
+
+ {{ t('usage.errors.detail.streamFailedAfterHeaders') }}
+
{{ row.status_code }}
diff --git a/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts
index 2f1d0e461497..3a7b23089d54 100644
--- a/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts
+++ b/frontend/src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts
@@ -114,3 +114,21 @@ it.each(['user', 'upstream'])('explains %s balance failures and preserves diagno
expect(wrapper.find('pre').text()).toContain('insufficient balance')
wrapper.unmount()
})
+
+it('labels HTTP 200 as wire status when the stream failed', async () => {
+ vi.clearAllMocks()
+ mocks.listRequestErrorUpstreamErrors.mockResolvedValue({ items: [] })
+ mocks.getRequestErrorDetail.mockResolvedValue({
+ id: 1, status_code: 200, phase: 'network', type: 'transport_error',
+ message: 'Upstream connection reset', upstream_status_code: null,
+ })
+ const wrapper = shallowMount(OpsErrorDetailModal, {
+ props: { show: true, errorId: 1, errorType: 'request' },
+ global: { stubs: { BaseDialog: { template: '
' }, Icon: true } },
+ })
+ await flushPromises()
+ expect(wrapper.text()).toContain('usage.errors.detail.clientHttpStatus')
+ expect(wrapper.text()).toContain('usage.errors.detail.streamFailedAfterHeaders')
+ expect(wrapper.text()).toContain('200')
+ wrapper.unmount()
+})
diff --git a/frontend/src/views/admin/ops/components/__tests__/OpsErrorLogTable.spec.ts b/frontend/src/views/admin/ops/components/__tests__/OpsErrorLogTable.spec.ts
index cade20799657..62cae763d0a9 100644
--- a/frontend/src/views/admin/ops/components/__tests__/OpsErrorLogTable.spec.ts
+++ b/frontend/src/views/admin/ops/components/__tests__/OpsErrorLogTable.spec.ts
@@ -132,3 +132,14 @@ it('labels historical balance failures by source while preserving the raw messag
expect(upstream.get('[data-testid="balance-source"]').text()).toBe('admin.ops.balanceError.upstream')
upstream.unmount()
})
+
+it('keeps HTTP 200 transport failures distinct from recovered upstream attempts', () => {
+ const failed = mountTable({ status_code: 200, type: 'transport_error', phase: 'network' })
+ expect(failed.text()).toContain('usage.errors.categories.transport_error')
+ expect(failed.text()).toContain('usage.errors.detail.streamFailedAfterHeaders')
+ expect(failed.text()).toContain('200')
+ failed.unmount()
+ const recovered = mountTable({ status_code: 200, type: 'upstream_error', phase: 'upstream' })
+ expect(recovered.text()).not.toContain('usage.errors.detail.streamFailedAfterHeaders')
+ recovered.unmount()
+})
diff --git a/tools/issue854-ui/README.md b/tools/issue854-ui/README.md
new file mode 100644
index 000000000000..83d08b11d3b9
--- /dev/null
+++ b/tools/issue854-ui/README.md
@@ -0,0 +1,31 @@
+# Issue854 browser evidence
+
+This harness renders the actual OpsErrorLogTable and OpsErrorDetailModal,
+including DataTable's mobile cards, BaseDialog, translations, and Tailwind CSS.
+It archives immutable Git revisions, renders baseline first, then candidate,
+and intercepts only the synthetic detail API. No backend or provider is called.
+
+Install frontend dependencies using the locked package manager. Provide an
+installed Playwright or playwright-core ES module and Chromium executable:
+
+```sh
+ISSUE854_PLAYWRIGHT_MODULE=/absolute/path/to/playwright-core/index.mjs \
+ISSUE854_CHROME=/absolute/path/to/chromium \
+node tools/issue854-ui/capture.mjs "$PWD" /outside/repository/evidence \
+ aa8e596e6d6f3e4648d6beba73b39b240dd5357a CANDIDATE_SHA
+```
+
+Use a new output directory per invocation. The manifest records source SHA/tree,
+component/CSS/lockfile Git blobs, fixture/harness hashes, browser, UTC capture time,
+viewport, PNG SHA256, and named assertions. Captures cover English/Chinese,
+1440×1000 and 390×844, table/cards, HTTP detail, and WS detail/diagnostics.
+
+The HTTP fixture preserves status200 + transport_error. The WS fixture matches
+Ops recovery persistence: outer phase internal / owner platform / source gateway,
+logical status409 and nested error.wire_status101, turn2, request_written=false,
+outcome=failed. Its baseline rendering is a display comparison using a synthetic
+candidate-shaped row, not a claim that baseline persisted that missing record.
+
+The fixture contains no production data or credentials. Browser requests are
+limited to loopback. PNG files and raw capture artifacts must stay outside Git;
+upload screenshots as native PR attachments and verify authenticated downloads.
diff --git a/tools/issue854-ui/capture.mjs b/tools/issue854-ui/capture.mjs
new file mode 100644
index 000000000000..46014c64aa31
--- /dev/null
+++ b/tools/issue854-ui/capture.mjs
@@ -0,0 +1,131 @@
+// Offline browser evidence: real components/CSS from immutable Git archives.
+// Usage: ISSUE854_PLAYWRIGHT_MODULE=/path/to/playwright/index.mjs node tools/issue854-ui/capture.mjs REPO OUTPUT BASELINE CANDIDATE
+import { createRequire } from 'node:module'
+import { execFileSync } from 'node:child_process'
+import * as fs from 'node:fs'
+import path from 'node:path'
+import { createHash } from 'node:crypto'
+import assert from 'node:assert/strict'
+const [repo, output, baseline, candidate] = process.argv.slice(2)
+assert(repo && output && baseline && candidate)
+fs.mkdirSync(output, { recursive: true, mode: 0o700 })
+const require = createRequire(path.join(repo, 'frontend/package.json'))
+const { createServer } = await import(path.join(path.dirname(require.resolve('vite/package.json')), 'dist/node/index.js'))
+const { default: vue } = await import(require.resolve('@vitejs/plugin-vue'))
+const { chromium } = await import(process.env.ISSUE854_PLAYWRIGHT_MODULE || 'playwright')
+const hash = data => createHash('sha256').update(data).digest('hex')
+const git = (...args) => execFileSync('git', ['-C', repo, ...args], { maxBuffer: 128 * 1024 * 1024 })
+const base = { created_at: '2026-11-15T00:00:00Z', platform: 'openai', model: 'fixture-model', severity: 'P1', resolved: false, upstream_status_code: null, user_email: '', account_name: '', group_name: '', client_ip: '', inbound_endpoint: '/v1/responses', upstream_endpoint: '/v1/responses', upstream_errors: '[]', is_business_limited: false }
+const rows = [
+ { ...base, id: 85401, request_id: 'fixture-http-transport', status_code: 200, phase: 'network', type: 'transport_error', error_owner: 'provider', error_source: 'upstream_transport', severity: 'error', request_type: 2, message: 'Synthetic upstream connection reset', error_body: JSON.stringify({ error: { code: 'upstream_http2_stream_error', message: 'Synthetic upstream connection reset' } }) },
+ { ...base, id: 85402, request_id: 'fixture-ws-owner-turn2', status_code: 409, severity: 'P3', phase: 'internal', type: 'invalid_request_error', error_owner: 'platform', error_source: 'gateway', request_type: 3, message: "The proven encrypted agent owner is currently unavailable. Preserve this task and context. Ask the administrator to check the original account's access and availability; ordinary account switching cannot establish compatibility.", error_body: JSON.stringify({ error: { code: 'encrypted_agent_recovery_owner_unavailable', message: "The proven encrypted agent owner is currently unavailable. Preserve this task and context. Ask the administrator to check the original account's access and availability; ordinary account switching cannot establish compatibility.", type: 'invalid_request_error', protocol: 'websocket', turn: 2, phase: 'before_upstream_write', outcome: 'failed', wire_status: 101, status: 409, request_written: false } }) }
+]
+fs.writeFileSync(path.join(output, 'fixtures.json'), JSON.stringify(rows, null, 2))
+const app = `
+
+Issue854 · Synthetic fixture · {{ new URLSearchParams(location.search).get('label') }}
+`
+// No substituted components, styles, translation messages, or API client.
+const fixedApp = app.replace("{{ new URLSearchParams(location.search).get('label') }}", '{{ label }}').replace('const rows =', "const label = new URLSearchParams(location.search).get('label')\nconst rows =")
+const main = `import { createApp } from 'vue'; import { createPinia } from 'pinia'; import i18n, { initI18n } from './src/i18n'; import './src/style.css'; import App from './Evidence.vue'; await initI18n(); createApp(App).use(createPinia()).use(i18n).mount('#app');`
+const manifest = { baseline, candidate, fixtureSHA256: hash(JSON.stringify(rows, null, 2)), harnessSHA256: hash(fs.readFileSync(new URL(import.meta.url))), captureOrder: ['before','after'], privacy: 'Only synthetic fixture; no production data, credentials, emails, addresses or opaque history. Browser network restricted to loopback.', versions: { node: process.version }, snapshots: [], captures: [], assertions: [], errors: [] }
+const browser = await chromium.launch({ executablePath: process.env.ISSUE854_CHROME || '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox','--disable-dev-shm-usage'] })
+manifest.versions.browser = browser.version()
+try {
+for (const [label, sha] of [['before', baseline], ['after', candidate]]) {
+ const root = path.join(output, label)
+ fs.mkdirSync(root, { recursive: true })
+ execFileSync('tar', ['-x', '-C', root], { input: git('archive', sha, 'frontend') })
+ const front = path.join(root, 'frontend')
+ fs.symlinkSync(path.join(repo, 'frontend/node_modules'), path.join(front, 'node_modules'), 'dir')
+ fs.writeFileSync(path.join(front, 'Evidence.vue'), fixedApp)
+ fs.writeFileSync(path.join(front, 'evidence.ts'), main)
+ fs.writeFileSync(path.join(front, 'index.html'), 'Issue854 synthetic evidence')
+ const blobFiles = ['frontend/src/views/admin/ops/components/OpsErrorLogTable.vue','frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue','frontend/src/utils/errorCategory.ts','frontend/src/style.css','frontend/tailwind.config.js','frontend/pnpm-lock.yaml']
+ manifest.snapshots.push({label, sha, tree: git('rev-parse', sha+'^{tree}').toString().trim(), blobs: Object.fromEntries(blobFiles.map(p=>[p,git('rev-parse',sha+':'+p).toString().trim()])) })
+ const server = await createServer({ configFile: false, root: front, plugins: [vue()], resolve: { alias: { '@': path.join(front,'src'), 'vue-i18n': require.resolve('vue-i18n/dist/vue-i18n.runtime.esm-bundler.js') } }, define: { __INTLIFY_JIT_COMPILATION__: true }, css: { postcss: { plugins: [require('tailwindcss')({ ...((await import(path.join(front,'tailwind.config.js'))).default), content: [path.join(front,'src/**/*.{vue,js,ts,jsx,tsx}'), path.join(front,'Evidence.vue')] }),require('autoprefixer')()] } }, server: { host: '127.0.0.1', port: 0, fs: { allow: [front, path.join(repo,'frontend')] } } })
+ await server.listen()
+ const url = server.resolvedUrls.local[0]
+ try {
+ for (const locale of ['en','zh']) for (const [device, viewport] of [['desktop',{width:1440,height:1000}],['mobile',{width:390,height:844}]]) {
+ const context = await browser.newContext({ viewport, deviceScaleFactor: 1, locale: locale === 'zh' ? 'zh-CN' : 'en-US', timezoneId: 'UTC', colorScheme: 'light' })
+ await context.addInitScript(locale => { localStorage.setItem('sub2api_locale',locale) },locale)
+ const page = await context.newPage()
+ page.on('pageerror', e => manifest.errors.push({label,locale,device,message:e.message}))
+ await page.route('**/*', async route => {
+ const u = new URL(route.request().url())
+ if (u.hostname !== '127.0.0.1') throw new Error('Unexpected external request: '+u.origin)
+ if (u.pathname.startsWith('/api/')) {
+ const item = rows.find(r=>u.pathname.endsWith('/'+r.id))
+ assert(item || u.pathname.endsWith('/upstream-errors'), 'Unexpected API path '+u.pathname)
+ return route.fulfill({json:{code:0,message:'ok',data:item || {items:[],total:0}}})
+ }
+ return route.continue()
+ })
+ await page.goto(url+'?label='+label, {waitUntil:'networkidle'})
+ const renderedRows = page.locator(device === 'desktop' ? 'tbody tr' : 'section .cursor-pointer').filter({has: page.locator(device === 'desktop' ? 'td' : '[data-field]')})
+ await renderedRows.first().waitFor()
+ const tableText = await page.locator('section').innerText()
+ assert(!tableText.includes('usage.errors.'), 'untranslated keys')
+ const httpRow = renderedRows.nth(0), wsRow = renderedRows.nth(1)
+ assert((await httpRow.innerText()).includes('200'))
+ assert((await wsRow.innerText()).includes('409'))
+ assert(!(await wsRow.innerText()).includes('101'))
+ const hintText = await httpRow.locator('p').allTextContents()
+ assert.equal(hintText.length, label==='after' ? 1 : 0, 'HTTP200 failure hint delta')
+ assert((await wsRow.innerText()).includes(locale==='en'?'Platform error':'平台错误'))
+ const css = await page.locator('section').evaluate(e => getComputedStyle(e.querySelector('.card')).borderRadius)
+ assert.notEqual(css, '0px', 'real project CSS must load')
+ manifest.assertions.push({label,locale,device,check:'table HTTP200 failure hint and WS logical409',pass:true,tableText})
+ const shot = async (view) => {
+ await page.evaluate(()=>document.fonts.ready)
+ const name = `${label}-${locale}-${device}-${view}.png`
+ const buf = await page.screenshot({path:path.join(output,name), animations:'disabled'})
+ manifest.captures.push({name,label,sha,locale,viewport,view,utc:new Date().toISOString(),sha256:hash(buf),bytes:buf.length})
+ }
+ await shot('table')
+ for (const [n,kind] of [[0,'http'],[1,'ws']]) {
+ await renderedRows.nth(n).click()
+ const dialog=page.getByRole('dialog')
+ await dialog.getByText(rows[n].request_id,{exact:true}).waitFor()
+ const text=await dialog.innerText()
+ assert(text.includes(String(rows[n].status_code)))
+ if(kind==='ws') { assert(text.includes('"wire_status": 101'));assert(text.includes('"turn": 2'));assert(text.includes('"request_written": false'));assert(text.includes('"outcome": "failed"')) }
+ if(kind==='http') assert.equal((await dialog.locator('p.text-amber-700').count()),label==='after'?1:0)
+ manifest.assertions.push({label,locale,device,check:kind+' actual detail shape',pass:true})
+ // Scroll the actual modal: preserve project CSS and viewport. No resized full-panel composite.
+ // Select the actual numeric status badge, not a positional metadata
+ // card. A preceding summary field must not move status off-screen.
+ const statusLabel=dialog.locator('.grid > div').filter({
+ has: page.locator('span').filter({hasText: new RegExp(`^${rows[n].status_code}$`)})
+ })
+ assert.equal(await statusLabel.count(), 1, 'one actual status card')
+ await statusLabel.evaluate(e=>e.scrollIntoView({block:'center',behavior:'instant'}))
+ const box=await statusLabel.boundingBox()
+ assert(box && box.y >= 50 && box.y+box.height <= viewport.height-20, 'entire status card must be inside viewport')
+ if(kind==='http' && label==='after') {
+ const warning=statusLabel.locator('p.text-amber-700')
+ assert.equal(await warning.count(),1)
+ const warningBox=await warning.boundingBox()
+ assert(warningBox && warningBox.y >= 50 && warningBox.y+warningBox.height <= viewport.height-20, 'failure warning must be inside viewport')
+ }
+ manifest.assertions.push({label,locale,device,check:kind+' status card viewport bounds',pass:true,box})
+ await shot(kind+'-detail-status')
+ if(kind==='ws') { await dialog.locator('pre').first().scrollIntoViewIfNeeded(); await shot('ws-detail-diagnostics') }
+ await dialog.getByRole('button',{name:'Close modal',exact:true}).click()
+ }
+ await context.close()
+ }
+ } finally { await server.close() }
+}
+assert.equal(manifest.errors.length,0,JSON.stringify(manifest.errors))
+} finally { await browser.close(); fs.writeFileSync(path.join(output,'manifest.json'),JSON.stringify(manifest,null,2)) }
+console.log(JSON.stringify({captures:manifest.captures.length,assertions:manifest.assertions.length,errors:manifest.errors}))