diff --git a/.github/workflows/anthropic-413.yml b/.github/workflows/anthropic-413.yml new file mode 100644 index 000000000000..6c2234c5727a --- /dev/null +++ b/.github/workflows/anthropic-413.yml @@ -0,0 +1,207 @@ +name: Anthropic HTTP 413 + +on: + pull_request: + branches: [production] + paths: + - 'backend/internal/handler/anthropic_413*' + - 'backend/internal/handler/account_auto_config_outcome.go' + - 'backend/internal/handler/gateway_handler.go' + - 'backend/internal/handler/ops_error_logger.go' + - 'backend/internal/service/gateway_forward.go' + - 'backend/internal/service/gateway_anthropic_passthrough.go' + - 'backend/internal/service/gateway_upstream_response.go' + - 'backend/internal/service/anthropic_413*' + - '.github/workflows/anthropic-413.yml' + +permissions: + contents: read + +env: + EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + RED_BASE_SHA: ff23a988f4c5825ec06a7efb4e0f16f2b1e65ced + REVIEW_RED_BASE_SHA: 4bb46c4c83de1f0cd08b7f3f4ba25ec01e3a3371 + +jobs: + red: + name: RED - pinned production source + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + # All production files and existing fixtures are the exact pre-fix tree. + # Only the new regression is copied from the candidate below. + - uses: actions/checkout@v6 + with: + ref: ff23a988f4c5825ec06a7efb4e0f16f2b1e65ced + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Run real handler regression against pre-fix source + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/anthropic-413-red" + mkdir -p "$evidence" + test "$(git rev-parse HEAD)" = "$RED_BASE_SHA" + git diff --exit-code + test -z "$(git status --porcelain)" + git fetch --no-tags --depth=1 origin "$EXPECTED_HEAD_SHA" + test "$(git rev-parse FETCH_HEAD)" = "$EXPECTED_HEAD_SHA" + regression=backend/internal/handler/anthropic_413_test.go + test ! -e "$regression" + restore() { + rm -f -- "$regression" + git diff --exit-code + test -z "$(git status --porcelain)" + } + trap restore EXIT + git show "$EXPECTED_HEAD_SHA:$regression" > "$regression" + { + printf 'candidate=%s\nbase=%s\n' "$EXPECTED_HEAD_SHA" "$RED_BASE_SHA" + git rev-parse HEAD^{tree} + sha256sum "$regression" + go version + printf '%s\n' 'go test -json -tags=unit ./internal/handler -run ^TestAnthropic413MessagesHTTP$/^apikey$/^stream$ -count=1 -timeout=5m' + } > "$evidence/metadata.txt" + set +e + (cd backend && go test -json -tags=unit ./internal/handler -run '^TestAnthropic413MessagesHTTP$/^apikey$/^stream$' -count=1 -timeout=5m) > "$evidence/red.jsonl" 2> "$evidence/red.stderr" + result=$? + set -e + printf '%s\n' "$result" > "$evidence/exit-code.txt" + cat "$evidence/red.jsonl" "$evidence/red.stderr" + test "$result" -eq 1 + python3 - "$evidence/red.jsonl" <<'PY' + import json, pathlib, sys + events = [json.loads(line) for line in pathlib.Path(sys.argv[1]).read_text().splitlines()] + test = "TestAnthropic413MessagesHTTP/apikey/stream" + assert any(e.get("Test") == test and e.get("Action") == "run" for e in events), "regression did not run" + assert any(e.get("Test") == test and e.get("Action") == "fail" for e in events), "intended regression did not fail" + assert not any(e.get("Action") == "skip" for e in events), "skips are not RED evidence" + output = "".join(e.get("Output", "") for e in events) + assert "anthropic_413_wire_status" in output, "missing intended status assertion" + assert "expected: 413" in output and "actual : 502" in output, "wrong failure reason" + assert not any(s in output for s in ("[build failed]", "panic:", "no tests to run")), "invalid RED evidence" + PY + - uses: actions/upload-artifact@v7 + if: always() + with: + name: anthropic-413-red-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/anthropic-413-red/ + if-no-files-found: error + + review-red: + name: RED - L1 and L2 on reviewed implementation + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + with: + ref: 4bb46c4c83de1f0cd08b7f3f4ba25ec01e3a3371 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Require both independent-review failures in JSON and SSE + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/anthropic-413-review-red" + mkdir -p "$evidence" + test "$(git rev-parse HEAD)" = "$REVIEW_RED_BASE_SHA" + git diff --exit-code + test -z "$(git status --porcelain)" + git fetch --no-tags --depth=1 origin "$EXPECTED_HEAD_SHA" + test "$(git rev-parse FETCH_HEAD)" = "$EXPECTED_HEAD_SHA" + regression=backend/internal/handler/anthropic_413_review_test.go + test ! -e "$regression" + restore() { + rm -f -- "$regression" + git diff --exit-code + test -z "$(git status --porcelain)" + } + trap restore EXIT + git show "$EXPECTED_HEAD_SHA:$regression" > "$regression" + { + printf 'candidate=%s\nreview_base=%s\n' "$EXPECTED_HEAD_SHA" "$REVIEW_RED_BASE_SHA" + git rev-parse HEAD^{tree} + sha256sum "$regression" + go version + printf '%s\n' 'go test -json -tags=unit ./internal/handler -run ^TestAnthropic413Review(AutoConfigNoCooldown|BudgetRepairMonitoring)$ -count=1 -timeout=5m' + } > "$evidence/metadata.txt" + set +e + (cd backend && go test -json -tags=unit ./internal/handler -run '^TestAnthropic413Review(AutoConfigNoCooldown|BudgetRepairMonitoring)$' -count=1 -timeout=5m) > "$evidence/red.jsonl" 2> "$evidence/red.stderr" + result=$? + set -e + printf '%s\n' "$result" > "$evidence/exit-code.txt" + cat "$evidence/red.jsonl" "$evidence/red.stderr" + test "$result" -eq 1 + python3 - "$evidence/red.jsonl" <<'PY' + import json, pathlib, sys + events = [json.loads(line) for line in pathlib.Path(sys.argv[1]).read_text().splitlines()] + markers = { + "TestAnthropic413ReviewAutoConfigNoCooldown": "anthropic_413_L1_final_observation", + "TestAnthropic413ReviewBudgetRepairMonitoring": "anthropic_413_L2_final_visible", + } + for parent, marker in markers.items(): + for boundary in ("json", "sse"): + test = parent + "/" + boundary + assert any(e.get("Test") == test and e.get("Action") == "run" for e in events), f"missing test: {test}" + assert any(e.get("Test") == test and e.get("Action") == "fail" for e in events), f"missing intended failure: {test}" + output = "".join(e.get("Output", "") for e in events if e.get("Test") == test) + assert marker in output, f"wrong failure reason: {test}" + assert not any(e.get("Action") == "skip" for e in events), "skips are not RED evidence" + output = "".join(e.get("Output", "") for e in events) + assert not any(s in output for s in ("[build failed]", "panic:", "no tests to run")), "invalid RED evidence" + PY + - uses: actions/upload-artifact@v7 + if: always() + with: + name: anthropic-413-review-red-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/anthropic-413-review-red/ + if-no-files-found: error + + candidate: + name: Candidate - mock regressions, race and production build + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Candidate handler, wire and ops regressions + shell: bash + run: | + set -euo pipefail + evidence="$RUNNER_TEMP/anthropic-413-candidate" + mkdir -p "$evidence" + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + git diff --exit-code + test -z "$(git status --porcelain)" + { git rev-parse HEAD HEAD^{tree}; go version; } > "$evidence/metadata.txt" + cd backend + go test -tags=unit ./internal/handler -run '^TestAnthropic413(MessagesHTTP|Review.*)$' -count=1 -v -timeout=5m 2>&1 | tee "$evidence/regression.log" + - name: Focused boundary regressions and race + shell: bash + run: | + set -euo pipefail + cd backend + go test -race -tags=unit ./internal/handler -run '^Test(Anthropic413|AutoConfig|GatewayEnsureForwardErrorResponse|GatewayForwardErrorAlreadyCommunicated|StreamWrittenGuard|HandleFailoverError|HandleSelectionExhausted|FailoverClientGone|OpsErrorLoggerMiddleware_(Google|RequestScoped|IntermediateSkipMonitoring|RecoveredTelemetry)|ShouldSkipFinalOpsFailureUsesOnlyFinalAttemptRule|SetOpsLocalErrorTypeClearsRequestScopedMark)' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/anthropic-413-candidate/race.log" + go test -tags=unit ./internal/service -run '^Test(GatewayService_Forward_|GatewayService_AnthropicAPIKeyPassthrough_|GatewayCompatPoolMode429AllowsSameAccountRetry|CalculateAnthropic429ResetTime|RateLimitService_HandleUpstreamError_(OAuth401|NonOAuth401|NonOAuthModel401)|HandleUpstreamTransportError|ClaudeClientCancelForwardStopsActualHTTPAndDoesNotRetry)' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/anthropic-413-candidate/service.log" + - name: Build affected production packages without test tags + shell: bash + run: | + set -euo pipefail + (cd backend && go build ./internal/handler ./internal/service) 2>&1 | tee "$RUNNER_TEMP/anthropic-413-candidate/build.log" + git diff --exit-code + test -z "$(git status --porcelain)" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: anthropic-413-candidate-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/anthropic-413-candidate/ + if-no-files-found: error diff --git a/backend/internal/handler/account_auto_config_outcome.go b/backend/internal/handler/account_auto_config_outcome.go index 2a7848ddd204..5cd369b5af61 100644 --- a/backend/internal/handler/account_auto_config_outcome.go +++ b/backend/internal/handler/account_auto_config_outcome.go @@ -36,6 +36,11 @@ func observeAutoConfigRequest(c *gin.Context, ops *service.OpsService, w *opsCap } ops.ObserveConcurrencyResult(service.AccountConcurrencyResult{AccountID: id, StartedAt: started}) } + // Earlier attempts still report their own failures. The final request-size + // rejection says nothing about the selected account's concurrency capacity. + if isOpsRequestSizeRejection(c) { + return + } id := c.GetInt64(opsAccountIDKey) if id <= 0 || failed[id] || service.IsPrismBrowserAttempt(c, id) { return diff --git a/backend/internal/handler/anthropic_413_review_test.go b/backend/internal/handler/anthropic_413_review_test.go new file mode 100644 index 000000000000..89227a138ecc --- /dev/null +++ b/backend/internal/handler/anthropic_413_review_test.go @@ -0,0 +1,244 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type anthropic413ReviewSettings struct{ service.SettingRepository } + +func (*anthropic413ReviewSettings) GetValue(_ context.Context, key string) (string, error) { + if key == service.SettingKeyRectifierSettings { + return `{"enabled":true,"thinking_budget_enabled":true,"thinking_signature_enabled":false,"apikey_signature_enabled":false}`, nil + } + return "", service.ErrSettingNotFound +} + +func (*anthropic413ReviewSettings) GetMultiple(context.Context, []string) (map[string]string, error) { + return map[string]string{}, nil +} + +type anthropic413ReviewRun struct { + response *httptest.ResponseRecorder + accounts []int64 + bodies [][]byte + events []*service.OpsUpstreamErrorEvent + entries []*service.OpsInsertErrorLogInput + observed []service.AccountConcurrencyResult + before map[int64]service.AutoConfigConcurrencyState + after map[int64]service.AutoConfigConcurrencyState +} + +// This fixture runs the real Messages handler, HTTP transport, ops middleware +// and its installed concurrency observer. The observer applies the same pure +// state transition used by RecordConcurrencyResult, without a database worker. +func runAnthropic413ReviewRequest(t *testing.T, committed bool, firstStatus int) *anthropic413ReviewRun { + t.Helper() + gin.SetMode(gin.TestMode) + run := &anthropic413ReviewRun{ + response: httptest.NewRecorder(), + before: map[int64]service.AutoConfigConcurrencyState{}, + after: map[int64]service.AutoConfigConcurrencyState{}, + } + var bodyMu sync.Mutex + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + bodyMu.Lock() + run.bodies = append(run.bodies, body) + attempt := len(run.bodies) + bodyMu.Unlock() + w.Header().Set("Content-Type", "application/json") + if attempt == 1 && firstStatus != 0 { + w.WriteHeader(firstStatus) + if firstStatus == http.StatusBadRequest { + _, _ = io.WriteString(w, `{"type":"error","error":{"type":"invalid_request_error","message":"thinking.budget_tokens must be >= 1024"}}`) + } else { + _, _ = io.WriteString(w, `{"type":"error","error":{"type":"api_error","message":"synthetic earlier service failure"}}`) + } + return + } + w.WriteHeader(http.StatusRequestEntityTooLarge) + _, _ = io.WriteString(w, `{"type":"error","error":{"type":"request_too_large","message":"fixture-must-not-leak"}}`) + })) + t.Cleanup(provider.Close) + target, err := url.Parse(provider.URL) + require.NoError(t, err) + upstream := &anthropic413HTTPUpstream{client: provider.Client(), target: target} + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Ops.Enabled = true + groupID := int64(4130) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive} + policy := service.DefaultOAuthAutoConfig() + policy.Revision = "synthetic-413-review" + policy.UpgradeEnabled = true + policy.UpgradeGroupIDs = []int64{groupID} + policy.SuccessesPerStep, policy.MaxConcurrency, policy.UpgradeStep, policy.CooldownSeconds = 10, 20, 1, 120 + var accounts []*service.Account + for _, id := range []int64{4131, 4132} { + accounts = append(accounts, &service.Account{ + ID: id, Name: "synthetic-review", Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 10, + Credentials: map[string]any{"api_key": "fixture-key"}, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + }) + state := service.AutoConfigConcurrencyState{ + Revision: policy.Revision, Concurrency: 10, Successes: 3, Required: 10, Maximum: 20, Step: 1, + PausedUntil: time.Now().Add(-time.Hour), + } + run.before[id], run.after[id] = state, state + } + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: accounts}, nil, nil, nil, nil) + settings := service.NewSettingService(&anthropic413ReviewSettings{}, cfg) + rateLimits := service.NewRateLimitService(&anthropic413AccountRepo{}, nil, cfg, nil, nil) + gw := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, nil, cfg, + snapshot, nil, nil, rateLimits, nil, nil, upstream, + nil, nil, nil, nil, nil, settings, nil, nil, nil, nil, nil, nil, + ) + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + h := &GatewayHandler{ + gatewayService: gw, billingCacheService: billing, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + if firstStatus == http.StatusBadRequest { + rule := newBodyLimitPassthroughRule(http.StatusBadRequest, "synthetic repair rule") + rule.Platforms = []string{service.PlatformAnthropic} + rule.ErrorCodes = []int{http.StatusBadRequest} + rule.SkipMonitoring = true + rules := &errorPassthroughRepoStub{} + rules.rules = append(rules.rules, rule) + h.errorPassthroughService = service.NewErrorPassthroughService(rules, nil) + } + setupOpsErrorLogTestQueue(t, 4) + ops := service.NewOpsService(nil, nil, cfg, nil, nil, nil, nil, nil, nil, nil, nil) + require.True(t, ops.IsMonitoringEnabled(context.Background()), "fixture must enable real ops monitoring") + ops.SetAutoConfigObserver(func(result service.AccountConcurrencyResult) { + run.observed = append(run.observed, result) + state := run.after[result.AccountID] + next, _ := service.AdvanceConcurrency(state, state.Concurrency, policy, result, time.Now()) + run.after[result.AccountID] = next + }) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.POST("/v1/messages", func(c *gin.Context) { + apiKey := &service.APIKey{ID: 4133, UserID: 4134, GroupID: &groupID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 4134, Balance: 100, Concurrency: 10}} + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + if committed { + c.Header("Content-Type", "text/event-stream") + _, err := io.WriteString(c.Writer, "event: ping\ndata: {\"type\":\"ping\"}\n\n") + require.NoError(t, err) + c.Writer.Flush() + } + h.Messages(c) + if value, ok := c.Get(service.OpsUpstreamErrorsKey); ok { + run.events = append(run.events, value.([]*service.OpsUpstreamErrorEvent)...) + } + }) + body := fmt.Sprintf(`{"model":"claude-sonnet-4-5","max_tokens":16,"thinking":{"type":"enabled","budget_tokens":1},"stream":%t,"messages":[{"role":"user","content":"synthetic-413-review"}]}`, committed) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req = req.WithContext(context.WithValue(req.Context(), ctxkey.Group, group)) + router.ServeHTTP(run.response, req) + bodyMu.Lock() + run.bodies = append([][]byte(nil), run.bodies...) + bodyMu.Unlock() + upstream.mu.Lock() + run.accounts = append(run.accounts, upstream.accounts...) + upstream.mu.Unlock() + for len(opsErrorLogQueue) > 0 { + run.entries = append(run.entries, (<-opsErrorLogQueue).entry) + } + if committed { + require.Equal(t, http.StatusOK, run.response.Code) + require.Equal(t, 1, strings.Count(run.response.Body.String(), "event: error\n")) + require.Contains(t, run.response.Body.String(), `"type":"request_too_large"`) + } else { + require.Equal(t, http.StatusRequestEntityTooLarge, run.response.Code) + require.JSONEq(t, fmt.Sprintf(`{"type":"error","error":{"type":"request_too_large","message":%q}}`, anthropic413ClientMessage), run.response.Body.String()) + } + require.NotContains(t, run.response.Body.String(), "fixture-must-not-leak") + return run +} + +func TestAnthropic413ReviewAutoConfigNoCooldown(t *testing.T) { + for _, boundary := range []string{"json", "sse"} { + t.Run(boundary, func(t *testing.T) { + run := runAnthropic413ReviewRequest(t, boundary == "sse", 0) + require.Len(t, run.accounts, 1) + require.Len(t, run.entries, 1, "direct 413 is the monitoring positive control") + require.Equal(t, http.StatusRequestEntityTooLarge, run.entries[0].StatusCode) + require.Empty(t, run.observed, "anthropic_413_L1_final_observation: final 413 must not reach concurrency cooldown") + require.Equal(t, run.before, run.after, "success progress, cooldown and failure timestamps must remain unchanged") + }) + } +} + +func TestAnthropic413ReviewPreservesEarlierFailures(t *testing.T) { + for _, boundary := range []string{"json", "sse"} { + t.Run(boundary, func(t *testing.T) { + run := runAnthropic413ReviewRequest(t, boundary == "sse", http.StatusServiceUnavailable) + require.Len(t, run.accounts, 2) + require.NotEqual(t, run.accounts[0], run.accounts[1], "the 503 must exercise real account failover") + require.Len(t, run.observed, 1, "only the earlier independent account failure is observed") + require.Equal(t, run.accounts[0], run.observed[0].AccountID) + require.False(t, run.observed[0].Success) + require.NotNil(t, run.after[run.accounts[0]].LastFailureAt) + require.True(t, run.after[run.accounts[0]].PausedUntil.After(run.before[run.accounts[0]].PausedUntil)) + require.Equal(t, run.before[run.accounts[1]], run.after[run.accounts[1]]) + require.Len(t, run.events, 1, "prior failure history must not be cleared") + require.Equal(t, http.StatusServiceUnavailable, run.events[0].UpstreamStatusCode) + }) + } +} + +func TestAnthropic413ReviewBudgetRepairMonitoring(t *testing.T) { + for _, boundary := range []string{"json", "sse"} { + t.Run(boundary, func(t *testing.T) { + run := runAnthropic413ReviewRequest(t, boundary == "sse", http.StatusBadRequest) + require.Len(t, run.accounts, 2, "exactly one budget repair, then terminal 413") + require.Equal(t, run.accounts[0], run.accounts[1]) + require.Len(t, run.bodies, 2) + require.Equal(t, int64(1), gjson.GetBytes(run.bodies[0], "thinking.budget_tokens").Int()) + require.Equal(t, int64(service.BudgetRectifyBudgetTokens), gjson.GetBytes(run.bodies[1], "thinking.budget_tokens").Int()) + require.Len(t, run.events, 1) + require.Equal(t, "budget_constraint_error", run.events[0].Kind) + require.Equal(t, http.StatusBadRequest, run.events[0].UpstreamStatusCode) + require.True(t, run.events[0].SkipMonitoring, "preserve the earlier attempt's rule snapshot") + require.Len(t, run.observed, 1, "retain the prior attempt's failure even on the final account") + require.False(t, run.observed[0].Success) + require.Len(t, run.entries, 1, "anthropic_413_L2_final_visible: earlier 400 skip_monitoring must not hide final 413") + entry := run.entries[0] + require.Equal(t, http.StatusRequestEntityTooLarge, entry.StatusCode) + require.Equal(t, "request_too_large", entry.ErrorType) + require.Equal(t, "request", entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) + require.True(t, entry.IsBusinessLimited) + require.Nil(t, entry.AccountID) + }) + } +} diff --git a/backend/internal/handler/anthropic_413_test.go b/backend/internal/handler/anthropic_413_test.go new file mode 100644 index 000000000000..6bcc97767da6 --- /dev/null +++ b/backend/internal/handler/anthropic_413_test.go @@ -0,0 +1,257 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// The fixture sends a small synthetic request. The provider rejects it with +// HTTP 413, so neither a huge allocation nor a real provider is needed. +const anthropic413ClientMessage = "Request body is too large. Anthropic Messages requests are limited to 32 MiB. Reduce the request size and try again." + +// Rewrite the destination at the transport boundary, including the hardcoded +// OAuth endpoint, so every auth variant uses only this local HTTP fixture. +type anthropic413HTTPUpstream struct { + client *http.Client + target *url.URL + mu sync.Mutex + accounts []int64 +} + +func (u *anthropic413HTTPUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + u.mu.Lock() + u.accounts = append(u.accounts, accountID) + u.mu.Unlock() + local := req.Clone(req.Context()) + local.URL.Scheme = u.target.Scheme + local.URL.Host = u.target.Host + local.Host = u.target.Host + return u.client.Do(local) +} + +func (u *anthropic413HTTPUpstream) DoWithTLS(req *http.Request, proxy string, accountID int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxy, accountID, concurrency) +} + +type anthropic413AccountRepo struct { + service.AccountRepository + mu sync.Mutex + mutations []string +} + +func (r *anthropic413AccountRepo) record(kind string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.mutations = append(r.mutations, kind) + return nil +} + +func (r *anthropic413AccountRepo) SetError(context.Context, int64, string) error { + return r.record("error") +} + +func (r *anthropic413AccountRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error { + return r.record("temp_unschedulable") +} + +func (r *anthropic413AccountRepo) SetModelRateLimit(context.Context, int64, string, time.Time, ...string) error { + return r.record("model_rate_limit") +} + +func TestAnthropic413MessagesHTTP(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, variant := range []struct { + name string + accountType string + passthrough bool + omit413 bool + cooldown bool + override string + }{ + {name: "apikey", accountType: service.AccountTypeAPIKey}, + {name: "passthrough", accountType: service.AccountTypeAPIKey, passthrough: true}, + {name: "apikey_custom_codes", accountType: service.AccountTypeAPIKey, omit413: true}, + {name: "passthrough_custom_codes", accountType: service.AccountTypeAPIKey, passthrough: true, omit413: true}, + {name: "oauth", accountType: service.AccountTypeOAuth}, + {name: "setup_token", accountType: service.AccountTypeSetupToken}, + {name: "apikey_cooldown_rule", accountType: service.AccountTypeAPIKey, cooldown: true}, + {name: "oauth_cooldown_rule", accountType: service.AccountTypeOAuth, cooldown: true}, + {name: "apikey_custom_override", accountType: service.AccountTypeAPIKey, override: "custom"}, + {name: "passthrough_body_override", accountType: service.AccountTypeAPIKey, passthrough: true, override: "body"}, + } { + t.Run(variant.name, func(t *testing.T) { + for _, boundary := range []string{"nonstream", "stream", "headers", "ping", "partial"} { + t.Run(boundary, func(t *testing.T) { + stream := boundary != "nonstream" + committed := boundary == "headers" || boundary == "ping" || boundary == "partial" + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + if len(body) > 256*1024 || !strings.Contains(string(body), "synthetic-413-input") || r.URL.Path != "/v1/messages" { + t.Errorf("unexpected synthetic request: path=%s bytes=%d", r.URL.Path, len(body)) + } + w.Header().Set("Content-Type", "text/html") + w.Header().Set("X-Request-Id", "fixture-must-not-leak") + w.Header().Set("Retry-After", "999") + w.WriteHeader(http.StatusRequestEntityTooLarge) + _, _ = io.WriteString(w, "Request body exceeds the 32 MiB limit for Messages requests; fixture-must-not-leak") + })) + t.Cleanup(provider.Close) + target, err := url.Parse(provider.URL) + require.NoError(t, err) + upstream := &anthropic413HTTPUpstream{client: provider.Client(), target: target} + cfg := &config.Config{RunMode: config.RunModeSimple} + groupID := int64(4130) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive} + var accounts []*service.Account + for _, id := range []int64{4131, 4132} { + account := &service.Account{ + ID: id, Name: "synthetic-413", Platform: service.PlatformAnthropic, Type: variant.accountType, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + Credentials: map[string]any{"api_key": "fixture-key", "access_token": "fixture-token"}, + Extra: map[string]any{"anthropic_passthrough": variant.passthrough}, + AccountGroups: []service.AccountGroup{{AccountID: id, GroupID: groupID}}, + } + if variant.omit413 { + account.Credentials["custom_error_codes_enabled"] = true + account.Credentials["custom_error_codes"] = []any{float64(401), float64(429), float64(500)} + } + if variant.cooldown { + account.Credentials["temp_unschedulable_enabled"] = true + account.Credentials["temp_unschedulable_rules"] = []any{map[string]any{ + "error_code": float64(413), "keywords": []any{"32 MiB"}, "duration_minutes": float64(10), + }} + } + accounts = append(accounts, account) + } + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: accounts}, nil, nil, nil, nil) + repo := &anthropic413AccountRepo{} + rateLimits := service.NewRateLimitService(repo, nil, cfg, nil, nil) + gw := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, nil, cfg, + snapshot, nil, nil, rateLimits, nil, nil, upstream, + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billing.Stop) + h := &GatewayHandler{ + gatewayService: gw, billingCacheService: billing, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + } + if variant.override != "" { + rule := newBodyLimitPassthroughRule(http.StatusOK, "fixture-override-must-not-leak") + rule.Platforms = []string{service.PlatformAnthropic} + rule.PassthroughBody = variant.override == "body" + rule.SkipMonitoring = true + rules := &errorPassthroughRepoStub{} + rules.rules = append(rules.rules, rule) + h.errorPassthroughService = service.NewErrorPassthroughService(rules, nil) + } + rec := httptest.NewRecorder() + body := fmt.Sprintf(`{"model":"claude-sonnet-4-5","max_tokens":16,"stream":%t,"messages":[{"role":"user","content":"synthetic-413-input"}]}`, stream) + req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req = req.WithContext(context.WithValue(req.Context(), ctxkey.Group, group)) + apiKey := &service.APIKey{ID: 4133, UserID: 4134, GroupID: &groupID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 4134, Balance: 100, Concurrency: 10}} + prefix := "" + setupOpsErrorLogTestQueue(t, 1) + ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + var c *gin.Context + router.POST("/v1/messages", func(handlerContext *gin.Context) { + c = handlerContext + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + if committed { + c.Header("Content-Type", "text/event-stream") + switch boundary { + case "ping": + prefix = "event: ping\ndata: {\"type\":\"ping\"}\n\n" + case "partial": + prefix = partialMessageStartSSE + } + if prefix != "" { + _, writeErr := io.WriteString(c.Writer, prefix) + require.NoError(t, writeErr) + } + c.Writer.Flush() + } + h.Messages(c) + }) + // Exercise actual ops middleware, selection, Forward and wire output. + router.ServeHTTP(rec, req) + + if !committed { + require.Equal(t, http.StatusRequestEntityTooLarge, rec.Code, "anthropic_413_wire_status: upstream HTTP 413 must reach the client") + require.Contains(t, rec.Result().Header.Get("Content-Type"), "application/json") + require.JSONEq(t, fmt.Sprintf(`{"type":"error","error":{"type":"request_too_large","message":%q}}`, anthropic413ClientMessage), rec.Body.String()) + } else { + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "text/event-stream", rec.Result().Header.Get("Content-Type")) + require.True(t, strings.HasPrefix(rec.Body.String(), prefix)) + terminal := strings.TrimPrefix(rec.Body.String(), prefix) + var data []string + for _, line := range strings.Split(terminal, "\n") { + if strings.HasPrefix(line, "data: ") { + data = append(data, strings.TrimPrefix(line, "data: ")) + } else { + require.True(t, line == "" || line == "event: error", "unexpected terminal SSE line: %s", line) + } + } + require.Len(t, data, 1, "exactly one terminal SSE error") + require.JSONEq(t, fmt.Sprintf(`{"type":"error","error":{"type":"request_too_large","message":%q}}`, anthropic413ClientMessage), data[0]) + } + require.NotContains(t, rec.Body.String(), "fixture-must-not-leak") + require.Empty(t, rec.Result().Header.Get("X-Request-Id")) + require.Empty(t, rec.Result().Header.Get("Retry-After")) + require.Equal(t, int64(1), OpsErrorLogQueueLength(), "413 must remain observable even when an override requests skip_monitoring") + entry := (<-opsErrorLogQueue).entry + require.Equal(t, http.StatusRequestEntityTooLarge, entry.StatusCode, "ops records logical 413 even on an already committed HTTP 200 stream") + require.Equal(t, "request_too_large", entry.ErrorType) + require.Equal(t, "request", entry.ErrorPhase) + require.Equal(t, "client", entry.ErrorOwner) + require.Equal(t, "client_request", entry.ErrorSource) + require.Equal(t, "P3", entry.Severity) + require.True(t, entry.IsBusinessLimited) + require.Nil(t, entry.AccountID, "client rejection must not be attributed to account health") + require.Nil(t, entry.UpstreamStatusCode) + require.Empty(t, entry.UpstreamErrors) + require.NotContains(t, entry.ErrorMessage, "must-not-leak") + phase, businessLimited, owner, _ := classifyOpsErrorLog(c, "request_too_large", anthropic413ClientMessage, "", http.StatusRequestEntityTooLarge) + require.Equal(t, "request", phase, "request size must not be classified as an upstream outage") + require.Equal(t, "client", owner, "request rejection must not pollute provider/group health") + require.True(t, businessLimited, "SLA aggregation must exclude the request rejection even with upstream diagnostics") + upstream.mu.Lock() + defer upstream.mu.Unlock() + require.Len(t, upstream.accounts, 1, "413 must not replay the payload or fail over to another account") + repo.mu.Lock() + defer repo.mu.Unlock() + require.Empty(t, repo.mutations, "request size rejection must not change account health") + }) + } + }) + } +} diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 04ed5ccd6dc1..8ce1085d3105 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -1703,10 +1703,22 @@ func applyOpsStreamErrorSnapshot(entry *service.OpsInsertErrorLogInput, streamEr } } +// Only the trusted local marker identifies this final request outcome; an +// arbitrary upstream error body cannot opt out of account observations. +func isOpsRequestSizeRejection(c *gin.Context) bool { + errType, _ := service.OpsLocalErrorType(c) + return service.IsOpsRequestScopedError(c) && errType == "request_too_large" +} + func shouldSkipFinalOpsFailure(c *gin.Context) bool { if c == nil { return false } + // A preceding repair attempt's rule belongs to that attempt, not the final + // request-size rejection. Retain its event and SkipMonitoring snapshot. + if isOpsRequestSizeRejection(c) { + return false + } if v, ok := c.Get(service.OpsSkipPassthroughKey); ok { if skip, _ := v.(bool); skip { return true @@ -2161,6 +2173,8 @@ func inferStreamFailureStatus(_ *gin.Context, parsed parsedOpsError) int { return http.StatusUnauthorized case "invalid_request_error": return http.StatusBadRequest + case "request_too_large": + return http.StatusRequestEntityTooLarge case "overloaded_error", "service_unavailable_error": return http.StatusServiceUnavailable } @@ -2213,6 +2227,7 @@ func guessPlatformFromPath(path string) string { func isKnownOpsErrorType(t string) bool { switch t { case "invalid_request_error", + "request_too_large", "authentication_error", "permission_error", "model_not_found", @@ -2275,7 +2290,7 @@ func classifyOpsPhase(errType, message, code string) string { return "request" } return "upstream" - case service.OpsClientCanceledCode, "invalid_request_error", "permission_error", "forbidden_error", "not_found_error", "model_not_found": + case service.OpsClientCanceledCode, "invalid_request_error", "request_too_large", "permission_error", "forbidden_error", "not_found_error", "model_not_found": return "request" case "upstream_error", "overloaded_error": return "upstream" @@ -2291,7 +2306,7 @@ func classifyOpsPhase(errType, message, code string) string { func classifyOpsSeverity(errType string, status int) string { switch errType { - case service.OpsClientCanceledCode, "invalid_request_error", "authentication_error", "permission_error", "forbidden_error", "not_found_error", "model_not_found", "billing_error", "subscription_error": + case service.OpsClientCanceledCode, "invalid_request_error", "request_too_large", "authentication_error", "permission_error", "forbidden_error", "not_found_error", "model_not_found", "billing_error", "subscription_error": return "P3" } if status >= 500 { @@ -2347,6 +2362,9 @@ func classifyOpsErrorLog(c *gin.Context, errType, message, code string, status i } func classifyOpsIsBusinessLimited(errType, phase, code string, status int, message string, localClientAuthError ...bool) bool { + if errType == "request_too_large" && phase == "request" && status == http.StatusRequestEntityTooLarge { + return true + } if len(localClientAuthError) > 0 && localClientAuthError[0] { return true } diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index e416fea5c3f5..a3c468ae0585 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -121,6 +121,9 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput( Passthrough: true, }) } + if isAnthropicRequestTooLarge(account, resp) { + return handleAnthropicRequestTooLarge(c, resp) + } // 透传分支禁止 400 请求体降级重试(该重试会改写请求体) if resp.StatusCode >= 400 && resp.StatusCode != 400 && s.shouldRetryUpstreamError(account, resp.StatusCode) { diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index ba86d683f7c8..03f5ca93f3b7 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -410,6 +410,9 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A UpstreamURL: safeUpstreamURL(upstreamReq.URL.String()), }) } + if isAnthropicRequestTooLarge(account, resp) { + return handleAnthropicRequestTooLarge(c, resp) + } // 优先检测thinking block签名错误(400)并重试一次 if resp.StatusCode == 400 { @@ -465,6 +468,9 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A retryResp, retryErr := s.httpUpstream.DoWithTLS(retryReq, proxyURL, account.ID, account.Concurrency, tlsProfile) s.rateLimitService.observeQualityResponse(retryReq.Context(), account, retryResp, retryErr) if retryErr == nil { + if isAnthropicRequestTooLarge(account, retryResp) { + return handleAnthropicRequestTooLarge(c, retryResp) + } if retryResp.StatusCode < 400 { // 重试请求被上游接受后同步 ParsedRequest,保证 usage/日志看到真实请求体。 lastWireBody = retryWireBody @@ -672,6 +678,11 @@ func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *A } break } + // A signature/budget repair above can also receive 413. Stop before the + // retry-exhausted and account-policy paths, regardless of custom error codes. + if isAnthropicRequestTooLarge(account, resp) { + return handleAnthropicRequestTooLarge(c, resp) + } if resp == nil || resp.Body == nil { return nil, errors.New("upstream request failed: empty response") } diff --git a/backend/internal/service/gateway_upstream_response.go b/backend/internal/service/gateway_upstream_response.go index 8c5e7768441d..9ec316905d5e 100644 --- a/backend/internal/service/gateway_upstream_response.go +++ b/backend/internal/service/gateway_upstream_response.go @@ -361,7 +361,58 @@ func (s *GatewayService) readUpstreamErrorBody(resp *http.Response) ([]byte, err return io.ReadAll(io.LimitReader(resp.Body, limit)) } +const anthropicRequestTooLargeMessage = "Request body is too large. Anthropic Messages requests are limited to 32 MiB. Reduce the request size and try again." + +var errAnthropicRequestTooLarge = errors.New("anthropic request body too large") + +func isAnthropicRequestTooLarge(account *Account, resp *http.Response) bool { + if account == nil || account.Platform != PlatformAnthropic || resp == nil || resp.StatusCode != http.StatusRequestEntityTooLarge { + return false + } + // Bedrock and Vertex have separate limits and protocol handling. + return account.Type == AccountTypeAPIKey || account.IsAnthropicOAuthOrSetupToken() +} + +// handleAnthropicRequestTooLarge owns the rejected response body and returns a +// terminal error, never a failover error. Neither account policies nor error +// passthrough rules may turn this request rejection into retries or an outage. +func handleAnthropicRequestTooLarge(c *gin.Context, resp *http.Response) (*ForwardResult, error) { + if resp.Body != nil { + _ = resp.Body.Close() + } + if c.Request != nil && c.Request.Context().Err() != nil { + return nil, c.Request.Context().Err() + } + setOpsUpstreamError(c, http.StatusRequestEntityTooLarge, anthropicRequestTooLargeMessage, "") + MarkOpsRequestScopedError(c, "request_too_large") + MarkResponseCommitted(c) + payload := `{"type":"error","error":{"type":"request_too_large","message":` + strconv.Quote(anthropicRequestTooLargeMessage) + `}}` + if !c.Writer.Written() { + c.Data(http.StatusRequestEntityTooLarge, "application/json", []byte(payload)) + return nil, errAnthropicRequestTooLarge + } + + // Flushed headers alone commit HTTP status. Record the logical 413 and + // append one terminal event only when the existing response is an SSE stream. + MarkOpsStreamErrorValue(c, OpsStreamError{ + ErrType: "request_too_large", + Message: anthropicRequestTooLargeMessage, + IntendedStatus: http.StatusRequestEntityTooLarge, + RequestScoped: true, + }) + if strings.HasPrefix(strings.ToLower(c.Writer.Header().Get("Content-Type")), "text/event-stream") { + if _, err := fmt.Fprintf(c.Writer, "event: error\ndata: %s\n\n", payload); err != nil { + _ = c.Error(err) + } + c.Writer.Flush() + } + return nil, errAnthropicRequestTooLarge +} + func (s *GatewayService) handleErrorResponse(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, requestedModel ...string) (*ForwardResult, error) { + if isAnthropicRequestTooLarge(account, resp) { + return handleAnthropicRequestTooLarge(c, resp) + } // Upstream returned a non-success HTTP status; count Ollama Cloud / OpenCode Go activity. scheduleOllamaCloudUsageActivity(s.deferredService, account) scheduleOpenCodeGoUsageActivity(s.deferredService, account)