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-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/workflows/encrypted-history-409.yml b/.github/workflows/encrypted-history-409.yml index 93d6e66b26f9..b0e052f9cc2d 100644 --- a/.github/workflows/encrypted-history-409.yml +++ b/.github/workflows/encrypted-history-409.yml @@ -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..e497ba0a8786 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,13 @@ 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) # 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 +121,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" "$metadata_leaf" "${weekly_leaves[@]}" 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" @@ -153,7 +161,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 +198,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 +235,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" @@ -265,12 +273,19 @@ 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" "$metadata_leaf" "${omission_added[@]}" 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") @@ -294,7 +309,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,7 +347,7 @@ 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" @@ -382,7 +397,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 +474,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 +540,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..61a3883d2512 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: @@ -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..910e58d22bd2 100644 --- a/.github/workflows/readable-continuation-409.yml +++ b/.github/workflows/readable-continuation-409.yml @@ -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..a64b9e9bcd15 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,6 +204,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/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 @@ -264,6 +268,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_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index b361d2689eb8..5fec03d6f578 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 { 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/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..91e79b8aca77 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 } diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index db80033374eb..65f92fd0a63c 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()) @@ -384,7 +388,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 +396,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 +411,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 +436,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 +466,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_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_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_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index d26560e52b10..8060555faa29 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")