diff --git a/.github/scripts/assert-issue895-review-red.py b/.github/scripts/assert-issue895-review-red.py
new file mode 100644
index 000000000000..5541d6387424
--- /dev/null
+++ b/.github/scripts/assert-issue895-review-red.py
@@ -0,0 +1,94 @@
+"""Require the exact F1 RED failures and every intact/fence/400 control."""
+
+import json
+import re
+import sys
+from collections import Counter
+from pathlib import Path
+
+
+PACKAGE = "github.com/Wei-Shaw/sub2api/internal/service"
+PROJECTION = "TestIssue892OpaqueEnvironmentProjectionRefused"
+ACTUAL = "TestIssue892ActualSendOpaqueIntegrityAndDelivery"
+FENCES = "TestIssue892PreparedUnknownOwnerRechecksFences"
+RECOVERY = "TestIssue892ManualTimezone400Recovery"
+MARKERS = {
+ **{f"{PROJECTION}/{kind}/{mode}": "Issue895 F1 projection must refuse a changed opaque envelope"
+ for kind in ("oauth", "apikey") for mode in ("http", "ws")},
+ **{f"{ACTUAL}/{mode}/{mutation}": "Issue895 F1 actual send must reject a changed opaque item"
+ for mode in ("http", "ws") for mutation in ("envelope", "drop")},
+}
+CONTROLS = (
+ {f"{ACTUAL}/{mode}/intact" for mode in ("http", "ws")}
+ | {f"{FENCES}/{mode}/{fence}" for mode in ("http", "ws") for fence in ("pending", "failed")}
+ | {f"{RECOVERY}/{mode}" for mode in ("enabled", "disabled", "ordinary400", "SSE")}
+)
+
+
+def expected_results():
+ # Each fixture calls t.Run once with a slash-containing name. Those slash
+ # prefixes are filters, not separately created intermediate test events.
+ return {
+ **dict.fromkeys(CONTROLS, "pass"),
+ **dict.fromkeys(MARKERS, "fail"),
+ PROJECTION: "fail",
+ ACTUAL: "fail",
+ FENCES: "pass",
+ RECOVERY: "pass",
+ None: "fail",
+ }
+
+
+def validate(code, raw):
+ if code != 1:
+ raise ValueError("expected ordinary go test failure exit 1")
+ if re.search(r"build failed|build-fail|undefined:|setup failed|no tests to run|"
+ r"panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|"
+ r"signal:|timed out|timeout|deadline exceeded|--- SKIP:", raw, re.I):
+ raise ValueError("invalid build/setup/runtime evidence")
+ events = []
+ for line in raw.splitlines():
+ if not line.strip():
+ continue
+ try:
+ event = json.loads(line)
+ except json.JSONDecodeError as error:
+ raise ValueError("non-JSON setup or process output") from error
+ if not isinstance(event, dict) or event.get("Package") != PACKAGE:
+ raise ValueError("unexpected package or malformed event")
+ events.append(event)
+ expected = expected_results()
+ counts = Counter()
+ outputs = {}
+ for event in events:
+ action, name = event.get("Action"), event.get("Test")
+ if action not in ("start", "run", "pause", "cont", "output", "pass", "fail"):
+ raise ValueError("unexpected action, skip or build event")
+ if name not in expected or (action == "start" and name is not None):
+ raise ValueError("unselected test or package start")
+ counts[action, name] += 1
+ if action in ("pass", "fail") and action != expected[name]:
+ raise ValueError(f"unexpected result: {name}")
+ if action == "output":
+ output = event.get("Output")
+ if not isinstance(output, str):
+ raise ValueError("malformed output")
+ outputs[name] = outputs.get(name, "") + output
+ if counts["start", None] != 1:
+ raise ValueError("missing or duplicate package start")
+ for name, result in expected.items():
+ if name is not None and counts["run", name] != 1:
+ raise ValueError(f"missing or duplicate run: {name}")
+ if counts[result, name] != 1 or counts["pass", name] + counts["fail", name] != 1:
+ raise ValueError(f"missing or duplicate terminal: {name}")
+ for name, marker in MARKERS.items():
+ if marker not in outputs.get(name, ""):
+ raise ValueError(f"wrong business assertion: {name}")
+
+
+if __name__ == "__main__":
+ try:
+ validate(int(sys.argv[1]), Path(sys.argv[2]).read_text())
+ except (ValueError, OSError, IndexError) as error:
+ raise SystemExit(str(error)) from error
+ print("F1 RED: exactly 8 named failures and 10 passing controls verified")
diff --git a/.github/scripts/prepare-ws-owner-red-fixtures.sh b/.github/scripts/prepare-ws-owner-red-fixtures.sh
index 74ca0b2beb5f..9f933bd719ff 100644
--- a/.github/scripts/prepare-ws-owner-red-fixtures.sh
+++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh
@@ -11,6 +11,7 @@ if grep -q 'requireCompletedOwners' "$tree/$contract"; then
fi
for target in \
+ backend/internal/service/openai_400_omit_history.go \
backend/internal/service/openai_409_omit_history.go \
backend/internal/service/openai_lossy_history_restart.go \
backend/internal/service/openai_tool_provenance.go \
@@ -63,6 +64,11 @@ exclude_new_fixture() {
# New service tests require new private proof/diagnostic types. Their own RED
# uses handler tests; every candidate GREEN retains them and all negative cases.
exclude_new_fixture backend/internal/service/openai_ws_owner_conflict_test.go
+# Issue892's later matrix also imports the OAuth dial seam and 400/842 test
+# helpers absent from these historical overlays. It is not a selected oracle
+# here; its own RED and every clean candidate GREEN retain both exact files.
+exclude_new_fixture backend/internal/handler/openai_issue892_timezone_test.go
+exclude_new_fixture backend/internal/service/openai_issue892_timezone_test.go
# Very old Issue805 baselines intentionally exclude the later readable harness.
# Only that dependency absence permits removing its new consumer as well.
if ! test -f "$tree/backend/internal/handler/openai_409_ws_rebuild_test.go"; then
diff --git a/.github/scripts/test_assert_issue895_review_red.py b/.github/scripts/test_assert_issue895_review_red.py
new file mode 100644
index 000000000000..6a30ed536372
--- /dev/null
+++ b/.github/scripts/test_assert_issue895_review_red.py
@@ -0,0 +1,153 @@
+"""Remote-only verifier tests; synthetic transcripts never count as Go evidence."""
+
+import importlib.util
+import json
+import unittest
+from pathlib import Path
+
+
+SPEC = importlib.util.spec_from_file_location("issue895_red", Path(__file__).with_name("assert-issue895-review-red.py"))
+GATE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(GATE)
+
+
+# Independent oracle for the actual Go fixture: four roots and eighteen
+# direct t.Run children, with no events for slash prefixes inside their names.
+EXPECTED = {
+ "TestIssue892OpaqueEnvironmentProjectionRefused": "fail",
+ "TestIssue892OpaqueEnvironmentProjectionRefused/apikey/http": "fail",
+ "TestIssue892OpaqueEnvironmentProjectionRefused/apikey/ws": "fail",
+ "TestIssue892OpaqueEnvironmentProjectionRefused/oauth/http": "fail",
+ "TestIssue892OpaqueEnvironmentProjectionRefused/oauth/ws": "fail",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery": "fail",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/http/intact": "pass",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/http/envelope": "fail",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/http/drop": "fail",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws/intact": "pass",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws/envelope": "fail",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws/drop": "fail",
+ "TestIssue892PreparedUnknownOwnerRechecksFences": "pass",
+ "TestIssue892PreparedUnknownOwnerRechecksFences/http/pending": "pass",
+ "TestIssue892PreparedUnknownOwnerRechecksFences/http/failed": "pass",
+ "TestIssue892PreparedUnknownOwnerRechecksFences/ws/pending": "pass",
+ "TestIssue892PreparedUnknownOwnerRechecksFences/ws/failed": "pass",
+ "TestIssue892ManualTimezone400Recovery": "pass",
+ "TestIssue892ManualTimezone400Recovery/enabled": "pass",
+ "TestIssue892ManualTimezone400Recovery/disabled": "pass",
+ "TestIssue892ManualTimezone400Recovery/ordinary400": "pass",
+ "TestIssue892ManualTimezone400Recovery/SSE": "pass",
+ None: "fail",
+}
+
+
+def evidence():
+ events = [{"Action": "start", "Package": GATE.PACKAGE}]
+ for root, result in EXPECTED.items():
+ if root is None or "/" in root:
+ continue
+ events.append({"Action": "run", "Test": root})
+ for name, terminal in EXPECTED.items():
+ if name is None or not name.startswith(root + "/"):
+ continue
+ events.append({"Action": "run", "Test": name})
+ if terminal == "fail":
+ marker = ("Issue895 F1 projection must refuse a changed opaque envelope"
+ if root == "TestIssue892OpaqueEnvironmentProjectionRefused"
+ else "Issue895 F1 actual send must reject a changed opaque item")
+ events.append({"Action": "output", "Test": name, "Output": marker})
+ events.append({"Action": terminal, "Test": name})
+ events.append({"Action": result, "Test": root})
+ events.append({"Action": "fail"})
+ for event in events:
+ event["Package"] = GATE.PACKAGE
+ return events
+
+
+def transcript(events):
+ return "".join(json.dumps(event) + "\n" for event in events)
+
+
+class Issue895ReviewRedTest(unittest.TestCase):
+ def test_accepts_exact_expected_failures_and_controls(self):
+ GATE.validate(1, transcript(evidence()))
+ self.assertEqual(EXPECTED, GATE.expected_results())
+ self.assertEqual(8, len(GATE.MARKERS))
+ self.assertEqual(10, len(GATE.CONTROLS))
+
+ def test_accepts_no_intermediate_prefix_events_and_rejects_invented_ones(self):
+ GATE.validate(1, transcript(evidence()))
+ for prefix in ("TestIssue892OpaqueEnvironmentProjectionRefused/apikey",
+ "TestIssue892OpaqueEnvironmentProjectionRefused/oauth",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/http",
+ "TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws",
+ "TestIssue892PreparedUnknownOwnerRechecksFences/http",
+ "TestIssue892PreparedUnknownOwnerRechecksFences/ws"):
+ self.assertNotIn(prefix, EXPECTED)
+ extra = [{"Package": GATE.PACKAGE, "Action": action, "Test": prefix}
+ for action in ("run", "fail")]
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(evidence() + extra))
+
+ def test_rejects_any_extra_control_failure_including_intact(self):
+ for name in GATE.CONTROLS:
+ with self.subTest(name=name):
+ events = evidence()
+ for event in events:
+ if event.get("Test") == name and event["Action"] == "pass":
+ event["Action"] = "fail"
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(events))
+
+ def test_rejects_wrong_business_assertion(self):
+ for name in GATE.MARKERS:
+ events = evidence()
+ for event in events:
+ if event.get("Test") == name and event["Action"] == "output":
+ event["Output"] = "unrelated assertion failure"
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(events))
+
+ def test_rejects_missing_runs_leaves_or_terminals_and_duplicates(self):
+ for name, result in EXPECTED.items():
+ events = evidence()
+ terminal = next(event for event in events if event.get("Test") == name and event["Action"] == result)
+ for bad in ([event for event in events if event is not terminal], events + [terminal]):
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(bad))
+ if name is not None:
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript([event for event in events if event.get("Test") != name]))
+ run = next(event for event in events if event.get("Test") == name and event["Action"] == "run")
+ for bad in ([event for event in events if event is not run], events + [run]):
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(bad))
+
+ def test_rejects_unselected_failure_and_incorrect_parent_or_package(self):
+ events = evidence()
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(events + [{"Package": GATE.PACKAGE, "Action": "fail", "Test": "TestUnexpected"}]))
+ for name, result in EXPECTED.items():
+ bad = evidence()
+ for event in bad:
+ if event.get("Test") == name and event["Action"] == result:
+ event["Action"] = "pass" if result == "fail" else "fail"
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(bad))
+
+ def test_rejects_compile_setup_skip_panic_timeout_and_abnormal_exit(self):
+ for message in ("build failed", "undefined: fixture", "setup failed", "no tests to run",
+ "panic: fixture", "panic_recovered", "fatal error: fixture", "runtime error: fixture",
+ "WARNING: DATA RACE", "signal: killed", "test timed out", "timeout", "context deadline exceeded", "--- SKIP:"):
+ for suffix in (message, transcript([{"Package": GATE.PACKAGE, "Action": "output", "Output": message}])):
+ with self.subTest(message=message), self.assertRaises(ValueError):
+ GATE.validate(1, transcript(evidence()) + suffix)
+ for action in ("skip", "build-fail"):
+ with self.assertRaises(ValueError):
+ GATE.validate(1, transcript(evidence() + [{"Package": GATE.PACKAGE, "Action": action}]))
+ for code in (0, 2, 124, 137, -9):
+ with self.assertRaises(ValueError):
+ GATE.validate(code, transcript(evidence()))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml
index 1af9ad96f92f..3e8d1d3e9c43 100644
--- a/.github/workflows/issue715-agent-recovery.yml
+++ b/.github/workflows/issue715-agent-recovery.yml
@@ -406,7 +406,7 @@ jobs:
# Manager fields and readable-payload methods live together. Restore
# both transport callers with that manager; retain candidate tests and
# standalone admission/principal helpers required by current HTTP.
- trap 'git restore --source=HEAD -- "$target" "$caller" "$passthrough" 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 -- "$target" "$caller" "$passthrough" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go backend/internal/service/openai_issue892_timezone_test.go; git diff --exit-code' EXIT
git restore --source="$original" -- "$target" "$caller" "$passthrough"
expected=$(git rev-parse "$original:$target")
actual=$(git hash-object "$target")
@@ -442,6 +442,20 @@ jobs:
echo "retained_candidate path=$retained expected_blob=$expected_retained tested_blob=$actual_retained"
test "$expected_retained" = "$actual_retained"
done
+ # The later timezone proof fixture requires manager.protected, which
+ # this historical manager does not have. Exclude only this untouched
+ # non-target fixture; keep the selected wire regression unchanged.
+ fixture=backend/internal/service/openai_issue892_timezone_test.go
+ if test -f "$fixture"; then
+ if git cat-file -e "$original:$fixture" 2>/dev/null; then
+ echo "refusing to remove a historical fixture" >&2
+ exit 1
+ fi
+ expected_fixture=$(git rev-parse "HEAD:$fixture")
+ test "$(git hash-object "$fixture")" = "$expected_fixture"
+ printf 'excluded later fixture path=%s candidate_blob=%s baseline=%s\n' "$fixture" "$expected_fixture" "$original"
+ rm -- "$fixture"
+ fi
git diff --exit-code HEAD -- backend/internal/service/openai_ws_agent_recovery_test.go
set +e
(cd backend && go test -tags=unit ./internal/service -run '^TestIssue715WSBridgeValidatesBuiltPayload$' -count=1 -v -timeout=5m) > "$RUNNER_TEMP/issue715-ws-wire-red.log" 2>&1
diff --git a/.github/workflows/issue892-timezone-integrity.yml b/.github/workflows/issue892-timezone-integrity.yml
new file mode 100644
index 000000000000..07e5818d4a9f
--- /dev/null
+++ b/.github/workflows/issue892-timezone-integrity.yml
@@ -0,0 +1,169 @@
+name: Issue892 protected timezone projection
+
+on:
+ pull_request:
+ branches: [production]
+ paths:
+ - 'backend/internal/service/openai*.go'
+ - 'backend/internal/service/setting_request_timezone*.go'
+ - 'backend/internal/handler/openai*.go'
+ - '.github/scripts/assert-issue895-review-red.py'
+ - '.github/scripts/test_assert_issue895_review_red.py'
+ - '.github/workflows/issue892-timezone-integrity.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: issue892-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+env:
+ EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
+ BASELINE_SHA: 321f11c1a4d23302961c223ac030fd09e3f9e6e8
+
+jobs:
+ evidence:
+ runs-on: ubuntu-latest
+ timeout-minutes: 35
+ services:
+ postgres:
+ image: postgres:16-alpine
+ env:
+ POSTGRES_USER: fixture
+ POSTGRES_PASSWORD: fixture
+ POSTGRES_DB: issue892
+ ports: ['15432:5432']
+ options: >-
+ --health-cmd "pg_isready -U fixture -d issue892"
+ --health-interval 5s --health-timeout 5s --health-retries 10
+ steps:
+ - uses: actions/checkout@v6
+ with:
+ ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ fetch-depth: 0
+ persist-credentials: false
+ - 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: Exact clean candidate GREEN
+ shell: bash
+ run: |
+ set -euo pipefail
+ test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA"
+ test -z "$(git status --porcelain)"
+ mkdir -p "$RUNNER_TEMP/issue892"
+ git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue892/candidate.txt"
+ python3 -B -m unittest discover -s .github/scripts -p 'test_assert_issue895_review_red.py' -v 2>&1 | tee "$RUNNER_TEMP/issue892/review-red-verifier-tests.log"
+ bash -n .github/scripts/prepare-ws-owner-red-fixtures.sh
+ gofmt -d backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_issue892_timezone_test.go backend/internal/handler/openai_issue892_timezone_test.go backend/internal/handler/openai_issue842_boundaries_test.go > "$RUNNER_TEMP/issue892/format.patch"
+ cat "$RUNNER_TEMP/issue892/format.patch"
+ test ! -s "$RUNNER_TEMP/issue892/format.patch"
+ cd backend
+ go test -mod=readonly -race -json -tags=unit ./internal/service ./internal/handler -run '^Test(Issue(892|842|805)|OpenAI400History|ForwardEncryptedContentSSERetry|EncryptedSSERetry|RequestTimezone|OpenAIAgentRecoveryCompaction|WithoutOpenAIRemoteCompaction)' -count=1 -timeout=12m 2>&1 | tee "$RUNNER_TEMP/issue892/green.jsonl"
+ if grep -Eiq '"Action":"skip"|no tests to run|panic:|panic_recovered|WARNING: DATA RACE' "$RUNNER_TEMP/issue892/green.jsonl"; then exit 1; fi
+ python3 - "$RUNNER_TEMP/issue892/green.jsonl" <<'PY'
+ import json, sys
+ events = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')]
+ passed = {(e.get('Package', '').rsplit('/', 1)[-1], e.get('Test')) for e in events if e.get('Action') == 'pass'}
+ for name in ('FrozenAccountTimezoneProjection', 'AccountReselectionUsesOriginalSource', 'TimezonePolicyControlsProjection', 'ManualTimezone400Recovery', 'OpaqueEnvironmentProjectionRefused', 'ActualSendOpaqueIntegrityAndDelivery', 'PreparedUnknownOwnerRechecksFences'):
+ assert ('service', 'TestIssue892' + name) in passed, name
+ for name in ('HTTPManualTimezone', 'WSManualTimezone', 'OpaqueEnvironmentAdapters', 'HTTP64SwitchMatrix'):
+ assert ('handler', 'TestIssue892' + name) in passed, name
+ import itertools
+ for optout, beta, recovery, stream, scenario in itertools.product(('false', 'true'), ('false', 'true'), ('false', 'true'), ('false', 'true'), ('unknown_top', 'unknown_part', 'same', 'reasoning400')):
+ name = f'TestIssue892HTTP64SwitchMatrix/optout={optout}/beta={beta}/recovery400={recovery}/stream={stream}/{scenario}'
+ assert ('handler', name) in passed, name
+ for kind, mode, scenario in itertools.product(('oauth', 'apikey'), ('http', 'ctx_pool', 'passthrough', 'http_bridge'), ('mismatch', 'aligned', 'pending', 'failed')):
+ assert ('handler', f'TestIssue892OpaqueEnvironmentAdapters/{kind}/{mode}/{scenario}') in passed
+ PY
+ test -z "$(git status --porcelain)"
+ - name: Frozen production behavioral RED with identical new tests
+ shell: bash
+ run: |
+ set -euo pipefail
+ git worktree add --detach "$RUNNER_TEMP/issue892-red" "$BASELINE_SHA"
+ test "$(git -C "$RUNNER_TEMP/issue892-red" rev-parse HEAD)" = "$BASELINE_SHA"
+ test -z "$(git -C "$RUNNER_TEMP/issue892-red" status --porcelain)"
+ git rev-parse "$BASELINE_SHA" "$BASELINE_SHA^{tree}" > "$RUNNER_TEMP/issue892/baseline.txt"
+ # No production overlay: the entire old tree stays at the frozen SHA.
+ # Only the two new test files are copied, with their Git blobs verified.
+ for target in backend/internal/service/openai_issue892_timezone_test.go backend/internal/handler/openai_issue892_timezone_test.go; do
+ test ! -e "$RUNNER_TEMP/issue892-red/$target"
+ git show "$EXPECTED_HEAD_SHA:$target" > "$RUNNER_TEMP/issue892-red/$target"
+ expected=$(git rev-parse "$EXPECTED_HEAD_SHA:$target")
+ actual=$(git hash-object "$RUNNER_TEMP/issue892-red/$target")
+ echo "$target expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue892/test-blobs.txt"
+ test "$expected" = "$actual"
+ done
+ cd "$RUNNER_TEMP/issue892-red"
+ git diff --exit-code
+ git status --porcelain > "$RUNNER_TEMP/issue892/red-status.txt"
+ set +e
+ (cd backend && go test -mod=readonly -json -tags=unit ./internal/handler -run '^TestIssue892((HTTP|WS)ManualTimezone|HTTP64SwitchMatrix)$' -count=1 -timeout=6m) > "$RUNNER_TEMP/issue892/red.jsonl" 2>&1
+ result=$?
+ set -e
+ cat "$RUNNER_TEMP/issue892/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"|context deadline exceeded' "$RUNNER_TEMP/issue892/red.jsonl"; then exit 1; fi
+ python3 - "$RUNNER_TEMP/issue892/red.jsonl" <<'PY'
+ import itertools, json, sys
+ events = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')]
+ failed = {e.get('Test') for e in events if e.get('Action') == 'fail'}
+ def require_red(name, marker, websocket=False):
+ assert name in failed, f'missing behavioral RED: {name}'
+ output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name)
+ assert marker in output, f'wrong failure point: {name}'
+ assert 'encrypted_agent_recovery_wire_changed' in output or (websocket and 'close_status=1008' in output), f'not an integrity policy refusal: {name}'
+ for kind, stream, owner in itertools.product(('oauth', 'apikey'), ('false', 'true'), ('unknown', 'same', 'other')):
+ require_red(f'TestIssue892HTTPManualTimezone/{kind}/stream={stream}/owner={owner}', 'Issue892 manual timezone full history must reach selected account once')
+ for kind, mode, owner in itertools.product(('oauth', 'apikey'), ('ctx_pool', 'passthrough', 'http_bridge'), ('unknown', 'same', 'other')):
+ require_red(f'TestIssue892WSManualTimezone/{kind}/{mode}/owner={owner}', 'Issue892 WS manual timezone full history must reach selected account once', websocket=True)
+ passed = {e.get('Test') for e in events if e.get('Action') == 'pass'}
+ corrected = 0
+ for optout, beta, recovery, stream, scenario in itertools.product(('false', 'true'), ('false', 'true'), ('false', 'true'), ('false', 'true'), ('unknown_top', 'unknown_part', 'same', 'reasoning400')):
+ name = f'TestIssue892HTTP64SwitchMatrix/optout={optout}/beta={beta}/recovery400={recovery}/stream={stream}/{scenario}'
+ if optout == 'true' and (scenario == 'same' or (scenario.startswith('unknown_') and beta == 'false')):
+ require_red(name, 'Issue892 64-case matrix must preserve switch semantics')
+ corrected += 1
+ else:
+ assert name in passed, f'matrix control failed on baseline: {name}'
+ assert corrected == 16
+ PY
+ git diff --exit-code
+ - name: Review F1 behavioral RED at the independently reviewed head
+ shell: bash
+ run: |
+ set -euo pipefail
+ reviewed=0fd8d600532bd759b2c33526db4773c615e1bc58
+ git worktree add --detach "$RUNNER_TEMP/issue895-review-red" "$reviewed"
+ cd "$RUNNER_TEMP/issue895-review-red"
+ test "$(git rev-parse HEAD)" = "$reviewed"
+ target=backend/internal/service/openai_issue892_timezone_test.go
+ git show "$EXPECTED_HEAD_SHA:$target" > "$target"
+ test "$(git hash-object "$target")" = "$(git rev-parse "$EXPECTED_HEAD_SHA:$target")"
+ git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue892/review-red-source.txt"
+ git diff --exit-code -- 'backend/**/*.go' ':!backend/**/*_test.go'
+ set +e
+ (cd backend && go test -mod=readonly -json -tags=unit ./internal/service -run '^TestIssue892(OpaqueEnvironmentProjectionRefused|ActualSendOpaqueIntegrityAndDelivery|PreparedUnknownOwnerRechecksFences|ManualTimezone400Recovery)$' -count=1 -timeout=2m) > "$RUNNER_TEMP/issue892/review-red.jsonl" 2>&1
+ result=$?
+ set -e
+ cat "$RUNNER_TEMP/issue892/review-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"|context deadline exceeded' "$RUNNER_TEMP/issue892/review-red.jsonl"; then exit 1; fi
+ python3 -B "$GITHUB_WORKSPACE/.github/scripts/assert-issue895-review-red.py" "$result" "$RUNNER_TEMP/issue892/review-red.jsonl"
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: issue892-${{ env.EXPECTED_HEAD_SHA }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/issue892/
+ if-no-files-found: error
diff --git a/backend/internal/handler/openai_issue842_boundaries_test.go b/backend/internal/handler/openai_issue842_boundaries_test.go
index de65f7decfa7..bfeffbd3c774 100644
--- a/backend/internal/handler/openai_issue842_boundaries_test.go
+++ b/backend/internal/handler/openai_issue842_boundaries_test.go
@@ -49,7 +49,7 @@ func TestIssue842HTTPBuilderChangesStopBeforeNetwork(t *testing.T) {
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")
+ body, want := issue842History(t, false, "reasoning_status")
settingsRepo := &issue842Settings{values: map[string]string{}}
switch change {
case "namespace":
@@ -69,6 +69,17 @@ func TestIssue842HTTPBuilderChangesStopBeforeNetwork(t *testing.T) {
h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
issue805Policy(t, h.cfg, true)
answer := issue758Request(t, h, body)
+ if change == "timezone" {
+ require.Equal(t, http.StatusOK, answer.Code, "Issue892 permits the administrator's finite timezone projection: %s", answer.Body.String())
+ want, setErr := sjson.Set(want, "input.1.content", "\n"+service.DefaultOpenAIRequestTimezone+"\n")
+ require.NoError(t, setErr)
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ require.Len(t, u.frames, 1)
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[0], "input").Raw)
+ require.Equal(t, "9007199254740993", gjson.GetBytes(u.frames[0], "input.1.sequence").Raw)
+ return
+ }
require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String())
require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_wire_changed")
u.mu.Lock()
diff --git a/backend/internal/handler/openai_issue892_timezone_test.go b/backend/internal/handler/openai_issue892_timezone_test.go
new file mode 100644
index 000000000000..b4ca88a5df9a
--- /dev/null
+++ b/backend/internal/handler/openai_issue892_timezone_test.go
@@ -0,0 +1,487 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "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"
+ coderws "github.com/coder/websocket"
+ "github.com/redis/go-redis/v9"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+func issue892Settings() map[string]string {
+ return map[string]string{
+ service.SettingKeyCyberSessionBlockEnabled: "false",
+ service.SettingKeyOpenAIRequestTimezoneEnabled: "true",
+ service.SettingKeyOpenAIRequestTimezoneAuto: "false",
+ service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "false",
+ service.SettingKeyOpenAI400OmitEncryptedHistoryEnabled: "false",
+ }
+}
+
+func issue892History(t *testing.T, stream bool, timezone string) (string, string) {
+ t.Helper()
+ body, want := issue842History(t, stream, "reasoning_content")
+ const environment = "\n/fixture\nAsia/Singapore\n"
+ var err error
+ body, err = sjson.Set(body, "input.-1", map[string]any{"role": "user", "content": environment})
+ require.NoError(t, err)
+ want, err = sjson.Set(want, "input.-1", map[string]any{"role": "user", "content": strings.Replace(environment, "Asia/Singapore", timezone, 1)})
+ require.NoError(t, err)
+ return body, want
+}
+
+func TestIssue892HTTPManualTimezone(t *testing.T) {
+ for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} {
+ for _, stream := range []bool{false, true} {
+ for _, owner := range []string{"unknown", "same", "other"} {
+ t.Run(fmt.Sprintf("%s/stream=%t/owner=%s", kind, stream, owner), 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 := &issue842Transport{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}
+ accounts[i].Extra = map[string]any{"openai_request_timezone": []string{"America/Los_Angeles", "Asia/Tokyo"}[i], "codex_fingerprint_mode": "off"}
+ }
+ accounts[1].Schedulable = false
+ newNode := func(disabled bool) *OpenAIGatewayHandler {
+ settings := service.NewSettingService(&issue842Settings{values: issue892Settings()}, cfg)
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, transport, repository.NewGatewayCache(clients()), settings, accounts...)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ issue805Policy(t, h.cfg, disabled)
+ return h
+ }
+ offset := 0
+ if owner != "unknown" {
+ 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)
+ offset = 1
+ }
+ original := issue805Owners(t, clients())
+ require.Len(t, original, offset, "completed ownership must precede the opt-out request")
+ for _, raw := range original {
+ require.True(t, issue805CompletedOwner(raw, 1), "the same-account regression requires a completed producer on A")
+ }
+ selected, timezone := "Bearer fixture-ws-one", "America/Los_Angeles"
+ if owner == "other" {
+ accounts[0].Schedulable = false
+ accounts[1].Schedulable = true
+ selected, timezone = "Bearer fixture-ws-two", "Asia/Tokyo"
+ }
+ body, want := issue892History(t, stream, timezone)
+ answer := issue758Request(t, newNode(true), body)
+ require.Equal(t, http.StatusOK, answer.Code, "Issue892 manual timezone full history must reach selected account once: %s", answer.Body.String())
+ issue758CompletedResponse(t, answer.Body.String(), stream)
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ require.Len(t, u.frames, offset+1, "no omission, retry, warmup or tool-result replay")
+ require.Equal(t, selected, u.ids[offset])
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[offset], "input").Raw)
+ require.Equal(t, "9007199254740993", gjson.GetBytes(u.frames[offset], "input.1.sequence").Raw)
+ for key, raw := range original {
+ require.Equal(t, raw, issue805Owners(t, clients())[key], "consumption must preserve the completed producer")
+ }
+ })
+ }
+ }
+ }
+}
+
+func issue892WSNode(t *testing.T, kind, mode, upstream string, cache service.GatewayCache, disabled, otherOwner 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"}}, issue892Settings(), 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, kind
+ a.Credentials = map[string]any{"api_key": "fixture-ws-one", "access_token": "fixture-ws-one", "base_url": upstream, "chatgpt_account_id": "fixture892-A"}
+ a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode
+ a.Extra["openai_oauth_responses_websockets_v2_enabled"] = true
+ a.Extra["openai_oauth_responses_websockets_v2_mode"] = mode
+ a.Extra["openai_request_timezone"] = "America/Los_Angeles"
+ a.Extra["codex_fingerprint_mode"] = "off"
+ cfg.Gateway.OpenAIWS.OAuthEnabled = true
+ cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 15
+ issue805Policy(t, cfg, disabled)
+ other := *a
+ other.ID, other.Priority = 2, 1
+ other.Credentials = map[string]any{"api_key": "fixture-ws-two", "access_token": "fixture-ws-two", "base_url": upstream, "chatgpt_account_id": "fixture892-B"}
+ other.Extra = make(map[string]any, len(a.Extra))
+ for key, value := range a.Extra {
+ other.Extra[key] = value
+ }
+ other.Extra["openai_request_timezone"] = "Asia/Tokyo"
+ if otherOwner {
+ reset := time.Now().Add(time.Hour)
+ a.RateLimitResetAt = &reset
+ }
+ *httpUpstream = &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ *repo = &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, other}}}
+ })
+ if kind == service.AccountTypeOAuth {
+ require.NoError(t, service.RouteIssue842OAuthSocketsToLoopbackForTest(h.handler.gatewayService, upstream))
+ }
+ return h
+}
+
+func TestIssue892WSManualTimezone(t *testing.T) {
+ for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} {
+ for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} {
+ for _, owner := range []string{"unknown", "same", "other"} {
+ t.Run(kind+"/"+mode+"/owner="+owner, func(t *testing.T) {
+ clients := issue805Redis(t)
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ offset := 0
+ if owner != "unknown" {
+ producer := issue892WSNode(t, kind, 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")
+ require.Eventually(t, func() bool {
+ owners := issue805Owners(t, clients())
+ for _, raw := range owners {
+ if !issue805CompletedOwner(raw, 1) {
+ return false
+ }
+ }
+ return len(owners) == 1
+ }, time.Second, 5*time.Millisecond)
+ issue600Finish(t, producer, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
+ offset = 1
+ }
+ original := issue805Owners(t, clients())
+ consumer := issue892WSNode(t, kind, mode, srv.URL, repository.NewGatewayCache(clients()), true, owner == "other")
+ selected, timezone := "Bearer fixture-ws-one", "America/Los_Angeles"
+ if owner == "other" {
+ selected, timezone = "Bearer fixture-ws-two", "Asia/Tokyo"
+ }
+ body, want := issue892History(t, true, timezone)
+ body, err := sjson.Set(body, "type", "response.create")
+ require.NoError(t, err)
+ for turn := 0; turn < 2; turn++ {
+ issue715WSSend(t, consumer.clientConn, body)
+ ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+ _, answer, readErr := consumer.clientConn.Read(ctx)
+ cancel()
+ require.NotErrorIs(t, readErr, context.DeadlineExceeded)
+ if readErr != nil {
+ t.Logf("Issue892 WS refusal close_status=%d", coderws.CloseStatus(readErr))
+ }
+ require.NoError(t, readErr, "Issue892 WS manual timezone full history must reach selected account once")
+ require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), "Issue892 WS manual timezone full history must reach selected account once: %s", answer)
+ }
+ issue600Finish(t, consumer, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ require.Len(t, u.frames, offset+2, "one generation per client turn")
+ for i, frame := range u.frames[offset:] {
+ require.Equal(t, selected, u.ids[offset+i])
+ 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(u.frames), u.http)
+ require.Zero(t, u.ws)
+ } else {
+ require.Equal(t, len(u.frames), u.ws)
+ require.Zero(t, u.http)
+ }
+ for key, raw := range original {
+ require.Equal(t, raw, issue805Owners(t, clients())[key])
+ }
+ })
+ }
+ }
+ }
+}
+
+type issue892LateFenceCache struct {
+ service.GatewayCache
+ issue715WSDeliveryCache
+ client *redis.Client
+ fence string
+ reads atomic.Int64
+}
+
+func (c *issue892LateFenceCache) GetOpenAIAgentRecovery(ctx context.Context, key string) (string, error) {
+ if c.reads.Add(1) == 2 {
+ value := "failed"
+ if c.fence == "pending" {
+ value = `pending:fixture-late892:[1,1,"` + strings.Repeat("a", 64) + `","` + strings.Repeat("b", 64) + `"]`
+ }
+ if err := c.client.Set(ctx, "openai_agent_owner:v1:"+key, value, time.Minute).Err(); err != nil {
+ return "", err
+ }
+ }
+ return c.issue715WSDeliveryCache.GetOpenAIAgentRecovery(ctx, key)
+}
+
+func TestIssue892OpaqueEnvironmentAdapters(t *testing.T) {
+ for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} {
+ for _, mode := range []string{"http", service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} {
+ for _, scenario := range []string{"mismatch", "aligned", "pending", "failed"} {
+ t.Run(kind+"/"+mode+"/"+scenario, func(t *testing.T) {
+ clients := issue805Redis(t)
+ baseCache := repository.NewGatewayCache(clients())
+ var cache service.GatewayCache = baseCache
+ if scenario == "pending" || scenario == "failed" {
+ cache = &issue892LateFenceCache{GatewayCache: baseCache, issue715WSDeliveryCache: baseCache.(issue715WSDeliveryCache), client: clients(), fence: scenario}
+ }
+ u := &issue805Oracle{}
+ srv := u.server(t)
+ stream := mode != "http"
+ body, want := issue892History(t, stream, "America/Los_Angeles")
+ environment := strings.Replace(issue892EnvironmentForAdapter, "Asia/Singapore", "America/Los_Angeles", 1)
+ if scenario == "mismatch" {
+ environment = issue892EnvironmentForAdapter
+ }
+ var err error
+ for _, target := range []*string{&body, &want} {
+ *target, err = sjson.Set(*target, "input.0.role", "user")
+ require.NoError(t, err)
+ *target, err = sjson.Set(*target, "input.0.content.0.text", environment)
+ require.NoError(t, err)
+ }
+ if mode == "http" {
+ target, parseErr := url.Parse(srv.URL)
+ require.NoError(t, parseErr)
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ account := issue715AccountsOfType(kind)[0]
+ account.Credentials = map[string]any{"api_key": "fixture-ws-one", "access_token": "fixture-ws-one", "base_url": srv.URL}
+ account.Extra = map[string]any{"openai_request_timezone": "America/Los_Angeles", "codex_fingerprint_mode": "off"}
+ transport := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ settings := service.NewSettingService(&issue842Settings{values: issue892Settings()}, cfg)
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, transport, cache, settings, account)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ issue805Policy(t, h.cfg, true)
+ answer := issue758Request(t, h, body)
+ if scenario == "aligned" {
+ require.Equal(t, http.StatusOK, answer.Code, answer.Body.String())
+ issue758CompletedResponse(t, answer.Body.String(), false)
+ } else {
+ require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String())
+ if scenario == "mismatch" {
+ require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_wire_changed")
+ } else {
+ require.Contains(t, []string{"encrypted_agent_recovery_owner_conflict", "encrypted_agent_recovery_owner_unavailable", "encrypted_agent_recovery_delivery_pending"}, gjson.Get(answer.Body.String(), "error.code").String())
+ }
+ }
+ } else {
+ h := issue892WSNode(t, kind, mode, srv.URL, cache, true, false)
+ body, err = sjson.Set(body, "type", "response.create")
+ require.NoError(t, err)
+ issue715WSSend(t, h.clientConn, body)
+ if scenario == "aligned" {
+ require.Equal(t, "response.completed", gjson.GetBytes(issue715WSRead(t, h.clientConn), "type").String())
+ } else {
+ code := "encrypted_agent_recovery_wire_changed"
+ if scenario == "pending" {
+ code = "encrypted_agent_recovery_delivery_pending"
+ } else if scenario == "failed" {
+ code = "encrypted_agent_recovery_owner_unavailable"
+ }
+ issue805WSRefusal(t, h.clientConn, code)
+ }
+ issue600Finish(t, h, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}})
+ }
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if scenario == "aligned" {
+ require.Len(t, u.frames, 1, "an intact first-seen opaque envelope reaches the selected adapter once")
+ require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[0], "input").Raw)
+ require.JSONEq(t, gjson.Get(body, "input.0").Raw, gjson.GetBytes(u.frames[0], "input.0").Raw)
+ require.Equal(t, "9007199254740993", gjson.GetBytes(u.frames[0], "input.1.sequence").Raw)
+ require.Len(t, issue805Owners(t, clients()), 1, "the new opaque output must complete transactional delivery")
+ } else {
+ require.Empty(t, u.frames, "changed opaque envelopes and new delivery fences must stop before physical send")
+ }
+ })
+ }
+ }
+ }
+}
+
+const issue892EnvironmentForAdapter = "\nAsia/Singapore\n"
+
+// The four scenario classes reproduce the reported matrix dimensions using
+// public synthetic inputs: two unknown opaque shapes, a completed same owner,
+// and an explicit HTTP 400 on two historical encrypted reasoning items.
+// Baseline: 40 successes, 8 raw 400s, 16 local timezone 409s. Candidate: the
+// same 8 raw 400s remain; the 16 local timezone refusals must reach upstream.
+func TestIssue892HTTP64SwitchMatrix(t *testing.T) {
+ for _, disabled := range []bool{false, true} {
+ for _, beta := range []bool{false, true} {
+ for _, recovery400 := range []bool{false, true} {
+ for _, stream := range []bool{false, true} {
+ for _, scenario := range []string{"unknown_top", "unknown_part", "same", "reasoning400"} {
+ t.Run(fmt.Sprintf("optout=%t/beta=%t/recovery400=%t/stream=%t/%s", disabled, beta, recovery400, stream, scenario), 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) {
+ 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()
+ w.Header().Set("Content-Type", "application/json")
+ if scenario == "reasoning400" && strings.Contains(string(body), "AAAA-fixture-1111") {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = io.WriteString(w, `{"error":{"code":"invalid_encrypted_content","message":"The encrypted content could not be verified."}}`)
+ return
+ }
+ output := `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"fixture matrix completed"}]}]`
+ if scenario == "same" && n == 1 {
+ output = "[" + issue715Agent + "]"
+ }
+ response := fmt.Sprintf(`{"id":"resp_matrix892_%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 {
+ _, _ = io.WriteString(w, response)
+ }
+ }))
+ defer srv.Close()
+ target, err := url.Parse(srv.URL)
+ require.NoError(t, err)
+ cfg := &config.Config{RunMode: config.RunModeSimple}
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ account := issue715Accounts()[0]
+ account.Credentials = map[string]any{"access_token": "fixture-matrix892", "base_url": srv.URL}
+ account.Extra = map[string]any{"openai_request_timezone": "America/Los_Angeles", "codex_fingerprint_mode": "off"}
+ newNode := func(optout, omission bool) *OpenAIGatewayHandler {
+ values := issue892Settings()
+ values[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled] = fmt.Sprint(omission)
+ values[service.SettingKeyOpenAI400OmitEncryptedHistoryEnabled] = fmt.Sprint(recovery400)
+ settings := service.NewSettingService(&issue842Settings{beta: omission, values: values}, cfg)
+ transport := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
+ h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, transport, repository.NewGatewayCache(clients()), settings, account)
+ h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ issue805Policy(t, h.cfg, optout)
+ return h
+ }
+ offset := 0
+ if scenario == "same" {
+ first := issue758Request(t, newNode(false, false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1))
+ require.Equal(t, http.StatusOK, first.Code, first.Body.String())
+ issue758CompletedResponse(t, first.Body.String(), stream)
+ offset = 1
+ }
+ original := issue805Owners(t, clients())
+ require.Len(t, original, offset)
+ body, want := issue892History(t, stream, "America/Los_Angeles")
+ if scenario == "unknown_top" {
+ for _, text := range []*string{&body, &want} {
+ *text, err = sjson.SetRaw(*text, "input.0", `{"type":"agent_message","author":"/fixture","recipient":"/fixture/worker","encrypted_content":"fixture-matrix892-top"}`)
+ require.NoError(t, err)
+ }
+ }
+ if scenario == "reasoning400" {
+ input := `[{"type":"reasoning","encrypted_content":"AAAA-fixture-1111","summary":[{"type":"summary_text","text":"visible reasoning one"}]},{"type":"reasoning","encrypted_content":"BBBB-fixture-2222","summary":[{"type":"summary_text","text":"visible reasoning two"}]},{"type":"function_call","name":"inspect","call_id":"call_fixture","arguments":"{\"sequence\":9007199254740993}"},{"type":"function_call_output","call_id":"call_fixture","output":"already completed"},{"role":"user","content":"Explain recorded result","sequence":9007199254740993}]`
+ body = fmt.Sprintf(`{"model":"gpt-5.1","store":false,"stream":%t,"input":%s}`, stream, input)
+ body, err = sjson.Set(body, "input.-1", map[string]any{"role": "user", "content": issue892EnvironmentForAdapter})
+ require.NoError(t, err)
+ want, err = sjson.Set(body, "input.5.content", strings.Replace(issue892EnvironmentForAdapter, "Asia/Singapore", "America/Los_Angeles", 1))
+ require.NoError(t, err)
+ }
+ answer := issue758Request(t, newNode(disabled, beta), body)
+ status, sends := http.StatusOK, 1
+ if scenario == "reasoning400" {
+ if recovery400 {
+ sends = 2
+ } else {
+ status = http.StatusBadRequest
+ }
+ }
+ require.Equal(t, status, answer.Code, "Issue892 64-case matrix must preserve switch semantics: %s", answer.Body.String())
+ if status == http.StatusOK {
+ issue758CompletedResponse(t, answer.Body.String(), stream)
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ require.Len(t, bodies, offset+sends)
+ for _, id := range identities {
+ require.Equal(t, "Bearer fixture-matrix892", id)
+ }
+ if scenario == "reasoning400" {
+ // Reasoning-only history follows the existing OAuth call-ID
+ // normalization on both sends. Keep call/output association exact.
+ for _, path := range []string{"input.2.call_id", "input.3.call_id"} {
+ want, err = sjson.Set(want, path, "fc_fixture")
+ require.NoError(t, err)
+ }
+ for _, payload := range bodies[offset:] {
+ for _, path := range []string{"input.2", "input.3", "input.4", "input.5"} {
+ require.JSONEq(t, gjson.Get(want, path).Raw, gjson.GetBytes(payload, path).Raw)
+ }
+ require.Equal(t, "9007199254740993", gjson.GetBytes(payload, "input.4.sequence").Raw)
+ }
+ if recovery400 {
+ require.NotContains(t, string(bodies[offset+1]), "AAAA-fixture-1111")
+ require.NotContains(t, string(bodies[offset+1]), "BBBB-fixture-2222")
+ }
+ } else if beta && scenario != "same" {
+ require.NotContains(t, string(bodies[offset]), "fixture-task-reference-715")
+ require.NotContains(t, string(bodies[offset]), "fixture-matrix892-top")
+ require.Equal(t, "9007199254740993", gjson.GetBytes(bodies[offset], "input.1.sequence").Raw)
+ } else {
+ if !disabled {
+ // Independent legacy strict-protocol oracle: the
+ // existing normalizer removes reasoning.content.
+ // Protected opt-out history must retain that text.
+ want, err = sjson.Delete(want, "input.5.content")
+ require.NoError(t, err)
+ }
+ 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)
+ }
+ owners := issue805Owners(t, clients())
+ if !disabled && !beta && strings.HasPrefix(scenario, "unknown_") {
+ require.Len(t, owners, 1, "strict mode retains its existing successful consumption learning")
+ for _, raw := range owners {
+ require.True(t, issue805CompletedOwner(raw, 1))
+ }
+ } else {
+ require.Equal(t, original, owners, "opt-out and omission cannot republish consumed ownership")
+ }
+ })
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/backend/internal/service/openai_400_omit_history.go b/backend/internal/service/openai_400_omit_history.go
index bc507ce7071f..fe4190d2244e 100644
--- a/backend/internal/service/openai_400_omit_history.go
+++ b/backend/internal/service/openai_400_omit_history.go
@@ -58,6 +58,12 @@ func (s *OpenAIGatewayService) prepareOpenAI400HistoryRecovery(ctx context.Conte
return refuse("delivery_unconfirmed")
}
expectedInput := r.inputDigest
+ if r.nativeReplayPrepared && !r.omittedHistory {
+ if r.nativeAccountID != account.ID {
+ return refuse("history_integrity")
+ }
+ expectedInput = r.nativeInputDigest
+ }
if r.omittedHistory && r.apiReplayPrepared {
expectedInput = r.apiInputDigest
}
@@ -87,6 +93,9 @@ func (s *OpenAIGatewayService) prepareOpenAI400HistoryRecovery(ctx context.Conte
// remains unchanged. Original keys/known/owner are retained for record and
// route checks; omitted inputs must never be published as consumed inputs.
next.inputDigest = openAIAgentRecoveryInputDigest(clean)
+ if next.nativeReplayPrepared && !next.omittedHistory {
+ next.nativeInputDigest = next.inputDigest
+ }
if next.omittedHistory && next.apiReplayPrepared {
// The retry skips native adaptation, so its final-send expectation must
// include this omission while retaining the frozen controls and route.
diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go
index 7da5b063f9e8..625e46049cc5 100644
--- a/backend/internal/service/openai_agent_message_recovery.go
+++ b/backend/internal/service/openai_agent_message_recovery.go
@@ -55,8 +55,9 @@ type openAIAgentRecoveryRequest struct {
previousResponseID string
inputDigest [32]byte
replaySource []byte // immutable pre-builder source, never a retry's mutable wire
- nativeOAuthInput [32]byte
- nativeOAuthPrepared bool
+ nativeInputDigest [32]byte
+ nativeReplayPrepared bool
+ nativeAccountID int64
replayControlsDigest [32]byte
apiControlsDigest [32]byte
apiInputDigest [32]byte
@@ -485,8 +486,11 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable")
}
expectedInput, expectedControls := request.inputDigest, request.replayControlsDigest
- if request.nativeOAuthPrepared && account.UsesOpenAICodexProtocol() && !request.omittedHistory {
- expectedInput = request.nativeOAuthInput
+ if request.nativeReplayPrepared && !request.omittedHistory {
+ if request.nativeAccountID != account.ID {
+ return noop, openAIAgentRecoveryRefusal(ctx, "route_identity")
+ }
+ expectedInput = request.nativeInputDigest
}
if request.omittedHistory && account.IsOpenAIApiKey() && request.apiReplayPrepared {
expectedInput, expectedControls = request.apiInputDigest, request.apiControlsDigest
@@ -512,14 +516,14 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con
}
items := openAIAgentRecoveryItemDigests(body)
if len(items) != len(request.items) {
- if request.owner != nil {
+ if request.owner != nil || request.preservesHistory() {
return noop, openAIAgentRecoveryError("wire_changed")
}
return noop, nil
}
for i := range items {
if items[i] != request.items[i] {
- if request.owner != nil {
+ if request.owner != nil || request.preservesHistory() {
return noop, openAIAgentRecoveryError("wire_changed")
}
return noop, nil
diff --git a/backend/internal/service/openai_agent_replay_metadata.go b/backend/internal/service/openai_agent_replay_metadata.go
index a6bdbb6db718..bcf3175cb3dc 100644
--- a/backend/internal/service/openai_agent_replay_metadata.go
+++ b/backend/internal/service/openai_agent_replay_metadata.go
@@ -3,6 +3,7 @@ package service
import (
"context"
"encoding/json"
+ "slices"
"strings"
"unicode/utf8"
@@ -26,19 +27,19 @@ func (s *OpenAIGatewayService) PrepareOpenAIAgentReplayBody(body []byte) ([]byte
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.
+// Derive the selected account's native input from the immutable source before
+// other builders run. OAuth stateless metadata and administrator-enabled manual
+// timezone normalization are the only permitted projections here.
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() {
+ if r == nil || !r.disableOwnerBinding || !r.preservesHistory() || r.omittedHistory || r.omitted400History || account == nil || !account.IsOpenAI() {
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)
+ projected, err := s.projectOpenAIAgentAccountReplay(ctx, account, r.replaySource, "http")
if err != nil {
return ctx, nil, err
}
@@ -46,12 +47,39 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentOAuthReplay(ctx context.Context
if err != nil {
return ctx, nil, err
}
+ if tools := gjson.GetBytes(projected, "tools"); tools.Exists() {
+ next, err = sjson.SetRawBytes(next, "tools", []byte(tools.Raw))
+ if err != nil {
+ return ctx, nil, err
+ }
+ }
private := *r
- private.nativeOAuthInput = openAIAgentRecoveryInputDigest(projected)
- private.nativeOAuthPrepared = true
+ private.nativeInputDigest = openAIAgentRecoveryInputDigest(projected)
+ private.nativeReplayPrepared = true
+ private.nativeAccountID = account.ID
return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &private), next, nil
}
+func (s *OpenAIGatewayService) projectOpenAIAgentAccountReplay(ctx context.Context, account *Account, source []byte, transport string) ([]byte, error) {
+ projected := append([]byte(nil), source...)
+ if account.UsesOpenAICodexProtocol() {
+ var err error
+ projected, err = projectOpenAIOAuthReasoningMetadata(projected)
+ if err != nil {
+ return nil, err
+ }
+ }
+ // Auto mode retains its existing transport-boundary body preservation.
+ projected = s.normalizeRequestTimezone(ctx, account, projected, transport)
+ // An opaque item's readable envelope is part of its protected identity,
+ // even when role=user makes it eligible for the general timezone builder.
+ // Refuse that projection; never authorize it by replacing the item proof.
+ if !slices.Equal(openAIAgentRecoveryItemDigests(source), openAIAgentRecoveryItemDigests(projected)) {
+ return nil, openAIAgentRecoveryRefusal(ctx, "input_integrity")
+ }
+ return projected, 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.
diff --git a/backend/internal/service/openai_issue892_timezone_test.go b/backend/internal/service/openai_issue892_timezone_test.go
new file mode 100644
index 000000000000..f4030e99f8f6
--- /dev/null
+++ b/backend/internal/service/openai_issue892_timezone_test.go
@@ -0,0 +1,402 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+ "github.com/tidwall/sjson"
+)
+
+const issue892Environment = "\n/fixture\nAsia/Singapore\n"
+
+func issue892PrepareHTTP(t *testing.T, svc *OpenAIGatewayService, ctx context.Context, account *Account, source []byte) (context.Context, []byte, error) {
+ t.Helper()
+ // Older unrelated RED overlays predate this method. Keep them compilable;
+ // this regression requires the method whenever it is actually executed.
+ preparer, ok := any(svc).(interface {
+ prepareOpenAIAgentOAuthReplay(context.Context, *Account, []byte) (context.Context, []byte, error)
+ })
+ require.True(t, ok)
+ return preparer.prepareOpenAIAgentOAuthReplay(ctx, account, source)
+}
+
+func issue892PrepareWS(t *testing.T, manager *openAIWSAgentRecovery, account *Account, source []byte) ([]byte, error) {
+ t.Helper()
+ preparer, ok := any(manager).(interface {
+ prepareReadable(*Account, []byte) ([]byte, error)
+ })
+ require.True(t, ok)
+ return preparer.prepareReadable(account, source)
+}
+
+func issue892FrozenSource(t *testing.T) []byte {
+ t.Helper()
+ // Independently remove the metadata normalized before the original freeze.
+ body := []byte(strings.ReplaceAll(strings.ReplaceAll(issue842Source, `,"status":"completed"`, ""), `,"id":"rs_fixture842"`, ""))
+ var err error
+ body, err = sjson.SetBytes(body, "input.-1", map[string]any{"role": "user", "content": issue892Environment})
+ require.NoError(t, err)
+ body, err = sjson.SetBytes(body, "input.-1", map[string]any{"role": "user", "content": []any{map[string]any{"type": "input_text", "text": issue892Environment}, map[string]any{"type": "input_text", "text": "Keep Asia/Singapore in ordinary task text"}}})
+ require.NoError(t, err)
+ return body
+}
+
+func issue892Expected(t *testing.T, source []byte, timezone string) []byte {
+ t.Helper()
+ environment := strings.Replace(issue892Environment, "Asia/Singapore", timezone, 1)
+ want, err := sjson.SetBytes(source, "input.5.content", environment)
+ require.NoError(t, err)
+ want, err = sjson.SetBytes(want, "input.6.content.0.text", environment)
+ require.NoError(t, err)
+ return want
+}
+
+func TestIssue892FrozenAccountTimezoneProjection(t *testing.T) {
+ for _, kind := range []string{AccountTypeAPIKey, AccountTypeOAuth} {
+ for _, transport := range []string{"http", "ws"} {
+ for _, mutation := range []string{"intact", "task", "cipher", "arguments", "result", "number", "order", "timezone", "outside_environment", "source", "account"} {
+ t.Run(kind+"/"+transport+"/"+mutation, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: timezoneEnabledSettings()}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ manager, c, account := issue715WSManager(t, svc, context.Background())
+ defer manager.abort()
+ account.Type = kind
+ account.Extra = map[string]any{openAIRequestTimezoneExtraKey: "America/Los_Angeles"}
+ source := issue892FrozenSource(t)
+ original := append([]byte(nil), source...)
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, source, "fixture-session", "gpt-6-astra")
+ var payload []byte
+ var err error
+ if transport == "http" {
+ ctx, payload, err = issue892PrepareHTTP(t, svc, ctx, account, source)
+ } else {
+ payload, err = issue892PrepareWS(t, manager, account, source)
+ }
+ require.NoError(t, err)
+ require.Equal(t, original, source, "account preparation must preserve the original bytes")
+ require.Equal(t, openAIAgentRecoveryInputDigest(issue892Expected(t, source, "America/Los_Angeles")), openAIAgentRecoveryInputDigest(payload), "Issue892 account timezone must be projected from the frozen source")
+ path, value := "", "unauthorized892"
+ switch mutation {
+ case "task", "source":
+ path = "input.2.content"
+ case "cipher":
+ path = "input.0.encrypted_content"
+ case "arguments":
+ path = "input.3.arguments"
+ case "result":
+ path = "input.4.output"
+ case "number":
+ payload, err = sjson.SetRawBytes(payload, "input.2.sequence", []byte("9007199254740992"))
+ case "order":
+ payload, err = sjson.DeleteBytes(payload, "input.2")
+ case "timezone":
+ path, value = "input.5.content", strings.Replace(issue892Environment, "Asia/Singapore", "Asia/Tokyo", 1)
+ case "outside_environment":
+ path = "input.6.content.1.text"
+ case "account":
+ account.ID++
+ }
+ require.NoError(t, err)
+ if path != "" {
+ payload, err = sjson.SetBytes(payload, path, value)
+ require.NoError(t, err)
+ }
+ if mutation == "source" {
+ source = append([]byte(nil), payload...)
+ if transport == "http" {
+ _, _, err = issue892PrepareHTTP(t, svc, ctx, account, source)
+ require.Error(t, err, "a prepared body cannot replace the original source")
+ return
+ }
+ }
+ if transport == "http" {
+ req, requestErr := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(payload))
+ require.NoError(t, requestErr)
+ finish, attemptErr := svc.prepareOpenAIAgentRecoveryAttempt(ctx, account, req)
+ defer finish(false)
+ err = attemptErr
+ } else {
+ 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)
+ } else {
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal)
+ require.Equal(t, "wire_changed", refusal.Reason)
+ }
+ })
+ }
+ }
+ }
+}
+
+func TestIssue892AccountReselectionUsesOriginalSource(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: timezoneEnabledSettings()}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ manager, c, account := issue715WSManager(t, svc, context.Background())
+ defer manager.abort()
+ source := issue892FrozenSource(t)
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, source, "fixture-session", "gpt-6-astra")
+ for _, zone := range []string{"America/Los_Angeles", "Asia/Tokyo", "Asia/Singapore"} {
+ account.ID++
+ account.Extra = map[string]any{openAIRequestTimezoneExtraKey: zone}
+ next, body, err := issue892PrepareHTTP(t, svc, ctx, account, source)
+ require.NoError(t, err)
+ require.Equal(t, openAIAgentRecoveryInputDigest(issue892Expected(t, source, zone)), openAIAgentRecoveryInputDigest(body))
+ require.Equal(t, openAIAgentRecoveryInputDigest(source), openAIAgentRecoveryFromContext(next).inputDigest)
+ body, err = issue892PrepareWS(t, manager, account, source)
+ require.NoError(t, err)
+ require.Equal(t, openAIAgentRecoveryInputDigest(issue892Expected(t, source, zone)), openAIAgentRecoveryInputDigest(body))
+ }
+ require.Equal(t, "9007199254740993", gjson.GetBytes(source, "input.2.sequence").Raw)
+}
+
+func TestIssue892TimezonePolicyControlsProjection(t *testing.T) {
+ for _, mode := range []string{"disabled", "auto", "manual", "aligned"} {
+ t.Run(mode, func(t *testing.T) {
+ svc := timezoneAutoService(mode != "disabled", mode == "auto", nil)
+ svc.cfg = &config.Config{}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ manager, c, account := issue715WSManager(t, svc, context.Background())
+ defer manager.abort()
+ timezone := "America/Los_Angeles"
+ if mode == "aligned" {
+ timezone = "Asia/Singapore"
+ }
+ account.Extra = map[string]any{openAIRequestTimezoneExtraKey: timezone}
+ source := issue892FrozenSource(t)
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, source, "fixture-session", "gpt-6-astra")
+ _, body, err := issue892PrepareHTTP(t, svc, ctx, account, source)
+ require.NoError(t, err)
+ want := source
+ if mode == "manual" {
+ want = issue892Expected(t, source, timezone)
+ }
+ require.Equal(t, openAIAgentRecoveryInputDigest(want), openAIAgentRecoveryInputDigest(body))
+ body, err = issue892PrepareWS(t, manager, account, source)
+ require.NoError(t, err)
+ require.Equal(t, openAIAgentRecoveryInputDigest(want), openAIAgentRecoveryInputDigest(body))
+ })
+ }
+}
+
+func TestIssue892OpaqueEnvironmentProjectionRefused(t *testing.T) {
+ for _, kind := range []string{AccountTypeAPIKey, AccountTypeOAuth} {
+ for _, transport := range []string{"http", "ws"} {
+ t.Run(kind+"/"+transport, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: timezoneEnabledSettings()}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ manager, c, account := issue715WSManager(t, svc, context.Background())
+ defer manager.abort()
+ account.Type, account.Extra = kind, map[string]any{openAIRequestTimezoneExtraKey: "America/Los_Angeles"}
+ source, err := sjson.SetBytes(issue892FrozenSource(t), "input.0.role", "user")
+ require.NoError(t, err)
+ source, err = sjson.SetBytes(source, "input.0.content", []any{map[string]any{"type": "input_text", "text": issue892Environment}})
+ require.NoError(t, err)
+ original := append([]byte(nil), source...)
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, source, "fixture-session", "gpt-6-astra")
+ if transport == "http" {
+ _, _, err = issue892PrepareHTTP(t, svc, ctx, account, source)
+ } else {
+ _, err = issue892PrepareWS(t, manager, account, source)
+ }
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal, "Issue895 F1 projection must refuse a changed opaque envelope")
+ require.Equal(t, "wire_changed", refusal.Reason)
+ require.Equal(t, original, source)
+ })
+ }
+ }
+}
+
+func TestIssue892ActualSendOpaqueIntegrityAndDelivery(t *testing.T) {
+ for _, transport := range []string{"http", "ws"} {
+ for _, mutation := range []string{"intact", "envelope", "drop"} {
+ t.Run(transport+"/"+mutation, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: timezoneEnabledSettings()}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ manager, c, account := issue715WSManager(t, svc, context.Background())
+ defer manager.abort()
+ account.Extra = map[string]any{openAIRequestTimezoneExtraKey: "America/Los_Angeles"}
+ source := issue892FrozenSource(t)
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, source, "fixture-session", "gpt-6-astra")
+ var payload []byte
+ var err error
+ if transport == "http" {
+ ctx, payload, err = issue892PrepareHTTP(t, svc, ctx, account, source)
+ } else {
+ payload, err = issue892PrepareWS(t, manager, account, source)
+ }
+ require.NoError(t, err)
+ switch mutation {
+ case "envelope":
+ payload, err = sjson.SetBytes(payload, "input.0.content", "changed opaque envelope")
+ case "drop":
+ payload, err = sjson.DeleteBytes(payload, "input.0")
+ }
+ require.NoError(t, err)
+ // Model the former permissive input projection. The independent
+ // original item proof must still reject it at the actual send gate.
+ // No item digest is replaced, including for an unknown owner.
+ var finish func(bool)
+ if transport == "http" {
+ openAIAgentRecoveryFromContext(ctx).nativeInputDigest = openAIAgentRecoveryInputDigest(payload)
+ req, requestErr := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(payload))
+ require.NoError(t, requestErr)
+ finish, err = svc.prepareOpenAIAgentRecoveryAttempt(ctx, account, req)
+ defer finish(false)
+ } else {
+ manager.protected.inputDigest = openAIAgentRecoveryInputDigest(payload)
+ err = manager.beginSocket(account, source, payload, "wss://native.example/v1/responses", http.Header{"Authorization": {"Bearer fixture"}}, "ctx_pool")
+ }
+ if mutation != "intact" {
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal, "Issue895 F1 actual send must reject a changed opaque item even if input projection matched")
+ require.Equal(t, "wire_changed", refusal.Reason)
+ return
+ }
+ require.NoError(t, err)
+ request := openAIAgentRecoveryFromContext(ctx)
+ if transport == "ws" {
+ request = manager.request
+ }
+ require.Nil(t, request.owner, "exercise a first-seen opaque item")
+ require.NotNil(t, request.delivery, "an intact unknown owner must retain its delivery fence")
+ output := []byte(`{"type":"response.completed","response":{"id":"resp_fixture892_delivery","status":"completed","output":[{"type":"agent_message","encrypted_content":"fixture-new-output892"}]}}`)
+ assertReserved := func() error {
+ require.Len(t, request.delivery.keys, 1, "reserve the new opaque output before client exposure")
+ for key := range request.delivery.keys {
+ svc.agentMessageRecovery.mu.Lock()
+ binding := svc.agentMessageRecovery.bindings[key]
+ svc.agentMessageRecovery.mu.Unlock()
+ require.NotEmpty(t, binding.pending, "client write must observe a pending reservation")
+ }
+ return nil
+ }
+ if transport == "http" {
+ c.Request = c.Request.WithContext(ctx)
+ require.NoError(t, observeOpenAIAgentRecoveryOutput(c, output, true))
+ require.NoError(t, assertReserved())
+ finish(true)
+ } else {
+ require.NoError(t, manager.write(output, assertReserved))
+ }
+ })
+ }
+ }
+}
+
+func TestIssue892PreparedUnknownOwnerRechecksFences(t *testing.T) {
+ for _, transport := range []string{"http", "ws"} {
+ for _, fence := range []string{"pending", "failed"} {
+ t.Run(transport+"/"+fence, func(t *testing.T) {
+ svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: timezoneEnabledSettings()}
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ manager, c, account := issue715WSManager(t, svc, context.Background())
+ defer manager.abort()
+ account.Extra = map[string]any{openAIRequestTimezoneExtraKey: "America/Los_Angeles"}
+ source := issue892FrozenSource(t)
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, source, "fixture-session", "gpt-6-astra")
+ var payload []byte
+ var err error
+ if transport == "http" {
+ ctx, payload, err = issue892PrepareHTTP(t, svc, ctx, account, source)
+ } else {
+ payload, err = issue892PrepareWS(t, manager, account, source)
+ }
+ require.NoError(t, err)
+ request := openAIAgentRecoveryFromContext(ctx)
+ require.Nil(t, request.owner)
+ require.Len(t, request.keys, 1)
+ late := openAIAgentRecoveryBinding{accountID: account.ID, expiresAt: time.Now().Add(time.Minute), failed: fence == "failed"}
+ if fence == "pending" {
+ late.pending = "fixture-late-owner892"
+ }
+ svc.agentMessageRecovery.mu.Lock()
+ svc.agentMessageRecovery.bindings = map[[32]byte]openAIAgentRecoveryBinding{request.keys[0]: late}
+ svc.agentMessageRecovery.mu.Unlock()
+ if transport == "http" {
+ req, requestErr := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(payload))
+ require.NoError(t, requestErr)
+ finish, attemptErr := svc.prepareOpenAIAgentRecoveryAttempt(ctx, account, req)
+ defer finish(false)
+ err = attemptErr
+ } else {
+ err = manager.beginSocket(account, source, payload, "wss://native.example/v1/responses", http.Header{"Authorization": {"Bearer fixture"}}, "ctx_pool")
+ }
+ var refusal *OpenAIAgentRecoveryError
+ require.ErrorAs(t, err, &refusal, "a fence appearing after preparation must prevent the actual send")
+ require.Contains(t, []string{"owner_conflict", "owner_unavailable", "delivery_pending"}, refusal.Reason)
+ require.Nil(t, request.delivery)
+ })
+ }
+ }
+}
+
+func TestIssue892ManualTimezone400Recovery(t *testing.T) {
+ for _, mode := range []string{"enabled", "disabled", "ordinary400", "SSE"} {
+ t.Run(mode, func(t *testing.T) {
+ response := func(status int, body string) *http.Response {
+ return &http.Response{StatusCode: status, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(body))}
+ }
+ failure := response(http.StatusBadRequest, history400Failure)
+ if mode == "ordinary400" {
+ failure = response(http.StatusBadRequest, `{"error":{"code":"invalid_request_error","message":"fixture rejection"}}`)
+ }
+ if mode == "SSE" {
+ failure = newStreamLineageSSEResponse(encryptedSSERetryEvent(encryptedSSERetryFailure))
+ }
+ upstream := &httpUpstreamSequenceRecorder{responses: []*http.Response{failure, response(http.StatusOK, `{"id":"resp_fixture892","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`)}}
+ svc := newStreamLineageHTTPService(upstream)
+ svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true
+ svc.settingService = NewSettingService(&history400SettingsRepo{values: map[string]string{
+ SettingKeyOpenAIRequestTimezoneEnabled: "true",
+ SettingKeyOpenAIRequestTimezoneAuto: "false",
+ SettingKeyOpenAI400OmitEncryptedHistoryEnabled: fmt.Sprint(mode != "disabled"),
+ }}, svc.cfg)
+ input := "[" + gjson.Get(issue715OpaqueBody, "input.0").Raw + "," + strings.TrimPrefix(history400Input, "[")
+ body, err := sjson.SetBytes(history400Body(input, mode == "SSE"), "input.-1", map[string]any{"role": "user", "content": issue892Environment})
+ require.NoError(t, err)
+ c, rec := newStreamLineageTestContext("fixture892-400")
+ c.Set("api_key", &APIKey{ID: 7, AllowLongContext: true})
+ ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, body, "fixture892-400", "gpt-5.1")
+ c.Request = c.Request.WithContext(ctx)
+ account := newStreamLineageHTTPAccount()
+ account.Extra = map[string]any{openAIRequestTimezoneExtraKey: "America/Los_Angeles"}
+ _, err = svc.Forward(ctx, c, account, body)
+ if mode == "enabled" {
+ require.NoError(t, err, rec.Body.String())
+ require.Equal(t, 2, upstream.callCount, "one authorized same-account HTTP 400 recovery")
+ for _, path := range []string{"input.3", "input.4", "input.5", "input.6"} {
+ require.JSONEq(t, gjson.GetBytes(upstream.bodies[0], path).Raw, gjson.GetBytes(upstream.bodies[1], path).Raw)
+ }
+ require.Equal(t, upstream.reqs[0].URL.String(), upstream.reqs[1].URL.String())
+ require.Equal(t, upstream.reqs[0].Header.Get("Authorization"), upstream.reqs[1].Header.Get("Authorization"))
+ require.NotContains(t, string(upstream.bodies[1]), "AAAA-fixture-1111")
+ retryCtx := upstream.reqs[1].Context()
+ require.True(t, openAIAgentRecoveryFromContext(retryCtx).omitted400History)
+ _, replayed, prepareErr := issue892PrepareHTTP(t, svc, retryCtx, account, upstream.bodies[1])
+ require.NoError(t, prepareErr)
+ require.Equal(t, upstream.bodies[1], replayed, "an authorized 400 omission must not restore the original ciphertext")
+ require.Same(t, openAIAgentRecoveryFromContext(ctx), openAIAgentRecoveryFromContext(c.Request.Context()), "Forward restores the original recovery after returning")
+ _, _, prepareErr = issue892PrepareHTTP(t, svc, c.Request.Context(), account, upstream.bodies[1])
+ require.Error(t, prepareErr, "the original context cannot authorize a body with omitted ciphertext")
+ } else {
+ require.Error(t, err)
+ require.Equal(t, 1, upstream.callCount, "400 recovery must not expand to disabled, arbitrary 400 or SSE failures")
+ }
+ require.Contains(t, gjson.GetBytes(upstream.bodies[0], "input.6.content").String(), "America/Los_Angeles")
+ require.Contains(t, string(body), "Asia/Singapore")
+ })
+ }
+}
diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go
index dd8e0ebe47ab..079f7a960044 100644
--- a/backend/internal/service/openai_ws_agent_recovery.go
+++ b/backend/internal/service/openai_ws_agent_recovery.go
@@ -152,13 +152,12 @@ func (r *openAIWSAgentRecovery) prepareReadable(account *Account, source []byte)
return nil, err
}
if r.service.preserveOpenAIAgentHistory(source) {
- if account.UsesOpenAICodexProtocol() {
- clean, err = projectOpenAIOAuthReasoningMetadata(clean)
- if err != nil {
- return nil, err
- }
+ clean, err = r.service.projectOpenAIAgentAccountReplay(r.ctx, account, clean, "ws")
+ if err != nil {
+ return nil, err
}
- // Freeze before compatibility, timezone, OAuth or tool builders.
+ // Freeze the finite account projection before compatibility, OAuth
+ // or tool builders. Every turn/account starts from its source frame.
// begin may refresh owner records, but cannot trust a new input.
model := gjson.GetBytes(source, "model").String()
if initial != nil {
@@ -166,6 +165,7 @@ func (r *openAIWSAgentRecovery) prepareReadable(account *Account, source []byte)
}
ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, clean, r.session, model)
r.protected = openAIAgentRecoveryFromContext(ctx)
+ r.protected.nativeAccountID = account.ID
r.protectedSource = openAIAgentRecoveryInputDigest(source)
r.protectedControls = openAI409ControlsDigest(source)
}
@@ -286,6 +286,9 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte,
}
ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, source, r.session, model)
if r.protected != nil {
+ if r.protected.nativeAccountID != account.ID {
+ return openAIAgentRecoveryRefusal(ctx, "route_identity")
+ }
if openAIAgentRecoveryInputDigest(source) != r.protectedSource || openAI409ControlsDigest(source) != r.protectedControls {
return openAIAgentRecoveryRefusal(ctx, "input_integrity")
}