diff --git a/.github/scripts/pr1012-oracle.py b/.github/scripts/pr1012-oracle.py new file mode 100644 index 000000000000..bf7fac8f3675 --- /dev/null +++ b/.github/scripts/pr1012-oracle.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Verify named PR1012 behavior in go test JSONL; exit status alone is not RED.""" + +import itertools +import json +import re +import sys +from collections import Counter, defaultdict +from pathlib import Path + + +PKG = "github.com/Wei-Shaw/sub2api/internal/" +WS = "TestOpenAIWSRetryDeadlineAtGenerationWrite" +READERS = "TestSSETypeOnlyQuotaReaders" +NORMALIZED = "TestSSEQuotaNormalizedExplicitCodeReaders" +POOL429 = "TestSSEQuotaNormalizedPool429Readers" +QUOTAS = ("insufficient_quota", "quota_exceeded", "usage_limit_reached") +BOOLS = ("false", "true") +STAGES = ("backoff", "user_slot", "account_slot", "handshake", "inflight", "output", "canceled") + + +def quota_leaves(): + return { + f"{READERS}/{kind}/{quota}/passthrough={passthrough}/pool502={pool}" + for kind, quota, passthrough, pool in itertools.product( + ("oauth", "apikey"), QUOTAS, BOOLS, BOOLS + ) + } + + +def normalized_quota_leaves(): + return { + f"{NORMALIZED}/{kind}/{quota}/{variant}/passthrough={passthrough}/pool502=true" + for kind, quota, variant, passthrough in itertools.product( + ("oauth", "apikey"), QUOTAS, ("uppercase", "padded"), BOOLS + ) + } + + +def pool429_quota_leaves(): + return { + f"{POOL429}/{kind}/{quota}/{variant}/passthrough={passthrough}/pool={policy}" + for kind, quota, variant, passthrough, policy in itertools.product( + ("oauth", "apikey"), QUOTAS, ("uppercase", "padded"), BOOLS, ("default", "explicit429") + ) + } + + +def green_tests(): + service = quota_leaves() | normalized_quota_leaves() | pool429_quota_leaves() | { + READERS, + NORMALIZED, + POOL429, + "TestSSEQuotaBareErrorCanComplete", + "TestSSEQuotaClassificationRetainsExplicitCodeAndIntegrity", + "TestSSEQuotaNormalizedAfterOutputCannotReplay", + "TestSSEQuotaTerminalDoesNotGrantHTTPRejectionProof", + "TestStrictSameAccountRetryRequiresCurrentBinding", + "TestSameAccountRetrySchedulerCannotEscape", + "TestStrictSessionAffinityLosingFirstTurnReleasesSlot", + "TestOAuthNormalEOFBeforeOutputPreservesAccount", + "TestOAuthNormalEOFAfterOutputCannotReplay", + "TestOpenAIGatewayService_ProxyResponsesWebSocketFromClient_ClientDisconnectStillDrainsUpstream", + "TestOpenAIResponseFlush_BareErrorFollowedByCompletedUsesCompletedTerminal", + "TestOpenAIStreamingPassthroughBareErrorTerminatesBeforeDone", + "TestOpenAIStreamingPassthroughBareErrorDrainsAuthoritativeFailedUsage", + } + service.update(f"TestSSEQuotaBareErrorCanComplete/{quota}" for quota in QUOTAS) + service.update( + f"TestSSEQuotaNormalizedAfterOutputCannotReplay/{kind}/{quota}/{variant}/passthrough={passthrough}" + for kind, quota, variant, passthrough in itertools.product( + ("oauth", "apikey"), QUOTAS, ("uppercase", "padded"), BOOLS + ) + ) + service.update(f"TestStrictSameAccountRetryRequiresCurrentBinding/{owner}" for owner in ("947101", "947102", "0")) + service.update( + f"TestSameAccountRetrySchedulerCannotEscape/advanced={advanced}/weighted={weighted}/{scenario}" + for advanced, weighted, scenario in itertools.product( + BOOLS, BOOLS, ("busy", "recovered", "excluded", "disabled", "wrong_group", "no_session", "expired", "canceled") + ) + ) + handler = {WS, "TestSSEQuotaWithoutResetUsesBoundedAccountFailover", "TestOAuthRetryOwnerBusyAfterSlotRelease", "TestIssue917ResponsesCooldown"} + handler.update(f"{WS}/{stage}" for stage in STAGES) + handler.update( + f"TestSSEQuotaWithoutResetUsesBoundedAccountFailover/{kind}/{form}/passthrough={passthrough}/stream={stream}" + for kind, form, passthrough, stream in itertools.product( + ("oauth", "apikey"), QUOTAS + tuple(f"type:{quota}" for quota in QUOTAS), BOOLS, BOOLS + ) + ) + handler.update( + f"TestOAuthRetryOwnerBusyAfterSlotRelease/{scenario}/switches={switches}" + for scenario, switches in itertools.product(("busy_timeout", "recovered", "exhausted", "canceled"), (0, 2)) + ) + handler.update( + f"TestIssue917ResponsesCooldown/{route}/{case}" + for route, case in itertools.product( + ("normal", "passthrough", "oauth"), + ("initial", "after_output", "disabled", "nonmatching", "legacy_timing", "before_stream", "threshold_eof", "threshold_pair_before_output", "threshold_pair_after_output", "context_window", "encrypted_request", "cyber_policy"), + ) + ) + return {(PKG + "service", name) for name in service} | {(PKG + "handler", name) for name in handler} + + +def verify(mode, status_path, log_path): + status = int(Path(status_path).read_text().strip()) + rows = [] + for line in Path(log_path).read_text().splitlines(): + if not line.strip() or line.startswith("go: downloading "): + continue + rows.append(json.loads(line)) + assert rows, "missing Go test execution" + output = "".join(row.get("Output", "") for row in rows) + forbidden = r"WARNING: DATA RACE|race detected during execution of test|panic:|fatal error:|test timed out|build failed|setup failed|undefined:|syntax error:|no tests to run|signal: killed|fixture read timed out|handler did not release the retry|upstream retry lease remained open|retry handshake was not observed|retry never reached the held handshake" + assert not re.search(forbidden, output, re.I), "non-behavior failure in evidence" + assert not any(row.get("Action") in ("skip", "build-fail") for row in rows), "skipped/build-failed execution" + handler_red = mode in ("red-b1", "red-backoff") + packages = {PKG + "service", PKG + "handler"} if mode == "green" else {PKG + ("handler" if handler_red else "service")} + assert all(row.get("Package") in packages for row in rows), "unexpected package or compiler event" + assert all(row.get("Action") in ("start", "run", "output", "pass", "fail", "pause", "cont") for row in rows), "unexpected Go event" + counts = Counter((row.get("Package"), row.get("Test"), row.get("Action")) for row in rows) + fragments = defaultdict(str) + for row in rows: + fragments[(row.get("Package"), row.get("Test"))] += row.get("Output", "") + failed = {(row.get("Package"), row["Test"]) for row in rows if row.get("Action") == "fail" and row.get("Test")} + if mode == "green": + assert status == 0, f"GREEN exit {status}" + expected = green_tests() + terminal = "pass" + assert not failed, f"unexpected GREEN failures: {failed}" + for package in (PKG + "service", PKG + "handler"): + assert counts[(package, None, "pass")] == 1, f"missing package PASS: {package}" + assert counts[(package, None, "fail")] == 0, f"package failed: {package}" + else: + assert status == 1, f"RED must be a test failure, got {status}" + assert mode in ("red-b1", "red-b3", "red-f1", "red-f2", "red-backoff"), mode + package = PKG + ("handler" if handler_red else "service") + names = {WS + ("/handshake" if mode == "red-b1" else "/backoff")} if handler_red else quota_leaves() + if mode == "red-f1": + names = normalized_quota_leaves() + if mode == "red-f2": + names = pool429_quota_leaves() + expected = {(package, name) for name in names} + terminal = "fail" + # Slash-containing names passed to one t.Run do not create parent tests. + expected_failures = expected | {(package, WS if handler_red else READERS)} + if mode == "red-f1": + expected_failures = expected | {(package, NORMALIZED)} + if mode == "red-f2": + expected_failures = expected | {(package, POOL429)} + assert failed == expected_failures, f"missing or unexpected RED assertions: {failed ^ expected_failures}" + assert counts[(package, None, "fail")] == 1, "missing package failure" + assert counts[(package, None, "pass")] == 0, "unexpected package PASS" + assert not re.search(r"context deadline exceeded|runtime error:|panic_recovered|signal:", output, re.I), "runtime/setup failure is not RED" + for key in expected: + observed = fragments[key] + if handler_red: + stage = "handshake" if mode == "red-b1" else "backoff" + assert f"retry deadline observation: stage={stage} generations=2" in observed, key + assert "retry deadline: no generation may start after D" in observed, key + if mode == "red-backoff": + assert "retry deadline fallback observation: stage=backoff second_after_deadline=true owners=[Bearer fixture-deadline-owner Bearer fixture-healthy-backup]" in observed, key + wanted, actual = 1, 2 + elif mode == "red-f2": + assert "SSE pool quota observation: semantic_status=429 retry=true deadline_zero=true rejection_proof=false output_bytes=0 retry_started=false raw_preserved=true" in observed, key + assert "terminal normalized quota must veto same-account pool retry" in observed, key + assert re.search(r"Error:\s+Should be false", observed), key + assert len(re.findall(r"Error Trace:", observed)) == 1, key + continue + elif mode == "red-f1": + assert "SSE normalized quota observation:" in observed, key + assert "semantic_status=502" in observed, key + assert "terminal normalized explicit quota must preserve semantic 429" in observed, key + wanted, actual = 429, 502 + else: + assert "semantic_status=502" in observed, key + assert "terminal type-only quota must preserve semantic 429" in observed, key + wanted, actual = 429, 502 + assert re.search(rf"expected:\s+{wanted}\b", observed), key + assert re.search(rf"actual\s*:\s+{actual}\b", observed), key + for package, name in expected: + assert counts[(package, name, "run")] == 1, f"missing/duplicate RUN: {name}" + assert counts[(package, name, terminal)] == 1, f"missing/duplicate {terminal}: {name}" + assert sum(counts[(package, name, action)] for action in ("pass", "fail", "skip")) == 1, name + print(f"{mode}: verified {len(expected)} exact named executions") + + +if __name__ == "__main__": + verify(*sys.argv[1:]) diff --git a/.github/workflows/pr1012-retry-quota-oracle.yml b/.github/workflows/pr1012-retry-quota-oracle.yml new file mode 100644 index 000000000000..22398df16a9b --- /dev/null +++ b/.github/workflows/pr1012-retry-quota-oracle.yml @@ -0,0 +1,277 @@ +name: PR1012 retry deadline and SSE quota oracle + +on: + pull_request: + branches: [production] + paths: + - '.github/workflows/pr1012-retry-quota-oracle.yml' + - '.github/scripts/pr1012-oracle.py' + - 'backend/internal/handler/openai_gateway_handler.go' + - 'backend/internal/handler/openai_ws_retry_deadline_test.go' + - 'backend/internal/handler/openai_retry_owner_test.go' + - 'backend/internal/service/openai_retry_deadline_test_support.go' + - 'backend/internal/service/openai_sse_quota_type_test.go' + - 'backend/internal/service/openai_ws_forwarder_ingress.go' + - 'backend/internal/service/openai_gateway_passthrough.go' + - 'backend/internal/service/openai_gateway_upstream_errors.go' + - 'backend/internal/service/openai_account_runtime_block_fastpath.go' + - 'backend/go.mod' + - 'backend/go.sum' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pr1012-oracle-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + behavior: + runs-on: ubuntu-latest + timeout-minutes: 40 + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: fixture + POSTGRES_PASSWORD: fixture + POSTGRES_DB: issue917_fixture + ports: ['15432:5432'] + options: >- + --health-cmd "pg_isready -U fixture -d issue917_fixture" + --health-interval 5s --health-timeout 5s --health-retries 10 + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + BASELINE_SHA: 991cd30e2910d5eeb6ab55f6b7fc93e9a494e1a6 + F1_UNSAFE_SHA: 282af88f3fbf767b0235fec62ca5596bdc3d8449 + F2_UNSAFE_SHA: 5c3dafcbb9520d4792f5520f99408fd577f2838a + BACKOFF_UNSAFE_SHA: 282af88f3fbf767b0235fec62ca5596bdc3d8449 + ISSUE917_TEST_POSTGRES_DSN: 'postgres://fixture:fixture@127.0.0.1:15432/issue917_fixture?sslmode=disable' + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - name: Record identity and restore only the two defective production blobs + id: prepare + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + red="$RUNNER_TEMP/pr1012-red" + mkdir -p "$evidence" + printf 'candidate=%s\nbaseline=%s\n' "$CANDIDATE_SHA" "$BASELINE_SHA" > "$evidence/identity.txt" + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + git rev-parse HEAD HEAD^{tree} > "$evidence/green-identity.txt" + git worktree add --detach "$red" "$CANDIDATE_SHA" + production=(backend/internal/service/openai_gateway_passthrough.go backend/internal/service/openai_ws_forwarder_ingress.go) + for path in "${production[@]}"; do + git show "$BASELINE_SHA:$path" > "$red/$path" + blob="$(git rev-parse "$BASELINE_SHA:$path")" + test "$(git -C "$red" hash-object "$path")" = "$blob" + printf '%s %s\n' "$blob" "$path" >> "$evidence/baseline-blobs.txt" + printf '%s %s\n' "$(git rev-parse "$CANDIDATE_SHA:$path")" "$path" >> "$evidence/candidate-blobs.txt" + done + expected="$(printf '%s\n' "${production[@]}" | sort)" + test "$(git -C "$red" diff --name-only | sort)" = "$expected" + test -z "$(git -C "$red" ls-files --others --exclude-standard)" + git -C "$red" diff -- "${production[@]}" > "$evidence/red-production.diff" + oracles=(backend/internal/handler/openai_ws_retry_deadline_test.go backend/internal/handler/openai_retry_owner_test.go backend/internal/service/openai_sse_quota_type_test.go backend/internal/service/openai_retry_deadline_test_support.go .github/scripts/pr1012-oracle.py .github/workflows/pr1012-retry-quota-oracle.yml) + for path in "${oracles[@]}"; do + blob="$(git rev-parse "$CANDIDATE_SHA:$path")" + test "$(git -C "$red" hash-object "$path")" = "$blob" + test "$(git hash-object "$path")" = "$blob" + printf '%s %s\n' "$blob" "$path" >> "$evidence/oracle-blobs.txt" + done + - name: Record F1 identity and restore only the unsafe normalized-quota classifier + id: prepare_f1 + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + red="$RUNNER_TEMP/pr1012-f1-red" + printf 'candidate=%s\nunsafe=%s\n' "$CANDIDATE_SHA" "$F1_UNSAFE_SHA" > "$evidence/f1-identity.txt" + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + git worktree add --detach "$red" "$CANDIDATE_SHA" + test "$(git -C "$red" rev-parse HEAD)" = "$CANDIDATE_SHA" + git -C "$red" rev-parse HEAD HEAD^{tree} >> "$evidence/f1-identity.txt" + path=backend/internal/service/openai_gateway_passthrough.go + git show "$F1_UNSAFE_SHA:$path" > "$red/$path" + blob="$(git rev-parse "$F1_UNSAFE_SHA:$path")" + test "$(git -C "$red" hash-object "$path")" = "$blob" + printf '%s %s\n' "$blob" "$path" > "$evidence/f1-unsafe-blob.txt" + printf '%s %s\n' "$(git rev-parse "$CANDIDATE_SHA:$path")" "$path" > "$evidence/f1-candidate-blob.txt" + test "$(git -C "$red" diff --name-only)" = "$path" + test -z "$(git -C "$red" ls-files --others --exclude-standard)" + git -C "$red" diff -- "$path" > "$evidence/f1-red-production.diff" + oracles=(backend/internal/handler/openai_ws_retry_deadline_test.go backend/internal/handler/openai_retry_owner_test.go backend/internal/service/openai_sse_quota_type_test.go backend/internal/service/openai_retry_deadline_test_support.go .github/scripts/pr1012-oracle.py .github/workflows/pr1012-retry-quota-oracle.yml) + for path in "${oracles[@]}"; do + blob="$(git rev-parse "$CANDIDATE_SHA:$path")" + test "$(git -C "$red" hash-object "$path")" = "$blob" + test "$(git hash-object "$path")" = "$blob" + printf '%s %s\n' "$blob" "$path" >> "$evidence/f1-oracle-blobs.txt" + done + - name: Isolate the F2 retry veto and the observed backoff fallback defects + id: prepare_remaining + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + for blocker in f2 backoff; do + red="$RUNNER_TEMP/pr1012-$blocker-red" + if [ "$blocker" = f2 ]; then + unsafe="$F2_UNSAFE_SHA" + path=backend/internal/service/openai_gateway_upstream_errors.go + else + unsafe="$BACKOFF_UNSAFE_SHA" + path=backend/internal/handler/openai_gateway_handler.go + fi + printf 'candidate=%s\nunsafe=%s\n' "$CANDIDATE_SHA" "$unsafe" > "$evidence/$blocker-identity.txt" + git worktree add --detach "$red" "$CANDIDATE_SHA" + test "$(git -C "$red" rev-parse HEAD)" = "$CANDIDATE_SHA" + git -C "$red" rev-parse HEAD HEAD^{tree} >> "$evidence/$blocker-identity.txt" + git show "$unsafe:$path" > "$red/$path" + blob="$(git rev-parse "$unsafe:$path")" + test "$(git -C "$red" hash-object "$path")" = "$blob" + printf '%s %s\n' "$blob" "$path" > "$evidence/$blocker-unsafe-blob.txt" + printf '%s %s\n' "$(git rev-parse "$CANDIDATE_SHA:$path")" "$path" > "$evidence/$blocker-candidate-blob.txt" + test "$(git -C "$red" diff --name-only)" = "$path" + test -z "$(git -C "$red" ls-files --others --exclude-standard)" + git -C "$red" diff -- "$path" > "$evidence/$blocker-red-production.diff" + oracles=(backend/internal/handler/openai_ws_retry_deadline_test.go backend/internal/handler/openai_retry_owner_test.go backend/internal/service/openai_sse_quota_type_test.go backend/internal/service/openai_retry_deadline_test_support.go .github/scripts/pr1012-oracle.py .github/workflows/pr1012-retry-quota-oracle.yml) + for oracle in "${oracles[@]}"; do + blob="$(git rev-parse "$CANDIDATE_SHA:$oracle")" + test "$(git -C "$red" hash-object "$oracle")" = "$blob" + test "$(git hash-object "$oracle")" = "$blob" + printf '%s %s\n' "$blob" "$oracle" >> "$evidence/$blocker-oracle-blobs.txt" + done + done + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Runner prerequisites + id: prerequisites + run: | + set -euo pipefail + go version | tee "$RUNNER_TEMP/pr1012-evidence/go-version.txt" + go version | grep -q 'go1.27.4' + python3 --version + 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 + redis-server --version + - name: RED B1 requires the observed second generation after D + if: ${{ !cancelled() && steps.prerequisites.outcome == 'success' }} + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + set +e + (cd "$RUNNER_TEMP/pr1012-red/backend" && go test -p=2 -race -tags=unit,retrydeadline ./internal/handler -run '^TestOpenAIWSRetryDeadlineAtGenerationWrite$/^handshake$' -count=1 -json -timeout=3m) > "$evidence/red-b1.jsonl" 2>&1 + status=$? + set -e + printf '%s\n' "$status" > "$evidence/red-b1.exitcode" + cat "$evidence/red-b1.jsonl" + python3 .github/scripts/pr1012-oracle.py red-b1 "$evidence/red-b1.exitcode" "$evidence/red-b1.jsonl" 2>&1 | tee "$evidence/red-b1-verdict.txt" + - name: RED B3 requires semantic502 in all 24 type-only reader leaves + if: ${{ !cancelled() && steps.prerequisites.outcome == 'success' }} + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + set +e + (cd "$RUNNER_TEMP/pr1012-red/backend" && go test -p=2 -race -tags=unit,retrydeadline ./internal/service -run '^TestSSETypeOnlyQuotaReaders$' -count=1 -json -timeout=3m) > "$evidence/red-b3.jsonl" 2>&1 + status=$? + set -e + printf '%s\n' "$status" > "$evidence/red-b3.exitcode" + cat "$evidence/red-b3.jsonl" + python3 .github/scripts/pr1012-oracle.py red-b3 "$evidence/red-b3.exitcode" "$evidence/red-b3.jsonl" 2>&1 | tee "$evidence/red-b3-verdict.txt" + - name: RED F1 requires semantic502 in all 24 normalized explicit-code reader leaves + if: ${{ !cancelled() && steps.prerequisites.outcome == 'success' && steps.prepare_f1.outcome == 'success' }} + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + set +e + (cd "$RUNNER_TEMP/pr1012-f1-red/backend" && go test -p=2 -race -tags=unit,retrydeadline ./internal/service -run '^TestSSEQuotaNormalizedExplicitCodeReaders$' -count=1 -json -timeout=3m) > "$evidence/red-f1.jsonl" 2>&1 + status=$? + set -e + printf '%s\n' "$status" > "$evidence/red-f1.exitcode" + cat "$evidence/red-f1.jsonl" + python3 .github/scripts/pr1012-oracle.py red-f1 "$evidence/red-f1.exitcode" "$evidence/red-f1.jsonl" 2>&1 | tee "$evidence/red-f1-verdict.txt" + - name: RED F2 requires retry=true alone in all 48 default and explicit429 quota reader leaves + if: ${{ !cancelled() && steps.prerequisites.outcome == 'success' && steps.prepare_remaining.outcome == 'success' }} + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + set +e + (cd "$RUNNER_TEMP/pr1012-f2-red/backend" && go test -p=2 -race -tags=unit,retrydeadline ./internal/service -run '^TestSSEQuotaNormalizedPool429Readers$' -count=1 -json -timeout=3m) > "$evidence/red-f2.jsonl" 2>&1 + status=$? + set -e + printf '%s\n' "$status" > "$evidence/red-f2.exitcode" + cat "$evidence/red-f2.jsonl" + python3 .github/scripts/pr1012-oracle.py red-f2 "$evidence/red-f2.exitcode" "$evidence/red-f2.jsonl" 2>&1 | tee "$evidence/red-f2-verdict.txt" + - name: RED backoff requires an observed backup generation after D + if: ${{ !cancelled() && steps.prerequisites.outcome == 'success' && steps.prepare_remaining.outcome == 'success' }} + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/pr1012-evidence" + set +e + (cd "$RUNNER_TEMP/pr1012-backoff-red/backend" && go test -p=2 -race -tags=unit,retrydeadline ./internal/handler -run '^TestOpenAIWSRetryDeadlineAtGenerationWrite$/^backoff$' -count=1 -json -timeout=3m) > "$evidence/red-backoff.jsonl" 2>&1 + status=$? + set -e + printf '%s\n' "$status" > "$evidence/red-backoff.exitcode" + cat "$evidence/red-backoff.jsonl" + python3 .github/scripts/pr1012-oracle.py red-backoff "$evidence/red-backoff.exitcode" "$evidence/red-backoff.jsonl" 2>&1 | tee "$evidence/red-backoff-verdict.txt" + - name: GREEN all retry stages, initial drain, quota, strict owner, output and Issue917 policy controls + if: ${{ !cancelled() && steps.prerequisites.outcome == 'success' }} + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + evidence="$RUNNER_TEMP/pr1012-evidence" + set +e + (cd backend && go test -p=2 -race -tags=unit,retrydeadline,issue917pg ./internal/service ./internal/handler -run '^Test(OpenAIWSRetryDeadlineAtGenerationWrite|SSETypeOnlyQuotaReaders|SSEQuotaNormalizedExplicitCodeReaders|SSEQuotaNormalizedPool429Readers|SSEQuotaNormalizedAfterOutputCannotReplay|SSEQuotaBareErrorCanComplete|SSEQuotaClassificationRetainsExplicitCodeAndIntegrity|SSEQuotaTerminalDoesNotGrantHTTPRejectionProof|SSEQuotaWithoutResetUsesBoundedAccountFailover|StrictSameAccountRetryRequiresCurrentBinding|SameAccountRetrySchedulerCannotEscape|StrictSessionAffinityLosingFirstTurnReleasesSlot|OAuthRetryOwnerBusyAfterSlotRelease|OAuthNormalEOFBeforeOutputPreservesAccount|OAuthNormalEOFAfterOutputCannotReplay|OpenAIGatewayService_ProxyResponsesWebSocketFromClient_ClientDisconnectStillDrainsUpstream|OpenAIResponseFlush_BareErrorFollowedByCompletedUsesCompletedTerminal|OpenAIStreamingPassthroughBareErrorTerminatesBeforeDone|OpenAIStreamingPassthroughBareErrorDrainsAuthoritativeFailedUsage|Issue917ResponsesCooldown)$' -count=1 -json -timeout=12m) > "$evidence/green.jsonl" 2>&1 + status=$? + set -e + printf '%s\n' "$status" > "$evidence/green.exitcode" + cat "$evidence/green.jsonl" + python3 .github/scripts/pr1012-oracle.py green "$evidence/green.exitcode" "$evidence/green.jsonl" 2>&1 | tee "$evidence/green-verdict.txt" + test -z "$(git status --porcelain)" + - name: Build actual production server without fixture tags + if: ${{ !cancelled() && steps.prerequisites.outcome == 'success' }} + env: + CGO_ENABLED: '0' + working-directory: backend + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + set +e + go build -trimpath -o "$RUNNER_TEMP/pr1012-server" ./cmd/server > "$RUNNER_TEMP/pr1012-evidence/build.log" 2>&1 + status=$? + set -e + printf '%s\n' "$status" > "$RUNNER_TEMP/pr1012-evidence/build.exitcode" + cat "$RUNNER_TEMP/pr1012-evidence/build.log" + test "$status" -eq 0 + - name: Upload raw immutable-head evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: pr1012-oracle-${{ env.CANDIDATE_SHA }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/pr1012-evidence + if-no-files-found: error + retention-days: 14 diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 11ed6767b560..a3151f0c8b8e 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3458,7 +3458,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { var oauth429FailoverState service.OpenAIOAuth429FailoverState wsAttemptMessage := append([]byte(nil), firstMessage...) initialDispatchStarted := false + wsSameAccountRetryExpired := false waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { + wsSameAccountRetryExpired = false if !service.OpenAIWSAgentRecoveryCanRetry(ctx) { return false } @@ -3486,7 +3488,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { case <-ctx.Done(): return false case <-time.After(retryDelay): - return service.OpenAISameAccountRetryAdmissible(ctx, account.ID) && service.OpenAIWSIngressCanFailover(ctx, c) + admissible := service.OpenAISameAccountRetryAdmissible(ctx, account.ID) + wsSameAccountRetryExpired = !admissible + return admissible && service.OpenAIWSIngressCanFailover(ctx, c) } } handleWSFailover := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { @@ -4407,6 +4411,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { } continue } + if wsSameAccountRetryExpired { + // This retry was admitted before D and expired during backoff. + // Switching accounts would discard its deadline and send after D. + releaseTurnSlots() + closeOpenAIWSFailoverExhausted(c, wsConn, failoverErr) + return + } if handleWSFailover(account, failoverErr) { break } diff --git a/backend/internal/handler/openai_retry_owner_test.go b/backend/internal/handler/openai_retry_owner_test.go index d71a22d50c18..b4702d5e9794 100644 --- a/backend/internal/handler/openai_retry_owner_test.go +++ b/backend/internal/handler/openai_retry_owner_test.go @@ -81,10 +81,11 @@ func (s *retryOwnerSlots) ReleaseAccountSlot(_ context.Context, id int64, _ stri type retryOwnerUpstream struct { service.HTTPUpstream - mu sync.Mutex - ids []int64 - exhaust bool - quota string + mu sync.Mutex + ids []int64 + exhaust bool + quota string + typeOnly bool } func (u *retryOwnerUpstream) Do(req *http.Request, _ string, id int64, _ int) (*http.Response, error) { @@ -95,6 +96,9 @@ func (u *retryOwnerUpstream) Do(req *http.Request, _ string, id int64, _ int) (* u.mu.Unlock() if first && u.quota != "" { frame := fmt.Sprintf("data: {\"type\":\"response.failed\",\"response\":{\"id\":\"resp_quota\",\"status\":\"failed\",\"error\":{\"code\":%q,\"type\":%q,\"message\":\"Quota exhausted\"}}}\n\n", u.quota, u.quota) + if u.typeOnly { + frame = fmt.Sprintf("data: {\"type\":\"response.failed\",\"response\":{\"id\":\"resp_quota\",\"status\":\"failed\",\"error\":{\"type\":%q,\"message\":\"Quota exhausted\"}}}\n\n", u.quota) + } return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(frame))}, nil } if fail { @@ -113,18 +117,21 @@ func (u *retryOwnerUpstream) Do(req *http.Request, _ string, id int64, _ int) (* func TestSSEQuotaWithoutResetUsesBoundedAccountFailover(t *testing.T) { gin.SetMode(gin.TestMode) for _, kind := range []string{service.AccountTypeOAuth, service.AccountTypeAPIKey} { - for _, code := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached"} { + for _, form := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached", "type:insufficient_quota", "type:quota_exceeded", "type:usage_limit_reached"} { + code := strings.TrimPrefix(form, "type:") for _, passthrough := range []bool{false, true} { for _, stream := range []bool{false, true} { - t.Run(fmt.Sprintf("%s/%s/passthrough=%t/stream=%t", kind, code, passthrough, stream), func(t *testing.T) { + t.Run(fmt.Sprintf("%s/%s/passthrough=%t/stream=%t", kind, form, passthrough, stream), func(t *testing.T) { accounts := issue715Accounts() for i := range accounts { accounts[i].Type = kind accounts[i].Credentials["api_key"] = "fixture-key" accounts[i].Credentials["pool_mode"] = true + accounts[i].Credentials["pool_mode_retry_status_codes"] = []any{float64(http.StatusBadGateway)} + accounts[i].Credentials["pool_mode_retry_count"] = float64(1) accounts[i].Extra = map[string]any{"openai_passthrough": passthrough} } - upstream := &retryOwnerUpstream{quota: code} + upstream := &retryOwnerUpstream{quota: code, typeOnly: strings.HasPrefix(form, "type:")} h := newOpenAIResponsesFailoverTestHandler(t, upstream, accounts...) c, rec := newOpenAIResponsesFailoverTestContext(t, nil) body := fmt.Sprintf(`{"model":"gpt-5.1","input":"hello","stream":%t}`, stream) diff --git a/backend/internal/handler/openai_ws_retry_deadline_test.go b/backend/internal/handler/openai_ws_retry_deadline_test.go new file mode 100644 index 000000000000..67715f65e034 --- /dev/null +++ b/backend/internal/handler/openai_ws_retry_deadline_test.go @@ -0,0 +1,319 @@ +//go:build unit && retrydeadline + +package handler + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type wsRetryDeadlineSlots struct { + service.ConcurrencyCache + mu sync.Mutex + stage string + deadline time.Time + + userAttempts int + userAcquired int + userReleased int + + accountAttempts int + accountAcquired int + accountReleased int + + waitEnteredBeforeDeadline bool +} + +func waitWSRetryDeadline(ctx context.Context, deadline time.Time) { + timer := time.NewTimer(time.Until(deadline.Add(25 * time.Millisecond))) + defer timer.Stop() + select { + case <-ctx.Done(): + case <-timer.C: + } +} + +func (s *wsRetryDeadlineSlots) AcquireUserSlot(ctx context.Context, id int64, max int, request string) (bool, error) { + s.mu.Lock() + s.userAttempts++ + hold := s.stage == "user_slot" && s.userAttempts == 2 + deadline := s.deadline + if hold { + s.waitEnteredBeforeDeadline = time.Now().Before(deadline) + } + s.mu.Unlock() + if hold { + waitWSRetryDeadline(ctx, deadline) + } + acquired, err := s.ConcurrencyCache.AcquireUserSlot(ctx, id, max, request) + if acquired { + s.mu.Lock() + s.userAcquired++ + s.mu.Unlock() + } + return acquired, err +} + +func (s *wsRetryDeadlineSlots) ReleaseUserSlot(ctx context.Context, id int64, request string) error { + s.mu.Lock() + s.userReleased++ + s.mu.Unlock() + return s.ConcurrencyCache.ReleaseUserSlot(ctx, id, request) +} + +func (s *wsRetryDeadlineSlots) AcquireAccountSlot(ctx context.Context, id int64, max int, request string) (bool, error) { + s.mu.Lock() + s.accountAttempts++ + hold := s.stage == "account_slot" && s.accountAttempts == 2 + deadline := s.deadline + if hold { + s.waitEnteredBeforeDeadline = time.Now().Before(deadline) + } + s.mu.Unlock() + if hold { + waitWSRetryDeadline(ctx, deadline) + } + acquired, err := s.ConcurrencyCache.AcquireAccountSlot(ctx, id, max, request) + if acquired { + s.mu.Lock() + s.accountAcquired++ + s.mu.Unlock() + } + return acquired, err +} + +func (s *wsRetryDeadlineSlots) ReleaseAccountSlot(ctx context.Context, id int64, request string) error { + s.mu.Lock() + s.accountReleased++ + s.mu.Unlock() + return s.ConcurrencyCache.ReleaseAccountSlot(ctx, id, request) +} + +func TestOpenAIWSRetryDeadlineAtGenerationWrite(t *testing.T) { + for _, stage := range []string{"backoff", "user_slot", "account_slot", "handshake", "inflight", "output", "canceled"} { + t.Run(stage, func(t *testing.T) { + slots := &wsRetryDeadlineSlots{ConcurrencyCache: testutil.NewRedisConcurrencyCache(t), stage: stage} + var gateway *service.OpenAIGatewayService + var accountID int64 + var mu sync.Mutex + var generations, handshakes int + var deadline time.Time + var owners []string + var generationTimes []time.Time + handshakeEntered := make(chan time.Time, 1) + handshakeClosed := make(chan struct{}, 1) + cancelHandshake := make(chan struct{}) + stopHandshake := sync.OnceFunc(func() { close(cancelHandshake) }) + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + handshakes++ + n := handshakes + d := deadline + mu.Unlock() + if n == 2 && (stage == "handshake" || stage == "canceled") { + handshakeEntered <- time.Now() + if stage == "handshake" { + waitWSRetryDeadline(r.Context(), d) + } else { + select { + case <-cancelHandshake: + case <-r.Context().Done(): + } + } + defer func() { handshakeClosed <- struct{}{} }() + } + conn, err := coderws.Accept(w, r, nil) + if err != nil { + return // client cancellation may end the held handshake + } + defer func() { _ = conn.CloseNow() }() + for { + _, frame, readErr := conn.Read(r.Context()) + if readErr != nil { + return + } + mu.Lock() + generations++ + generation := generations + owners = append(owners, r.Header.Get("Authorization")) + generationTimes = append(generationTimes, time.Now()) + if generation == 1 { + window := 1500 * time.Millisecond + if stage == "backoff" { + window = 150 * time.Millisecond + } + deadline = time.Now().Add(window) + service.SetOpenAIRetryDeadlineForTest(gateway, accountID, deadline) + slots.mu.Lock() + slots.deadline = deadline + slots.mu.Unlock() + } + d = deadline + mu.Unlock() + if gjson.GetBytes(frame, "generate").Exists() { + t.Error("fixture must count generation frames, with prewarming disabled") + } + if generation == 1 { + if stage == "output" { + _ = conn.Write(r.Context(), coderws.MessageText, []byte(`{"type":"response.output_text.delta","delta":"partial","output_index":0,"content_index":0}`)) + } + _ = conn.Write(r.Context(), coderws.MessageText, []byte(`{"type":"error","error":{"code":"rate_limit_exceeded","type":"rate_limit_error","message":"limited"}}`)) + return + } + if stage == "inflight" && generation == 2 { + _ = conn.Write(r.Context(), coderws.MessageText, []byte(`{"type":"response.output_text.delta","delta":"ok","output_index":0,"content_index":0}`)) + waitWSRetryDeadline(r.Context(), d) + } + terminal := fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_deadline_%d","model":"gpt-5.1","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`, generation) + if conn.Write(r.Context(), coderws.MessageText, []byte(terminal)) != nil { + return + } + if stage == "handshake" { + return // bound the defective baseline's admitted generation + } + } + })) + t.Cleanup(provider.Close) + defer stopHandshake() + h := newOpenAIWSPassthroughHandlerHarnessWithAudit(t, provider.URL, nil, + map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false"}, testutil.NewRedisGatewayCache(t), + func(key *service.APIKey) { key.AllowLongContext = true }, + func(h *OpenAIGatewayHandler) { + mu.Lock() + gateway = h.gatewayService + mu.Unlock() + concurrency := service.NewConcurrencyService(slots) + service.SetOpenAIRetryConcurrencyForTest(gateway, concurrency) + h.concurrencyHelper = NewConcurrencyHelper(concurrency, SSEPingFormatNone, time.Second) + require.NoError(t, service.RouteIssue842OAuthSocketsToLoopbackForTest(gateway, provider.URL)) + }, + func(a *service.Account, cfg *config.Config, _ *service.HTTPUpstream, repo *service.AccountRepository) { + mu.Lock() + accountID = a.ID + mu.Unlock() + a.Type = service.AccountTypeOAuth + a.Credentials["access_token"] = "fixture-deadline-owner" + a.Extra["codex_fingerprint_mode"] = "off" + a.Extra["openai_oauth_responses_websockets_v2_mode"] = service.OpenAIWSIngressModeCtxPool + cfg.Gateway.OpenAIWS.OAuthEnabled = true + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 + cfg.Gateway.OpenAIWS.MaxIdlePerAccount = 1 + cfg.Gateway.OpenAIWS.PrewarmGenerateEnabled = false + cfg.Gateway.OpenAIWS.LBTopK = 1 + cfg.Gateway.MaxAccountSwitches = 2 + other := *a + other.ID, other.Priority = a.ID+1, 1000 + other.Credentials = map[string]any{"access_token": "fixture-healthy-backup"} + *repo = &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, other}}} + }) + issue715WSSend(t, h.clientConn, `{"type":"response.create","model":"gpt-5.1","input":"hello"}`) + var readTimedOut, unexpectedCompletion, outputObserved bool + if stage == "canceled" { + select { + case entered := <-handshakeEntered: + mu.Lock() + require.True(t, entered.Before(deadline), "retry passed the handler's checks before D") + mu.Unlock() + case <-time.After(5 * time.Second): + t.Fatal("retry never reached the held handshake") + } + require.NoError(t, h.clientConn.Close(coderws.StatusNormalClosure, "cancel pending retry")) + stopHandshake() + } else if stage == "inflight" { + require.Equal(t, "response.completed", gjson.GetBytes(issue715WSRead(t, h.clientConn), "type").String()) + issue715WSSend(t, h.clientConn, `{"type":"response.create","model":"gpt-5.1","input":"next turn"}`) + require.Equal(t, "response.completed", gjson.GetBytes(issue715WSRead(t, h.clientConn), "type").String()) + _ = h.clientConn.CloseNow() + } else { + readCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for { + _, frame, err := h.clientConn.Read(readCtx) + if err != nil { + readTimedOut = readCtx.Err() == context.DeadlineExceeded + break + } + if gjson.GetBytes(frame, "type").String() == "response.output_text.delta" { + outputObserved = true + } + if gjson.GetBytes(frame, "type").String() == "response.completed" { + // Defective production sends a second generation after D. + // Close and join it now, then fail on its observed count. + unexpectedCompletion = true + break + } + } + _ = h.clientConn.CloseNow() + } + select { + case <-h.handlerDone: + case <-time.After(5 * time.Second): + t.Fatal("handler did not release the retry") + } + if stage == "handshake" || stage == "canceled" { + if stage == "handshake" { + var entered time.Time + select { + case entered = <-handshakeEntered: + case <-time.After(time.Second): + t.Fatal("retry handshake was not observed before cleanup") + } + mu.Lock() + require.True(t, entered.Before(deadline), "handler checks must pass before the handshake crosses D") + mu.Unlock() + } + select { + case <-handshakeClosed: + case <-time.After(time.Second): + t.Fatal("upstream retry lease remained open") + } + } + mu.Lock() + observedGenerations := generations + observedOwners := append([]string(nil), owners...) + secondAfterDeadline := len(generationTimes) > 1 && !generationTimes[1].Before(deadline) + mu.Unlock() + want := 1 + if stage == "inflight" { + want = 3 + } + t.Logf("retry deadline observation: stage=%s generations=%d", stage, observedGenerations) + t.Logf("retry deadline fallback observation: stage=%s second_after_deadline=%t owners=%v", stage, secondAfterDeadline, observedOwners) + require.Equal(t, want, observedGenerations, "retry deadline: no generation may start after D") + require.False(t, readTimedOut, "fixture read timed out before observing retry closure") + require.False(t, unexpectedCompletion, "expired retry must not complete a generation") + if stage == "output" { + require.True(t, outputObserved, "the output control must actually commit output") + } else if stage != "inflight" { + require.False(t, outputObserved, "pre-output refusal must emit no generation output") + } + for _, owner := range observedOwners { + require.Equal(t, "Bearer fixture-deadline-owner", owner) + } + slots.mu.Lock() + require.Positive(t, slots.userAcquired) + require.Positive(t, slots.accountAcquired) + require.Equal(t, slots.userAcquired, slots.userReleased) + require.Equal(t, slots.accountAcquired, slots.accountReleased) + if stage == "user_slot" || stage == "account_slot" { + require.True(t, slots.waitEnteredBeforeDeadline) + } + slots.mu.Unlock() + inflight, waiters, _ := service.OpenAIRetryPoolLoadForTest(gateway, accountID) + require.Zero(t, inflight) + require.Zero(t, waiters) + }) + } +} diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index cab30ad3fb89..b0ca02d2d802 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -55,6 +55,23 @@ func isOpenAIQuotaExhaustedResponse(body []byte) bool { return false } +// isOpenAITerminalQuotaExhaustedResponse shares normalized SSE quota evidence +// between semantic classification and the final retry veto. It does not prove +// that an HTTP 200 stream rejected the request before execution. +func isOpenAITerminalQuotaExhaustedResponse(body []byte) bool { + if gjson.GetBytes(body, "type").String() != "response.failed" || !openAIEncryptedJSONUnambiguous(body) { + return false + } + switch openAIStreamFailedEventErrorCode(body) { + case "usage_limit_reached", "insufficient_quota", "quota_exceeded": + return true + case "": + return isOpenAIQuotaExhaustedResponse(body) + default: + return false // An unrelated explicit code keeps its own policy. + } +} + // classifyOpenAIOAuth429 distinguishes exhausted quota from transient throttling. func classifyOpenAIOAuth429(headers http.Header, responseBody []byte) (openAIOAuth429Disposition, *time.Time) { if snapshot := ParseCodexRateLimitHeaders(headers); snapshot != nil { @@ -87,6 +104,9 @@ func classifyOpenAIOAuth429(headers http.Header, responseBody []byte) (openAIOAu if isOpenAIQuotaExhaustedResponse(responseBody) { return openAIOAuth429QuotaExhausted, nil } + if isOpenAITerminalQuotaExhaustedResponse(responseBody) { + return openAIOAuth429QuotaExhausted, nil + } return openAIOAuth429Transient, nil } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 4b81769abdf3..f45f65875483 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1607,9 +1607,11 @@ func openAIStreamFailedEventSemanticStatus(payload []byte, message string) int { } switch { // Bare errors can precede a successful terminal. Only a terminal refusal - // with a recognized provider code grants the new quota failover behavior. - case gjson.GetBytes(payload, "type").String() == "response.failed" && - (code == "usage_limit_reached" || code == "insufficient_quota" || code == "quota_exceeded"): + // with unambiguous quota evidence grants the quota failover behavior. + case isOpenAITerminalQuotaExhaustedResponse(payload): + // Explicit codes retain their historical lowercase/trim normalization. + // An unrelated explicit code retains its existing semantic status and + // configured cooldown policy, even under a broad quota error type. return http.StatusTooManyRequests case strings.Contains(combined, "rate_limit"): return http.StatusTooManyRequests diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 82ac1face7d1..bb1c1fea8067 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -533,7 +533,8 @@ func (s *OpenAIGatewayService) newOpenAIAccountFailoverErrorWithClassificationHe upstreamMsg, retryableOnSameAccount || oauth429Retry, ) - if statusCode == http.StatusTooManyRequests && isOpenAIQuotaExhaustedResponse(responseBody) { + if statusCode == http.StatusTooManyRequests && + (isOpenAIQuotaExhaustedResponse(responseBody) || isOpenAITerminalQuotaExhaustedResponse(responseBody)) { // Exhausted quota cannot recover within a pool-mode retry budget either. failoverErr.RetryableOnSameAccount = false } diff --git a/backend/internal/service/openai_retry_deadline_test_support.go b/backend/internal/service/openai_retry_deadline_test_support.go new file mode 100644 index 000000000000..c0b80eee6ecf --- /dev/null +++ b/backend/internal/service/openai_retry_deadline_test_support.go @@ -0,0 +1,22 @@ +//go:build unit && retrydeadline + +package service + +import "time" + +// SetOpenAIRetryConcurrencyForTest makes scheduler and handler slot accounting +// use the same isolated cache in the real handler fixture. +func SetOpenAIRetryConcurrencyForTest(s *OpenAIGatewayService, concurrency *ConcurrencyService) { + s.concurrencyService = concurrency +} + +// SetOpenAIRetryDeadlineForTest seeds the existing account retry window without +// changing its production duration or the context carried by the real handler. +func SetOpenAIRetryDeadlineForTest(s *OpenAIGatewayService, accountID int64, deadline time.Time) { + s.openaiOAuth429RetryStartedAt.Store(accountID, deadline.Add(-openAIOAuth429RetryWindow)) +} + +// OpenAIRetryPoolLoadForTest observes lease cleanup through the pool's lock. +func OpenAIRetryPoolLoadForTest(s *OpenAIGatewayService, accountID int64) (int, int, int) { + return s.getOpenAIWSConnPool().AccountPoolLoad(accountID) +} diff --git a/backend/internal/service/openai_sse_quota_type_test.go b/backend/internal/service/openai_sse_quota_type_test.go new file mode 100644 index 000000000000..5a455f85fd50 --- /dev/null +++ b/backend/internal/service/openai_sse_quota_type_test.go @@ -0,0 +1,211 @@ +//go:build unit && retrydeadline + +package service + +import ( + "errors" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestSSETypeOnlyQuotaReaders(t *testing.T) { + for _, kind := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + for _, quota := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached"} { + for _, passthrough := range []bool{false, true} { + for _, pool := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/passthrough=%t/pool502=%t", kind, quota, passthrough, pool), func(t *testing.T) { + c, rec := newOpenAIUpstreamErrorTestContext(t) + cfg := &config.Config{} + repo := &oauth429RateLimitRepo{} + rateLimits := NewRateLimitService(repo, nil, cfg, nil, nil) + svc := &OpenAIGatewayService{cfg: cfg, rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(svc) + account := &Account{ID: 42, Platform: PlatformOpenAI, Type: kind, Credentials: map[string]any{ + "pool_mode": pool, "pool_mode_retry_status_codes": []any{float64(http.StatusBadGateway)}, + }} + payload := fmt.Sprintf(`{"type":"response.failed","response":{"status":"failed","error":{"type":%q,"message":"Quota exhausted"}}}`, quota) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: " + payload + "\n\n"))} + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } + var failure *UpstreamFailoverError + require.ErrorAs(t, err, &failure) + t.Logf("SSE quota observation: type=%s semantic_status=%d", quota, failure.StatusCode) + require.Equal(t, http.StatusTooManyRequests, failure.StatusCode, "terminal type-only quota must preserve semantic 429") + require.False(t, failure.RetryableOnSameAccount, "explicit pool502 retry must not resend the exhausted owner") + require.True(t, failure.SameAccountRetryDeadline.IsZero()) + require.False(t, failure.QuotaRejectedBeforeExecution, "HTTP200 SSE is not HTTP429 pre-execution rejection proof") + require.Empty(t, rec.Body.String(), "the pre-output terminal is still eligible for bounded account failover") + _, retryStarted := svc.openaiOAuth429RetryStartedAt.Load(account.ID) + require.False(t, retryStarted) + // API-key pools deliberately opt out of persistent health updates. + if !pool || kind == AccountTypeOAuth { + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.Equal(t, 1, repo.setRateLimitedCalls) + require.True(t, repo.lastRateLimitedUntil.After(time.Now())) + } + }) + } + } + } + } +} + +func TestSSEQuotaNormalizedExplicitCodeReaders(t *testing.T) { + runSSEQuotaNormalizedExplicitCodeReaders(t, []string{"pool502=true"}) +} + +func TestSSEQuotaNormalizedPool429Readers(t *testing.T) { + runSSEQuotaNormalizedExplicitCodeReaders(t, []string{"pool=default", "pool=explicit429"}) +} + +func runSSEQuotaNormalizedExplicitCodeReaders(t *testing.T, policies []string) { + t.Helper() + for _, kind := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + for _, quota := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached"} { + for _, variant := range []string{"uppercase", "padded"} { + for _, passthrough := range []bool{false, true} { + for _, policy := range policies { + t.Run(fmt.Sprintf("%s/%s/%s/passthrough=%t/%s", kind, quota, variant, passthrough, policy), func(t *testing.T) { + c, rec := newOpenAIUpstreamErrorTestContext(t) + cfg := &config.Config{} + repo := &oauth429RateLimitRepo{} + rateLimits := NewRateLimitService(repo, nil, cfg, nil, nil) + svc := &OpenAIGatewayService{cfg: cfg, rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(svc) + account := &Account{ID: 42, Platform: PlatformOpenAI, Type: kind, Credentials: map[string]any{ + "pool_mode": true, "pool_mode_retry_count": float64(2), + }} + switch policy { + case "pool502=true": + account.Credentials["pool_mode_retry_status_codes"] = []any{float64(http.StatusBadGateway)} + case "pool=explicit429": + account.Credentials["pool_mode_retry_status_codes"] = []any{float64(http.StatusTooManyRequests)} + } + code := strings.ToUpper(quota) + if variant == "padded" { + code = " " + quota + " " + } + payload := fmt.Sprintf(`{"type":"response.failed","response":{"error":{"type":"server_error","code":%q,"message":"Quota exhausted"}}}`, code) + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: " + payload + "\n\n"))} + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } + var failure *UpstreamFailoverError + require.ErrorAs(t, err, &failure) + t.Logf("SSE normalized quota observation: code=%q semantic_status=%d", code, failure.StatusCode) + require.Equal(t, http.StatusTooManyRequests, failure.StatusCode, "terminal normalized explicit quota must preserve semantic 429") + require.True(t, failure.SameAccountRetryDeadline.IsZero()) + require.False(t, failure.QuotaRejectedBeforeExecution, "HTTP200 SSE is not HTTP429 pre-execution rejection proof") + require.Empty(t, rec.Body.String(), "the pre-output terminal is still eligible for bounded account failover") + _, retryStarted := svc.openaiOAuth429RetryStartedAt.Load(account.ID) + require.False(t, retryStarted) + require.NotNil(t, failure.StreamFailedFrame) + require.Equal(t, payload, string(failure.StreamFailedFrame.Payload), "classification must preserve the raw frame used by rules") + t.Logf("SSE pool quota observation: semantic_status=%d retry=%t deadline_zero=%t rejection_proof=%t output_bytes=%d retry_started=%t raw_preserved=%t", + failure.StatusCode, failure.RetryableOnSameAccount, failure.SameAccountRetryDeadline.IsZero(), failure.QuotaRejectedBeforeExecution, + rec.Body.Len(), retryStarted, payload == string(failure.StreamFailedFrame.Payload)) + require.False(t, failure.RetryableOnSameAccount, "terminal normalized quota must veto same-account pool retry") + }) + } + } + } + } + } +} + +func TestSSEQuotaBareErrorCanComplete(t *testing.T) { + for _, quota := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached"} { + t.Run(quota, func(t *testing.T) { + c, rec := newOpenAIUpstreamErrorTestContext(t) + cfg := &config.Config{} + repo := &oauth429RateLimitRepo{} + rateLimits := NewRateLimitService(repo, nil, cfg, nil, nil) + svc := &OpenAIGatewayService{cfg: cfg, rateLimitService: rateLimits} + rateLimits.SetAccountRuntimeBlocker(svc) + account := &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + body := fmt.Sprintf("data: {\"type\":\"error\",\"error\":{\"type\":%q,\"message\":\"Quota exhausted\"}}\n\n", quota) + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_recovered\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":3}}}\n\n" + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body))} + _, err := svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + require.NoError(t, err) + require.Contains(t, rec.Body.String(), `"type":"response.completed"`) + require.NotContains(t, rec.Body.String(), `"type":"response.failed"`) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.Zero(t, repo.setRateLimitedCalls) + }) + } +} + +func TestSSEQuotaNormalizedAfterOutputCannotReplay(t *testing.T) { + for _, kind := range []string{AccountTypeOAuth, AccountTypeAPIKey} { + for _, quota := range []string{"insufficient_quota", "quota_exceeded", "usage_limit_reached"} { + for _, variant := range []string{"uppercase", "padded"} { + for _, passthrough := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/%s/passthrough=%t", kind, quota, variant, passthrough), func(t *testing.T) { + c, rec := newOpenAIUpstreamErrorTestContext(t) + svc := &OpenAIGatewayService{cfg: &config.Config{}} + account := &Account{ID: 42, Platform: PlatformOpenAI, Type: kind, Credentials: map[string]any{"pool_mode": true}} + code := strings.ToUpper(quota) + if variant == "padded" { + code = " " + quota + " " + } + payload := fmt.Sprintf(`{"type":"response.failed","response":{"error":{"type":"server_error","code":%q,"message":"Quota exhausted"}}}`, code) + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\",\"output_index\":0}\n\n" + "data: " + payload + "\n\n" + resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body))} + var err error + if passthrough { + _, err = svc.handleStreamingResponsePassthrough(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } else { + _, err = svc.handleStreamingResponse(c.Request.Context(), resp, c, account, time.Now(), "gpt-5.1", "gpt-5.1") + } + require.Error(t, err) + var failure *UpstreamFailoverError + require.False(t, errors.As(err, &failure), "terminal quota after output must not replay through failover") + require.Contains(t, rec.Body.String(), "partial") + }) + } + } + } + } +} + +func TestSSEQuotaClassificationRetainsExplicitCodeAndIntegrity(t *testing.T) { + for _, payload := range []string{ + `{"type":"response.failed","response":{"error":{"type":"insufficient_quota","code":"credit_balance_exhausted"}}}`, + `{"type":"response.failed","response":{"error":{"type":"insufficient_quota","type":"server_error"}}}`, + `{"type":"response.failed","response":{"error":{"type":"server_error","code":"INSUFFICIENT_QUOTA","code":"server_error"}}}`, + `{"type":"response.failed","response":{"error":{"type":"server_error","code":" QUOTA_EXCEEDED "}}`, + } { + require.Equal(t, http.StatusBadGateway, openAIStreamFailedEventSemanticStatus([]byte(payload), "Quota exhausted")) + require.False(t, isOpenAITerminalQuotaExhaustedResponse([]byte(payload))) + } + for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, 529} { + payload := []byte(fmt.Sprintf(`{"type":"response.failed","response":{"error":{"code":" INSUFFICIENT_QUOTA ","status_code":%d}}}`, status)) + require.Equal(t, status, openAIStreamFailedEventSemanticStatus(payload, "Quota exhausted"), "numeric status keeps precedence over normalized quota") + svc := &OpenAIGatewayService{} + account := &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + failure := svc.newOpenAIAccountFailoverErrorWithClassificationHeaders(account, status, nil, nil, payload, "Quota exhausted", false, true) + require.True(t, failure.RetryableOnSameAccount, "the quota veto remains scoped to semantic 429") + require.Equal(t, payload, failure.ResponseBody) + } + for _, payload := range []string{ + `{"type":"error","error":{"type":"server_error","code":" INSUFFICIENT_QUOTA "}}`, + `{"type":"response.failed","response":{"error":{"type":"insufficient_quota","code":"rate_limit_exceeded"}}}`, + } { + require.False(t, isOpenAITerminalQuotaExhaustedResponse([]byte(payload)), "bare errors and unrelated explicit codes do not gain terminal quota evidence") + } +} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index a5208fa2acc4..62ab3813dd7e 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1978,6 +1978,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } return nil, openAIWSAgentRecoveryClose(err) } + // Lease acquisition and admission can outlast an actual same-account + // retry's window. Ordinary accepted ingress must still drain on disconnect; + // admitted generations and later client turns keep their admission. + if latencyGenerationStartedTurn == 0 && openAISameAccountRetryFromContext(ctx).accountID > 0 { + if !OpenAISameAccountRetryAdmissible(ctx, latest.ID) || !OpenAIWSIngressCanFailover(priorityLatencyCtx, c) { + return nil, denyOpenAITurn("same_account_retry_unavailable") + } + } latencyGenerationStartedTurn = turn if err := lease.WriteJSONWithContextTimeout(ctx, json.RawMessage(payload), s.openAIWSWriteTimeout()); err != nil { return nil, wrapOpenAIWSIngressTurnError(