From 6088f11f39b38b372514268b2f0aa7c650ec945d Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 18:29:15 +0800 Subject: [PATCH 01/38] test: reproduce peer HTTP2 reset through gateway and Ops boundary --- .github/workflows/http2-stream-reset.yml | 60 ++++++++++ .../internal/handler/http2_peer_reset_test.go | 104 ++++++++++++++++++ 2 files changed, 164 insertions(+) create mode 100644 .github/workflows/http2-stream-reset.yml create mode 100644 backend/internal/handler/http2_peer_reset_test.go diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml new file mode 100644 index 000000000000..c73cd0a09303 --- /dev/null +++ b/.github/workflows/http2-stream-reset.yml @@ -0,0 +1,60 @@ +name: HTTP2 stream reset validation + +on: + pull_request: + branches: [production] + workflow_dispatch: + +permissions: + contents: read + +jobs: + regression: + if: github.head_ref == 'fix/http2-stream-error-clarity' || github.ref_name == 'fix/http2-stream-error-clarity' + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: RED real HTTP2 boundary against production + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + mkdir -p "$RUNNER_TEMP/http2-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/http2-evidence/head.txt" + baseline=ccf997c73868083d96c0bec56e71c1a34d26c98a + mapfile -t targets < <(git diff --name-only "$baseline" HEAD -- 'backend/**/*.go' ':!backend/**/*_test.go') + restore_head() { + for target in "${targets[@]}"; do git show "HEAD:$target" > "$target"; done + } + trap restore_head EXIT + for target in "${targets[@]}"; do + if git cat-file -e "$baseline:$target" 2>/dev/null; then git show "$baseline:$target" > "$target"; fi + done + git diff --stat > "$RUNNER_TEMP/http2-evidence/overlay.txt" + set +e + (cd backend && go test -tags=unit ./internal/handler -run '^TestHTTP2PeerResetBoundary$' -count=1 -v -timeout=3m) > "$RUNNER_TEMP/http2-evidence/red.log" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http2-evidence/red.log" + test "$result" -ne 0 + ! grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:' "$RUNNER_TEMP/http2-evidence/red.log" + grep -q 'peer reset must persist as transport_error, not synthetic HTTP 502' "$RUNNER_TEMP/http2-evidence/red.log" + grep -q -- '--- FAIL: TestHTTP2PeerResetBoundary' "$RUNNER_TEMP/http2-evidence/red.log" + restore_head + trap - EXIT + git diff --exit-code + - uses: actions/upload-artifact@v7 + if: always() + with: + name: http2-evidence-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/http2-evidence/ diff --git a/backend/internal/handler/http2_peer_reset_test.go b/backend/internal/handler/http2_peer_reset_test.go new file mode 100644 index 000000000000..612c1cd1d8f3 --- /dev/null +++ b/backend/internal/handler/http2_peer_reset_test.go @@ -0,0 +1,104 @@ +//go:build unit + +package handler + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +// Use the real Go HTTP/2 reader, including its unexported StreamError type. +// Only routing/TLS trust is injected; the service, handler, capture middleware, +// persistence preparation and user DTO mapper are production implementations. +type peerResetHTTPUpstream struct { + service.HTTPUpstream + client *http.Client + base *url.URL +} + +func (u *peerResetHTTPUpstream) Do(req *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + req.URL.Scheme, req.URL.Host = u.base.Scheme, u.base.Host + return u.client.Do(req) +} + +func TestHTTP2PeerResetBoundary(t *testing.T) { + gin.SetMode(gin.TestMode) + setupOpsErrorLogTestQueue(t, 8) + var submissions atomic.Int32 + upstream := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ProtoMajor != 2 { + t.Error("fixture must negotiate real HTTP/2") + } + _, _ = io.Copy(io.Discard, r.Body) + submissions.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + _, _ = io.WriteString(w, "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\"}\n\n") + w.(http.Flusher).Flush() + // net/http sends RST_STREAM(INTERNAL_ERROR), without a successful terminal. + panic(http.ErrAbortHandler) + })) + upstream.EnableHTTP2 = true + upstream.StartTLS() + defer upstream.Close() + base, err := url.Parse(upstream.URL) + require.NoError(t, err) + h := newOpenAIResponsesFailoverTestHandler(t, &peerResetHTTPUpstream{client: upstream.Client(), base: base}) + repo := &ingressRejectOpsRepo{} + ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + var outcomes []service.AccountConcurrencyResult + ops.SetAutoConfigObserver(func(result service.AccountConcurrencyResult) { outcomes = append(outcomes, result) }) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.POST("/v1/responses", func(c *gin.Context) { + seed, _ := newOpenAIResponsesFailoverTestContext(t, c.Request.Context()) + for key, value := range seed.Keys { + c.Set(key, value) + } + h.Responses(c) + }) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.1","stream":true,"input":"synthetic"}`))) + for len(opsErrorLogQueue) > 0 { + flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue}) + } + require.Equal(t, int32(1), submissions.Load(), "submitted request must never be replayed") + require.Equal(t, http.StatusOK, rec.Code) + require.Contains(t, rec.Body.String(), "partial") + require.Len(t, repo.entries, 1) + entry := repo.entries[0] + require.Equal(t, "transport_error", entry.ErrorType, "peer reset must persist as transport_error, not synthetic HTTP 502") + require.Equal(t, http.StatusOK, entry.StatusCode, "persist committed wire status") + require.Nil(t, entry.UpstreamStatusCode, "a reset has no upstream HTTP error status") + require.False(t, entry.IsBusinessLimited) + require.Len(t, outcomes, 1) + require.False(t, outcomes[0].Success) + body := rec.Body.String() + require.Equal(t, 1, strings.Count(body, "event: response.failed\n")) + require.NotContains(t, body, "event: error\n") + require.NotContains(t, body, "response.completed") + require.NotContains(t, body, "[DONE]") + for _, safe := range []string{"upstream_http2_stream_error", "reset by peer", "INTERNAL_ERROR", "incomplete", "Do not automatically retry"} { + require.Contains(t, body, safe) + } + detail := service.ToUserErrorRequestDetail(&service.OpsErrorLogDetail{ + OpsErrorLog: service.OpsErrorLog{Type: entry.ErrorType, Phase: entry.ErrorPhase, StatusCode: entry.StatusCode, Message: entry.ErrorMessage}, + ErrorBody: entry.ErrorBody, UpstreamStatusCode: entry.UpstreamStatusCode, + }) + payload, err := json.Marshal(detail) + require.NoError(t, err) + require.Equal(t, "transport_error", detail.Category) + for _, unsafe := range []string{"stream ID", "127.0.0.1", "synthetic-", "received from peer"} { + require.NotContains(t, body, unsafe) + require.NotContains(t, string(payload), unsafe) + } +} From 71b80ae35327a47fdd8b76b7812efd1bc66089c7 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 18:35:51 +0800 Subject: [PATCH 02/38] fix: preserve peer reset transport outcome and terminate without replay --- .github/workflows/http2-stream-reset.yml | 26 ++++ .../handler/account_auto_config_outcome.go | 6 +- backend/internal/handler/ops_error_logger.go | 14 ++- .../repository/account_auto_config.go | 2 +- .../channel_monitor_v2_aggregation.go | 2 +- .../repository/channel_monitor_v2_repo.go | 4 +- .../http2_peer_reset_integration_test.go | 48 ++++++++ .../repository/ops_client_rejection.go | 2 +- backend/internal/repository/ops_repo.go | 2 +- .../internal/repository/ops_repo_dashboard.go | 8 +- .../internal/repository/ops_repo_preagg.go | 6 +- .../repository/ops_repo_realtime_traffic.go | 2 +- .../repository/ops_repo_request_details.go | 2 +- .../internal/repository/ops_repo_trends.go | 14 +-- backend/internal/service/oauth_auto_config.go | 14 ++- .../service/openai_gateway_cc_pipeline.go | 3 + .../openai_gateway_chat_completions.go | 9 ++ .../openai_gateway_chat_completions_raw.go | 6 + .../openai_gateway_chat_completions_test.go | 4 +- ...eway_compat_buffered_read_failover_test.go | 11 ++ .../service/openai_gateway_messages.go | 10 ++ .../service/openai_gateway_passthrough.go | 5 + .../openai_gateway_response_handling.go | 10 ++ .../service/openai_gateway_service_test.go | 8 ++ .../service/openai_images_responses.go | 7 ++ .../internal/service/openai_images_test.go | 23 ++-- .../service/openai_stream_read_error.go | 116 ++++++++++++++++++ .../internal/service/ops_metrics_collector.go | 6 +- .../internal/service/ops_upstream_context.go | 1 + backend/internal/service/ops_user_error.go | 30 ++++- 30 files changed, 355 insertions(+), 46 deletions(-) create mode 100644 backend/internal/repository/http2_peer_reset_integration_test.go diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml index c73cd0a09303..f3e37677cfb9 100644 --- a/.github/workflows/http2-stream-reset.yml +++ b/.github/workflows/http2-stream-reset.yml @@ -53,6 +53,32 @@ jobs: restore_head trap - EXIT git diff --exit-code + - name: GREEN boundary and existing stream regressions + shell: bash + run: | + set -euo pipefail + cd backend + go test -tags=unit ./internal/handler ./internal/service ./internal/repository -run 'TestHTTP2|TestOpenAIStreaming|TestHandleChatStreaming|TestChatCompletionsBuffered|TestAnthropicBuffered|TestForwardAsAnthropic|TestForwardResponses|TestOpenAIImagesOAuthBodyRead|TestOps.*Stream|TestOpsBridge|TestAutoConfig|Test.*RawStream|Test.*StreamTruncat|Test.*ClientCancel|Test.*ClientDisconnect|Test.*Deadline|TestClassifyOpenAIAPIKeyHealth|TestOpsErrorWhere' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/http2-evidence/green.log" + - name: Ordinary production build + shell: bash + run: | + set -euo pipefail + cd backend + go build ./... 2>&1 | tee "$RUNNER_TEMP/http2-evidence/build.log" + - name: Race boundary and stream lifecycle + shell: bash + run: | + set -euo pipefail + cd backend + go test -race -tags=unit ./internal/handler ./internal/service -run 'TestHTTP2|TestOpenAIStreamingReadError|TestHandleChatStreamingResponse_ClassifiesHTTP2|TestAutoConfigRealRequestOutcomes|TestForwardAsAnthropic_ForceChatCompletionsStreamReadError' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/http2-evidence/race.log" + - name: PostgreSQL persistence and monitor regressions + shell: bash + run: | + set -euo pipefail + cd backend + go test -tags=integration ./internal/repository -run 'TestHTTP2PeerResetPersistence|TestGetErrorLogByID_APIKeyPrefixAndUpstreamStatus|TestChannelMonitorV2.*Error' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/http2-evidence/persistence.log" + ! grep -q -- '--- SKIP: TestHTTP2PeerResetPersistence' "$RUNNER_TEMP/http2-evidence/persistence.log" + git diff --exit-code - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/account_auto_config_outcome.go b/backend/internal/handler/account_auto_config_outcome.go index 5cd369b5af61..186ab44e3bce 100644 --- a/backend/internal/handler/account_auto_config_outcome.go +++ b/backend/internal/handler/account_auto_config_outcome.go @@ -21,11 +21,15 @@ func observeAutoConfigRequest(c *gin.Context, ops *service.OpsService, w *opsCap return } failed := map[int64]bool{} + failureCategories := map[int64]string{} if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok { for _, e := range events { if e != nil && e.AccountID > 0 { failed[e.AccountID] = true + if e.Kind == "transport_error" { + failureCategories[e.AccountID] = e.Kind + } } } } @@ -34,7 +38,7 @@ func observeAutoConfigRequest(c *gin.Context, ops *service.OpsService, w *opsCap if service.IsPrismBrowserAttempt(c, id) { continue } - ops.ObserveConcurrencyResult(service.AccountConcurrencyResult{AccountID: id, StartedAt: started}) + ops.ObserveConcurrencyResult(service.AccountConcurrencyResult{AccountID: id, StartedAt: started, FailureCategory: failureCategories[id]}) } // Earlier attempts still report their own failures. The final request-size // rejection says nothing about the selected account's concurrency capacity. diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 8ce1085d3105..24cc250c3397 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -1149,7 +1149,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { // Trust only the forwarding boundary's local marker. The captured SSE // parser cannot distinguish a bridge failure from an upstream failure and // otherwise overwrites real HTTP 200 evidence with a synthetic 502. - if marked, ok := service.GetOpsStreamError(c); ok && marked.BridgeFailure != nil { + if marked, ok := service.GetOpsStreamError(c); ok && (marked.BridgeFailure != nil || marked.TransportFailure != nil) { logOpsStreamErrorValue(c, ops, status, marked) return } @@ -1538,6 +1538,11 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus errorBody = string(payload) } } + if streamErr.TransportFailure != nil { + if payload, err := json.Marshal(gin.H{"error": streamErr.TransportFailure.ErrorFields()}); err == nil { + errorBody = string(payload) + } + } apiKey := getOpsAPIKey(c) clientRequestID, _ := c.Request.Context().Value(ctxkey.ClientRequestID).(string) @@ -1637,6 +1642,13 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus } entry.UpstreamErrorMessage, entry.UpstreamErrorDetail = nil, nil } + if streamErr.TransportFailure != nil { + entry.ErrorPhase, entry.ErrorType = "network", "transport_error" + entry.ErrorOwner, entry.ErrorSource, entry.Severity = "provider", "upstream_transport", "error" + entry.StatusCode, entry.UpstreamStatusCode = wireStatus, nil + entry.IsBusinessLimited = false + entry.UpstreamErrorDetail = nil + } suppressOpsUpstreamAttributionForClientRejection(entry) if apiKey != nil { diff --git a/backend/internal/repository/account_auto_config.go b/backend/internal/repository/account_auto_config.go index 5fb3593d364c..93efa022ff98 100644 --- a/backend/internal/repository/account_auto_config.go +++ b/backend/internal/repository/account_auto_config.go @@ -76,7 +76,7 @@ func (r *accountRepository) RecordConcurrencyResult(ctx context.Context, event s } now := time.Now().UTC() // Repeated failures within one cooldown do not flood history. - logFailure := !event.Success && (state.Revision != actual.Revision || state.LastFailureAt == nil || !now.Before(state.PausedUntil) || state.Successes > 0) + logFailure := !event.Success && event.FailureCategory != "transport_error" && (state.Revision != actual.Revision || state.LastFailureAt == nil || !now.Before(state.PausedUntil) || state.Successes > 0) state, next := service.AdvanceConcurrency(state, current, actual, event, now) encoded, err := json.Marshal(state) if err != nil { diff --git a/backend/internal/repository/channel_monitor_v2_aggregation.go b/backend/internal/repository/channel_monitor_v2_aggregation.go index 02f18f0adb68..b14e4500e02a 100644 --- a/backend/internal/repository/channel_monitor_v2_aggregation.go +++ b/backend/internal/repository/channel_monitor_v2_aggregation.go @@ -285,7 +285,7 @@ WITH dedup AS ( ) ) AND NOT current_error.is_count_tokens - AND (COALESCE(current_error.status_code, 0) >= 400 OR current_error.error_type = 'cyber_policy') + AND (COALESCE(current_error.status_code, 0) >= 400 OR current_error.error_type = 'cyber_policy' OR current_error.error_type = 'transport_error') ORDER BY COALESCE(NULLIF(current_error.request_id, ''), 'error:' || current_error.id::text), current_error.created_at DESC, current_error.id DESC ), classified AS ( SELECT *, CASE diff --git a/backend/internal/repository/channel_monitor_v2_repo.go b/backend/internal/repository/channel_monitor_v2_repo.go index 9f515f275f35..12e5359e20d8 100644 --- a/backend/internal/repository/channel_monitor_v2_repo.go +++ b/backend/internal/repository/channel_monitor_v2_repo.go @@ -790,12 +790,12 @@ func (r *channelMonitorV2Repository) loadErrorDetails(ctx context.Context, filte "current_error.created_at >= $1", "current_error.created_at < $2", "NOT current_error.is_count_tokens", - "(COALESCE(current_error.status_code, 0) >= 400 OR current_error.error_type = 'cyber_policy')", + "(COALESCE(current_error.status_code, 0) >= 400 OR current_error.error_type = 'cyber_policy' OR current_error.error_type = 'transport_error')", `(NULLIF(current_error.request_id, '') IS NULL OR NOT EXISTS ( SELECT 1 FROM ops_error_logs newer WHERE newer.request_id = current_error.request_id AND NOT newer.is_count_tokens - AND (COALESCE(newer.status_code, 0) >= 400 OR newer.error_type = 'cyber_policy') + AND (COALESCE(newer.status_code, 0) >= 400 OR newer.error_type = 'cyber_policy' OR newer.error_type = 'transport_error') AND (newer.created_at, newer.id) > (current_error.created_at, current_error.id) ))`, } diff --git a/backend/internal/repository/http2_peer_reset_integration_test.go b/backend/internal/repository/http2_peer_reset_integration_test.go new file mode 100644 index 000000000000..0a4584fa1d6e --- /dev/null +++ b/backend/internal/repository/http2_peer_reset_integration_test.go @@ -0,0 +1,48 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestHTTP2PeerResetPersistence(t *testing.T) { + ctx := context.Background() + repo := NewOpsRepository(integrationDB).(*opsRepository) + now := time.Now().UTC() + id, err := repo.InsertErrorLog(ctx, &service.OpsInsertErrorLogInput{ + RequestID: "synthetic-http2-reset", ErrorPhase: "network", ErrorType: "transport_error", + ErrorOwner: "provider", ErrorSource: "upstream_transport", Severity: "error", StatusCode: 200, + ErrorMessage: "Upstream connection reset by peer (HTTP/2 INTERNAL_ERROR). Content may be incomplete. Do not automatically retry the same request.", + ErrorBody: `{"error":{"type":"upstream_error","code":"upstream_http2_stream_error","category":"transport_error","reset_reason":"INTERNAL_ERROR"}}`, + Stream: true, CreatedAt: now, + }) + require.NoError(t, err) + t.Cleanup(func() { _, _ = integrationDB.ExecContext(ctx, "DELETE FROM ops_error_logs WHERE id = $1", id) }) + detail, err := repo.GetErrorLogByID(ctx, id) + require.NoError(t, err) + require.Equal(t, 200, detail.StatusCode) + require.Nil(t, detail.UpstreamStatusCode) + require.Equal(t, "transport_error", detail.Type) + start, end := now.Add(-time.Second), now.Add(time.Second) + list, err := repo.ListErrorLogs(ctx, &service.OpsErrorLogFilter{StartTime: &start, EndTime: &end, ErrorTypesAny: []string{"transport_error"}, Page: 1, PageSize: 20}) + require.NoError(t, err) + found := false + for _, row := range list.Errors { + if row.ID == id { + found = true + } + } + require.True(t, found, "HTTP 200 transport failures must remain visible in request-error lists") + user := service.ToUserErrorRequestDetail(detail) + require.Equal(t, "transport_error", user.Category) + var counted bool + err = integrationDB.QueryRowContext(ctx, "SELECT (COALESCE(status_code,0) >= 400 OR error_type = 'transport_error') FROM ops_error_logs WHERE id=$1", id).Scan(&counted) + require.NoError(t, err) + require.True(t, counted) +} diff --git a/backend/internal/repository/ops_client_rejection.go b/backend/internal/repository/ops_client_rejection.go index b8d0aba13fe1..f32ab3d35826 100644 --- a/backend/internal/repository/ops_client_rejection.go +++ b/backend/internal/repository/ops_client_rejection.go @@ -83,7 +83,7 @@ func opsEffectiveTypeSQL(alias string) string { // separately for upstream diagnostics. Missing IDs remain separate events. func opsMetricErrorRowsSQL(where string) string { key := `COALESCE(api_key_id, 0), COALESCE(group_id, 0), - COALESCE(NULLIF(request_id, ''), 'error:' || id::text), (COALESCE(status_code, 0) >= 400)` + COALESCE(NULLIF(request_id, ''), 'error:' || id::text), (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error')` return `(SELECT DISTINCT ON (` + key + `) current_error.*, ` + opsBusinessLimitedSQL("current_error") + ` AS effective_business_limited FROM ops_error_logs current_error diff --git a/backend/internal/repository/ops_repo.go b/backend/internal/repository/ops_repo.go index 59576373aeba..676de9f22abb 100644 --- a/backend/internal/repository/ops_repo.go +++ b/backend/internal/repository/ops_repo.go @@ -917,7 +917,7 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) { // but they are always client-visible blocked requests that belong in admin + user error // lists. Without the exemption the entire streaming-path cyber sink would be invisible. if !opsFilterIncludesRecoveredProviderRows(filter, phaseFilter) { - clauses = append(clauses, "(COALESCE(e.status_code, 0) >= 400 OR e.error_type = 'cyber_policy')") + clauses = append(clauses, "(COALESCE(e.status_code, 0) >= 400 OR e.error_type = 'cyber_policy' OR e.error_type = 'transport_error')") } if filter.StartTime != nil && !filter.StartTime.IsZero() { diff --git a/backend/internal/repository/ops_repo_dashboard.go b/backend/internal/repository/ops_repo_dashboard.go index 27a1b623b891..4ad140e549d9 100644 --- a/backend/internal/repository/ops_repo_dashboard.go +++ b/backend/internal/repository/ops_repo_dashboard.go @@ -925,9 +925,9 @@ func (r *opsRepository) queryErrorCounts(ctx context.Context, filter *service.Op q := ` SELECT - COALESCE(COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400), 0) AS error_total, - COALESCE(COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400 AND effective_business_limited), 0) AS business_limited, - COALESCE(COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400 AND NOT effective_business_limited AND error_type <> 'client_canceled'), 0) AS error_sla, + COALESCE(COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error')), 0) AS error_total, + COALESCE(COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND effective_business_limited), 0) AS business_limited, + COALESCE(COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND NOT effective_business_limited AND error_type <> 'client_canceled'), 0) AS error_sla, COALESCE(COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT effective_business_limited AND COALESCE(upstream_status_code, status_code, 0) NOT IN (429, 529)), 0) AS upstream_excl, COALESCE(COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT effective_business_limited AND COALESCE(upstream_status_code, status_code, 0) = 429), 0) AS upstream_429, COALESCE(COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT effective_business_limited AND COALESCE(upstream_status_code, status_code, 0) = 529), 0) AS upstream_529 @@ -986,7 +986,7 @@ WITH usage_buckets AS ( error_buckets AS ( SELECT date_trunc('minute', created_at) AS bucket, COUNT(*) AS err_cnt FROM ` + errorSource + ` - AND COALESCE(status_code, 0) >= 400 + AND (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') GROUP BY 1 ), combined AS ( diff --git a/backend/internal/repository/ops_repo_preagg.go b/backend/internal/repository/ops_repo_preagg.go index e0c18ef7f11a..f279a67a79bb 100644 --- a/backend/internal/repository/ops_repo_preagg.go +++ b/backend/internal/repository/ops_repo_preagg.go @@ -88,9 +88,9 @@ error_agg AS ( bucket_start, CASE WHEN GROUPING(platform) = 1 THEN NULL ELSE platform END AS platform, CASE WHEN GROUPING(group_id) = 1 THEN NULL ELSE group_id END AS group_id, - COUNT(*) FILTER (WHERE COALESCE(client_status_code, 0) >= 400) AS error_count_total, - COUNT(*) FILTER (WHERE COALESCE(client_status_code, 0) >= 400 AND is_business_limited) AS business_limited_count, - COUNT(*) FILTER (WHERE COALESCE(client_status_code, 0) >= 400 AND NOT is_business_limited AND error_type <> 'client_canceled') AS error_count_sla, + COUNT(*) FILTER (WHERE (COALESCE(client_status_code, 0) >= 400 OR error_type = 'transport_error')) AS error_count_total, + COUNT(*) FILTER (WHERE (COALESCE(client_status_code, 0) >= 400 OR error_type = 'transport_error') AND is_business_limited) AS business_limited_count, + COUNT(*) FILTER (WHERE (COALESCE(client_status_code, 0) >= 400 OR error_type = 'transport_error') AND NOT is_business_limited AND error_type <> 'client_canceled') AS error_count_sla, COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT is_business_limited AND COALESCE(effective_status_code, 0) NOT IN (429, 529)) AS upstream_error_count_excl_429_529, COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT is_business_limited AND COALESCE(effective_status_code, 0) = 429) AS upstream_429_count, COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT is_business_limited AND COALESCE(effective_status_code, 0) = 529) AS upstream_529_count diff --git a/backend/internal/repository/ops_repo_realtime_traffic.go b/backend/internal/repository/ops_repo_realtime_traffic.go index a9b0b929a11d..43a2a9e0b9da 100644 --- a/backend/internal/repository/ops_repo_realtime_traffic.go +++ b/backend/internal/repository/ops_repo_realtime_traffic.go @@ -54,7 +54,7 @@ error_buckets AS ( COALESCE(COUNT(*), 0) AS error_count FROM ops_error_logs ` + errorWhere + ` - AND COALESCE(status_code, 0) >= 400 + AND (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') GROUP BY 1 ), combined AS ( diff --git a/backend/internal/repository/ops_repo_request_details.go b/backend/internal/repository/ops_repo_request_details.go index c5290495fad3..df7210a079ac 100644 --- a/backend/internal/repository/ops_repo_request_details.go +++ b/backend/internal/repository/ops_repo_request_details.go @@ -133,7 +133,7 @@ WITH combined AS ( LEFT JOIN groups g ON g.id = o.group_id LEFT JOIN accounts a ON a.id = o.account_id WHERE o.created_at >= $1 AND o.created_at < $2 - AND COALESCE(o.status_code, 0) >= 400 + AND (COALESCE(o.status_code, 0) >= 400 OR o.error_type = 'transport_error') ) ` diff --git a/backend/internal/repository/ops_repo_trends.go b/backend/internal/repository/ops_repo_trends.go index 65a5ca8679d4..a44af33b04e4 100644 --- a/backend/internal/repository/ops_repo_trends.go +++ b/backend/internal/repository/ops_repo_trends.go @@ -52,7 +52,7 @@ error_buckets AS ( SELECT ` + errorBucketExpr + ` AS bucket, COUNT(*) AS error_count FROM ` + opsMetricErrorRowsSQL(errorWhere) + ` - WHERE COALESCE(status_code, 0) >= 400 + WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') GROUP BY 1 ), switch_buckets AS ( @@ -200,7 +200,7 @@ error_totals AS ( COUNT(*) AS error_count FROM ops_error_logs WHERE created_at >= $1 AND created_at < $2 - AND COALESCE(status_code, 0) >= 400 + AND (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND is_count_tokens = FALSE -- 排除 count_tokens 请求的错误 GROUP BY 1 ), @@ -274,7 +274,7 @@ error_totals AS ( WHERE created_at >= $1 AND created_at < $2 AND platform = $3 AND group_id IS NOT NULL - AND COALESCE(status_code, 0) >= 400 + AND (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND is_count_tokens = FALSE -- 排除 count_tokens 请求的错误 GROUP BY 1 ), @@ -450,9 +450,9 @@ func (r *opsRepository) GetErrorTrend(ctx context.Context, filter *service.OpsDa q := ` SELECT ` + bucketExpr + ` AS bucket, - COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400) AS error_total, - COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400 AND effective_business_limited) AS business_limited, - COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400 AND NOT effective_business_limited AND error_type <> 'client_canceled') AS error_sla, + COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error')) AS error_total, + COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND effective_business_limited) AS business_limited, + COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND NOT effective_business_limited AND error_type <> 'client_canceled') AS error_sla, COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT effective_business_limited AND COALESCE(upstream_status_code, status_code, 0) NOT IN (429, 529)) AS upstream_excl, COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT effective_business_limited AND COALESCE(upstream_status_code, status_code, 0) = 429) AS upstream_429, COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT effective_business_limited AND COALESCE(upstream_status_code, status_code, 0) = 529) AS upstream_529 @@ -565,7 +565,7 @@ SELECT COUNT(*) FILTER (WHERE NOT effective_business_limited AND error_type <> 'client_canceled') AS sla, COUNT(*) FILTER (WHERE effective_business_limited) AS business_limited FROM ` + opsMetricErrorRowsSQL(where) + ` -WHERE COALESCE(status_code, 0) >= 400 +WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') GROUP BY 1 ORDER BY total DESC LIMIT 20` diff --git a/backend/internal/service/oauth_auto_config.go b/backend/internal/service/oauth_auto_config.go index 4102eb3b3466..40db6deacf93 100644 --- a/backend/internal/service/oauth_auto_config.go +++ b/backend/internal/service/oauth_auto_config.go @@ -401,10 +401,12 @@ func (s *AccountOpsService) validateModelBillingGroupSelections(ctx context.Cont } type AccountConcurrencyResult struct { - Reset bool - AccountID int64 - StartedAt time.Time - Success bool + // Transport failures interrupt the success streak but do not prove capacity exhaustion. + FailureCategory string + Reset bool + AccountID int64 + StartedAt time.Time + Success bool } type AccountConcurrencyRepository interface { RecordConcurrencyResult(context.Context, AccountConcurrencyResult, OAuthAutoConfig) error @@ -443,7 +445,9 @@ func AdvanceConcurrency(state AutoConfigConcurrencyState, current int, c OAuthAu if !result.Success { state.Successes = 0 state.LastFailureAt = &now - state.PausedUntil = now.Add(time.Duration(c.CooldownSeconds) * time.Second) + if result.FailureCategory != "transport_error" { + state.PausedUntil = now.Add(time.Duration(c.CooldownSeconds) * time.Second) + } return state, current } if current <= 0 || current >= maximum || result.StartedAt.Before(state.PausedUntil) { diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index ef4c6b61dc7e..b5a18423f670 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -358,6 +358,9 @@ func (s *OpenAIGatewayService) scanCCStream( ) } st.Err = err + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, err); handled { + st.Err = resetErr + } } return st } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index f1049d293865..28025584c842 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -850,6 +850,9 @@ func (s *OpenAIGatewayService) newOpenAICompatBufferedReadFailoverError( return err } + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, readErr.cause); handled { + return resetErr + } classifiedErr := newOpenAIUpstreamStreamReadError(readErr.cause) code, message, ok := OpenAIUpstreamStreamReadErrorDetails(classifiedErr) if !ok { @@ -1273,6 +1276,9 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( if clientDisconnected || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", err) } + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, err); handled { + return resultWithUsage(), resetErr + } return resultWithUsage(), newOpenAIUpstreamStreamReadError(err) } if frame, ok := parser.Finish(); ok { @@ -1348,6 +1354,9 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( if clientDisconnected || errors.Is(ev.err, context.Canceled) || errors.Is(ev.err, context.DeadlineExceeded) { return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", ev.err) } + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, ev.err); handled { + return resultWithUsage(), resetErr + } return resultWithUsage(), newOpenAIUpstreamStreamReadError(ev.err) } lastDataAt = time.Now() diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index d5f1f4bc4965..ee0d90d362b8 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -467,6 +467,12 @@ func (s *OpenAIGatewayService) streamRawChatCompletions( errors.Is(scanErr, context.Canceled) || errors.Is(scanErr, context.DeadlineExceeded) + if !clientAborted && !terminal.Terminated() { + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, scanErr); handled { + return resultWithUsage(), resetErr + } + } + // 上游在任何终止信号之前结束:连接被 reset(scanErr != nil)或干净 EOF。 // 两者都不能再记成功——此前统一返回 nil error,把上游截断伪装成 // `HTTP 200 + usage 0/0`,客户端收到半截回答且 Ops 侧完全无感。 diff --git a/backend/internal/service/openai_gateway_chat_completions_test.go b/backend/internal/service/openai_gateway_chat_completions_test.go index 744c1a6794e7..71a4c283eba5 100644 --- a/backend/internal/service/openai_gateway_chat_completions_test.go +++ b/backend/internal/service/openai_gateway_chat_completions_test.go @@ -614,9 +614,9 @@ func TestHandleChatStreamingResponse_ClassifiesHTTP2ReadError(t *testing.T) { code, message, ok := OpenAIUpstreamStreamReadErrorDetails(err) require.True(t, ok) require.Equal(t, OpenAIUpstreamHTTP2StreamErrorCode, code) - require.Equal(t, "Upstream HTTP/2 stream failed", message) + require.Equal(t, "Upstream connection reset by peer (HTTP/2 INTERNAL_ERROR). Content may be incomplete. Do not automatically retry the same request.", message) require.NotContains(t, message, "stream ID") - require.NotContains(t, message, "INTERNAL_ERROR") + require.Contains(t, message, "INTERNAL_ERROR") } func TestNormalizeResponsesRequestServiceTier(t *testing.T) { diff --git a/backend/internal/service/openai_gateway_compat_buffered_read_failover_test.go b/backend/internal/service/openai_gateway_compat_buffered_read_failover_test.go index c28bef796a61..a04bb6d4a3a6 100644 --- a/backend/internal/service/openai_gateway_compat_buffered_read_failover_test.go +++ b/backend/internal/service/openai_gateway_compat_buffered_read_failover_test.go @@ -52,6 +52,17 @@ func TestChatCompletionsBufferedResponsesReadErrorReturnsFailover(t *testing.T) require.Error(t, err) require.Nil(t, result) + if readError.name == "http2_reset" { + var failoverErr *UpstreamFailoverError + require.NotErrorAs(t, err, &failoverErr, "peer reset after submission must never authorize replay") + code, message, ok := OpenAIUpstreamStreamReadErrorDetails(err) + require.True(t, ok) + require.Equal(t, readError.expectedCode, code) + require.Contains(t, message, "INTERNAL_ERROR") + require.Equal(t, 502, rec.Code) + require.Contains(t, rec.Body.String(), "Do not automatically retry") + return + } var failoverErr *UpstreamFailoverError require.ErrorAs(t, err, &failoverErr) require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 3f870d0d9b1c..a7386843e133 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -1332,6 +1332,11 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if err := scanner.Err(); err != nil { handleScanErr(err) + if !clientDisconnected { + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, err); handled { + return resultWithUsage(), resetErr + } + } return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", err) } if frame, ok := parser.Finish(); ok { @@ -1405,6 +1410,11 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( } if ev.err != nil { handleScanErr(ev.err) + if !clientDisconnected { + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, ev.err); handled { + return resultWithUsage(), resetErr + } + } return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", ev.err) } lastDataAt = time.Now() diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index aa0c3dafdf9e..16ddd83c2ac2 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -2676,6 +2676,11 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthroughWithImage( logger.LegacyPrintf("service.openai_gateway", "[OpenAI passthrough] SSE line too long: account=%d max_size=%d error=%v", account.ID, maxLineSize, err) return resultWithUsage(), err } + if !clientDisconnected && ctx.Err() == nil { + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, upstreamRequestID, err); handled { + return resultWithUsage(), resetErr + } + } if !openAIStreamClientOutputStarted(c, clientOutputStarted) { msg := "OpenAI stream disconnected before completion" if errText := strings.TrimSpace(err.Error()); errText != "" { diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index fc1490884a55..0d0f892c0c7d 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -552,6 +552,16 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. sendErrorEvent("response_too_large", "Upstream response exceeded the size limit") return resultWithUsage(), scanErr, true } + if !clientDisconnected && ctx.Err() == nil { + if _, reset := openAIHTTP2PeerResetReason(scanErr); reset { + discardIncompletePluginEvent() + flushPending("Client disconnected during reset flush") + errorEventSent = true + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, upstreamRequestID, scanErr); handled { + return resultWithUsage(), resetErr, true + } + } + } if !openAIStreamClientOutputStarted(c, clientOutputStarted) && !eventShouldFlush { msg := "OpenAI stream disconnected before completion" if errText := strings.TrimSpace(scanErr.Error()); errText != "" { diff --git a/backend/internal/service/openai_gateway_service_test.go b/backend/internal/service/openai_gateway_service_test.go index d1329af7fc3f..18d48e540d9e 100644 --- a/backend/internal/service/openai_gateway_service_test.go +++ b/backend/internal/service/openai_gateway_service_test.go @@ -1726,6 +1726,14 @@ func TestOpenAIStreamingReadErrorAfterOutputUsesResponsesErrorSchema(t *testing. require.NotContains(t, body, "stream ID") require.NotContains(t, body, "response.completed") require.NotContains(t, body, "[DONE]") + if tc.code == OpenAIUpstreamHTTP2StreamErrorCode { + require.Equal(t, 1, strings.Count(body, "event: response.failed\n")) + require.Contains(t, body, "INTERNAL_ERROR") + require.Contains(t, body, "Do not automatically retry") + require.NotContains(t, body, "event: error\n") + require.True(t, IsResponseCommitted(c)) + return + } require.Equal(t, 1, strings.Count(body, "event: error\n")) require.True(t, IsResponseCommitted(c), "the handler must not append another failure") var events []gjson.Result diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 51feeb30fdfe..7488c03d7a54 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -2095,6 +2095,13 @@ func (s *OpenAIGatewayService) handleOpenAIImagesOAuthResponseError( writerSizeBeforeResponse int, err error, ) error { + requestID := "" + if resp != nil { + requestID = resp.Header.Get("x-request-id") + } + if resetErr, handled := handleOpenAIHTTP2PeerReset(c, account, requestID, err); handled { + return resetErr + } responseWritten := c != nil && c.Writer != nil && OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c) != writerSizeBeforeResponse if code, message, ok := OpenAIUpstreamStreamReadErrorDetails(err); ok { // A body transport failure after a successful HTTP status is retryable only diff --git a/backend/internal/service/openai_images_test.go b/backend/internal/service/openai_images_test.go index dad3978c8714..3aff8711096c 100644 --- a/backend/internal/service/openai_images_test.go +++ b/backend/internal/service/openai_images_test.go @@ -1162,7 +1162,7 @@ func TestOpenAIGatewayServiceForwardImages_OAuth429CarriesSameAccountRetryWindow require.WithinDuration(t, startedAt.Add(openAIOAuth429RetryWindow), failoverErr.SameAccountRetryDeadline, time.Second) } -func TestOpenAIImagesOAuthBodyReadTransportErrorFailover(t *testing.T) { +func TestOpenAIImagesOAuthBodyReadPeerResetNeverReplays(t *testing.T) { gin.SetMode(gin.TestMode) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -1183,22 +1183,25 @@ func TestOpenAIImagesOAuthBodyReadTransportErrorFailover(t *testing.T) { err := svc.handleOpenAIImagesOAuthResponseError(context.Background(), c, account, "gpt-image-2", "https://api.openai.com/v1/responses", resp, OpenAIImagesJSONKeepaliveAdjustedWrittenSize(c), readErr) var failoverErr *UpstreamFailoverError - require.ErrorAs(t, err, &failoverErr) - require.Equal(t, http.StatusBadGateway, failoverErr.StatusCode) - require.JSONEq(t, `{"error":{"type":"upstream_error","code":"upstream_http2_stream_error","message":"Upstream HTTP/2 stream failed"}}`, string(failoverErr.ResponseBody)) - require.Equal(t, "req_h2_read_failure", failoverErr.ResponseHeaders.Get("x-request-id")) - require.Equal(t, "preserved", failoverErr.ResponseHeaders.Get("x-upstream")) - resp.Header.Set("X-Upstream", "mutated") - require.Equal(t, "preserved", failoverErr.ResponseHeaders.Get("x-upstream")) + require.NotErrorAs(t, err, &failoverErr, "submitted image requests must not replay after peer reset") + code, message, ok := OpenAIUpstreamStreamReadErrorDetails(err) + require.True(t, ok) + require.Equal(t, OpenAIUpstreamHTTP2StreamErrorCode, code) + require.Contains(t, message, "INTERNAL_ERROR") + require.Equal(t, http.StatusBadGateway, rec.Code) + require.Contains(t, rec.Body.String(), "Do not automatically retry") + require.NotContains(t, rec.Body.String(), "req_h2_read_failure") + require.NotContains(t, rec.Body.String(), "preserved") rawEvents, ok := c.Get(OpsUpstreamErrorsKey) require.True(t, ok) events, ok := rawEvents.([]*OpsUpstreamErrorEvent) require.True(t, ok) require.Len(t, events, 1) - require.Equal(t, "failover", events[0].Kind) + require.Equal(t, "transport_error", events[0].Kind) + require.Zero(t, events[0].UpstreamStatusCode) require.Equal(t, "req_h2_read_failure", events[0].UpstreamRequestID) - require.Equal(t, "Upstream HTTP/2 stream failed", events[0].Message) + require.Equal(t, message, events[0].Message) } func TestOpenAIImagesOAuthBodyReadErrorsNotMisclassified(t *testing.T) { diff --git a/backend/internal/service/openai_stream_read_error.go b/backend/internal/service/openai_stream_read_error.go index 9fda5708ee9b..1683998f6b93 100644 --- a/backend/internal/service/openai_stream_read_error.go +++ b/backend/internal/service/openai_stream_read_error.go @@ -2,9 +2,15 @@ package service import ( "context" + "encoding/json" "errors" "fmt" + "net/http" + "regexp" "strings" + + "github.com/gin-gonic/gin" + "golang.org/x/net/http2" ) const ( @@ -69,6 +75,9 @@ func OpenAIUpstreamStreamReadErrorDetails(err error) (code, message string, ok b } func classifyOpenAIUpstreamStreamReadError(err error) (code, message string) { + if reason, ok := openAIHTTP2PeerResetReason(err); ok { + return OpenAIUpstreamHTTP2StreamErrorCode, openAIHTTP2PeerResetMessage(reason) + } if err != nil { if errors.Is(err, ErrOpenAIUpstreamStreamTruncated) { return OpenAIUpstreamStreamTruncatedCode, "Upstream response stream ended before completion" @@ -84,3 +93,110 @@ func classifyOpenAIUpstreamStreamReadError(err error) (code, message string) { } return OpenAIUpstreamStreamReadErrorCode, "Upstream response stream was interrupted" } + +// net/http uses an unexported copy of http2.StreamError. Match its complete +// peer-reset signature, not an arbitrary mention of HTTP/2 in an error body. +var openAIHTTP2PeerResetPattern = regexp.MustCompile(`(?:^|: )stream error: stream ID [0-9]+; ([^;\r\n]+); received from peer$`) + +func safeHTTP2ResetReason(reason string) string { + switch reason { + case "NO_ERROR", "PROTOCOL_ERROR", "INTERNAL_ERROR", "FLOW_CONTROL_ERROR", "SETTINGS_TIMEOUT", "STREAM_CLOSED", "FRAME_SIZE_ERROR", "REFUSED_STREAM", "CANCEL", "COMPRESSION_ERROR", "CONNECT_ERROR", "ENHANCE_YOUR_CALM", "INADEQUATE_SECURITY", "HTTP_1_1_REQUIRED": + return reason + default: + return "" + } +} + +func openAIHTTP2PeerResetReason(err error) (string, bool) { + if !shouldClassifyOpenAIUpstreamStreamReadError(err) { + return "", false + } + var streamErr http2.StreamError + if errors.As(err, &streamErr) && streamErr.Cause != nil && streamErr.Cause.Error() == "received from peer" { + return safeHTTP2ResetReason(streamErr.Code.String()), true + } + match := openAIHTTP2PeerResetPattern.FindStringSubmatch(err.Error()) + if len(match) != 2 { + return "", false + } + return safeHTTP2ResetReason(match[1]), true +} + +func openAIHTTP2PeerResetMessage(reason string) string { + protocol := "HTTP/2" + if reason = safeHTTP2ResetReason(reason); reason != "" { + protocol += " " + reason + } + return "Upstream connection reset by peer (" + protocol + "). Content may be incomplete. Do not automatically retry the same request." +} + +// OpsTransportFailure is trusted local evidence, never inferred from SSE text. +// Keeping it separate from HTTP status avoids both false success and 502 policy. +type OpsTransportFailure struct { + ResetReason string `json:"reset_reason,omitempty"` +} + +func (f *OpsTransportFailure) ErrorFields() map[string]any { + return map[string]any{"type": "upstream_error", "code": OpenAIUpstreamHTTP2StreamErrorCode, + "category": "transport_error", "protocol": "HTTP/2", "reset_reason": safeHTTP2ResetReason(f.ResetReason), + "message": openAIHTTP2PeerResetMessage(f.ResetReason)} +} + +// handleOpenAIHTTP2PeerReset ends this submitted request at the read boundary. +// The caller must discard any incomplete staged event before invoking it. A +// typed read error (not UpstreamFailoverError) prevents account or request replay. +func handleOpenAIHTTP2PeerReset(c *gin.Context, account *Account, requestID string, cause error) (error, bool) { + if c == nil || c.Request == nil || !shouldClassifyOpenAIUpstreamStreamReadError(cause, c.Request.Context()) { + return nil, false + } + reason, ok := openAIHTTP2PeerResetReason(cause) + if !ok { + return nil, false + } + classified := newOpenAIUpstreamStreamReadError(cause) + if marked, exists := GetOpsStreamError(c); exists && marked.TransportFailure != nil { + return classified, true + } + StopOpenAICompactSSEKeepaliveCommitted(c) + StopOpenAIImagesJSONKeepaliveCommitted(c) + failure := &OpsTransportFailure{ResetReason: reason} + message := openAIHTTP2PeerResetMessage(reason) + c.Set(OpsUpstreamStatusCodeKey, 0) + c.Set(OpsUpstreamErrorMessageKey, message) + c.Set(OpsUpstreamErrorDetailKey, "") + event := OpsUpstreamErrorEvent{Kind: "transport_error", Stage: "response_body", Reason: reason, + Message: message, UpstreamRequestID: requestID, ProxyID: opsUpstreamProxyID(account), ProxyName: opsUpstreamProxyName(account)} + if account != nil { + event.Platform, event.AccountID, event.AccountName = account.Platform, account.ID, account.Name + } + appendOpsUpstreamError(c, event) + MarkOpsStreamErrorValue(c, OpsStreamError{TransportFailure: failure, ErrType: "upstream_error", + Code: OpenAIUpstreamHTTP2StreamErrorCode, Message: message, IntendedStatus: http.StatusBadGateway, CountTowardsSLA: true}) + fields := failure.ErrorFields() + // HTTP bridge WebSocket callers own their frame writer; don't write HTTP SSE + // to an upgraded connection. Their caller consumes the typed safe details. + if GetOpenAIClientTransport(c) == OpenAIClientTransportWS { + return classified, true + } + if c.Writer.Written() && strings.Contains(c.Writer.Header().Get("Content-Type"), "text/event-stream") { + eventType := "error" + payload := map[string]any{"error": fields} + if strings.HasSuffix(strings.TrimRight(c.Request.URL.Path, "/"), "/responses") { + eventType = "response.failed" + payload = map[string]any{"type": eventType, "sequence_number": 0, "response": map[string]any{"status": "failed", "error": fields}} + } else if strings.HasSuffix(c.Request.URL.Path, "/messages") { + payload["type"] = "error" + } + data, _ := json.Marshal(payload) + _, _ = fmt.Fprintf(c.Writer, "\n\nevent: %s\ndata: %s\n\n", eventType, data) + c.Writer.Flush() + } else { + status := http.StatusBadGateway + if c.Writer.Written() { + status = c.Writer.Status() + } + c.JSON(status, gin.H{"error": fields}) + } + MarkResponseCommitted(c) + return classified, true +} diff --git a/backend/internal/service/ops_metrics_collector.go b/backend/internal/service/ops_metrics_collector.go index cd0e8b3eab07..9e73069b86b3 100644 --- a/backend/internal/service/ops_metrics_collector.go +++ b/backend/internal/service/ops_metrics_collector.go @@ -546,9 +546,9 @@ func (c *OpsMetricsCollector) queryErrorCounts(ctx context.Context, start, end t ) { q := ` SELECT - COALESCE(COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400), 0) AS error_total, - COALESCE(COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400 AND is_business_limited), 0) AS business_limited, - COALESCE(COUNT(*) FILTER (WHERE COALESCE(status_code, 0) >= 400 AND NOT is_business_limited), 0) AS error_sla, + COALESCE(COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error')), 0) AS error_total, + COALESCE(COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND is_business_limited), 0) AS business_limited, + COALESCE(COUNT(*) FILTER (WHERE (COALESCE(status_code, 0) >= 400 OR error_type = 'transport_error') AND NOT is_business_limited), 0) AS error_sla, COALESCE(COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT is_business_limited AND COALESCE(upstream_status_code, status_code, 0) NOT IN (429, 529)), 0) AS upstream_excl, COALESCE(COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT is_business_limited AND COALESCE(upstream_status_code, status_code, 0) = 429), 0) AS upstream_429, COALESCE(COUNT(*) FILTER (WHERE error_owner = 'provider' AND NOT is_business_limited AND COALESCE(upstream_status_code, status_code, 0) = 529), 0) AS upstream_529 diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index 7344c5d25cc7..44d2263e4e6b 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -186,6 +186,7 @@ func IsOpsRequestScopedError(c *gin.Context) bool { // 由于 HTTP 状态码停留在 2xx,ops_error_logger 中间件在 status<400 分支消费该标记并 // 补记错误日志;标记方是 handler.handleStreamingAwareError 或各 service 的带内检测。 type OpsStreamError struct { + TransportFailure *OpsTransportFailure // BridgeFailure is set only by the local BPS conversion boundary. It keeps // real upstream HTTP evidence while assigning failure ownership to gateway. BridgeFailure *basispoints.BridgeFailure diff --git a/backend/internal/service/ops_user_error.go b/backend/internal/service/ops_user_error.go index 0c44b9f37e5e..e4cd6fd0193d 100644 --- a/backend/internal/service/ops_user_error.go +++ b/backend/internal/service/ops_user_error.go @@ -1,6 +1,9 @@ package service -import "time" +import ( + "encoding/json" + "time" +) // UserErrorRequest 是面向终端用户的"错误请求"精简脱敏视图(白名单)。 // 严禁包含 account / api_key_prefix / upstream_endpoint / user_email 等 @@ -39,6 +42,9 @@ type UserErrorRequestList struct { // MapUserErrorCategory 把后端 error_phase + error_type 映射为用户侧粗分类码。 // 返回的是稳定的分类 code(前端做 i18n),不是展示文案。 func MapUserErrorCategory(phase, errType string) string { + if errType == "transport_error" { + return "transport_error" + } switch phase { case "auth": return "auth" @@ -68,6 +74,8 @@ func MapUserErrorCategory(phase, errType string) string { // 注意:"other" 与未知分类都走 default 返回空切片——"other" 无对应的 phase/type 组合,无法精确反查,因此等价于不过滤。 func CategoryToFilter(category string) (phases []string, errorTypes []string) { switch category { + case "transport_error": + return nil, []string{"transport_error"} case "auth": return []string{"auth"}, nil case "service_unavailable": @@ -102,6 +110,10 @@ func ToUserErrorRequest(e *OpsErrorLog) *UserErrorRequest { if e.ClientIP != nil { clientIP = *e.ClientIP } + message := e.Message + if e.Type == "transport_error" { + message = openAIHTTP2PeerResetMessage("") + } return &UserErrorRequest{ ID: e.ID, CreatedAt: e.CreatedAt, @@ -110,7 +122,7 @@ func ToUserErrorRequest(e *OpsErrorLog) *UserErrorRequest { StatusCode: e.StatusCode, Category: MapUserErrorCategory(e.Phase, e.Type), Platform: e.Platform, - Message: e.Message, + Message: message, KeyName: e.APIKeyName, KeyDeleted: e.APIKeyDeleted, ClientIP: clientIP, @@ -125,6 +137,7 @@ func ToUserErrorRequest(e *OpsErrorLog) *UserErrorRequest { // 在 UserErrorRequest 基础上额外暴露 error_body(上游错误响应正文)与 upstream_status_code; // 仍严禁任何内部/敏感字段。 type UserErrorRequestDetail struct { + ResetReason string `json:"reset_reason,omitempty"` UserErrorRequest ErrorBody string `json:"error_body"` UpstreamStatusCode *int `json:"upstream_status_code,omitempty"` @@ -136,6 +149,19 @@ func ToUserErrorRequestDetail(e *OpsErrorLogDetail) *UserErrorRequestDetail { return nil } base := ToUserErrorRequest(&e.OpsErrorLog) + if e.Type == "transport_error" { + var envelope struct { + Error struct { + ResetReason string `json:"reset_reason"` + } `json:"error"` + } + _ = json.Unmarshal([]byte(e.ErrorBody), &envelope) + reason := safeHTTP2ResetReason(envelope.Error.ResetReason) + base.Message = openAIHTTP2PeerResetMessage(reason) + failure := &OpsTransportFailure{ResetReason: reason} + body, _ := json.Marshal(map[string]any{"error": failure.ErrorFields()}) + return &UserErrorRequestDetail{UserErrorRequest: *base, ErrorBody: string(body), ResetReason: reason} + } return &UserErrorRequestDetail{ UserErrorRequest: *base, ErrorBody: e.ErrorBody, From ac32a9b3e5129490c62dbdd991635d306231d0fc Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 18:39:21 +0800 Subject: [PATCH 03/38] test: cover reset adapters and localize safe user error details --- .github/http2-stream-reset-preview.mjs | 84 ++++++++++++++ .github/workflows/http2-stream-reset.yml | 40 +++++++ .../internal/handler/http2_peer_reset_test.go | 103 ++++++++++++++++++ .../internal/service/http2_peer_reset_test.go | 87 +++++++++++++++ .../components/user/UserErrorDetailModal.vue | 3 +- .../user/UserErrorRequestsTable.vue | 5 +- .../user/__tests__/UserErrorTransport.spec.ts | 29 +++++ frontend/src/i18n/locales/en/dashboard.ts | 2 + frontend/src/i18n/locales/zh/dashboard.ts | 2 + frontend/src/types/index.ts | 1 + frontend/src/utils/userErrorMessage.ts | 16 +++ frontend/src/views/user/UsageView.vue | 2 +- 12 files changed, 370 insertions(+), 4 deletions(-) create mode 100644 .github/http2-stream-reset-preview.mjs create mode 100644 backend/internal/service/http2_peer_reset_test.go create mode 100644 frontend/src/components/user/__tests__/UserErrorTransport.spec.ts create mode 100644 frontend/src/utils/userErrorMessage.ts diff --git a/.github/http2-stream-reset-preview.mjs b/.github/http2-stream-reset-preview.mjs new file mode 100644 index 000000000000..c72ac61ed36b --- /dev/null +++ b/.github/http2-stream-reset-preview.mjs @@ -0,0 +1,84 @@ +// Actual user error component and project styles, with synthetic DTO fixtures. +// Images and browser logs are evidence artifacts, never source files. +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { execFileSync } from 'node:child_process' +import { createRequire } from 'node:module' +import { dirname, join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +const [repoArg, outputArg] = process.argv.slice(2) +const repo = resolve(repoArg), output = resolve(outputArg), root = join(repo, 'frontend') +const req = createRequire(join(root, 'package.json')) +const { createServer } = await import(pathToFileURL(join(dirname(req.resolve('vite/package.json')), 'dist/node/index.js')).href) +const vue = (await import(pathToFileURL(req.resolve('@vitejs/plugin-vue')).href)).default +const { chromium } = await import(pathToFileURL(process.env.SUB2API_PLAYWRIGHT_MODULE).href) +const git = (...args) => execFileSync('git', args, { cwd: repo, encoding: 'utf8' }).trimEnd() +const sha = git('rev-parse', 'HEAD'), baseline = 'ccf997c73868083d96c0bec56e71c1a34d26c98a' +mkdirSync(output, { recursive: true }) +const scratch = mkdtempSync(join(output, 'vite-')), entryName = `.http2-preview-${process.pid}.js`, entry = join(root, entryName) +let before = true, server, browser +const errors = [], captures = [] +const origin = 'http://127.0.0.1:4299' +try { + writeFileSync(entry, ` +import {mount} from '@vue/test-utils'; +import {i18n,loadLocaleMessages} from '/src/i18n/index.ts'; +import View from '/src/components/user/UserErrorDetailModal.vue'; +import '/src/style.css'; +const params=new URL(location.href).searchParams; +const locale=params.get('locale')||'en',before=params.get('before')==='1'; +await loadLocaleMessages(locale);i18n.global.locale.value=locale; +window.fixture={id:833,created_at:'2026-11-13T10:00:00Z',model:'example-model',inbound_endpoint:'/v1/responses',status_code:before?502:200,category:before?'upstream':'transport_error',platform:'openai',message:before?'Upstream HTTP/2 stream failed':'Upstream connection reset by peer (HTTP/2 INTERNAL_ERROR). Content may be incomplete. Do not automatically retry the same request.',reset_reason:before?undefined:'INTERNAL_ERROR',upstream_status_code:before?502:undefined,key_name:'Demo key',key_deleted:false,error_body:JSON.stringify({error:{type:'upstream_error',code:'upstream_http2_stream_error',...(before?{}:{category:'transport_error',protocol:'HTTP/2',reset_reason:'INTERNAL_ERROR'})}},null,2)}; +window.preview=mount(View,{attachTo:'#app',props:{show:false,errorId:833},global:{plugins:[i18n]}}); +await window.preview.setProps({show:true}); +`, { flag: 'wx' }) + process.chdir(root) + server = await createServer({ root, configFile: false, cacheDir: scratch, + resolve: { alias: { '@': join(root, 'src') } }, + plugins: [{ name: 'http2-preview', enforce: 'pre', load(id) { + const clean = id.split('?')[0] + if (clean === join(root, 'src/api/usage.ts')) return 'export const getMyErrorDetail=async()=>window.fixture' + if (before && !id.includes('?') && clean === join(root, 'src/components/user/UserErrorDetailModal.vue')) return git('show', baseline + ':frontend/src/components/user/UserErrorDetailModal.vue') + }, configureServer(vite) { + vite.middlewares.use((request, response, next) => { + if (request.url === '/' || request.url?.startsWith('/?')) { + response.setHeader('Content-Type', 'text/html') + response.end('
') + } else if (request.url === '/favicon.ico') { response.statusCode = 204; response.end() } else next() + }) + } }, vue()], + server: { host: '127.0.0.1', port: 4299, strictPort: true }, + optimizeDeps: { entries: [], include: ['vue', 'vue-i18n', '@vue/test-utils'] } + }) + await server.listen() + browser = await chromium.launch({ headless: true }) + const page = await browser.newPage({ viewport: { width: 1180, height: 900 }, timezoneId: 'UTC' }) + page.on('pageerror', error => errors.push(error.message)) + await page.route('**/*', route => { + if (new URL(route.request().url()).origin === origin) return route.continue() + errors.push('unexpected external request'); return route.abort() + }) + for (const state of ['before', 'after']) { + before = state === 'before'; server.moduleGraph.invalidateAll() + for (const locale of ['en', 'zh']) { + await page.goto(origin + '/?locale=' + locale + '&before=' + (before ? '1' : '0'), { waitUntil: 'networkidle' }) + await page.getByText('example-model', { exact: true }).waitFor() + const dialog = page.getByRole('dialog'), text = await dialog.innerText() + if (!before) { + for (const expected of [locale === 'en' ? 'Do not automatically retry' : '请勿自动重试', 'HTTP/2 INTERNAL_ERROR', '200']) if (!text.includes(expected)) throw Error('Missing ' + expected) + for (const forbidden of ['502', 'stream ID', 'usage.errors.']) if (text.includes(forbidden)) throw Error('Unexpected ' + forbidden) + } + const name = `${state}-${locale}.png` + await dialog.screenshot({ path: join(output, name) }) + captures.push({ name, sha: before ? baseline : sha, fixture: state, text }) + await page.getByLabel('Close modal').click() + await page.getByRole('dialog').waitFor({ state: 'detached' }) + } + } + writeFileSync(join(output, 'manifest.json'), JSON.stringify({ sha, baseline, captures, errors, boundary: 'Real UserErrorDetailModal, BaseDialog, EN/ZH translations and styles. Synthetic API DTOs; before uses baseline component. No production traffic.' }, null, 2)) + if (errors.length) throw Error(errors.join('\n')) + console.log('Rendered and exercised before/after error details in EN/ZH at ' + sha) +} finally { + await browser?.close(); await server?.close() + rmSync(entry, { force: true }); rmSync(scratch, { recursive: true, force: true }) +} diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml index f3e37677cfb9..039ef81d166a 100644 --- a/.github/workflows/http2-stream-reset.yml +++ b/.github/workflows/http2-stream-reset.yml @@ -84,3 +84,43 @@ jobs: with: name: http2-evidence-${{ github.event.pull_request.head.sha || github.sha }} path: ${{ runner.temp }}/http2-evidence/ + + user-surface: + if: github.head_ref == 'fix/http2-stream-error-clarity' || github.ref_name == 'fix/http2-stream-error-clarity' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + - uses: pnpm/action-setup@v6 + with: + version: 9 + - uses: actions/setup-node@v6 + with: + node-version: '22' + cache: pnpm + cache-dependency-path: frontend/pnpm-lock.yaml + - run: pnpm --dir frontend install --frozen-lockfile + - name: Real component regressions and production frontend build + shell: bash + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/http2-ui" + git rev-parse HEAD > "$RUNNER_TEMP/http2-ui/head.txt" + pnpm --dir frontend exec vitest run src/components/user/__tests__/UserErrorTransport.spec.ts src/components/user/__tests__/UserErrorDetailModal.spec.ts 2>&1 | tee "$RUNNER_TEMP/http2-ui/component.log" + pnpm --dir frontend run build 2>&1 | tee "$RUNNER_TEMP/http2-ui/build.log" + - name: Isolated screenshot browser + run: | + npm install --prefix "$RUNNER_TEMP/http2-browser" --no-save --ignore-scripts playwright@1.56.1 + node "$RUNNER_TEMP/http2-browser/node_modules/playwright/cli.js" install --with-deps chromium + - name: Actual component before and after in English and Chinese + env: + SUB2API_PLAYWRIGHT_MODULE: ${{ runner.temp }}/http2-browser/node_modules/playwright/index.mjs + run: node .github/http2-stream-reset-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/http2-ui" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: http2-ui-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/http2-ui/ diff --git a/backend/internal/handler/http2_peer_reset_test.go b/backend/internal/handler/http2_peer_reset_test.go index 612c1cd1d8f3..b844964a01a1 100644 --- a/backend/internal/handler/http2_peer_reset_test.go +++ b/backend/internal/handler/http2_peer_reset_test.go @@ -4,6 +4,8 @@ package handler import ( "encoding/json" + "fmt" + "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" "io" "net/http" "net/http/httptest" @@ -102,3 +104,104 @@ func TestHTTP2PeerResetBoundary(t *testing.T) { require.NotContains(t, string(payload), unsafe) } } + +func TestHTTP2PeerResetAdaptersNeverReplay(t *testing.T) { + for _, mode := range []string{"responses", "passthrough", "responses_via_chat", "chat_via_responses", "raw_chat"} { + for _, partial := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/partial=%v", mode, partial), func(t *testing.T) { + setupOpsErrorLogTestQueue(t, 8) + var submissions atomic.Int32 + upstream := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ProtoMajor != 2 { + t.Error("expected HTTP/2") + } + _, _ = io.Copy(io.Discard, r.Body) + submissions.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(200) + if partial { + if strings.HasSuffix(r.URL.Path, "/chat/completions") { + _, _ = io.WriteString(w, "data: {\"id\":\"synthetic\",\"object\":\"chat.completion.chunk\",\"model\":\"gpt-5.1\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"partial\"},\"finish_reason\":null}]}\n\n") + } else { + _, _ = io.WriteString(w, "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\"}\n\n") + } + } + w.(http.Flusher).Flush() + panic(http.ErrAbortHandler) + })) + upstream.EnableHTTP2 = true + upstream.StartTLS() + defer upstream.Close() + base, err := url.Parse(upstream.URL) + require.NoError(t, err) + extra := map[string]any{} + kind := service.AccountTypeOAuth + if mode == "passthrough" { + extra["openai_passthrough"] = true + } + if mode == "responses_via_chat" || mode == "raw_chat" { + kind = service.AccountTypeAPIKey + extra[openai_compat.ExtraKeyResponsesMode] = string(openai_compat.ResponsesSupportModeForceChatCompletions) + } + accounts := []service.Account{} + for i := int64(1); i <= 2; i++ { + accounts = append(accounts, service.Account{ID: i, Name: "synthetic", Platform: service.PlatformOpenAI, Type: kind, Status: service.StatusActive, Schedulable: true, Priority: int(i), Credentials: map[string]any{"api_key": "synthetic", "access_token": "synthetic", "base_url": "https://example.invalid"}, Extra: extra}) + } + h := newOpenAIResponsesFailoverTestHandler(t, &peerResetHTTPUpstream{client: upstream.Client(), base: base}, accounts...) + repo := &ingressRejectOpsRepo{} + ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + var outcomes []service.AccountConcurrencyResult + ops.SetAutoConfigObserver(func(r service.AccountConcurrencyResult) { outcomes = append(outcomes, r) }) + endpoint := "/v1/responses" + body := `{"model":"gpt-5.1","stream":true,"input":"synthetic"}` + handler := h.Responses + if mode == "chat_via_responses" || mode == "raw_chat" { + endpoint = "/v1/chat/completions" + body = `{"model":"gpt-5.1","stream":true,"messages":[{"role":"user","content":"synthetic"}]}` + handler = h.ChatCompletions + } + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.POST(endpoint, func(c *gin.Context) { + seed, _ := newOpenAIResponsesFailoverTestContext(t, c.Request.Context()) + for k, v := range seed.Keys { + c.Set(k, v) + } + handler(c) + }) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(body))) + for len(opsErrorLogQueue) > 0 { + flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue}) + } + require.Equal(t, int32(1), submissions.Load(), "a submitted request must never be replayed after peer reset") + require.Len(t, repo.entries, 1, rec.Body.String()) + entry := repo.entries[0] + require.Equal(t, "transport_error", entry.ErrorType) + require.Nil(t, entry.UpstreamStatusCode) + require.Equal(t, rec.Code, entry.StatusCode) + require.Len(t, outcomes, 1) + require.False(t, outcomes[0].Success) + outcomeJSON, err := json.Marshal(outcomes[0]) + require.NoError(t, err) + require.Contains(t, string(outcomeJSON), `"FailureCategory":"transport_error"`) + if partial { + require.Equal(t, 200, rec.Code) + require.Contains(t, rec.Body.String(), "partial") + terminal := "event: response.failed\n" + if endpoint == "/v1/chat/completions" { + terminal = "event: error\n" + } + require.Equal(t, 1, strings.Count(rec.Body.String(), terminal)) + } else { + require.Equal(t, 502, rec.Code) + } + require.Contains(t, rec.Body.String(), "upstream_http2_stream_error") + require.Contains(t, rec.Body.String(), "INTERNAL_ERROR") + for _, forbidden := range []string{"[DONE]", "response.completed", "stream ID", "127.0.0.1"} { + require.NotContains(t, rec.Body.String(), forbidden) + } + }) + } + } +} diff --git a/backend/internal/service/http2_peer_reset_test.go b/backend/internal/service/http2_peer_reset_test.go new file mode 100644 index 000000000000..87aac09b36ed --- /dev/null +++ b/backend/internal/service/http2_peer_reset_test.go @@ -0,0 +1,87 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "testing" + "time" + + "github.com/stretchr/testify/require" + "golang.org/x/net/http2" +) + +func TestHTTP2PeerResetSafeClassification(t *testing.T) { + for _, tc := range []struct { + name string + err error + peer bool + reason string + }{ + {"stdlib wrapped", fmt.Errorf("reader: %w", errors.New("stream error: stream ID 123; INTERNAL_ERROR; received from peer")), true, "INTERNAL_ERROR"}, + {"typed", http2.StreamError{StreamID: 999, Code: http2.ErrCodeCancel, Cause: errors.New("received from peer")}, true, "CANCEL"}, + {"unknown reason", errors.New("stream error: stream ID 6; customer-secret; received from peer"), true, ""}, + {"arbitrary http2", errors.New("http2: stream diagnostic customer-secret"), false, ""}, + {"unrelated internal error", errors.New("INTERNAL_ERROR customer-secret"), false, ""}, + {"local cause", http2.StreamError{StreamID: 999, Code: http2.ErrCodeInternal, Cause: errors.New("customer-secret")}, false, ""}, + {"cancel", fmt.Errorf("stream error: stream ID 6; INTERNAL_ERROR; received from peer: %w", context.Canceled), false, ""}, + {"deadline", context.DeadlineExceeded, false, ""}, + {"clean truncation", ErrOpenAIUpstreamStreamTruncated, false, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + _, message := classifyOpenAIUpstreamStreamReadError(tc.err) + require.NotContains(t, message, "customer-secret") + require.NotContains(t, message, "stream ID") + if tc.peer { + require.Contains(t, message, "reset by peer") + require.Contains(t, message, "Do not automatically retry") + if tc.reason != "" { + require.Contains(t, message, tc.reason) + } + } else { + require.NotContains(t, message, "reset by peer") + } + }) + } +} + +func TestHTTP2PeerResetDoesNotTriggerHTTPHealthBreaker(t *testing.T) { + reset := newOpenAIUpstreamStreamReadError(errors.New("stream error: stream ID 3; INTERNAL_ERROR; received from peer")) + status, _, eligible := classifyOpenAIAPIKeyHealthFailure(reset) + require.False(t, eligible) + require.Zero(t, status) + status, _, eligible = classifyOpenAIAPIKeyHealthFailure(&UpstreamFailoverError{StatusCode: http.StatusBadGateway}) + require.True(t, eligible, "genuine HTTP 502 remains eligible") + require.Equal(t, 502, status) +} + +func TestHTTP2PeerResetConcurrencyDoesNotInventCooldown(t *testing.T) { + now := time.Now() + cfg := DefaultOAuthAutoConfig() + cfg.Revision = "synthetic" + cfg.SuccessesPerStep = 4 + cfg.MaxConcurrency = 10 + cfg.UpgradeStep = 1 + cfg.CooldownSeconds = 60 + state := AutoConfigConcurrencyState{Revision: cfg.Revision, Concurrency: 2, Successes: 3} + var event AccountConcurrencyResult + require.NoError(t, json.Unmarshal([]byte(`{"AccountID":7,"Success":false,"FailureCategory":"transport_error"}`), &event)) + next, concurrency := AdvanceConcurrency(state, 2, cfg, event, now) + require.Zero(t, next.Successes, "transport interruption must not count as success") + require.Equal(t, 2, concurrency) + require.True(t, next.PausedUntil.IsZero(), "transport reset does not prove an account capacity cooldown") +} + +func TestHTTP2PeerResetUserDetailsDiscardArbitraryDiagnostics(t *testing.T) { + status := 502 + detail := ToUserErrorRequestDetail(&OpsErrorLogDetail{OpsErrorLog: OpsErrorLog{Type: "transport_error", Phase: "network", StatusCode: 200, Message: "stream ID 123 customer-secret"}, UpstreamStatusCode: &status, ErrorBody: `{"error":{"reset_reason":"customer-secret","cause":"private","headers":{"Authorization":"secret"}}}`}) + data, err := json.Marshal(detail) + require.NoError(t, err) + require.Nil(t, detail.UpstreamStatusCode) + require.Contains(t, string(data), "transport_error") + for _, forbidden := range []string{"stream ID", "customer-secret", "Authorization", "private", "502"} { + require.NotContains(t, string(data), forbidden) + } +} diff --git a/frontend/src/components/user/UserErrorDetailModal.vue b/frontend/src/components/user/UserErrorDetailModal.vue index 1aba399372d9..f84657f0d51b 100644 --- a/frontend/src/components/user/UserErrorDetailModal.vue +++ b/frontend/src/components/user/UserErrorDetailModal.vue @@ -58,7 +58,7 @@
{{ t('usage.errors.message') }} -

{{ detail.message }}

+

{{ userErrorMessage(detail, t) }}

@@ -77,6 +77,7 @@ import BaseDialog from '@/components/common/BaseDialog.vue' import { getMyErrorDetail } from '@/api/usage' import { formatDateTime } from '@/utils/format' import type { UserErrorRequestDetail } from '@/types' +import { userErrorMessage } from '@/utils/userErrorMessage' const props = defineProps<{ show: boolean diff --git a/frontend/src/components/user/UserErrorRequestsTable.vue b/frontend/src/components/user/UserErrorRequestsTable.vue index 2465fe2f6668..97338bc68b90 100644 --- a/frontend/src/components/user/UserErrorRequestsTable.vue +++ b/frontend/src/components/user/UserErrorRequestsTable.vue @@ -52,8 +52,8 @@ {{ row.message }} + :title="userErrorMessage(row, t)" + >{{ userErrorMessage(row, t) }} - @@ -121,6 +121,7 @@ ') + } else if (request.url === '/favicon.ico') { response.statusCode = 204; response.end() } else next() + }) + } }, vue()], + server: { host: '127.0.0.1', port: 4298, strictPort: true }, + optimizeDeps: { entries: [], include: ['vue', 'pinia', 'vue-i18n', 'vue-router', 'axios', '@vue/test-utils', 'chart.js', 'marked', 'dompurify'] } + }) + await server.listen() + browser = await chromium.launch({ headless: true }) + const page = await browser.newPage({ viewport: { width: 1440, height: 1050 }, timezoneId: 'UTC' }) + page.on('pageerror', error => errors.push(error.message)) + page.on('console', message => { if (message.type() === 'error') errors.push(message.text()) }) + await page.route('**/*', route => { + if (new URL(route.request().url()).origin === origin) return route.continue() + errors.push('Unexpected external request'); return route.abort() + }) + for (const state of ['before', 'after']) { + before = state === 'before' + server.moduleGraph.invalidateAll() + for (const locale of ['en', 'zh']) { + await page.goto(origin + '/?locale=' + locale, { waitUntil: 'networkidle' }) + await page.getByRole('button', { name: locale === 'en' ? 'Error Requests' : '错误请求', exact: true }).click() + const categoryLabel = locale === 'en' ? 'Category' : '分类' + const statusLabel = locale === 'en' ? 'Status' : '状态码' + const control = label => page.locator('.input-label').filter({ hasText: new RegExp('^' + label + '$') }).locator('..').getByRole('button').first() + await control(categoryLabel).click() + await page.getByRole('option', { name: locale === 'en' ? 'Transport error' : '传输错误', exact: true }).click() + await page.getByText('example-reset-model', { exact: true }).waitFor() + await control(statusLabel).click() + const optionLabel = locale === 'en' ? '200 — Stream failed after headers' : '200 — 响应头发送后流失败' + const http200 = page.getByRole('option', { name: optionLabel, exact: true }) + if (before) { + if (await http200.count()) throw Error('Baseline unexpectedly offers HTTP200') + } else { + await http200.waitFor() + } + const dropdownName = `${state}-status-options-${locale}.png` + await page.screenshot({ path: join(output, dropdownName), fullPage: true }) + captures.push({ name: dropdownName, componentSha: before ? baseline : sha, locale }) + if (before) { + await page.getByRole('listbox').press('Escape') + } else { + await http200.click() + await page.waitForFunction(() => window.filterRequests.some(r => r.url === '/usage/errors' && r.params.category === 'transport_error' && r.params.status_code === 200)) + await page.getByText('example-reset-model', { exact: true }).waitFor() + if (await page.getByText('example-http-model', { exact: true }).count()) throw Error('Filtered HTTP200 result includes HTTP502 fixture') + const selectedName = `after-filtered-${locale}.png` + await page.screenshot({ path: join(output, selectedName), fullPage: true }) + captures.push({ name: selectedName, componentSha: sha, locale }) + await control(statusLabel).click() + await page.getByRole('option', { name: '502', exact: true }).click() + await page.waitForFunction(() => window.filterRequests.some(r => r.url === '/usage/errors' && r.params.category === 'transport_error' && r.params.status_code === 502)) + } + const observed = await page.evaluate(() => window.filterRequests) + if (observed.some(r => r.url === '/usage' && (r.params.status_code !== undefined || r.params.category !== undefined))) throw Error('Error filters leaked into normal usage requests') + requests.push({ state, locale, observed }) + } + } + writeFileSync(join(output, 'manifest.json'), JSON.stringify({ sha, baseline, captures, requests, errors, + boundary: 'Real user UsageView, Select, error table, API modules, Axios parameter construction and CSS; synthetic API responses; unrelated layout/charts stubbed. Baseline UsageView cannot choose200; candidate chooses transport+200 and submits both filters. No production traffic.' }, null, 2)) + if (errors.length) throw Error(errors.join('\n')) + console.log('PASS real UsageView transport+HTTP200 filtering and API arguments at ' + sha) +} finally { + await browser?.close(); await server?.close() + rmSync(entry, { force: true }); rmSync(scratch, { recursive: true, force: true }) +} diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml index b1e20368feb8..381b70f5e26f 100644 --- a/.github/workflows/http2-stream-reset.yml +++ b/.github/workflows/http2-stream-reset.yml @@ -24,6 +24,31 @@ jobs: with: go-version-file: backend/go.mod cache-dependency-path: backend/go.sum + - name: F1 behavioral RED through the real AIOps evidence query + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + mkdir -p "$RUNNER_TEMP/http2-evidence" + target=backend/internal/repository/ai_ops.go + baseline=3137257829f0cc48466911aa4a249dd03f3c088f + restore_ai_ops() { git show "HEAD:$target" > "$target"; } + trap restore_ai_ops EXIT + git show "$baseline:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" + git rev-parse HEAD "$baseline:$target" > "$RUNNER_TEMP/http2-evidence/f1-red-identity.txt" + set +e + (cd backend && go test -tags=integration ./internal/repository -run '^TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure$' -count=1 -v -timeout=5m) > "$RUNNER_TEMP/http2-evidence/f1-red.log" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http2-evidence/f1-red.log" + test "$result" -eq 1 + if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|race detected|signal: (killed|segmentation)' "$RUNNER_TEMP/http2-evidence/f1-red.log"; then exit 1; fi + grep -q -- '--- FAIL: TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure' "$RUNNER_TEMP/http2-evidence/f1-red.log" + grep -q 'AIOps must count one success plus the committed HTTP200 transport failure' "$RUNNER_TEMP/http2-evidence/f1-red.log" + restore_ai_ops + trap - EXIT + git diff --exit-code - name: RED real HTTP2 boundary against production shell: bash run: | @@ -133,9 +158,13 @@ jobs: run: | set -euo pipefail cd backend - go test -tags=integration ./internal/repository -run 'TestHTTP2PeerResetPersistence|TestGetErrorLogByID_APIKeyPrefixAndUpstreamStatus|TestChannelMonitorV2.*Error' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/http2-evidence/persistence.log" + go test -tags=integration ./internal/repository -run 'TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure|TestHTTP2PeerResetPersistence|TestGetErrorLogByID_APIKeyPrefixAndUpstreamStatus|TestChannelMonitorV2.*Error' -count=1 -v -timeout=10m 2>&1 | tee "$RUNNER_TEMP/http2-evidence/persistence.log" if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|race detected|signal: (killed|segmentation)' "$RUNNER_TEMP/http2-evidence/persistence.log"; then exit 1; fi grep -q -- '--- PASS: TestHTTP2PeerResetPersistence' "$RUNNER_TEMP/http2-evidence/persistence.log" + grep -q -- '--- PASS: TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure' "$RUNNER_TEMP/http2-evidence/persistence.log" + go test -race -tags=integration ./internal/repository -run '^TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure$' -count=1 -v -timeout=5m 2>&1 | tee "$RUNNER_TEMP/http2-evidence/f1-race.log" + if grep -Eiq 'build failed|no tests to run|undefined:|--- SKIP:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|race detected|signal: (killed|segmentation)' "$RUNNER_TEMP/http2-evidence/f1-race.log"; then exit 1; fi + grep -q -- '--- PASS: TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure' "$RUNNER_TEMP/http2-evidence/f1-race.log" git diff --exit-code - uses: actions/upload-artifact@v7 if: always() @@ -161,13 +190,38 @@ jobs: cache: pnpm cache-dependency-path: frontend/pnpm-lock.yaml - run: pnpm --dir frontend install --frozen-lockfile + - name: F2 behavioral RED through the actual UsageView status control + shell: bash + run: | + set -euo pipefail + mkdir -p "$RUNNER_TEMP/http2-ui" + target=frontend/src/views/user/UsageView.vue + baseline=3137257829f0cc48466911aa4a249dd03f3c088f + restore_usage_view() { git show "HEAD:$target" > "$target"; } + trap restore_usage_view EXIT + git show "$baseline:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" + git rev-parse HEAD "$baseline:$target" > "$RUNNER_TEMP/http2-ui/f2-red-identity.txt" + set +e + pnpm --dir frontend exec vitest run src/views/user/__tests__/UsageView.spec.ts > "$RUNNER_TEMP/http2-ui/f2-red.log" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http2-ui/f2-red.log" + test "$result" -eq 1 + if grep -Eiq 'No test files found|no tests|[0-9]+ skipped|Failed to resolve|Unhandled Errors|Unhandled Rejection|SyntaxError|ReferenceError|TypeError|Transform failed|panic|DATA RACE' "$RUNNER_TEMP/http2-ui/f2-red.log"; then exit 1; fi + grep -q 'HTTP200 must be selectable from the real error status control' "$RUNNER_TEMP/http2-ui/f2-red.log" + grep -q '1 failed' "$RUNNER_TEMP/http2-ui/f2-red.log" + restore_usage_view + trap - EXIT + git diff --exit-code - name: Real component regressions and production frontend build shell: bash run: | set -euo pipefail mkdir -p "$RUNNER_TEMP/http2-ui" git rev-parse HEAD > "$RUNNER_TEMP/http2-ui/head.txt" - pnpm --dir frontend exec vitest run src/components/user/__tests__/UserErrorTransport.spec.ts src/components/user/__tests__/UserErrorDetailModal.spec.ts 2>&1 | tee "$RUNNER_TEMP/http2-ui/component.log" + pnpm --dir frontend exec vitest run src/views/user/__tests__/UsageView.spec.ts src/components/user/__tests__/UserErrorTransport.spec.ts src/components/user/__tests__/UserErrorDetailModal.spec.ts 2>&1 | tee "$RUNNER_TEMP/http2-ui/component.log" + if grep -Eiq 'No test files found|Unhandled Errors|Unhandled Rejection|Transform failed|panic|DATA RACE' "$RUNNER_TEMP/http2-ui/component.log"; then exit 1; fi pnpm --dir frontend run build 2>&1 | tee "$RUNNER_TEMP/http2-ui/build.log" - name: Isolated screenshot browser run: | @@ -177,6 +231,10 @@ jobs: env: SUB2API_PLAYWRIGHT_MODULE: ${{ runner.temp }}/http2-browser/node_modules/playwright/index.mjs run: node .github/http2-stream-reset-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/http2-ui" + - name: Actual error-tab category and HTTP200 filter before and after + env: + SUB2API_PLAYWRIGHT_MODULE: ${{ runner.temp }}/http2-browser/node_modules/playwright/index.mjs + run: node .github/http2-user-filter-preview.mjs "$GITHUB_WORKSPACE" "$RUNNER_TEMP/http2-ui/filters" - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/repository/ai_ops.go b/backend/internal/repository/ai_ops.go index 1324e97a4065..d1f4b68e2ba8 100644 --- a/backend/internal/repository/ai_ops.go +++ b/backend/internal/repository/ai_ops.go @@ -200,7 +200,9 @@ func readAIOpsAccounts(ctx context.Context, tx *sql.Tx, ids []int64) (map[int64] // dedup key prevents retries/log duplication becoming fictitious sample size; // recovered failover rows, business rejections, 429/529 and client cancels are // deliberately excluded from automatic fault evidence. -var aiOpsEvidenceSQL = `WITH successes AS ( +// A final failure wins over a conflicting completed usage trace for the same +// request: partial billable output must not add a second, successful sample. +var aiOpsEvidenceSQL = `WITH success_candidates AS ( SELECT u.request_id,u.model,COALESCE(u.reasoning_effort,'') AS effort, t.detail->'protocol_decision'->>'upstream' AS protocol, CASE WHEN u.input_tokens+u.cache_read_tokens<4000 THEN 'small' WHEN u.input_tokens+u.cache_read_tokens<32000 THEN 'medium' ELSE 'large' END AS input_bucket, @@ -222,10 +224,13 @@ var aiOpsEvidenceSQL = `WITH successes AS ( request_id,model FROM ops_error_logs o WHERE account_id=$1 AND created_at>=$2 AND created_at<$3 AND NOT is_count_tokens AND NOT ` + opsBusinessLimitedSQL("o") + ` AND ` + opsEffectiveOwnerSQL("o") + `='provider' AND NOT ` + opsExplicitRequestRejectionSQL("o", "400, 404, 413, 422, 500, 502, 503", append(append([]string{}, service.OpsContextLimitRejectionNeedles...), service.OpsModelCapabilityRejectionNeedles...)) + ` - AND status_code>=400 AND error_type<>'client_canceled' + AND (status_code>=400 OR error_type='transport_error') AND error_type<>'client_canceled' AND COALESCE(NULLIF(upstream_status_code,0),status_code) NOT IN (429,529) - AND (COALESCE(NULLIF(upstream_status_code,0),status_code)>=500 OR error_phase IN ('connect','transport')) + AND (COALESCE(NULLIF(upstream_status_code,0),status_code)>=500 OR error_phase IN ('connect','transport') OR error_type='transport_error') ORDER BY COALESCE(NULLIF(request_id,''),'error:'||id::text),created_at DESC,id DESC +), successes AS ( + SELECT s.* FROM success_candidates s + WHERE NOT EXISTS (SELECT 1 FROM failures f WHERE f.request_id<>'' AND f.request_id=s.request_id) ) SELECT (SELECT COUNT(*) FROM successes),(SELECT COUNT(*) FROM failures), (SELECT COUNT(*) FROM successes WHERE model<>'' AND effort<>'' AND protocol IN ('http','ws')), diff --git a/backend/internal/repository/http2_ai_ops_evidence_integration_test.go b/backend/internal/repository/http2_ai_ops_evidence_integration_test.go new file mode 100644 index 000000000000..e1bf8d1aed61 --- /dev/null +++ b/backend/internal/repository/http2_ai_ops_evidence_integration_test.go @@ -0,0 +1,132 @@ +//go:build integration + +package repository + +import ( + "context" + "database/sql" + "encoding/json" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/google/uuid" + "github.com/stretchr/testify/require" +) + +func TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure(t *testing.T) { + ctx := context.Background() + tx, err := integrationDB.BeginTx(ctx, nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + + // Everything stays in this transaction: no global policy, cohorts or other + // tests' observations are changed by this evidence-reader regression. + suffix := uuid.NewString() + var userID, keyID, accountID, otherAccountID int64 + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO users(email,password_hash) VALUES($1,'synthetic') RETURNING id`, "http2-"+suffix+"@test.invalid").Scan(&userID)) + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO api_keys(user_id,key,name) VALUES($1,$2,'synthetic') RETURNING id`, userID, "http2-"+suffix).Scan(&keyID)) + for _, id := range []*int64{&accountID, &otherAccountID} { + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO accounts(name,platform,type,status,schedulable) VALUES($1,'openai','oauth','active',true) RETURNING id`, "http2-"+uuid.NewString()).Scan(id)) + } + now := time.Now().UTC().Truncate(time.Second) + stamp := now.Add(-time.Minute) + policy := service.DefaultAIOpsPolicy() + policy.ObservationSeconds = 300 + accounts := map[int64]aiOpsAccount{accountID: {quotaKnown: true}} + model := "gpt-5.4" + + addUsage := func(requestID, outcome string) int64 { + t.Helper() + var usageID int64 + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO usage_logs(user_id,api_key_id,account_id,request_id,model,reasoning_effort,input_tokens,output_tokens,stream,created_at) VALUES($1,$2,$3,$4,$5,'high',100,10,true,$6) RETURNING id`, userID, keyID, accountID, requestID, model, stamp).Scan(&usageID)) + trace := map[string]any{ + "version": 1, "started_at": stamp.Add(-time.Second).Format(time.RFC3339Nano), + "outcome": outcome, "status": 200, "body_complete": outcome == "success", + "canceled": false, "truncated": outcome != "success", "client_disconnect": false, + "downstream_error": false, "terminal": "completed", + "protocol_decision": map[string]string{"upstream": "http"}, + } + raw, marshalErr := json.Marshal(trace) + require.NoError(t, marshalErr) + _, insertErr := tx.ExecContext(ctx, `INSERT INTO request_timing_details(usage_log_id,trace_id,created_at,detail) VALUES($1,$2::uuid,$3,$4::jsonb)`, usageID, uuid.NewString(), stamp, string(raw)) + require.NoError(t, insertErr) + return usageID + } + addError := func(requestID, phase, errorType, owner, source string, status int, upstream any, business, countTokens bool, account int64, at time.Time, errorModel string) int64 { + t.Helper() + var id int64 + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO ops_error_logs(account_id,request_id,model,error_phase,error_type,error_owner,error_source,severity,status_code,upstream_status_code,is_business_limited,is_count_tokens,created_at) VALUES($1,$2,$3,$4,$5,$6,$7,'error',$8,$9,$10,$11,$12) RETURNING id`, account, requestID, errorModel, phase, errorType, owner, source, status, upstream, business, countTokens, at).Scan(&id)) + return id + } + capture := func() service.AIOpsEvidenceSnapshot { + t.Helper() + evidence, captureErr := captureAIOpsEvidence(ctx, tx, accountID, policy, now, accounts) + require.NoError(t, captureErr) + return evidence + } + assertResetPopulation := func() { + t.Helper() + evidence := capture() + require.Equal(t, 2, evidence.Samples, "AIOps must count one success plus the committed HTTP200 transport failure") + require.InDelta(t, 0.5, evidence.ErrorRate, 0.000001) + require.True(t, evidence.ModelCoverageComplete, "same known model/effort/protocol cohort must remain complete") + require.Equal(t, model, evidence.Model) + require.Equal(t, "high", evidence.Effort) + require.Equal(t, "http", evidence.Protocol) + } + + addUsage("success-"+suffix, "success") + resetRequestID := "reset-" + suffix + resetID := addError(resetRequestID, "network", "transport_error", "provider", "upstream_transport", 200, nil, false, false, accountID, stamp, model) + assertResetPopulation() + var actualStatus int + var upstreamStatus sql.NullInt64 + require.NoError(t, tx.QueryRowContext(ctx, `SELECT status_code,upstream_status_code FROM ops_error_logs WHERE id=$1`, resetID).Scan(&actualStatus, &upstreamStatus)) + require.Equal(t, 200, actualStatus) + require.False(t, upstreamStatus.Valid, "evidence classification must not fabricate an upstream HTTP502") + + addError(resetRequestID, "network", "transport_error", "provider", "upstream_transport", 200, nil, false, false, accountID, stamp.Add(time.Second), model) + partialUsageID := addUsage(resetRequestID, "failed") // billable partial output is not success + assertResetPopulation() + // Even a conflicting completed usage trace cannot count the same failed + // request again as a successful sample in the error-rate denominator. + _, err = tx.ExecContext(ctx, `UPDATE request_timing_details SET detail=detail||'{"outcome":"success","body_complete":true,"truncated":false}'::jsonb WHERE usage_log_id=$1`, partialUsageID) + require.NoError(t, err) + assertResetPopulation() + + for _, control := range []struct { + name, phase, errorType, owner string + status int + upstream any + business, countTokens bool + }{ + {name: "recovered_failover", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 200, upstream: 502}, + {name: "business", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 503, upstream: 503, business: true}, + {name: "business_transport", phase: "network", errorType: "transport_error", owner: "provider", status: 200, business: true}, + {name: "cancellation", phase: "network", errorType: "client_canceled", owner: "provider", status: 499}, + {name: "rate_limit", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 429, upstream: 429}, + {name: "overload", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 529, upstream: 529}, + {name: "wrapped_rate_limit", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 502, upstream: 429}, + {name: "wrapped_overload", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 502, upstream: 529}, + {name: "count_tokens", phase: "network", errorType: "transport_error", owner: "provider", status: 200, countTokens: true}, + {name: "client_owned", phase: "network", errorType: "transport_error", owner: "client", status: 200}, + } { + t.Logf("excluded control: %s", control.name) + addError(control.name+suffix, control.phase, control.errorType, control.owner, "upstream_transport", control.status, control.upstream, control.business, control.countTokens, accountID, stamp, model) + assertResetPopulation() + } + addError("other-account"+suffix, "network", "transport_error", "provider", "upstream_transport", 200, nil, false, false, otherAccountID, stamp, model) + addError("outside-window"+suffix, "network", "transport_error", "provider", "upstream_transport", 200, nil, false, false, accountID, now.Add(-time.Hour), model) + assertResetPopulation() + + unknownID := addError("unknown-model"+suffix, "network", "transport_error", "provider", "upstream_transport", 200, nil, false, false, accountID, stamp, "unknown-model") + require.False(t, capture().ModelCoverageComplete, "transport inclusion must preserve unknown-model cohort blocking") + _, err = tx.ExecContext(ctx, `DELETE FROM ops_error_logs WHERE id=$1`, unknownID) + require.NoError(t, err) + addError("http503"+suffix, "upstream", "upstream_error", "provider", "upstream_http", 503, 503, false, false, accountID, stamp, model) + evidence := capture() + require.Equal(t, 3, evidence.Samples, "genuine upstream HTTP failures remain eligible alongside transport failures") + require.InDelta(t, 2.0/3.0, evidence.ErrorRate, 0.000001) + require.True(t, evidence.ModelCoverageComplete) +} diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 25012440bdb1..fe3c43bd6a61 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -529,6 +529,7 @@ export default { tabs: { usage: 'Usage', errors: 'Error Requests', ranking: 'User Ranking' }, errors: { peerReset: 'Upstream connection reset by peer ({protocol}). Content may be incomplete. Do not automatically retry the same request.', + http200StreamFailure: '200 — Stream failed after headers', time: 'Time', model: 'Model', endpoint: 'Endpoint', status: 'Status', category: 'Category', platform: 'Platform', message: 'Message', keyName: 'Key Name', keyDeleted: 'Deleted', allKeys: 'All keys', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index 06e26d8160cd..d521c9a16b50 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -534,6 +534,7 @@ export default { tabs: { usage: '用量明细', errors: '错误请求', ranking: '用户排行' }, errors: { peerReset: '上游连接被对端重置({protocol})。内容可能不完整,请勿自动重试同一请求。', + http200StreamFailure: '200 — 响应头发送后流失败', time: '时间', model: '模型', endpoint: '端点', status: '状态码', category: '分类', platform: '平台', message: '错误信息', keyName: 'Key 名称', keyDeleted: '已删除', allKeys: '全部 Key', diff --git a/frontend/src/views/user/UsageView.vue b/frontend/src/views/user/UsageView.vue index c8721482577f..aae460e1e05b 100644 --- a/frontend/src/views/user/UsageView.vue +++ b/frontend/src/views/user/UsageView.vue @@ -320,10 +320,12 @@ const errorCategoryOptions = computed(() => [ ...errorCategoryCodes.map((c) => ({ value: c, label: t('usage.errors.categories.' + c) })), ]) -// 状态码候选用固定常用列表(与管理端 UsageFilters 共用常量),不受当前页数据限制: +// Status is the actual client HTTP boundary, including a failed stream whose +// headers were already committed as 200. Options must not depend on this page. // 后端 status_code 过滤对全量生效,若只列当前页出现过的码,用户就选不到仅在后续页的码。 const errorStatusOptions = computed(() => [ { value: null, label: t('usage.errors.allStatuses') }, + { value: 200, label: t('usage.errors.http200StreamFailure') }, ...COMMON_ERROR_STATUS_CODES.map((c) => ({ value: c, label: String(c) })), ]) diff --git a/frontend/src/views/user/__tests__/UsageView.spec.ts b/frontend/src/views/user/__tests__/UsageView.spec.ts index f7d89245b96a..03d2b22cee51 100644 --- a/frontend/src/views/user/__tests__/UsageView.spec.ts +++ b/frontend/src/views/user/__tests__/UsageView.spec.ts @@ -54,6 +54,10 @@ const messages: Record = { 'admin.usage.allModels': 'All models', 'usage.allApiKeys': 'All API Keys', 'usage.errors.allKeys': 'All API Keys', + 'usage.errors.allStatuses': 'All status codes', + 'usage.errors.allCategories': 'All categories', + 'usage.errors.categories.transport_error': 'Transport error', + 'usage.errors.http200StreamFailure': '200 — Stream failed after headers', 'usage.tabs.usage': 'Usage records', 'usage.tabs.errors': 'Error records', 'usage.apiKeyFilter': 'API Key', @@ -150,13 +154,14 @@ const usageLog = { native_compaction_v2: false, } -function mountUsageView() { +function mountUsageView(realSelect = false) { return mount(UsageView, { + attachTo: realSelect ? document.body : undefined, global: { stubs: { AppLayout: simpleStub, Pagination: true, - Select: true, + Select: !realSelect, DateRangePicker: true, Icon: true, UsageStatsCards: chartStub, @@ -219,6 +224,41 @@ describe('user UsageView', () => { getAvailable.mockResolvedValue([{ id: 1, name: 'default' }]) }) + it('selects HTTP200 transport errors through the actual error-tab controls and submits both API filters', async () => { + const wrapper = mountUsageView(true) + try { + await flushPromises() + await wrapper.findAll('button').find(button => button.text() === 'Error records')!.trigger('click') + await flushPromises() + const selects = wrapper.findAllComponents(Select) + const category = selects.find(select => (select.props('options') as SelectOption[]).some(option => option.value === 'transport_error'))! + await category.get('button').trigger('click') + await flushPromises() + const transport = Array.from(document.querySelectorAll('[role="option"]')).find(option => option.textContent?.trim() === 'Transport error')! + transport.click() + await flushPromises() + + const status = selects.find(select => (select.props('options') as SelectOption[]).some(option => option.value === 502))! + expect(status.props('options'), 'HTTP200 must be selectable from the real error status control').toContainEqual({ value: 200, label: '200 — Stream failed after headers' }) + await status.get('button').trigger('click') + await flushPromises() + const http200 = Array.from(document.querySelectorAll('[role="option"]')).find(option => option.textContent?.trim() === '200 — Stream failed after headers')! + http200.click() + await flushPromises() + expect(listMyErrorRequests).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'transport_error', status_code: 200, page: 1 })) + + await status.get('button').trigger('click') + await flushPromises() + Array.from(document.querySelectorAll('[role="option"]')).find(option => option.textContent?.trim() === '502')!.click() + await flushPromises() + expect(listMyErrorRequests).toHaveBeenLastCalledWith(expect.objectContaining({ category: 'transport_error', status_code: 502 })) + await wrapper.findAll('button').find(button => button.text() === 'Usage records')!.trigger('click') + expect(query.mock.calls.every(([params]) => params.status_code === undefined && params.category === undefined)).toBe(true) + } finally { + wrapper.unmount() + } + }) + it('passes the same own API key choices to traffic and usage details', async () => { const wrapper = mountUsageView(); await flushPromises() const usageOptions = wrapper.findAllComponents(Select).find(select => From a724804a36259b80cf5b8fbc43803e18bfc07ea1 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 22:33:10 +0800 Subject: [PATCH 15/38] test: retain AIOps query mocks across success cohort filtering --- backend/internal/repository/ai_ops_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/internal/repository/ai_ops_test.go b/backend/internal/repository/ai_ops_test.go index 484730df4481..1642c0e6244e 100644 --- a/backend/internal/repository/ai_ops_test.go +++ b/backend/internal/repository/ai_ops_test.go @@ -85,7 +85,7 @@ func TestAIOpsApplyAccountAuditAndOutboxAreAtomic(t *testing.T) { m.ExpectQuery("SELECT revision,config FROM ai_ops_policy").WillReturnRows(sqlmock.NewRows([]string{"revision", "config"}).AddRow(p.Revision, aiOpsJSON(p))) m.ExpectQuery("SELECT EXISTS.*serverless_routing_v1").WillReturnRows(sqlmock.NewRows([]string{"unsupported"}).AddRow(false)) m.ExpectQuery("SELECT a.id,a.ai_ops_revision").WithArgs("{11,12}").WillReturnRows(aiOpsAccountRows()) - m.ExpectQuery("WITH successes").WillReturnRows(sqlmock.NewRows([]string{"successes", "failures", "known", "cohorts", "unknown_failures", "model", "effort", "protocol", "input_bucket", "cache_bucket", "output_bucket"}).AddRow(30, 0, 30, 1, 0, "gpt-test", "high", "http", "small", "uncached", "small")) + m.ExpectQuery("WITH success").WillReturnRows(sqlmock.NewRows([]string{"successes", "failures", "known", "cohorts", "unknown_failures", "model", "effort", "protocol", "input_bucket", "cache_bucket", "output_bucket"}).AddRow(30, 0, 30, 1, 0, "gpt-test", "high", "http", "small", "uncached", "small")) for i := 0; i < 2; i++ { m.ExpectQuery("SELECT platform,type").WillReturnRows(sqlmock.NewRows([]string{"platform", "type", "credentials", "extra"}).AddRow("openai", "oauth", `{"model_mapping":{"gpt-test":"gpt-test"}}`, `{}`)) m.ExpectQuery("SELECT COALESCE.*allowed_models").WillReturnRows(sqlmock.NewRows([]string{"models", "group_models"}).AddRow(`[]`, `{}`)) @@ -165,7 +165,7 @@ func TestAIOpsEvidenceForEmptyTargetDoesNotPoisonLaterTargets(t *testing.T) { require.NoError(t, err) accounts := map[int64]aiOpsAccount{11: {id: 11, concurrency: 20, healthy: true, quotaKnown: true}, 12: {id: 12, concurrency: 20, healthy: true, quotaKnown: true}} original := map[int64]aiOpsAccount{11: accounts[11], 12: accounts[12]} - m.ExpectQuery("WITH successes").WillReturnRows(sqlmock.NewRows([]string{"successes", "failures", "known", "cohorts", "unknown_failures", "model", "effort", "protocol", "input_bucket", "cache_bucket", "output_bucket"}).AddRow(0, 0, 0, 0, 0, nil, nil, nil, nil, nil, nil)) + m.ExpectQuery("WITH success").WillReturnRows(sqlmock.NewRows([]string{"successes", "failures", "known", "cohorts", "unknown_failures", "model", "effort", "protocol", "input_bucket", "cache_bucket", "output_bucket"}).AddRow(0, 0, 0, 0, 0, nil, nil, nil, nil, nil, nil)) e, err := captureAIOpsEvidence(context.Background(), tx, 11, aiOpsTestPolicy(), time.Now(), accounts) require.NoError(t, err) require.False(t, e.ModelCoverageComplete) @@ -188,7 +188,7 @@ func TestAIOpsInversePauseRollbackKeepsRecoverableOwner(t *testing.T) { m.ExpectQuery("SELECT data FROM ai_ops_actions WHERE id").WillReturnRows(sqlmock.NewRows([]string{"data"}).AddRow(aiOpsJSON(a))) m.ExpectQuery("SELECT revision,config FROM ai_ops_policy").WillReturnRows(sqlmock.NewRows([]string{"revision", "config"}).AddRow(p.Revision, aiOpsJSON(p))) m.ExpectQuery("SELECT a.id,a.ai_ops_revision").WillReturnRows(sqlmock.NewRows([]string{"id", "revision", "concurrency", "load_factor", "healthy", "managed", "paused", "control_revision", "owner", "groups", "fingerprint", "quota"}).AddRow(11, 5, 20, 10, true, false, false, 2, a.ID, "{7}", "a", true).AddRow(12, 6, 20, 10, true, false, false, 0, "", "{7}", "b", true)) - m.ExpectQuery("WITH successes").WillReturnRows(sqlmock.NewRows([]string{"successes", "failures", "known", "cohorts", "unknown_failures", "model", "effort", "protocol", "input_bucket", "cache_bucket", "output_bucket"}).AddRow(30, 0, 30, 1, 0, "gpt-test", "high", "http", "small", "uncached", "small")) + m.ExpectQuery("WITH success").WillReturnRows(sqlmock.NewRows([]string{"successes", "failures", "known", "cohorts", "unknown_failures", "model", "effort", "protocol", "input_bucket", "cache_bucket", "output_bucket"}).AddRow(30, 0, 30, 1, 0, "gpt-test", "high", "http", "small", "uncached", "small")) for i := 0; i < 2; i++ { m.ExpectQuery("SELECT platform,type").WillReturnRows(sqlmock.NewRows([]string{"platform", "type", "credentials", "extra"}).AddRow("openai", "oauth", `{"model_mapping":{"gpt-test":"gpt-test"}}`, `{}`)) m.ExpectQuery("SELECT COALESCE.*allowed_models").WillReturnRows(sqlmock.NewRows([]string{"models", "group_models"}).AddRow(`[]`, `{}`)) From f177caec5510f502270ff3ceb36fe43295f405f1 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 22:37:50 +0800 Subject: [PATCH 16/38] fix: scope AIOps outcome deduplication to real request identities --- backend/internal/repository/ai_ops.go | 8 +++--- .../http2_ai_ops_evidence_integration_test.go | 26 +++++++++++++++---- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/backend/internal/repository/ai_ops.go b/backend/internal/repository/ai_ops.go index d1f4b68e2ba8..26e521f9d054 100644 --- a/backend/internal/repository/ai_ops.go +++ b/backend/internal/repository/ai_ops.go @@ -203,7 +203,7 @@ func readAIOpsAccounts(ctx context.Context, tx *sql.Tx, ids []int64) (map[int64] // A final failure wins over a conflicting completed usage trace for the same // request: partial billable output must not add a second, successful sample. var aiOpsEvidenceSQL = `WITH success_candidates AS ( - SELECT u.request_id,u.model,COALESCE(u.reasoning_effort,'') AS effort, + SELECT u.request_id,u.api_key_id,u.model,COALESCE(u.reasoning_effort,'') AS effort, t.detail->'protocol_decision'->>'upstream' AS protocol, CASE WHEN u.input_tokens+u.cache_read_tokens<4000 THEN 'small' WHEN u.input_tokens+u.cache_read_tokens<32000 THEN 'medium' ELSE 'large' END AS input_bucket, CASE WHEN u.cache_read_tokens>0 THEN 'cached' ELSE 'uncached' END AS cache_bucket, @@ -221,7 +221,7 @@ var aiOpsEvidenceSQL = `WITH success_candidates AS ( AND COALESCE(u.image_count,0)=0 AND COALESCE(u.image_output_tokens,0)=0 AND COALESCE(u.billing_mode,'token') NOT IN ('image','video') ), failures AS ( SELECT DISTINCT ON (COALESCE(NULLIF(request_id,''),'error:'||id::text)) - request_id,model FROM ops_error_logs o WHERE account_id=$1 AND created_at>=$2 AND created_at<$3 + request_id,client_request_id,api_key_id,model FROM ops_error_logs o WHERE account_id=$1 AND created_at>=$2 AND created_at<$3 AND NOT is_count_tokens AND NOT ` + opsBusinessLimitedSQL("o") + ` AND ` + opsEffectiveOwnerSQL("o") + `='provider' AND NOT ` + opsExplicitRequestRejectionSQL("o", "400, 404, 413, 422, 500, 502, 503", append(append([]string{}, service.OpsContextLimitRejectionNeedles...), service.OpsModelCapabilityRejectionNeedles...)) + ` AND (status_code>=400 OR error_type='transport_error') AND error_type<>'client_canceled' @@ -230,7 +230,9 @@ var aiOpsEvidenceSQL = `WITH success_candidates AS ( ORDER BY COALESCE(NULLIF(request_id,''),'error:'||id::text),created_at DESC,id DESC ), successes AS ( SELECT s.* FROM success_candidates s - WHERE NOT EXISTS (SELECT 1 FROM failures f WHERE f.request_id<>'' AND f.request_id=s.request_id) + WHERE NOT EXISTS (SELECT 1 FROM failures f WHERE f.api_key_id=s.api_key_id AND ( + (f.request_id<>'' AND (f.request_id=s.request_id OR 'local:'||f.request_id=s.request_id)) + OR (f.client_request_id<>'' AND 'client:'||f.client_request_id=s.request_id))) ) SELECT (SELECT COUNT(*) FROM successes),(SELECT COUNT(*) FROM failures), (SELECT COUNT(*) FROM successes WHERE model<>'' AND effort<>'' AND protocol IN ('http','ws')), diff --git a/backend/internal/repository/http2_ai_ops_evidence_integration_test.go b/backend/internal/repository/http2_ai_ops_evidence_integration_test.go index e1bf8d1aed61..ffb57289b189 100644 --- a/backend/internal/repository/http2_ai_ops_evidence_integration_test.go +++ b/backend/internal/repository/http2_ai_ops_evidence_integration_test.go @@ -36,10 +36,10 @@ func TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure(t *testing.T) { accounts := map[int64]aiOpsAccount{accountID: {quotaKnown: true}} model := "gpt-5.4" - addUsage := func(requestID, outcome string) int64 { + addUsage := func(requestID, outcome string, usageKeyID int64) int64 { t.Helper() var usageID int64 - require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO usage_logs(user_id,api_key_id,account_id,request_id,model,reasoning_effort,input_tokens,output_tokens,stream,created_at) VALUES($1,$2,$3,$4,$5,'high',100,10,true,$6) RETURNING id`, userID, keyID, accountID, requestID, model, stamp).Scan(&usageID)) + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO usage_logs(user_id,api_key_id,account_id,request_id,model,reasoning_effort,input_tokens,output_tokens,stream,created_at) VALUES($1,$2,$3,$4,$5,'high',100,10,true,$6) RETURNING id`, userID, usageKeyID, accountID, requestID, model, stamp).Scan(&usageID)) trace := map[string]any{ "version": 1, "started_at": stamp.Add(-time.Second).Format(time.RFC3339Nano), "outcome": outcome, "status": 200, "body_complete": outcome == "success", @@ -56,7 +56,7 @@ func TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure(t *testing.T) { addError := func(requestID, phase, errorType, owner, source string, status int, upstream any, business, countTokens bool, account int64, at time.Time, errorModel string) int64 { t.Helper() var id int64 - require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO ops_error_logs(account_id,request_id,model,error_phase,error_type,error_owner,error_source,severity,status_code,upstream_status_code,is_business_limited,is_count_tokens,created_at) VALUES($1,$2,$3,$4,$5,$6,$7,'error',$8,$9,$10,$11,$12) RETURNING id`, account, requestID, errorModel, phase, errorType, owner, source, status, upstream, business, countTokens, at).Scan(&id)) + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO ops_error_logs(account_id,api_key_id,request_id,client_request_id,model,error_phase,error_type,error_owner,error_source,severity,status_code,upstream_status_code,is_business_limited,is_count_tokens,created_at) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,'error',$10,$11,$12,$13,$14) RETURNING id`, account, keyID, requestID, requestID+"-client", errorModel, phase, errorType, owner, source, status, upstream, business, countTokens, at).Scan(&id)) return id } capture := func() service.AIOpsEvidenceSnapshot { @@ -76,7 +76,7 @@ func TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure(t *testing.T) { require.Equal(t, "http", evidence.Protocol) } - addUsage("success-"+suffix, "success") + addUsage("local:success-"+suffix, "success", keyID) resetRequestID := "reset-" + suffix resetID := addError(resetRequestID, "network", "transport_error", "provider", "upstream_transport", 200, nil, false, false, accountID, stamp, model) assertResetPopulation() @@ -87,13 +87,29 @@ func TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure(t *testing.T) { require.False(t, upstreamStatus.Valid, "evidence classification must not fabricate an upstream HTTP502") addError(resetRequestID, "network", "transport_error", "provider", "upstream_transport", 200, nil, false, false, accountID, stamp.Add(time.Second), model) - partialUsageID := addUsage(resetRequestID, "failed") // billable partial output is not success + partialUsageID := addUsage("client:"+resetRequestID+"-client", "failed", keyID) // billable partial output is not success assertResetPopulation() // Even a conflicting completed usage trace cannot count the same failed // request again as a successful sample in the error-rate denominator. _, err = tx.ExecContext(ctx, `UPDATE request_timing_details SET detail=detail||'{"outcome":"success","body_complete":true,"truncated":false}'::jsonb WHERE usage_log_id=$1`, partialUsageID) require.NoError(t, err) assertResetPopulation() + for _, correlatedID := range []string{"local:" + resetRequestID, resetRequestID} { + _, err = tx.ExecContext(ctx, `UPDATE usage_logs SET request_id=$1 WHERE id=$2`, correlatedID, partialUsageID) + require.NoError(t, err) + assertResetPopulation() + } + _, err = tx.ExecContext(ctx, `SAVEPOINT other_key_control`) + require.NoError(t, err) + var otherKeyID int64 + require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO api_keys(user_id,key,name) VALUES($1,$2,'other synthetic key') RETURNING id`, userID, "other-"+suffix).Scan(&otherKeyID)) + addUsage("client:"+resetRequestID+"-client", "success", otherKeyID) + otherKeyEvidence := capture() + require.Equal(t, 3, otherKeyEvidence.Samples, "another API key's same client request ID must remain a separate success") + require.InDelta(t, 1.0/3.0, otherKeyEvidence.ErrorRate, 0.000001) + _, err = tx.ExecContext(ctx, `ROLLBACK TO SAVEPOINT other_key_control`) + require.NoError(t, err) + assertResetPopulation() for _, control := range []struct { name, phase, errorType, owner string From 839004a25da4c6c47669d02eba56e7ef08c1239e Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 23:40:31 +0800 Subject: [PATCH 17/38] test: reproduce OAuth 429 weekly window veto in remote Actions --- .../scripts/oauth429-weekly-only-evidence.py | 27 +++++ .github/workflows/oauth429-weekly-only.yml | 99 +++++++++++++++++++ .../service/oauth429_weekly_only_test.go | 53 ++++++++++ 3 files changed, 179 insertions(+) create mode 100644 .github/scripts/oauth429-weekly-only-evidence.py create mode 100644 .github/workflows/oauth429-weekly-only.yml create mode 100644 backend/internal/service/oauth429_weekly_only_test.go diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py new file mode 100644 index 000000000000..cd4321953e35 --- /dev/null +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -0,0 +1,27 @@ +"""Validate remote Go test events; never accept compilation failure as RED.""" +import json +from pathlib import Path +import sys + +mode, filename, status = sys.argv[1:] +events = [json.loads(line) for line in Path(filename).read_text().splitlines()] +output = "".join(event.get("Output", "") for event in events) +Path(filename).with_suffix(".log").write_text(output) +print(output) +assert events, "missing test events" +assert not any(event["Action"] == "skip" for event in events), "unexpected skip" +assert not any(text in output for text in ( + "build failed", "setup failed", "no tests to run", "undefined:", "panic:", +)), "infrastructure or compilation failure is not behavioral evidence" +failed = {event.get("Test") for event in events if event["Action"] == "fail"} +passed = {event.get("Test") for event in events if event["Action"] == "pass"} +if mode == "red": + assert int(status) != 0, "baseline unexpectedly passed" + for name in ("primary_weekly_zero_neighbor", "secondary_weekly_invalid_neighbor"): + assert "TestOAuth429WeeklyOnlyService/" + name in failed, name + assert "explicit weekly 99 must disable despite an unrelated neighbor" in output + assert "TestOAuth429WeeklyOnlyService/primary_weekly_five_hour_neighbor" in passed +else: + assert int(status) == 0 and not failed, "candidate failed" + assert "TestOAuth429WeeklyOnlyService" in passed, "missing candidate regression" +print(f"Validated {mode.upper()}: {len(passed)} passed events, {len(failed)} failed events") diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml new file mode 100644 index 000000000000..4d71a38e050d --- /dev/null +++ b/.github/workflows/oauth429-weekly-only.yml @@ -0,0 +1,99 @@ +name: OAuth 429 weekly-only RED GREEN + +on: + pull_request: + branches: [production] + paths: + - 'backend/internal/service/*429*' + - 'backend/internal/repository/oauth429_weekly_only*' + - '.github/workflows/oauth429-weekly-only.yml' + - '.github/scripts/oauth429-weekly-only-*' + +permissions: + contents: read + +env: + CANDIDATE: ${{ github.event.pull_request.head.sha }} + BASELINE: f895ea743f34a4c4ab6c9d01c01e13c931625a6e + +jobs: + red: + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Restore only affected production source in disposable checkout + shell: bash + run: | + set -euo pipefail + mkdir -p evidence + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt + git diff --exit-code + git worktree add --detach "$RUNNER_TEMP/oauth429-red" "$CANDIDATE" + target=backend/internal/service/openai_disable_scheduling_429.go + expected=ab9d5251a4acec7c17b0adb0f21ae59a71f89067 + test "$(git rev-parse "$BASELINE:$target")" = "$expected" + git show "$BASELINE:$target" > "$RUNNER_TEMP/oauth429-red/$target" + actual=$(git hash-object "$RUNNER_TEMP/oauth429-red/$target") + test "$actual" = "$expected" + printf '%s %s %s\n' "$BASELINE" "$actual" "$target" > evidence/restored-blobs.txt + git -C "$RUNNER_TEMP/oauth429-red" diff --stat > evidence/red-diff.txt + git hash-object backend/internal/service/oauth429_weekly_only_test.go > evidence/candidate-test-blob.txt + git hash-object "$RUNNER_TEMP/oauth429-red/backend/internal/service/oauth429_weekly_only_test.go" > evidence/red-test-blob.txt + diff evidence/candidate-test-blob.txt evidence/red-test-blob.txt + - name: Require behavioral RED from unchanged service regressions + shell: bash + run: | + set -euo pipefail + set +e + (cd "$RUNNER_TEMP/oauth429-red/backend" && go test -json -tags=unit ./internal/service -run '^TestOAuth429WeeklyOnly' -count=1 -timeout=10m) > evidence/red.jsonl 2> evidence/red.stderr + result=$? + set -e + printf '%s\n' "$result" > evidence/red-exit.txt + python3 .github/scripts/oauth429-weekly-only-evidence.py red evidence/red.jsonl "$result" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: oauth429-red-${{ github.event.pull_request.head.sha }} + path: evidence/ + if-no-files-found: error + green: + needs: red + 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: Clean candidate GREEN with race detector + shell: bash + run: | + set -euo pipefail + mkdir -p evidence + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt + git diff --exit-code + set +e + (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|TOTPRotationOn429)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr + result=$? + set -e + printf '%s\n' "$result" > evidence/green-exit.txt + python3 .github/scripts/oauth429-weekly-only-evidence.py green evidence/green.jsonl "$result" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: oauth429-green-${{ github.event.pull_request.head.sha }} + path: evidence/ + if-no-files-found: error diff --git a/backend/internal/service/oauth429_weekly_only_test.go b/backend/internal/service/oauth429_weekly_only_test.go new file mode 100644 index 000000000000..5df52ec24f32 --- /dev/null +++ b/backend/internal/service/oauth429_weekly_only_test.go @@ -0,0 +1,53 @@ +//go:build unit + +package service + +import ( + "context" + "net/http" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +type weeklyOnly429Repo struct { + scheduling429Repo + extra map[string]any +} + +func (r *weeklyOnly429Repo) UpdateExtra(_ context.Context, _ int64, extra map[string]any) error { + r.extra = extra + return nil +} + +// Exercise the public error service, its durable scheduling write and the +// existing Codex header parser/persistence path, using fictional observations. +func TestOAuth429WeeklyOnlyService(t *testing.T) { + for _, tc := range []struct { + name, neighbor string + reverse bool + want bool + }{ + {"primary_weekly_zero_neighbor", "0", false, true}, + {"secondary_weekly_invalid_neighbor", "invalid", true, true}, + {"primary_weekly_five_hour_neighbor", "300", false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + account := scheduling429Account() + delete(account.Extra, "codex_7d_used_percent") + headers := weekly429Headers("99", "0", tc.reverse) + neighbor := "secondary" + if tc.reverse { + neighbor = "primary" + } + headers.Set("x-codex-"+neighbor+"-window-minutes", tc.neighbor) + repo := &weeklyOnly429Repo{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.HandleUpstreamError(t.Context(), account, http.StatusTooManyRequests, headers, nil) + require.Equal(t, []int64{account.ID}, repo.ids, "explicit weekly 99 must disable despite an unrelated neighbor") + require.Equal(t, []bool{false}, repo.values) + require.NotEmpty(t, repo.extra, "the existing quota header parser must still persist the response") + }) + } +} From 42de34b7f7e4fedd43b7b5355c506e0b8ba63e4f Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 23:45:04 +0800 Subject: [PATCH 18/38] test: cover weekly evidence boundaries and HTTP WS rotation paths --- .../scripts/oauth429-weekly-only-evidence.py | 7 +- .github/workflows/oauth429-weekly-only.yml | 15 +- .../oauth429_weekly_only_integration_test.go | 67 ++++++ .../oauth429_weekly_only_gateway_test.go | 168 ++++++++++++++ .../service/oauth429_weekly_only_test.go | 212 +++++++++++++++++- 5 files changed, 463 insertions(+), 6 deletions(-) create mode 100644 backend/internal/repository/oauth429_weekly_only_integration_test.go create mode 100644 backend/internal/service/oauth429_weekly_only_gateway_test.go diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index cd4321953e35..eb89fe69a194 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -23,5 +23,10 @@ assert "TestOAuth429WeeklyOnlyService/primary_weekly_five_hour_neighbor" in passed else: assert int(status) == 0 and not failed, "candidate failed" - assert "TestOAuth429WeeklyOnlyService" in passed, "missing candidate regression" + required = ["RotationPreservesScheduling"] if mode == "repository" else [ + "Service", "HeaderBoundaries", "CachedIdentity", "PolicyGates", + "HTTPForward", "WSForward", "CombinedRotation", + ] + for name in required: + assert "TestOAuth429WeeklyOnly" + name in passed, "missing regression: " + name print(f"Validated {mode.upper()}: {len(passed)} passed events, {len(failed)} failed events") diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 4d71a38e050d..12df245daa83 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -86,11 +86,24 @@ jobs: git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt git diff --exit-code set +e - (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|TOTPRotationOn429)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr + (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|Weekly429Threshold|TOTPRotationOn429)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr result=$? set -e printf '%s\n' "$result" > evidence/green-exit.txt python3 .github/scripts/oauth429-weekly-only-evidence.py green evidence/green.jsonl "$result" + - name: Durable scheduling and rotation lifecycle on isolated PostgreSQL + if: success() || failure() + shell: bash + env: + CI: 'true' + run: | + set -euo pipefail + set +e + (cd backend && go test -json -tags=integration ./internal/repository -run '^TestOAuth429WeeklyOnlyRotationPreservesScheduling$' -count=1 -timeout=10m) > evidence/green-repository.jsonl 2> evidence/green-repository.stderr + result=$? + set -e + printf '%s\n' "$result" > evidence/green-repository-exit.txt + python3 .github/scripts/oauth429-weekly-only-evidence.py repository evidence/green-repository.jsonl "$result" - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/repository/oauth429_weekly_only_integration_test.go b/backend/internal/repository/oauth429_weekly_only_integration_test.go new file mode 100644 index 000000000000..72382e72b54a --- /dev/null +++ b/backend/internal/repository/oauth429_weekly_only_integration_test.go @@ -0,0 +1,67 @@ +//go:build integration + +package repository + +import ( + "fmt" + "net/http" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// Real PostgreSQL scheduling writes and the real queued rotation lifecycle. +// Upstream enrollment is fictional: no worker contacts an external service. +func TestOAuth429WeeklyOnlyRotationPreservesScheduling(t *testing.T) { + for _, mode := range []string{"permanent_disable", "manual_disable", "manual_enable"} { + for _, success := range []bool{false, true} { + t.Run(fmt.Sprintf("%s_success_%t", mode, success), func(t *testing.T) { + ctx, rotation, cfg := totpRotationFixture(t) + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + _, err := integrationDB.ExecContext(ctx, `UPDATE accounts SET schedulable=true,extra=$2::jsonb WHERE id=$1`, cfg.AccountID, `{"openai_disable_scheduling_on_429":true,"openai_totp_rotate_on_429":true}`) + require.NoError(t, err) + a, err := accounts.GetByID(ctx, cfg.AccountID) + require.NoError(t, err) + h := http.Header{} + h.Set("x-codex-primary-window-minutes", "10080") + h.Set("x-codex-primary-used-percent", "20") + h.Set("x-codex-secondary-window-minutes", "0") + if mode == "permanent_disable" { + h.Set("x-codex-primary-used-percent", "99") + } + rates := service.NewRateLimitService(accounts, nil, &config.Config{}, nil, nil) + rates.HandleUpstreamError(ctx, a, 429, h, nil) + task, err := rotation.CreateTOTPRotationOn429(ctx, a.ID, "fictional-snapshot", cfg.UpdatedAt) + require.NoError(t, err) + require.NotNil(t, task) + claimed, err := rotation.ClaimTOTPRotation(ctx, "fictional-worker") + require.NoError(t, err) + require.Equal(t, task.TaskID, claimed.TaskID) + want := mode == "manual_enable" + if mode != "permanent_disable" { + // Administrator changes the durable switch after the task was queued. + require.NoError(t, accounts.SetSchedulable(ctx, a.ID, want)) + } + before, err := accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + require.Equal(t, want, before.Schedulable) + if success { + for _, step := range [][3]string{{"running", "enrolling", ""}, {"enrolling", "prepared", "enc:fictional-new"}, {"prepared", "activating", ""}, {"activating", "verifying", ""}} { + require.NoError(t, rotation.TransitionTOTPRotation(ctx, task.TaskID, "fictional-worker", step[0], step[1], step[2])) + } + } + require.NoError(t, rotation.FinishTOTPRotation(ctx, task.TaskID, "fictional-worker", success, "")) + after, err := accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + require.Equal(t, want, after.Schedulable, "rotation completion must preserve the current manual/permanent switch") + _, err = rates.RecoverAccountAfterSuccessfulTest(ctx, a.ID) + require.NoError(t, err) + recovered, err := accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + require.Equal(t, want, recovered.Schedulable, "quota recovery must not reopen permanent/manual disable") + }) + } + } +} diff --git a/backend/internal/service/oauth429_weekly_only_gateway_test.go b/backend/internal/service/oauth429_weekly_only_gateway_test.go new file mode 100644 index 000000000000..33d97750b83c --- /dev/null +++ b/backend/internal/service/oauth429_weekly_only_gateway_test.go @@ -0,0 +1,168 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "github.com/stretchr/testify/require" +) + +func TestOAuth429WeeklyOnlyHTTPForward(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, passthrough := range []bool{false, true} { + name := "native" + if passthrough { + name = "passthrough" + } + t.Run(name, func(t *testing.T) { + for _, tc := range []struct { + name, weekly string + reverse, want bool + }{ + {"primary_zero_neighbor", "99", false, true}, + {"secondary_zero_neighbor", "99", true, true}, + {"weekly_equality", "98", false, false}, + {"5h_only_100", "", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + h := weekly429Headers(tc.weekly, "0", tc.reverse) + short := "secondary" + if tc.reverse { + short = "primary" + } + h.Set("x-codex-"+short+"-window-minutes", "0") + if tc.name == "5h_only_100" { + h = http.Header{} + h.Set("x-codex-primary-window-minutes", "300") + h.Set("x-codex-primary-used-percent", "100") + } + h.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{StatusCode: 429, Header: h, Body: io.NopCloser(strings.NewReader(`{"error":{"type":"usage_limit_reached","message":"fictional quota rejection","resets_in_seconds":7200}}`))}} + repo := &weeklyOnly429Repo{} + cfg := &config.Config{} + rates := NewRateLimitService(repo, nil, cfg, nil, nil) + gateway := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, rateLimitService: rates, cache: &stubGatewayCache{}, toolCorrector: NewCodexToolCorrector()} + rates.SetAccountRuntimeBlocker(gateway) + a := scheduling429Account() + a.Status = StatusActive + a.Concurrency = 1 + a.Credentials = map[string]any{"access_token": "fictional-oauth-token", "chatgpt_account_id": "fictional-owner"} + a.Extra["openai_passthrough"] = passthrough + a.Extra["openai_oauth_responses_websockets_v2_mode"] = OpenAIWSIngressModeOff + delete(a.Extra, "codex_7d_used_percent") + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.1.0") + _, err := gateway.Forward(t.Context(), c, a, []byte(`{"model":"gpt-5.2","stream":true,"input":"fictional test"}`)) + require.Error(t, err) + require.NotNil(t, upstream.lastReq, "must reach the actual HTTP transport boundary") + require.Equal(t, tc.want, len(repo.ids) > 0, "HTTP Forward must use weekly-only permanent scheduling policy") + if tc.want { + require.Equal(t, []bool{false}, repo.values) + } + }) + } + }) + } +} + +type weeklyOnlyWSRepo struct { + openAIWSRateLimitSignalRepo + writes []bool +} + +func (r *weeklyOnlyWSRepo) SetSchedulable(_ context.Context, _ int64, value bool) error { + r.writes = append(r.writes, value) + return nil +} + +// A real loopback upstream handshake/error frame enters via Forward. These are +// gateway entry-point tests, not direct calls to the shared side-effect helper. +func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, tc := range []struct { + name string + frame, cached, want bool + }{ + {"handshake_weekly_zero_neighbor", false, false, true}, + {"frame_with_weekly_handshake", true, false, true}, + {"body_only_no_percentage", true, false, false}, + {"frame_with_explicit_cache", true, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + h := weekly429Headers("99", "0", false) + h.Set("x-codex-secondary-window-minutes", "0") + if tc.name == "body_only_no_percentage" || tc.cached { + h = http.Header{} + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !tc.frame { + for k, v := range h { + w.Header()[k] = v + } + w.WriteHeader(429) + _, _ = w.Write([]byte(`{"error":{"type":"usage_limit_reached","resets_in_seconds":7200}}`)) + return + } + upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} + conn, err := upgrader.Upgrade(w, r, h) + if err != nil { + t.Errorf("upgrade: %v", err) + return + } + defer conn.Close() + var request map[string]any + if err := conn.ReadJSON(&request); err != nil { + t.Errorf("read: %v", err) + return + } + _ = conn.WriteJSON(map[string]any{"type": "error", "error": map[string]any{"type": "usage_limit_reached", "code": "rate_limit_exceeded", "message": "fictional quota rejection", "limit_window_minutes": 10080, "resets_in_seconds": 7200}}) + })) + defer server.Close() + cfg := newOpenAIWSV2TestConfig() + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + a := scheduling429Account() + a.Status = StatusActive + a.Concurrency = 1 + a.Credentials = openAIWSQuotaTestCredentials(AccountTypeOAuth, server.URL) + a.Extra["responses_websockets_v2_enabled"] = true + if tc.cached { + a.Extra["codex_7d_window_minutes"] = 10080 + } else { + delete(a.Extra, "codex_7d_used_percent") + } + repo := &weeklyOnlyWSRepo{} + rates := NewRateLimitService(repo, nil, cfg, nil, nil) + upstream := &httpUpstreamRecorder{} + gateway := &OpenAIGatewayService{accountRepo: repo, rateLimitService: rates, httpUpstream: upstream, cache: &stubGatewayCache{}, cfg: cfg, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector()} + pool := newOpenAIWSConnPool(cfg) + defer pool.Close() + pool.setClientDialerForTest(&openAIWSQuotaLocalDialer{url: "ws" + strings.TrimPrefix(server.URL, "http")}) + gateway.openaiWSPool = pool + rates.SetAccountRuntimeBlocker(gateway) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/openai/v1/responses", nil) + c.Request.Header.Set("User-Agent", "unit-test-agent/1.0") + _, err := gateway.Forward(t.Context(), c, a, []byte(`{"model":"gpt-5.1","stream":false,"input":"fictional test"}`)) + require.Error(t, err) + require.Equal(t, 429, rec.Code) + require.Nil(t, upstream.lastReq, "WS rejection must not fall back to HTTP") + require.Equal(t, tc.want, len(repo.writes) > 0, "WS Forward must use weekly-only permanent scheduling policy") + if tc.want { + require.Equal(t, []bool{false}, repo.writes) + } + }) + } +} diff --git a/backend/internal/service/oauth429_weekly_only_test.go b/backend/internal/service/oauth429_weekly_only_test.go index 5df52ec24f32..100c1555bc4b 100644 --- a/backend/internal/service/oauth429_weekly_only_test.go +++ b/backend/internal/service/oauth429_weekly_only_test.go @@ -4,8 +4,11 @@ package service import ( "context" + "fmt" "net/http" + "strconv" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/stretchr/testify/require" @@ -27,11 +30,10 @@ func TestOAuth429WeeklyOnlyService(t *testing.T) { for _, tc := range []struct { name, neighbor string reverse bool - want bool }{ - {"primary_weekly_zero_neighbor", "0", false, true}, - {"secondary_weekly_invalid_neighbor", "invalid", true, true}, - {"primary_weekly_five_hour_neighbor", "300", false, true}, + {"primary_weekly_zero_neighbor", "0", false}, + {"secondary_weekly_invalid_neighbor", "invalid", true}, + {"primary_weekly_five_hour_neighbor", "300", false}, } { t.Run(tc.name, func(t *testing.T) { account := scheduling429Account() @@ -51,3 +53,205 @@ func TestOAuth429WeeklyOnlyService(t *testing.T) { }) } } + +func TestOAuth429WeeklyOnlyHeaderBoundaries(t *testing.T) { + for _, tc := range []struct { + name string + headers http.Header + want bool + }{ + {"5h_only_100", http.Header{"X-Codex-Primary-Window-Minutes": {"300"}, "X-Codex-Primary-Used-Percent": {"100"}}, false}, + {"weekly_99_5h_0", weekly429Headers("99", "0", false), true}, + {"weekly_0_5h_100", weekly429Headers("0", "100", false), false}, + {"weekly_equal_threshold", weekly429Headers("98", "100", false), false}, + {"unknown_primary_100", http.Header{"X-Codex-Primary-Used-Percent": {"100"}}, false}, + {"unknown_windows", http.Header{"X-Codex-Primary-Window-Minutes": {"60"}, "X-Codex-Primary-Used-Percent": {"100"}}, false}, + {"weekly_missing_usage", weekly429Headers("", "100", false), false}, + {"weekly_invalid_usage", weekly429Headers("invalid", "100", false), false}, + {"weekly_nan", weekly429Headers("NaN", "100", false), false}, + {"weekly_infinity", weekly429Headers("+Inf", "100", false), false}, + {"weekly_negative", weekly429Headers("-1", "100", false), false}, + {"weekly_over_100", weekly429Headers("101", "100", false), false}, + } { + t.Run(tc.name, func(t *testing.T) { assertWeeklyOnly429Write(t, tc.headers, tc.want) }) + } + for _, reverse := range []bool{false, true} { + for _, neighbor := range []string{"0", "-1", "invalid", "", "absent", "300", "60"} { + t.Run(fmt.Sprintf("weekly_reverse_%t_neighbor_%s", reverse, neighbor), func(t *testing.T) { + h := weekly429Headers("99", "100", reverse) + short := "secondary" + if reverse { + short = "primary" + } + if neighbor == "absent" { + for _, field := range []string{"window-minutes", "used-percent", "reset-after-seconds"} { + h.Del("x-codex-" + short + "-" + field) + } + } else { + h.Set("x-codex-"+short+"-window-minutes", neighbor) + h.Set("x-codex-"+short+"-reset-after-seconds", "invalid") + } + assertWeeklyOnly429Write(t, h, true) + }) + } + } + for _, tc := range []struct { + name, key string + values []string + }{ + {"two_weekly_windows", "x-codex-secondary-window-minutes", []string{"10080"}}, + {"duplicate_weekly_window", "x-codex-primary-window-minutes", []string{"10080", "10080"}}, + {"conflicting_weekly_window", "x-codex-primary-window-minutes", []string{"10080", "300"}}, + {"hidden_weekly_neighbor", "x-codex-secondary-window-minutes", []string{"300", "10080"}}, + {"comma_weekly_neighbor", "x-codex-secondary-window-minutes", []string{"300, 10080"}}, + {"duplicate_weekly_usage", "x-codex-primary-used-percent", []string{"99", "99"}}, + {"conflicting_weekly_usage", "x-codex-primary-used-percent", []string{"99", "0"}}, + {"empty_weekly_usage", "x-codex-primary-used-percent", nil}, + {"duplicate_weekly_reset", "x-codex-primary-reset-after-seconds", []string{"7200", "7200"}}, + {"invalid_weekly_reset", "x-codex-primary-reset-after-seconds", []string{"invalid"}}, + {"empty_weekly_reset", "x-codex-primary-reset-after-seconds", nil}, + {"elapsed_weekly_reset", "x-codex-primary-reset-after-seconds", []string{"0"}}, + {"oversized_weekly_reset", "x-codex-primary-reset-after-seconds", []string{"604801"}}, + } { + t.Run(tc.name, func(t *testing.T) { + h := weekly429Headers("99", "0", false) + h[http.CanonicalHeaderKey(tc.key)] = tc.values + assertWeeklyOnly429Write(t, h, false) + }) + } +} + +func assertWeeklyOnly429Write(t *testing.T, headers http.Header, want bool) { + t.Helper() + // A high cached value deliberately challenges the no-fallback boundary. + account := scheduling429Account() + account.Extra["codex_7d_window_minutes"] = 10080 + repo := &weeklyOnly429Repo{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.HandleUpstreamError(t.Context(), account, 429, headers, nil) + if want { + require.Equal(t, []bool{false}, repo.values, "only explicit valid weekly evidence may permanently disable") + } else { + require.Empty(t, repo.ids, "ambiguous, missing or low weekly evidence must not reuse cached high usage") + } +} + +func TestOAuth429WeeklyOnlyCachedIdentity(t *testing.T) { + for _, tc := range []struct { + name string + mutate func(*Account) + want bool + }{ + {"explicit_fresh_weekly", func(*Account) {}, true}, + {"missing_window_identity", func(a *Account) { delete(a.Extra, "codex_7d_window_minutes") }, false}, + {"invalid_window_identity", func(a *Account) { a.Extra["codex_7d_window_minutes"] = "invalid" }, false}, + {"five_hour_identity", func(a *Account) { a.Extra["codex_7d_window_minutes"] = 300 }, false}, + {"stale_observation", func(a *Account) { + a.Extra["codex_usage_updated_at"] = time.Now().Add(-3 * time.Hour).Format(time.RFC3339Nano) + }, false}, + {"future_observation", func(a *Account) { + a.Extra["codex_usage_updated_at"] = time.Now().Add(time.Hour).Format(time.RFC3339Nano) + }, false}, + {"missing_observation", func(a *Account) { delete(a.Extra, "codex_usage_updated_at") }, false}, + {"identity_conflict", func(a *Account) { + a.Credentials = map[string]any{"chatgpt_account_id": "fictional-owner"} + a.Extra["chatgpt_account_id"] = "fictional-other" + }, false}, + {"workspace_conflict", func(a *Account) { + a.Credentials = map[string]any{"workspace_id": "fictional-owner"} + a.Extra["workspace_id"] = "fictional-other" + }, false}, + {"reset_elapsed", func(a *Account) { a.Extra["codex_7d_reset_at"] = time.Now().Add(-time.Minute).Format(time.RFC3339Nano) }, false}, + {"reset_invalid", func(a *Account) { a.Extra["codex_7d_reset_at"] = "invalid" }, false}, + {"reset_future", func(a *Account) { a.Extra["codex_7d_reset_at"] = time.Now().Add(time.Hour).Format(time.RFC3339Nano) }, true}, + {"relative_reset_elapsed", func(a *Account) { a.Extra["codex_7d_reset_after_seconds"] = 1 }, false}, + {"relative_reset_future", func(a *Account) { a.Extra["codex_7d_reset_after_seconds"] = 7200 }, true}, + {"fresh_field_versions", func(a *Account) { + a.Extra[CodexUsageFieldVersionsKey] = weeklyOnlyVersions(time.Now().Add(-time.Minute)) + }, true}, + {"stale_usage_fresh_global", func(a *Account) { + v := weeklyOnlyVersions(time.Now()) + v["codex_7d_used_percent"] = strconv.FormatInt(time.Now().Add(-3*time.Hour).UnixNano(), 10) + a.Extra[CodexUsageFieldVersionsKey] = v + }, false}, + {"stale_window_fresh_usage", func(a *Account) { + v := weeklyOnlyVersions(time.Now()) + v["codex_7d_window_minutes"] = strconv.FormatInt(time.Now().Add(-3*time.Hour).UnixNano(), 10) + a.Extra[CodexUsageFieldVersionsKey] = v + }, false}, + {"unversioned_window", func(a *Account) { + v := weeklyOnlyVersions(time.Now()) + delete(v, "codex_7d_window_minutes") + a.Extra[CodexUsageFieldVersionsKey] = v + }, false}, + {"invalid_versions", func(a *Account) { a.Extra[CodexUsageFieldVersionsKey] = "invalid" }, false}, + {"missing_relative_reset_version", func(a *Account) { + a.Extra[CodexUsageFieldVersionsKey] = weeklyOnlyVersions(time.Now()) + a.Extra["codex_7d_reset_after_seconds"] = 7200 + }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + a := scheduling429Account() + a.Extra["codex_7d_window_minutes"] = 10080 + tc.mutate(a) + r := &weeklyOnly429Repo{} + s := NewRateLimitService(r, nil, &config.Config{}, nil, nil) + s.HandleUpstreamError(t.Context(), a, 429, nil, nil) + require.Equal(t, tc.want, len(r.ids) > 0, "cached weekly identity and original observation must be trustworthy") + }) + } +} + +func weeklyOnlyVersions(observed time.Time) map[string]any { + stamp := strconv.FormatInt(observed.UnixNano(), 10) + return map[string]any{"codex_7d_used_percent": stamp, "codex_7d_window_minutes": stamp} +} + +func TestOAuth429WeeklyOnlyPolicyGates(t *testing.T) { + for _, tc := range []struct { + name string + status int + mutate func(*Account) + want bool + }{ + {"own_lower_threshold", 429, func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 97.5 }, true}, + {"own_equality", 429, func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 99.0 }, false}, + {"own_higher_threshold", 429, func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 100.0 }, false}, + {"invalid_threshold", 429, func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = "invalid" }, false}, + {"disabled_feature", 429, func(a *Account) { a.Extra[OpenAIDisableSchedulingOn429ExtraKey] = false }, false}, + {"not_upstream_429", 503, func(*Account) {}, false}, + {"body_only_weekly_limit", 429, func(a *Account) { delete(a.Extra, "codex_7d_used_percent") }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + a := scheduling429Account() + tc.mutate(a) + h := weekly429Headers("99", "0", false) + if tc.name == "body_only_weekly_limit" { + h = nil + } + r := &weeklyOnly429Repo{} + s := NewRateLimitService(r, nil, &config.Config{}, nil, nil) + s.HandleUpstreamError(t.Context(), a, tc.status, h, []byte(`{"error":{"type":"usage_limit_reached","limit_window_minutes":10080}}`)) + require.Equal(t, tc.want, len(r.ids) > 0) + }) + } +} + +func TestOAuth429WeeklyOnlyCombinedRotation(t *testing.T) { + for _, initial := range []bool{false, true} { + t.Run(fmt.Sprintf("initial_schedulable_%t", initial), func(t *testing.T) { + rotation, rotationRepo, account := newTOTP429TestService(t) + account.Schedulable = initial + account.Extra[OpenAIDisableSchedulingOn429ExtraKey] = true + repo := &weeklyOnly429Repo{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.openAITOTP429Rotator = rotation + h := weekly429Headers("99", "0", false) + h.Set("x-codex-secondary-window-minutes", "0") + rates.HandleUpstreamError(t.Context(), account, 429, h, nil) + require.Equal(t, []bool{false}, repo.values, "both enabled policies must only persist a disable") + require.Equal(t, 1, rotationRepo.calls, "real automatic rotation service must still queue the task") + require.Equal(t, initial, account.Schedulable, "neither policy may rewrite the shared/manual snapshot") + }) + } +} From 229f2d0ed5cea1996c8869a0129586cc6d25615d Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 23:46:12 +0800 Subject: [PATCH 19/38] fix: validate OAuth 429 weekly evidence independently of neighboring windows --- .../service/openai_disable_scheduling_429.go | 61 +++++++++++++------ ...mit_service_disable_scheduling_429_test.go | 2 +- 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index ab9d5251a4ac..b90d1f908b25 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -7,6 +7,7 @@ import ( "math" "net/http" "strconv" + "strings" "time" ) @@ -50,18 +51,29 @@ func openAI429WeeklyHeaderUsage(headers http.Header) (used float64, present, val // assumption. Require exactly one explicitly identified weekly window. prefix := "" for _, window := range []string{"primary", "secondary"} { - if key := "x-codex-" + window + "-window-minutes"; len(headers.Values(key)) > 0 { - minutes, err := strconv.Atoi(headers.Get(key)) - if err != nil || minutes <= 0 { - return 0, true, false - } - if minutes == 7*24*60 { - if prefix != "" { - return 0, true, false + values := headers.Values("x-codex-" + window + "-window-minutes") + claimsWeekly := false + // Inspect every value so a conflicting duplicate cannot hide a weekly + // claim behind Header.Get's first value (including comma-joined fields). + for _, value := range values { + for _, part := range strings.Split(value, ",") { + if minutes, err := strconv.Atoi(strings.TrimSpace(part)); err == nil && minutes == 7*24*60 { + claimsWeekly = true } - prefix = "x-codex-" + window + "-" } } + if !claimsWeekly { + // An unused, malformed or shorter neighbor says nothing about an + // independently identified weekly window. + continue + } + if prefix != "" || len(values) != 1 { + return 0, true, false + } + if minutes, err := strconv.Atoi(values[0]); err != nil || minutes != 7*24*60 { + return 0, true, false + } + prefix = "x-codex-" + window + "-" } if prefix == "" { return 0, true, false @@ -70,11 +82,14 @@ func openAI429WeeklyHeaderUsage(headers http.Header) (used float64, present, val if prefix == "x-codex-secondary-" { weekly = snapshot.SecondaryUsedPercent } - if weekly == nil || !validOpenAI429Percent(*weekly) { + if len(headers.Values(prefix+"used-percent")) != 1 || weekly == nil || !validOpenAI429Percent(*weekly) { return 0, true, false } - if key := prefix + "reset-after-seconds"; len(headers.Values(key)) > 0 { - seconds, err := strconv.ParseInt(headers.Get(key), 10, 64) + if values, exists := headers[http.CanonicalHeaderKey(prefix+"reset-after-seconds")]; exists { + if len(values) != 1 { + return 0, true, false + } + seconds, err := strconv.ParseInt(values[0], 10, 64) if err != nil || seconds <= 0 || seconds > int64((7*24*time.Hour)/time.Second) { return 0, true, false } @@ -90,17 +105,18 @@ func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time) return 0, false } extra := account.Extra - if _, exists := extra["codex_7d_window_minutes"]; exists { - minutes, ok := resolveAccountExtraNumber(extra, "codex_7d_window_minutes") - if !ok || minutes != 7*24*60 { - return 0, false - } + // A normalized legacy primary snapshot may have no window identity. Its + // "7d" field name alone is not evidence for a permanent scheduling change. + minutes, ok := resolveAccountExtraNumber(extra, "codex_7d_window_minutes") + if !ok || minutes != 7*24*60 { + return 0, false } used, ok := resolveAccountExtraNumber(extra, "codex_7d_used_percent") if !ok || !validOpenAI429Percent(used) { return 0, false } observed := codexUpdatesTime(extra) + windowObserved := observed if versions, exists := extra[CodexUsageFieldVersionsKey]; exists { fields, ok := versions.(map[string]any) if !ok { @@ -111,11 +127,18 @@ func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time) return 0, false } observed = time.Unix(0, stamp) + stamp, err = strconv.ParseInt(fmt.Sprint(fields["codex_7d_window_minutes"]), 10, 64) + if err != nil || stamp <= 0 { + return 0, false + } + windowObserved = time.Unix(0, stamp) } // Permanent pauses require a known, recent observation, unlike temporary // scheduling guards that may retain legacy snapshots without timestamps. - if observed.IsZero() || observed.After(now) || now.Sub(observed) >= openAICodexAutoPauseStaleAfter { - return 0, false + for _, observation := range []time.Time{observed, windowObserved} { + if observation.IsZero() || observation.After(now) || now.Sub(observation) >= openAICodexAutoPauseStaleAfter { + return 0, false + } } if raw, exists := extra["codex_7d_reset_at"]; exists { reset, err := parseTime(fmt.Sprint(raw)) diff --git a/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go b/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go index 1aedb049b866..da640678720a 100644 --- a/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go +++ b/backend/internal/service/ratelimit_service_disable_scheduling_429_test.go @@ -40,7 +40,7 @@ func (r *scheduling429Repo) SetSchedulable(ctx context.Context, id int64, enable func scheduling429Account() *Account { return &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Schedulable: true, - Extra: map[string]any{OpenAIDisableSchedulingOn429ExtraKey: true, "codex_7d_used_percent": 99.0, "codex_usage_updated_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339Nano)}} + Extra: map[string]any{OpenAIDisableSchedulingOn429ExtraKey: true, "codex_7d_used_percent": 99.0, "codex_7d_window_minutes": 10080, "codex_usage_updated_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339Nano)}} } func TestRateLimitDisableSchedulingOn429ScopeAndObservation(t *testing.T) { From c545207e3c913a636b75c626c99003269d5c4412 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 23:48:25 +0800 Subject: [PATCH 20/38] test: complete WebSocket ingress evidence and document caller coverage --- .../scripts/oauth429-weekly-only-evidence.py | 2 +- .github/workflows/oauth429-weekly-only.yml | 11 +- .../oauth429_weekly_only_gateway_test.go | 63 +++++++ docs/testing/oauth429-weekly-only.md | 154 ++++++++++++++++++ 4 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 docs/testing/oauth429-weekly-only.md diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index eb89fe69a194..50eada8c0df6 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -25,7 +25,7 @@ assert int(status) == 0 and not failed, "candidate failed" required = ["RotationPreservesScheduling"] if mode == "repository" else [ "Service", "HeaderBoundaries", "CachedIdentity", "PolicyGates", - "HTTPForward", "WSForward", "CombinedRotation", + "HTTPForward", "WSForward", "WSClientIngress", "CombinedRotation", ] for name in required: assert "TestOAuth429WeeklyOnly" + name in passed, "missing regression: " + name diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 12df245daa83..705b33cb886e 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -46,9 +46,14 @@ jobs: test "$actual" = "$expected" printf '%s %s %s\n' "$BASELINE" "$actual" "$target" > evidence/restored-blobs.txt git -C "$RUNNER_TEMP/oauth429-red" diff --stat > evidence/red-diff.txt - git hash-object backend/internal/service/oauth429_weekly_only_test.go > evidence/candidate-test-blob.txt - git hash-object "$RUNNER_TEMP/oauth429-red/backend/internal/service/oauth429_weekly_only_test.go" > evidence/red-test-blob.txt - diff evidence/candidate-test-blob.txt evidence/red-test-blob.txt + git ls-files 'backend/internal/service/*429*test.go' 'backend/internal/repository/oauth429_weekly_only*test.go' > evidence/retained-tests.txt + while IFS= read -r test_file; do + candidate_blob=$(git hash-object "$test_file") + red_blob=$(git hash-object "$RUNNER_TEMP/oauth429-red/$test_file") + test "$candidate_blob" = "$red_blob" + printf '%s %s\n' "$candidate_blob" "$test_file" >> evidence/retained-test-blobs.txt + done < evidence/retained-tests.txt + git -C "$RUNNER_TEMP/oauth429-red" diff --exit-code -- '*_test.go' - name: Require behavioral RED from unchanged service regressions shell: bash run: | diff --git a/backend/internal/service/oauth429_weekly_only_gateway_test.go b/backend/internal/service/oauth429_weekly_only_gateway_test.go index 33d97750b83c..657fa6dc1275 100644 --- a/backend/internal/service/oauth429_weekly_only_gateway_test.go +++ b/backend/internal/service/oauth429_weekly_only_gateway_test.go @@ -9,8 +9,10 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" "github.com/stretchr/testify/require" @@ -166,3 +168,64 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { }) } } + +func TestOAuth429WeeklyOnlyWSClientIngress(t *testing.T) { + gin.SetMode(gin.TestMode) + cfg := newOpenAIWSV2TestConfig() + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + h := weekly429Headers("99", "0", true) + h.Set("x-codex-primary-window-minutes", "0") + capture := &openAIWSCaptureConn{events: [][]byte{[]byte(`{"type":"error","error":{"type":"usage_limit_reached","code":"rate_limit_exceeded","message":"fictional rejection","resets_in_seconds":7200}}`)}} + dialer := &openAIWSCaptureDialer{conn: capture, handshake: h} + pool := newOpenAIWSConnPool(cfg) + defer pool.Close() + pool.setClientDialerForTest(dialer) + a := scheduling429Account() + a.Status = StatusActive + a.Concurrency = 1 + a.Credentials = openAIWSQuotaTestCredentials(AccountTypeOAuth, "") + a.Extra["responses_websockets_v2_enabled"] = true + delete(a.Extra, "codex_7d_used_percent") + repo := &weeklyOnlyWSRepo{} + rates := NewRateLimitService(repo, nil, cfg, nil, nil) + gateway := &OpenAIGatewayService{accountRepo: repo, rateLimitService: rates, httpUpstream: &httpUpstreamRecorder{}, cache: &stubGatewayCache{}, cfg: cfg, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector(), openaiWSPool: pool} + rates.SetAccountRuntimeBlocker(gateway) + done := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + done <- err + return + } + defer conn.CloseNow() + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + _, first, err := conn.Read(ctx) + if err != nil { + done <- err + return + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r.Clone(ctx) + c.Request.Header.Set("User-Agent", "unit-test-agent/1.0") + done <- gateway.ProxyResponsesWebSocketFromClient(ctx, c, conn, a, "fictional-token", first, nil) + })) + defer server.Close() + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) + require.NoError(t, err) + defer client.CloseNow() + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-5.1","stream":false}`))) + select { + case err := <-done: + var failover *UpstreamFailoverError + require.ErrorAs(t, err, &failover) + require.Equal(t, 429, failover.StatusCode) + require.Positive(t, dialer.DialCount(), "client ingress must reach the upstream adapter") + require.Equal(t, []bool{false}, repo.writes, "client WebSocket ingress must preserve explicit secondary weekly evidence") + case <-ctx.Done(): + t.Fatal("client ingress did not finish") + } +} diff --git a/docs/testing/oauth429-weekly-only.md b/docs/testing/oauth429-weekly-only.md new file mode 100644 index 000000000000..31b9c7f01e86 --- /dev/null +++ b/docs/testing/oauth429-weekly-only.md @@ -0,0 +1,154 @@ +# OAuth 429 weekly-only permanent disable + +Baseline: `f895ea743f34a4c4ab6c9d01c01e13c931625a6e`. +Only production change: `backend/internal/service/openai_disable_scheduling_429.go`. +All public fixtures are fictional. Local work is static only; dynamic evidence is +produced by `.github/workflows/oauth429-weekly-only.yml` on GitHub Actions. + +An opted-in OAuth owner is permanently disabled only on an actual upstream 429 +when valid explicitly identified 10080-minute usage is strictly above its own +threshold (default 98). Primary and secondary are judged independently. A 5h, +zero, absent or malformed unrelated neighbor cannot veto valid weekly evidence. +Two weekly windows, duplicate weekly fields, invalid weekly usage/reset, and +unidentified quota observations fail closed without reusing cached high usage. +The percentage is not inferred from a body `usage_limit_reached` or +`limit_window_minutes` field. No maximum across percentages is selected. + +When there are no current quota observation headers, cache fallback requires +`codex_7d_window_minutes=10080` and retains account identity, percentage, +observation, per-field provenance, staleness and reset checks. If field versions +exist, both usage and window identity must have valid fresh versions. Legacy +snapshots without an explicit window no longer authorize a permanent disable. +Current unclassified/short-only quota headers continue to block cache fallback. + +## Execution coverage + +| Test | Boundary exercised | +| --- | --- | +| `TestOAuth429WeeklyOnlyService` | Public RateLimitService → actual policy → spy durable write + existing quota header parser/persistence | +| `TestOAuth429WeeklyOnlyHeaderBoundaries` | Both weekly positions; zero/invalid/absent/5h neighbors; 5h-only 100; missing/low/invalid weekly; duplicates and conflicts; no reuse of high cache | +| `TestOAuth429WeeklyOnlyCachedIdentity` | Explicit identity; global/field freshness; identity mismatch; future/stale/missing versions; absolute/relative resets | +| `TestOAuth429WeeklyOnlyPolicyGates` | Own threshold, strict equality, invalid threshold, opt-out, non429, body-only weekly classification | +| `TestOAuth429WeeklyOnlyHTTPForward` | Actual `Forward` entry, native and OAuth passthrough HTTP paths, mocked transport response, primary/secondary weekly zero-neighbor and negative cases | +| `TestOAuth429WeeklyOnlyWSForward` | Actual `Forward` entry, real loopback WS upstream handshake 429 and error frames, handshake quota and explicit-cache/body-only controls | +| `TestOAuth429WeeklyOnlyWSClientIngress` | Real loopback client socket → `ProxyResponsesWebSocketFromClient` ctx_pool path → upstream adapter fixture → secondary weekly error frame | +| `TestOAuth429WeeklyOnlyCombinedRotation` | Actual RateLimitService and auto2FA service together, real queue method with spy storage, manual snapshot untouched | +| `TestOAuth429WeeklyOnlyRotationPreservesScheduling` | Isolated PostgreSQL: actual permanent scheduling write, real automatic rotation repository lifecycle success/failure, manual enable/disable after queueing, successful-test recovery | +| Existing scheduling/weekly/managed-owner/TOTP tests selected by workflow | Owner projection fences, per-account opt-in, persistence errors, deduplication, cancellation independence, retry blocking and independent rotation | + +These are isolated regression tests, not live production acceptance. The HTTP +transport is mocked, the WS loopback upstream and credentials are fictional, and +no paid calls or production writes occur. The repository lifecycle uses fictional +worker transitions; no real 2FA enrollment runs. The combined service and durable +repository tests are separate boundaries, not a claimed end-to-end worker test. + +## Caller coverage limits + +The three direct entrances to the permanent policy are the common +`handleUpstreamErrorAfterStreakReset`, gateway +`handleOpenAIAccountUpstreamError`, and BPS `coolDownExcelBPS`. The gateway shares +its observation context with the common handler, avoiding duplicate permanent +writes. Native HTTP/passthrough and WS Forward/client ctx_pool have entry-point +execution above. Existing image/BPS/managed/SIWC tests call shared handlers; they +are not full image/BPS transport acceptance. WS passthrough and HTTP bridge, +images, embeddings, count tokens, model listing, alpha search, chat/messages +compatibility and BPS repair variants are statically mapped below, not all +individually executed by this focused suite. + +Generic provider callers below also reach the common service; non-OpenAI or +non-OAuth owners remain excluded by the existing policy. Account connection-test +`reconcileOpenAI429State` (account_test_service.go) is a separate temporary-state +reconciliation path and does not call this permanent policy. This repair does +not extend permanent-disable behavior into that path. + +The inventory lists direct production calls to policy/shared error handlers and +HTTP/WS wrapper entry calls. It is a static inventory, not a runtime coverage +report. Line numbers refer to this change's source tree. + +| Source | Enclosing caller | Callee | +| --- | --- | --- | +| `antigravity_gateway_retry.go:1279` | `handleUpstreamError` | `HandleUpstreamError` | +| `gateway_anthropic_passthrough.go:228` | `forwardAnthropicAPIKeyPassthroughWithInput` | `handleFailoverSideEffects` | +| `gateway_anthropic_passthrough.go:255` | `forwardAnthropicAPIKeyPassthroughWithInput` | `handleErrorResponse` | +| `gateway_anthropic_passthrough.go:869` | `invalidNonStreamingJSONFailoverError` | `HandleUpstreamError` | +| `gateway_anthropic_passthrough.go:871` | `invalidNonStreamingJSONFailoverError` | `HandleUpstreamError` | +| `gateway_bedrock.go:316` | `handleBedrockUpstreamErrors` | `handleFailoverSideEffects` | +| `gateway_bedrock.go:335` | `handleBedrockUpstreamErrors` | `handleErrorResponse` | +| `gateway_count_tokens.go:228` | `ForwardCountTokens` | `HandleUpstreamError` | +| `gateway_count_tokens.go:332` | `forwardCountTokensAnthropicAPIKeyPassthrough` | `HandleUpstreamError` | +| `gateway_forward.go:739` | `Forward` | `handleFailoverSideEffects` | +| `gateway_forward.go:768` | `Forward` | `handleErrorResponse` | +| `gateway_forward.go:806` | `Forward` | `handleFailoverSideEffects` | +| `gateway_forward.go:810` | `Forward` | `handleErrorResponse` | +| `gateway_forward.go:1046` | `sseStreamErrorEventFailover` | `handleFailoverSideEffects` | +| `gateway_forward_as_chat_completions.go:168` | `ForwardAsChatCompletions` | `HandleUpstreamError` | +| `gateway_forward_as_responses.go:179` | `ForwardAsResponses` | `HandleUpstreamError` | +| `gateway_systemone.go:149` | `handleSystemOneErrorResponse` | `HandleUpstreamError` | +| `gateway_upstream_response.go:474` | `handleErrorResponse` | `HandleUpstreamError` | +| `gateway_upstream_response.go:476` | `handleErrorResponse` | `HandleUpstreamError` | +| `gateway_upstream_response.go:590` | `handleRetryExhaustedSideEffects` | `HandleUpstreamError` | +| `gateway_upstream_response.go:592` | `handleRetryExhaustedSideEffects` | `HandleUpstreamError` | +| `gateway_upstream_response.go:604` | `handleFailoverSideEffects` | `HandleUpstreamError` | +| `gateway_upstream_response.go:607` | `handleFailoverSideEffects` | `HandleUpstreamError` | +| `gemini_messages_compat_service.go:3183` | `handleGeminiUpstreamError` | `HandleUpstreamError` | +| `openai_account_runtime_block_fastpath.go:98` | `handleOpenAIAccountUpstreamError` | `maybeDisableOpenAISchedulingOn429` | +| `openai_account_runtime_block_fastpath.go:233` | `handleOpenAIAccountUpstreamError` | `handleUpstreamErrorAfterStreakReset` | +| `openai_alpha_search.go:104` | `ForwardAlphaSearch` | `handleFailoverSideEffects` | +| `openai_alpha_search.go:183` | `forwardAlphaSearchViaResponsesWebSearch` | `handleFailoverSideEffects` | +| `openai_codex_models_service.go:1921` | `handleCodexModelsManifestAccountAuthError` | `handleOpenAIAccountUpstreamError` | +| `openai_embeddings.go:160` | `ForwardEmbeddings` | `handleOpenAIAccountUpstreamError` | +| `openai_excel_bps.go:36` | `handleExcelBPSUnauthorized` | `handleOpenAIAccountUpstreamError` | +| `openai_excel_bps.go:71` | `handleExcelBPSUnauthorized` | `HandleUpstreamError` | +| `openai_excel_bps.go:283` | `forwardExcelBPS` | `coolDownExcelBPS` | +| `openai_excel_bps.go:668` | `forwardExcelBPS` | `handleOpenAIAccountUpstreamError` | +| `openai_excel_bps.go:775` | `forwardExcelBPS` | `coolDownExcelBPS` | +| `openai_excel_bps.go:819` | `forwardExcelBPS` | `coolDownExcelBPS` | +| `openai_excel_bps.go:924` | `forwardExcelBPS` | `coolDownExcelBPS` | +| `openai_excel_bps_images.go:304` | `forwardExcelBPSImages` | `coolDownExcelBPS` | +| `openai_excel_bps_ratelimit.go:59` | `coolDownExcelBPS` | `maybeDisableOpenAISchedulingOn429` | +| `openai_excel_bps_ratelimit.go:62` | `coolDownExcelBPS` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_cc_pipeline.go:141` | `failoverOpenAIUpstreamHTTPError` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_chat_completions.go:708` | `handleChatCompletionsErrorResponse` | `handleCompatErrorResponse` | +| `openai_gateway_count_tokens.go:107` | `ForwardResponsesInputTokens` | `HandleUpstreamError` | +| `openai_gateway_count_tokens.go:352` | `ForwardCountTokensAsAnthropic` | `HandleUpstreamError` | +| `openai_gateway_forward.go:1488` | `Forward` | `handleErrorResponse` | +| `openai_gateway_forward.go:1499` | `Forward` | `handleErrorResponse` | +| `openai_gateway_forward.go:1550` | `Forward` | `handleFailoverSideEffects` | +| `openai_gateway_forward.go:1561` | `Forward` | `handleErrorResponse` | +| `openai_gateway_forward.go:1660` | `Forward` | `handleFailoverSideEffects` | +| `openai_gateway_forward.go:1666` | `Forward` | `handleErrorResponse` | +| `openai_gateway_grok.go:207` | `forwardGrokResponses` | `handleErrorResponse` | +| `openai_gateway_messages.go:641` | `handleAnthropicErrorResponse` | `handleCompatErrorResponse` | +| `openai_gateway_passthrough.go:1024` | `handleFailoverErrorResponsePassthrough` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_passthrough.go:1097` | `handleErrorResponsePassthrough` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_passthrough.go:1883` | `handleOpenAIStreamTerminalAccountSideEffects` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_responses_chat_fallback.go:179` | `forwardResponsesViaRawChatCompletions` | `handleErrorResponse` | +| `openai_gateway_upstream_errors.go:597` | `handleFailoverSideEffects` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_upstream_errors.go:599` | `handleFailoverSideEffects` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_upstream_errors.go:713` | `handleErrorResponse` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_upstream_errors.go:784` | `handleErrorResponse` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_upstream_errors.go:999` | `handleCompatErrorResponse` | `handleOpenAIAccountUpstreamError` | +| `openai_images.go:798` | `forwardOpenAIImagesAPIKey` | `handleFailoverSideEffects` | +| `openai_images_responses.go:993` | `handleOpenAIImagesErrorResponse` | `handleOpenAIAccountUpstreamError` | +| `openai_images_responses.go:1936` | `forwardOpenAIImagesOAuth` | `handleFailoverSideEffects` | +| `openai_images_responses.go:2125` | `handleOpenAIImagesOAuthResponseError` | `handleOpenAIAccountUpstreamError` | +| `openai_images_responses.go:2198` | `handleOpenAIImagesOAuthResponseError` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_ingress.go:1749` | `ProxyResponsesWebSocketFromClient` | `handleOpenAIWSDialTransientFailure` | +| `openai_ws_forwarder_ingress.go:1992` | `ProxyResponsesWebSocketFromClient` | `handleOpenAIWSErrorEventTransientFailure` | +| `openai_ws_forwarder_ingress.go:2160` | `ProxyResponsesWebSocketFromClient` | `handleOpenAIWSTerminalTransientFailure` | +| `openai_ws_forwarder_support.go:325` | `handleOpenAIWSTerminalTransientFailure` | `handleOpenAIWSFailureAccountSideEffects` | +| `openai_ws_forwarder_support.go:340` | `handleOpenAIWSErrorEventTransientFailure` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:367` | `handleOpenAIWSFailureAccountSideEffects` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:379` | `handleOpenAIWSDialTransientFailure` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:721` | `persistOpenAIWSRateLimitSignal` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_v2.go:379` | `forwardOpenAIWSV2` | `handleOpenAIWSDialTransientFailure` | +| `openai_ws_forwarder_v2.go:958` | `forwardOpenAIWSV2` | `handleOpenAIWSErrorEventTransientFailure` | +| `openai_ws_forwarder_v2.go:1085` | `forwardOpenAIWSV2` | `handleOpenAIWSTerminalTransientFailure` | +| `openai_ws_http_bridge.go:696` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_http_bridge.go:816` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSFailureAccountSideEffects` | +| `openai_ws_http_bridge.go:980` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSFailureAccountSideEffects` | +| `openai_ws_http_bridge.go:1088` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSTerminalTransientFailure` | +| `openai_ws_v2_passthrough_adapter.go:981` | `proxyResponsesWebSocketV2Passthrough` | `handleOpenAIWSDialTransientFailure` | +| `openai_ws_v2_passthrough_adapter.go:1596` | `proxyResponsesWebSocketV2Passthrough` | `handleOpenAIWSFailureAccountSideEffects` | +| `ratelimit_service.go:354` | `HandleUpstreamError` | `handleUpstreamErrorAfterStreakReset` | +| `ratelimit_service.go:360` | `handleUpstreamErrorAfterStreakReset` | `maybeDisableOpenAISchedulingOn429` | From 692b62c947d42bab8a34cbc565cb48e62eee4141 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 23:51:58 +0800 Subject: [PATCH 21/38] fix: keep cached weekly identity paired with its usage observation --- .../scripts/oauth429-weekly-only-evidence.py | 2 +- .../service/oauth429_weekly_only_test.go | 28 +++++++++++++++++++ .../service/openai_disable_scheduling_429.go | 5 ++++ docs/testing/oauth429-weekly-only.md | 4 ++- 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index 50eada8c0df6..493b858efdbf 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -24,7 +24,7 @@ else: assert int(status) == 0 and not failed, "candidate failed" required = ["RotationPreservesScheduling"] if mode == "repository" else [ - "Service", "HeaderBoundaries", "CachedIdentity", "PolicyGates", + "Service", "HeaderBoundaries", "CachedIdentity", "CacheDoesNotRelabelUnidentifiedUsage", "PolicyGates", "HTTPForward", "WSForward", "WSClientIngress", "CombinedRotation", ] for name in required: diff --git a/backend/internal/service/oauth429_weekly_only_test.go b/backend/internal/service/oauth429_weekly_only_test.go index 100c1555bc4b..db3b6a6ce331 100644 --- a/backend/internal/service/oauth429_weekly_only_test.go +++ b/backend/internal/service/oauth429_weekly_only_test.go @@ -255,3 +255,31 @@ func TestOAuth429WeeklyOnlyCombinedRotation(t *testing.T) { }) } } + +func TestOAuth429WeeklyOnlyCacheDoesNotRelabelUnidentifiedUsage(t *testing.T) { + for _, order := range []string{"usage_without_window", "window_without_usage"} { + t.Run(order, func(t *testing.T) { + now := time.Now() + first := weekly429Headers("20", "0", false) + second := http.Header{"X-Codex-Primary-Used-Percent": {"100"}} + if order == "window_without_usage" { + first = http.Header{"X-Codex-Primary-Used-Percent": {"100"}} + second = http.Header{"X-Codex-Primary-Window-Minutes": {"10080"}} + } + // Use the real parser, normalizer and field-version merge: a partial + // packet must not borrow another packet's weekly identity. + oldSnapshot, newSnapshot := ParseCodexRateLimitHeaders(first), ParseCodexRateLimitHeaders(second) + oldSnapshot.UpdatedAt = now.Add(-2 * time.Minute).Format(time.RFC3339Nano) + newSnapshot.UpdatedAt = now.Add(-time.Minute).Format(time.RFC3339Nano) + older := buildCodexUsageExtraUpdates(oldSnapshot, now) + newer := buildCodexUsageExtraUpdates(newSnapshot, now) + a := scheduling429Account() + a.Extra = mergeCodexUsageUpdates(older, newer) + a.Extra[OpenAIDisableSchedulingOn429ExtraKey] = true + repo := &weeklyOnly429Repo{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.HandleUpstreamError(t.Context(), a, 429, nil, nil) + require.Empty(t, repo.ids, "cached usage must share the explicit weekly identity's source observation") + }) + } +} diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index b90d1f908b25..ed57e4d21f9f 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -132,6 +132,11 @@ func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time) return 0, false } windowObserved = time.Unix(0, stamp) + // Partial normalized packets can otherwise pair an unidentified + // primary percentage with another observation's explicit weekly window. + if !windowObserved.Equal(observed) { + return 0, false + } } // Permanent pauses require a known, recent observation, unlike temporary // scheduling guards that may retain legacy snapshots without timestamps. diff --git a/docs/testing/oauth429-weekly-only.md b/docs/testing/oauth429-weekly-only.md index 31b9c7f01e86..682e3958db79 100644 --- a/docs/testing/oauth429-weekly-only.md +++ b/docs/testing/oauth429-weekly-only.md @@ -17,7 +17,8 @@ The percentage is not inferred from a body `usage_limit_reached` or When there are no current quota observation headers, cache fallback requires `codex_7d_window_minutes=10080` and retains account identity, percentage, observation, per-field provenance, staleness and reset checks. If field versions -exist, both usage and window identity must have valid fresh versions. Legacy +exist, both usage and window identity must have valid fresh versions from the same +source observation. A partial packet cannot borrow another packet's weekly identity. Legacy snapshots without an explicit window no longer authorize a permanent disable. Current unclassified/short-only quota headers continue to block cache fallback. @@ -28,6 +29,7 @@ Current unclassified/short-only quota headers continue to block cache fallback. | `TestOAuth429WeeklyOnlyService` | Public RateLimitService → actual policy → spy durable write + existing quota header parser/persistence | | `TestOAuth429WeeklyOnlyHeaderBoundaries` | Both weekly positions; zero/invalid/absent/5h neighbors; 5h-only 100; missing/low/invalid weekly; duplicates and conflicts; no reuse of high cache | | `TestOAuth429WeeklyOnlyCachedIdentity` | Explicit identity; global/field freshness; identity mismatch; future/stale/missing versions; absolute/relative resets | +| `TestOAuth429WeeklyOnlyCacheDoesNotRelabelUnidentifiedUsage` | Actual parser/normalizer/merge; partial usage-only and window-only packets cannot combine into weekly evidence | | `TestOAuth429WeeklyOnlyPolicyGates` | Own threshold, strict equality, invalid threshold, opt-out, non429, body-only weekly classification | | `TestOAuth429WeeklyOnlyHTTPForward` | Actual `Forward` entry, native and OAuth passthrough HTTP paths, mocked transport response, primary/secondary weekly zero-neighbor and negative cases | | `TestOAuth429WeeklyOnlyWSForward` | Actual `Forward` entry, real loopback WS upstream handshake 429 and error frames, handshake quota and explicit-cache/body-only controls | From d392072e373b45568fea3666e0fadf300f38d522 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 13 Nov 2026 23:54:52 +0800 Subject: [PATCH 22/38] test: require explicit weekly cache despite nonweekly 429 headers --- .../scripts/oauth429-weekly-only-evidence.py | 5 ++- .../service/oauth429_weekly_only_test.go | 36 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index 493b858efdbf..0fcec43fa279 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -19,12 +19,15 @@ assert int(status) != 0, "baseline unexpectedly passed" for name in ("primary_weekly_zero_neighbor", "secondary_weekly_invalid_neighbor"): assert "TestOAuth429WeeklyOnlyService/" + name in failed, name + for name in ("five_hour_100_zero_neighbor", "five_hour_100_invalid_neighbor"): + assert "TestOAuth429WeeklyOnlyNonweeklyHeadersAllowExplicitCache/" + name in failed, name + assert "nonweekly headers must not veto fresh explicit weekly cache" in output assert "explicit weekly 99 must disable despite an unrelated neighbor" in output assert "TestOAuth429WeeklyOnlyService/primary_weekly_five_hour_neighbor" in passed else: assert int(status) == 0 and not failed, "candidate failed" required = ["RotationPreservesScheduling"] if mode == "repository" else [ - "Service", "HeaderBoundaries", "CachedIdentity", "CacheDoesNotRelabelUnidentifiedUsage", "PolicyGates", + "Service", "HeaderBoundaries", "CachedIdentity", "NonweeklyHeadersAllowExplicitCache", "CacheDoesNotRelabelUnidentifiedUsage", "PolicyGates", "HTTPForward", "WSForward", "WSClientIngress", "CombinedRotation", ] for name in required: diff --git a/backend/internal/service/oauth429_weekly_only_test.go b/backend/internal/service/oauth429_weekly_only_test.go index db3b6a6ce331..3ac647cab7fe 100644 --- a/backend/internal/service/oauth429_weekly_only_test.go +++ b/backend/internal/service/oauth429_weekly_only_test.go @@ -283,3 +283,39 @@ func TestOAuth429WeeklyOnlyCacheDoesNotRelabelUnidentifiedUsage(t *testing.T) { }) } } + +func TestOAuth429WeeklyOnlyNonweeklyHeadersAllowExplicitCache(t *testing.T) { + for _, tc := range []struct { + name, neighbor string + mutate func(*Account) + want bool + }{ + {"five_hour_100_zero_neighbor", "0", nil, true}, + {"five_hour_100_invalid_neighbor", "invalid", nil, true}, + {"missing_cached_usage", "0", func(a *Account) { delete(a.Extra, "codex_7d_used_percent") }, false}, + {"unidentified_cached_usage", "0", func(a *Account) { delete(a.Extra, "codex_7d_window_minutes") }, false}, + {"cached_usage_equal_own_threshold", "0", func(a *Account) { a.Extra[OpenAIDisableSchedulingOn4297dThresholdExtraKey] = 99.0 }, false}, + {"cached_usage_below_threshold", "0", func(a *Account) { a.Extra["codex_7d_used_percent"] = 20.0 }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + a := scheduling429Account() + a.Extra[CodexUsageFieldVersionsKey] = weeklyOnlyVersions(time.Now().Add(-time.Minute)) + if tc.mutate != nil { + tc.mutate(a) + } + h := http.Header{} + h.Set("x-codex-primary-window-minutes", "300") + h.Set("x-codex-primary-used-percent", "100") + h.Set("x-codex-secondary-window-minutes", tc.neighbor) + h.Set("x-codex-secondary-used-percent", "0") + repo := &weeklyOnly429Repo{} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.HandleUpstreamError(t.Context(), a, 429, h, nil) + require.Equal(t, tc.want, len(repo.ids) > 0, "nonweekly headers must not veto fresh explicit weekly cache") + if tc.want { + require.Equal(t, []bool{false}, repo.values) + } + require.NotEmpty(t, repo.extra, "real quota parser/persistence path must run") + }) + } +} From ea1f151c53efdad0d67ed6cf55f79e199c4430ff Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:03:11 +0800 Subject: [PATCH 23/38] fix: preserve weekly evidence through cache and WebSocket error policies --- .../scripts/oauth429-weekly-only-evidence.py | 66 +++++++++++++----- .github/workflows/oauth429-weekly-only.yml | 56 +++++++++++++--- .../oauth429_weekly_only_gateway_test.go | 27 +++++++- .../service/oauth429_weekly_only_test.go | 67 ++++++++++++++++++- .../service/openai_disable_scheduling_429.go | 40 +++++++---- ...enai_disable_scheduling_429_weekly_test.go | 16 ++--- .../service/openai_gateway_passthrough.go | 1 + .../service/openai_gateway_service.go | 2 + .../internal/service/openai_gateway_usage.go | 7 +- .../service/openai_ws_forwarder_support.go | 2 + docs/testing/oauth429-weekly-only.md | 31 ++++++--- 11 files changed, 252 insertions(+), 63 deletions(-) diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index 0fcec43fa279..95e962f69b5c 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -1,33 +1,65 @@ -"""Validate remote Go test events; never accept compilation failure as RED.""" +"""Validate completed remote Go test evidence, rejecting crashes and stderr errors.""" import json from pathlib import Path import sys mode, filename, status = sys.argv[1:] -events = [json.loads(line) for line in Path(filename).read_text().splitlines()] +path = Path(filename) +events = [json.loads(line) for line in path.read_text().splitlines()] +stderr = path.with_suffix(".stderr").read_text() output = "".join(event.get("Output", "") for event in events) -Path(filename).with_suffix(".log").write_text(output) -print(output) +path.with_suffix(".log").write_text(output + stderr) +print(output + stderr) assert events, "missing test events" assert not any(event["Action"] == "skip" for event in events), "unexpected skip" -assert not any(text in output for text in ( +combined = (output + stderr).lower() +assert not any(text in combined for text in ( "build failed", "setup failed", "no tests to run", "undefined:", "panic:", -)), "infrastructure or compilation failure is not behavioral evidence" + "fatal error:", "warning: data race", "race detected", "signal:", + "sigsegv", "sigabrt", "segmentation fault", "test timed out", "unexpected fault", + "out of memory", "signal killed", "core dumped", +)), "runtime, race, infrastructure or compilation failure is not behavioral evidence" +started = {(event.get("Package"), event["Test"]) for event in events + if event["Action"] == "run" and event.get("Test")} +finished = {(event.get("Package"), event["Test"]) for event in events + if event["Action"] in ("pass", "fail") and event.get("Test")} +assert started and started == finished, "test execution did not finish" +package = "github.com/Wei-Shaw/sub2api/internal/" + ("repository" if mode == "repository" else "service") +terminal = [event for event in events if event.get("Package") == package + and not event.get("Test") and event["Action"] in ("pass", "fail")] +assert len(terminal) == 1, "missing completed package result" failed = {event.get("Test") for event in events if event["Action"] == "fail"} passed = {event.get("Test") for event in events if event["Action"] == "pass"} -if mode == "red": - assert int(status) != 0, "baseline unexpectedly passed" - for name in ("primary_weekly_zero_neighbor", "secondary_weekly_invalid_neighbor"): - assert "TestOAuth429WeeklyOnlyService/" + name in failed, name - for name in ("five_hour_100_zero_neighbor", "five_hour_100_invalid_neighbor"): - assert "TestOAuth429WeeklyOnlyNonweeklyHeadersAllowExplicitCache/" + name in failed, name - assert "nonweekly headers must not veto fresh explicit weekly cache" in output - assert "explicit weekly 99 must disable despite an unrelated neighbor" in output - assert "TestOAuth429WeeklyOnlyService/primary_weekly_five_hour_neighbor" in passed +if mode.startswith("red"): + assert int(status) == 1 and terminal[0]["Action"] == "fail", "expected normal go test assertion failure" + if mode == "red-cache": + assert "TestOAuth429WeeklyOnlySequentialCache/duplicate_usage" in failed + assert "rejected weekly headers must not poison a later headerless 429 cache" in output + else: + for name in ("primary_weekly_zero_neighbor", "secondary_weekly_invalid_neighbor"): + assert "TestOAuth429WeeklyOnlyService/" + name in failed, name + for name in ("five_hour_100_zero_neighbor", "five_hour_100_invalid_neighbor"): + assert "TestOAuth429WeeklyOnlyNonweeklyHeadersAllowExplicitCache/" + name in failed, name + assert "nonweekly headers must not veto fresh explicit weekly cache" in output + assert "explicit weekly 99 must disable despite an unrelated neighbor" in output + assert "TestOAuth429WeeklyOnlyService/primary_weekly_five_hour_neighbor" in passed + for name in ( + "HTTPForward/native/primary_zero_neighbor", + "HTTPForward/passthrough/secondary_zero_neighbor", + "WSForward/handshake_weekly_zero_neighbor", + "WSForward/frame_with_weekly_handshake", + "WSForward/frame_low_overrides_high_cache", + "WSForward/frame_invalid_overrides_high_cache", + "WSClientIngress", + ): + assert "TestOAuth429WeeklyOnly" + name in failed, name + assert "TestOAuth429WeeklyOnlyWSForward/body_only_no_percentage" in passed + assert "request admission denied:" not in output else: - assert int(status) == 0 and not failed, "candidate failed" + assert int(status) == 0 and not failed and terminal[0]["Action"] == "pass", "candidate failed" required = ["RotationPreservesScheduling"] if mode == "repository" else [ - "Service", "HeaderBoundaries", "CachedIdentity", "NonweeklyHeadersAllowExplicitCache", "CacheDoesNotRelabelUnidentifiedUsage", "PolicyGates", + "Service", "HeaderBoundaries", "CachedIdentity", "NonweeklyHeadersAllowExplicitCache", + "CacheDoesNotRelabelUnidentifiedUsage", "SequentialCache", "PolicyGates", "HTTPForward", "WSForward", "WSClientIngress", "CombinedRotation", ] for name in required: diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 705b33cb886e..3edff8d5e88e 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -5,6 +5,10 @@ on: branches: [production] paths: - 'backend/internal/service/*429*' + - 'backend/internal/service/openai_gateway_service.go' + - 'backend/internal/service/openai_gateway_usage.go' + - 'backend/internal/service/openai_gateway_passthrough.go' + - 'backend/internal/service/openai_ws_forwarder_support.go' - 'backend/internal/repository/oauth429_weekly_only*' - '.github/workflows/oauth429-weekly-only.yml' - '.github/scripts/oauth429-weekly-only-*' @@ -38,13 +42,19 @@ jobs: git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt git diff --exit-code git worktree add --detach "$RUNNER_TEMP/oauth429-red" "$CANDIDATE" - target=backend/internal/service/openai_disable_scheduling_429.go - expected=ab9d5251a4acec7c17b0adb0f21ae59a71f89067 - test "$(git rev-parse "$BASELINE:$target")" = "$expected" - git show "$BASELINE:$target" > "$RUNNER_TEMP/oauth429-red/$target" - actual=$(git hash-object "$RUNNER_TEMP/oauth429-red/$target") - test "$actual" = "$expected" - printf '%s %s %s\n' "$BASELINE" "$actual" "$target" > evidence/restored-blobs.txt + while read -r expected target; do + test "$(git rev-parse "$BASELINE:$target")" = "$expected" + git show "$BASELINE:$target" > "$RUNNER_TEMP/oauth429-red/$target" + actual=$(git hash-object "$RUNNER_TEMP/oauth429-red/$target") + test "$actual" = "$expected" + printf '%s %s %s\n' "$BASELINE" "$actual" "$target" >> evidence/restored-blobs.txt + done <<'BLOBS' + ab9d5251a4acec7c17b0adb0f21ae59a71f89067 backend/internal/service/openai_disable_scheduling_429.go + 849aec6c598b9ca5e94f218f76e7d7266505ae57 backend/internal/service/openai_gateway_service.go + 9fb1903315d1f086f4f38bd73a5a0a5f69f6542a backend/internal/service/openai_gateway_usage.go + 9dfffb6d6280278c5c21015ddffad12b706efa5c backend/internal/service/openai_ws_forwarder_support.go + aa0c3dafdf9e9e3f5ec78467fa08899c67e9ec89 backend/internal/service/openai_gateway_passthrough.go + BLOBS git -C "$RUNNER_TEMP/oauth429-red" diff --stat > evidence/red-diff.txt git ls-files 'backend/internal/service/*429*test.go' 'backend/internal/repository/oauth429_weekly_only*test.go' > evidence/retained-tests.txt while IFS= read -r test_file; do @@ -64,6 +74,28 @@ jobs: set -e printf '%s\n' "$result" > evidence/red-exit.txt python3 .github/scripts/oauth429-weekly-only-evidence.py red evidence/red.jsonl "$result" + - name: Isolate rejected-header cache poisoning with original parser sources + shell: bash + run: | + set -euo pipefail + git worktree add --detach "$RUNNER_TEMP/oauth429-cache-red" "$CANDIDATE" + while read -r expected target; do + test "$(git rev-parse "$BASELINE:$target")" = "$expected" + git show "$BASELINE:$target" > "$RUNNER_TEMP/oauth429-cache-red/$target" + test "$(git hash-object "$RUNNER_TEMP/oauth429-cache-red/$target")" = "$expected" + printf '%s %s %s\n' "$BASELINE" "$expected" "$target" >> evidence/cache-restored-blobs.txt + done <<'BLOBS' + 849aec6c598b9ca5e94f218f76e7d7266505ae57 backend/internal/service/openai_gateway_service.go + 9fb1903315d1f086f4f38bd73a5a0a5f69f6542a backend/internal/service/openai_gateway_usage.go + BLOBS + git -C "$RUNNER_TEMP/oauth429-cache-red" diff --exit-code -- '*_test.go' + git -C "$RUNNER_TEMP/oauth429-cache-red" diff --stat > evidence/cache-red-diff.txt + set +e + (cd "$RUNNER_TEMP/oauth429-cache-red/backend" && go test -json -tags=unit ./internal/service -run '^TestOAuth429WeeklyOnlySequentialCache$' -count=1 -timeout=10m) > evidence/red-cache.jsonl 2> evidence/red-cache.stderr + result=$? + set -e + printf '%s\n' "$result" > evidence/red-cache-exit.txt + python3 .github/scripts/oauth429-weekly-only-evidence.py red-cache evidence/red-cache.jsonl "$result" - uses: actions/upload-artifact@v7 if: always() with: @@ -91,7 +123,7 @@ jobs: git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt git diff --exit-code set +e - (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|Weekly429Threshold|TOTPRotationOn429)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr + (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|Weekly429Threshold|TOTPRotationOn429|OpenAIStream429|CalculateOpenAI429ResetTime)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr result=$? set -e printf '%s\n' "$result" > evidence/green-exit.txt @@ -109,6 +141,14 @@ jobs: set -e printf '%s\n' "$result" > evidence/green-repository-exit.txt python3 .github/scripts/oauth429-weekly-only-evidence.py repository evidence/green-repository.jsonl "$result" + - name: Ordinary backend build without test tags + if: success() || failure() + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + (cd backend && go build ./...) > evidence/ordinary-build.log 2>&1 + printf 'PASS go build ./... at %s\n' "$CANDIDATE" | tee -a evidence/ordinary-build.log - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/service/oauth429_weekly_only_gateway_test.go b/backend/internal/service/oauth429_weekly_only_gateway_test.go index 657fa6dc1275..6746304b45df 100644 --- a/backend/internal/service/oauth429_weekly_only_gateway_test.go +++ b/backend/internal/service/oauth429_weekly_only_gateway_test.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "strings" + "sync/atomic" "testing" "time" @@ -100,14 +101,29 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { {"frame_with_weekly_handshake", true, false, true}, {"body_only_no_percentage", true, false, false}, {"frame_with_explicit_cache", true, true, true}, + {"frame_low_overrides_high_cache", true, true, false}, + {"frame_invalid_overrides_high_cache", true, true, false}, } { t.Run(tc.name, func(t *testing.T) { h := weekly429Headers("99", "0", false) h.Set("x-codex-secondary-window-minutes", "0") - if tc.name == "body_only_no_percentage" || tc.cached { + if tc.name == "body_only_no_percentage" || tc.name == "frame_with_explicit_cache" { h = http.Header{} } + if tc.name == "frame_low_overrides_high_cache" { + h.Set("x-codex-primary-used-percent", "20") + } + if tc.name == "frame_invalid_overrides_high_cache" { + h.Set("x-codex-primary-used-percent", "invalid") + } + // A long handshake reset must not leak into ordinary-model temporary cooldown. + h.Set("x-codex-primary-reset-after-seconds", "500000") + if tc.name == "body_only_no_percentage" || tc.name == "frame_with_explicit_cache" { + h = http.Header{} + } + var peers atomic.Int64 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + peers.Add(1) if !tc.frame { for k, v := range h { w.Header()[k] = v @@ -144,7 +160,7 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { } else { delete(a.Extra, "codex_7d_used_percent") } - repo := &weeklyOnlyWSRepo{} + repo := &weeklyOnlyWSRepo{openAIWSRateLimitSignalRepo: openAIWSRateLimitSignalRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{*a}}}} rates := NewRateLimitService(repo, nil, cfg, nil, nil) upstream := &httpUpstreamRecorder{} gateway := &OpenAIGatewayService{accountRepo: repo, rateLimitService: rates, httpUpstream: upstream, cache: &stubGatewayCache{}, cfg: cfg, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector()} @@ -160,6 +176,11 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { _, err := gateway.Forward(t.Context(), c, a, []byte(`{"model":"gpt-5.1","stream":false,"input":"fictional test"}`)) require.Error(t, err) require.Equal(t, 429, rec.Code) + require.Positive(t, peers.Load(), "must observe the actual upstream peer") + if tc.frame { + require.NotEmpty(t, repo.rateLimitCalls) + require.WithinDuration(t, time.Now().Add(2*time.Hour), repo.rateLimitCalls[len(repo.rateLimitCalls)-1], 10*time.Second, "temporary cooldown must use the event reset, not handshake quota") + } require.Nil(t, upstream.lastReq, "WS rejection must not fall back to HTTP") require.Equal(t, tc.want, len(repo.writes) > 0, "WS Forward must use weekly-only permanent scheduling policy") if tc.want { @@ -187,7 +208,7 @@ func TestOAuth429WeeklyOnlyWSClientIngress(t *testing.T) { a.Credentials = openAIWSQuotaTestCredentials(AccountTypeOAuth, "") a.Extra["responses_websockets_v2_enabled"] = true delete(a.Extra, "codex_7d_used_percent") - repo := &weeklyOnlyWSRepo{} + repo := &weeklyOnlyWSRepo{openAIWSRateLimitSignalRepo: openAIWSRateLimitSignalRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{*a}}}} rates := NewRateLimitService(repo, nil, cfg, nil, nil) gateway := &OpenAIGatewayService{accountRepo: repo, rateLimitService: rates, httpUpstream: &httpUpstreamRecorder{}, cache: &stubGatewayCache{}, cfg: cfg, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), toolCorrector: NewCodexToolCorrector(), openaiWSPool: pool} rates.SetAccountRuntimeBlocker(gateway) diff --git a/backend/internal/service/oauth429_weekly_only_test.go b/backend/internal/service/oauth429_weekly_only_test.go index 3ac647cab7fe..b1dc7a7e1911 100644 --- a/backend/internal/service/oauth429_weekly_only_test.go +++ b/backend/internal/service/oauth429_weekly_only_test.go @@ -73,7 +73,13 @@ func TestOAuth429WeeklyOnlyHeaderBoundaries(t *testing.T) { {"weekly_negative", weekly429Headers("-1", "100", false), false}, {"weekly_over_100", weekly429Headers("101", "100", false), false}, } { - t.Run(tc.name, func(t *testing.T) { assertWeeklyOnly429Write(t, tc.headers, tc.want) }) + t.Run(tc.name, func(t *testing.T) { + cacheUsed := 99.0 + if tc.name == "5h_only_100" || tc.name == "unknown_primary_100" || tc.name == "unknown_windows" { + cacheUsed = 20 + } + assertWeeklyOnly429Write(t, tc.headers, tc.want, cacheUsed) + }) } for _, reverse := range []bool{false, true} { for _, neighbor := range []string{"0", "-1", "invalid", "", "absent", "300", "60"} { @@ -121,11 +127,14 @@ func TestOAuth429WeeklyOnlyHeaderBoundaries(t *testing.T) { } } -func assertWeeklyOnly429Write(t *testing.T, headers http.Header, want bool) { +func assertWeeklyOnly429Write(t *testing.T, headers http.Header, want bool, cachedUsage ...float64) { t.Helper() // A high cached value deliberately challenges the no-fallback boundary. account := scheduling429Account() account.Extra["codex_7d_window_minutes"] = 10080 + if len(cachedUsage) > 0 { + account.Extra["codex_7d_used_percent"] = cachedUsage[0] + } repo := &weeklyOnly429Repo{} rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) rates.HandleUpstreamError(t.Context(), account, 429, headers, nil) @@ -319,3 +328,57 @@ func TestOAuth429WeeklyOnlyNonweeklyHeadersAllowExplicitCache(t *testing.T) { }) } } + +type weeklyOnlyPersistedRepo struct { + weeklyOnly429Repo + stored *Account +} + +func (r *weeklyOnlyPersistedRepo) UpdateExtra(_ context.Context, _ int64, updates map[string]any) error { + r.stored.Extra = mergeCodexUsageUpdates(r.stored.Extra, updates) + return nil +} + +func (r *weeklyOnlyPersistedRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + reloaded := *r.stored + reloaded.Extra = shallowCopyMap(r.stored.Extra) + return &reloaded, nil +} + +func TestOAuth429WeeklyOnlySequentialCache(t *testing.T) { + for _, tc := range []struct { + name, key string + values []string + }{ + {"duplicate_usage", "x-codex-primary-used-percent", []string{"99", "20"}}, + {"conflicting_window", "x-codex-primary-window-minutes", []string{"10080", "300"}}, + {"conflicting_weekly_windows", "x-codex-secondary-window-minutes", []string{"10080"}}, + {"invalid_weekly_usage", "x-codex-primary-used-percent", []string{"invalid"}}, + } { + t.Run(tc.name, func(t *testing.T) { + a := scheduling429Account() + initial := ParseCodexRateLimitHeaders(weekly429Headers("20", "0", false)) + initial.UpdatedAt = time.Now().Add(-time.Minute).Format(time.RFC3339Nano) + a.Extra = mergeCodexUsageUpdates(a.Extra, buildCodexUsageExtraUpdates(initial, time.Now())) + repo := &weeklyOnlyPersistedRepo{stored: a} + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + h := weekly429Headers("99", "0", false) + h[http.CanonicalHeaderKey(tc.key)] = tc.values + first, err := repo.GetByID(t.Context(), a.ID) + require.NoError(t, err) + rates.HandleUpstreamError(t.Context(), first, 429, h, nil) + require.Empty(t, repo.ids, "invalid weekly headers must not disable on the first request") + reloaded, err := repo.GetByID(t.Context(), a.ID) + require.NoError(t, err) + rates.HandleUpstreamError(t.Context(), reloaded, 429, nil, nil) + require.Empty(t, repo.ids, "rejected weekly headers must not poison a later headerless 429 cache") + // A later independently valid weekly observation restores usable evidence. + valid := ParseCodexRateLimitHeaders(weekly429Headers("99", "0", false)) + require.NoError(t, repo.UpdateExtra(t.Context(), a.ID, buildCodexUsageExtraUpdates(valid, time.Now()))) + reloaded, err = repo.GetByID(t.Context(), a.ID) + require.NoError(t, err) + rates.HandleUpstreamError(t.Context(), reloaded, 429, nil, nil) + require.Equal(t, []bool{false}, repo.values) + }) + } +} diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index ed57e4d21f9f..77c8935746cf 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -15,6 +15,7 @@ const ( OpenAIDisableSchedulingOn429ExtraKey = "openai_disable_scheduling_on_429" OpenAIDisableSchedulingOn4297dThresholdExtraKey = "openai_disable_scheduling_on_429_7d_threshold_percent" DefaultOpenAIDisableSchedulingOn4297dThresholdPercent = 98.0 + openAI429WeeklyInvalidAtKey = "codex_7d_permanent_disable_invalid_at" ) func openAI429WeeklyThreshold(account *Account) (float64, bool) { @@ -33,20 +34,10 @@ func validOpenAI429Percent(value float64) bool { // A present but invalid/low weekly observation must never fall back to an older // high snapshot. The five-hour window does not participate in this policy. func openAI429WeeklyHeaderUsage(headers http.Header) (used float64, present, valid bool) { - hasObservation := false - for _, window := range []string{"primary", "secondary"} { - for _, field := range []string{"used-percent", "window-minutes", "reset-after-seconds"} { - _, exists := headers[http.CanonicalHeaderKey("x-codex-"+window+"-"+field)] - hasObservation = hasObservation || exists - } - } - if !hasObservation { - return 0, false, false - } - snapshot := ParseCodexRateLimitHeaders(headers) - if snapshot == nil { - return 0, true, false - } + return openAI429WeeklyParsedHeaderUsage(headers, ParseCodexRateLimitHeaders(headers)) +} + +func openAI429WeeklyParsedHeaderUsage(headers http.Header, snapshot *OpenAICodexUsageSnapshot) (used float64, present, valid bool) { // A permanent pause must not rely on Normalize's legacy primary=7d // assumption. Require exactly one explicitly identified weekly window. prefix := "" @@ -76,6 +67,11 @@ func openAI429WeeklyHeaderUsage(headers http.Header) (used float64, present, val prefix = "x-codex-" + window + "-" } if prefix == "" { + // Nonweekly/unidentified data is not a weekly observation. It neither + // supplies a weekly percentage nor vetoes independently valid cache. + return 0, false, false + } + if snapshot == nil { return 0, true, false } weekly := snapshot.PrimaryUsedPercent @@ -145,6 +141,14 @@ func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time) return 0, false } } + // Header.Get/Normalize can retain a conflicting packet's first value for + // ordinary quota display. That packet must never become permanent evidence. + if raw, exists := extra[openAI429WeeklyInvalidAtKey]; exists { + invalidAt, err := time.Parse(time.RFC3339Nano, fmt.Sprint(raw)) + if err != nil || !invalidAt.Before(observed) { + return 0, false + } + } if raw, exists := extra["codex_7d_reset_at"]; exists { reset, err := parseTime(fmt.Sprint(raw)) if err != nil || !reset.After(now) { @@ -182,6 +186,11 @@ func openAIDisableSchedulingOn429Enabled(account *Account) bool { type openAIDisableScheduling429ObservedKey struct{} +// Stream cooldowns intentionally discard ordinary-model handshake quota. The +// opt-in permanent weekly policy still needs that observation, including lows +// and invalid evidence that must prevent fallback to an older high snapshot. +type openAI429WeeklyHeadersKey struct{} + type openAIDisableScheduling429Observation struct { accountID int64 disabled bool @@ -222,6 +231,9 @@ func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context return ctx, false } threshold, thresholdValid := openAI429WeeklyThreshold(owner) + if evidence, ok := ctx.Value(openAI429WeeklyHeadersKey{}).(http.Header); ok { + headers = evidence + } used, usageValid := openAI429WeeklyUsage(owner, headers, time.Now()) if !thresholdValid || !usageValid || used <= threshold { return ctx, false diff --git a/backend/internal/service/openai_disable_scheduling_429_weekly_test.go b/backend/internal/service/openai_disable_scheduling_429_weekly_test.go index 591b81ca8a74..66fc63a09664 100644 --- a/backend/internal/service/openai_disable_scheduling_429_weekly_test.go +++ b/backend/internal/service/openai_disable_scheduling_429_weekly_test.go @@ -89,7 +89,7 @@ func TestDisableScheduling429RequiresWeeklyUsageStrictlyAboveThreshold(t *testin h.Set("x-codex-primary-reset-after-seconds", "") return h }()}, - {name: "reset-only response cannot reuse cached high usage", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-reset-after-seconds", "0"); return h }()}, + {name: "unidentified reset permits explicit weekly cache", want: true, headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-reset-after-seconds", "0"); return h }()}, {name: "weekly reset and window without usage cannot reuse cached high", headers: func() http.Header { h := http.Header{} h.Set("x-codex-primary-reset-after-seconds", "0") @@ -97,25 +97,25 @@ func TestDisableScheduling429RequiresWeeklyUsageStrictlyAboveThreshold(t *testin return h }()}, {name: "weekly window alone cannot reuse cached high", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", "10080"); return h }()}, - {name: "short window alone cannot reuse cached high", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", "300"); return h }()}, - {name: "empty window cannot reuse cached high", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", ""); return h }()}, - {name: "empty weekly window invalidates current high usage", headers: func() http.Header { + {name: "short window alone permits explicit weekly cache", want: true, headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", "300"); return h }()}, + {name: "empty unrelated window permits explicit weekly cache", want: true, headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-window-minutes", ""); return h }()}, + {name: "unidentified current usage permits explicit weekly cache", want: true, headers: func() http.Header { h := weekly429Headers("99", "100", false) h.Set("x-codex-primary-window-minutes", "") return h }()}, - {name: "nil header values still invalidate observation", headers: http.Header{http.CanonicalHeaderKey("x-codex-primary-window-minutes"): nil}}, + {name: "nil unrelated header permits explicit weekly cache", want: true, headers: http.Header{http.CanonicalHeaderKey("x-codex-primary-window-minutes"): nil}}, {name: "invalid current reset", headers: func() http.Header { h := weekly429Headers("99", "100", false) h.Set("x-codex-primary-reset-after-seconds", "invalid") return h }()}, - {name: "two short windows cannot invent weekly quota", headers: func() http.Header { + {name: "two short windows permit explicit weekly cache", want: true, headers: func() http.Header { h := weekly429Headers("99", "100", false) h.Set("x-codex-primary-window-minutes", "60") return h }()}, - {name: "legacy unclassified primary may be five hour", headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-used-percent", "100"); return h }()}, + {name: "unclassified primary does not veto explicit weekly cache", want: true, headers: func() http.Header { h := http.Header{}; h.Set("x-codex-primary-used-percent", "100"); return h }()}, {name: "two weekly windows are ambiguous", headers: func() http.Header { h := weekly429Headers("99", "100", false) h.Set("x-codex-secondary-window-minutes", "10080") @@ -126,7 +126,7 @@ func TestDisableScheduling429RequiresWeeklyUsageStrictlyAboveThreshold(t *testin h.Set("x-codex-primary-used-percent", "") return h }()}, - {name: "invalid current window", headers: func() http.Header { + {name: "invalid unidentified window permits explicit weekly cache", want: true, headers: func() http.Header { h := weekly429Headers("99", "100", false) h.Set("x-codex-primary-window-minutes", "invalid") return h diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index aa0c3dafdf9e..c7c8a79fba45 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1876,6 +1876,7 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects( } accountHeaders := headers if statusCode == http.StatusTooManyRequests { + ctx = context.WithValue(ctx, openAI429WeeklyHeadersKey{}, headers) // 普通模型的流式 429 不能继承外层 HTTP 200 的全局 quota 快照; // 只有 OAuth/SetupToken 的 Spark 配额 429 才需要保留 headers 读取明确的 5h/7d reset。 accountHeaders = openAIWSSemantic429Headers(account, model, headers) diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 849aec6c598b..5a5ebe2a3555 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -128,6 +128,8 @@ var codexCLIOnlyDebugHeaderWhitelist = []string{ // OpenAICodexUsageSnapshot represents Codex API usage limits from response headers type OpenAICodexUsageSnapshot struct { + // Preserve invalid raw weekly provenance across legacy normalization. + invalidWeekly429 bool PrimaryUsedPercent *float64 `json:"primary_used_percent,omitempty"` PrimaryResetAfterSeconds *int `json:"primary_reset_after_seconds,omitempty"` PrimaryWindowMinutes *int `json:"primary_window_minutes,omitempty"` diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 9fb1903315d1..1a82b648251f 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -1143,7 +1143,9 @@ func ParseCodexRateLimitHeaders(headers http.Header) *OpenAICodexUsageSnapshot { hasData = true } - if !hasData { + _, weeklyPresent, weeklyValid := openAI429WeeklyParsedHeaderUsage(headers, snapshot) + snapshot.invalidWeekly429 = weeklyPresent && !weeklyValid + if !hasData && !snapshot.invalidWeekly429 { return nil } @@ -1184,6 +1186,9 @@ func buildCodexUsageExtraUpdates(snapshot *OpenAICodexUsageSnapshot, fallbackNow baseTime := codexSnapshotBaseTime(snapshot, fallbackNow) updates := make(map[string]any) + if snapshot.invalidWeekly429 { + updates[openAI429WeeklyInvalidAtKey] = baseTime.Format(time.RFC3339Nano) + } // 保存原始 primary/secondary 字段,便于排查问题 if snapshot.PrimaryUsedPercent != nil { diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index 9dfffb6d6280..682049cc7b36 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -335,6 +335,7 @@ func (s *OpenAIGatewayService) handleOpenAIWSErrorEventTransientFailure(ctx cont status := openAIWSPayloadTransientStatus(payload) if status != 0 { if status == http.StatusTooManyRequests { + ctx = context.WithValue(ctx, openAI429WeeklyHeadersKey{}, headers) headers = openAIWSSemantic429Headers(account, canonicalModel, headers) } s.handleOpenAIAccountUpstreamError(ctx, account, status, headers, payload, canonicalModel) @@ -716,6 +717,7 @@ func (s *OpenAIGatewayService) persistOpenAIWSRateLimitSignal(ctx context.Contex // 可能只是成功连接时的全局快照,不能用于普通模型的 429 账号级限流。 // 实际拨号 HTTP 429 使用 nil responseBody,必须保留响应头。 if len(responseBody) > 0 { + ctx = context.WithValue(ctx, openAI429WeeklyHeadersKey{}, headers) headers = openAIWSSemantic429Headers(account, model, headers) } s.handleOpenAIAccountUpstreamError(ctx, account, http.StatusTooManyRequests, headers, responseBody, model) diff --git a/docs/testing/oauth429-weekly-only.md b/docs/testing/oauth429-weekly-only.md index 682e3958db79..2a8515a960f6 100644 --- a/docs/testing/oauth429-weekly-only.md +++ b/docs/testing/oauth429-weekly-only.md @@ -1,7 +1,8 @@ # OAuth 429 weekly-only permanent disable Baseline: `f895ea743f34a4c4ab6c9d01c01e13c931625a6e`. -Only production change: `backend/internal/service/openai_disable_scheduling_429.go`. +Production scope: weekly policy, quota snapshot header provenance, and the three +stream/WS sites that separate permanent-policy evidence from temporary cooldown headers. All public fixtures are fictional. Local work is static only; dynamic evidence is produced by `.github/workflows/oauth429-weekly-only.yml` on GitHub Actions. @@ -14,13 +15,17 @@ unidentified quota observations fail closed without reusing cached high usage. The percentage is not inferred from a body `usage_limit_reached` or `limit_window_minutes` field. No maximum across percentages is selected. -When there are no current quota observation headers, cache fallback requires +When there is no current explicit weekly observation, cache fallback requires `codex_7d_window_minutes=10080` and retains account identity, percentage, observation, per-field provenance, staleness and reset checks. If field versions exist, both usage and window identity must have valid fresh versions from the same -source observation. A partial packet cannot borrow another packet's weekly identity. Legacy +source observation. A partial packet cannot borrow another packet's weekly identity. +Rejected weekly headers carry an observation timestamp through parser/persistence; +a later headerless 429 cannot trust usage from that packet. A newer valid weekly +observation may supply fresh evidence again. Temporary quota normalization is unchanged. Legacy snapshots without an explicit window no longer authorize a permanent disable. -Current unclassified/short-only quota headers continue to block cache fallback. +Nonweekly or unidentified headers do not veto independently valid weekly cache; +unidentified percentages themselves never count as weekly evidence. ## Execution coverage @@ -30,9 +35,11 @@ Current unclassified/short-only quota headers continue to block cache fallback. | `TestOAuth429WeeklyOnlyHeaderBoundaries` | Both weekly positions; zero/invalid/absent/5h neighbors; 5h-only 100; missing/low/invalid weekly; duplicates and conflicts; no reuse of high cache | | `TestOAuth429WeeklyOnlyCachedIdentity` | Explicit identity; global/field freshness; identity mismatch; future/stale/missing versions; absolute/relative resets | | `TestOAuth429WeeklyOnlyCacheDoesNotRelabelUnidentifiedUsage` | Actual parser/normalizer/merge; partial usage-only and window-only packets cannot combine into weekly evidence | +| `TestOAuth429WeeklyOnlyNonweeklyHeadersAllowExplicitCache` | Public RateLimitService: explicit fresh cached 99 with only 300-minute 100 and zero/invalid neighbor; absent/unidentified cache and equality remain closed | +| `TestOAuth429WeeklyOnlySequentialCache` | Public error service → actual parser → per-field persist/merge → reload → headerless 429; duplicate/conflicting/invalid weekly packets cannot poison cache | | `TestOAuth429WeeklyOnlyPolicyGates` | Own threshold, strict equality, invalid threshold, opt-out, non429, body-only weekly classification | | `TestOAuth429WeeklyOnlyHTTPForward` | Actual `Forward` entry, native and OAuth passthrough HTTP paths, mocked transport response, primary/secondary weekly zero-neighbor and negative cases | -| `TestOAuth429WeeklyOnlyWSForward` | Actual `Forward` entry, real loopback WS upstream handshake 429 and error frames, handshake quota and explicit-cache/body-only controls | +| `TestOAuth429WeeklyOnlyWSForward` | Actual `Forward` entry, real loopback WS upstream handshake 429 and error frames, handshake quota, fresh low/invalid versus high cache, and explicit-cache/body-only controls; observes upstream peer and retains event-reset temporary cooldown | | `TestOAuth429WeeklyOnlyWSClientIngress` | Real loopback client socket → `ProxyResponsesWebSocketFromClient` ctx_pool path → upstream adapter fixture → secondary weekly error frame | | `TestOAuth429WeeklyOnlyCombinedRotation` | Actual RateLimitService and auto2FA service together, real queue method with spy storage, manual snapshot untouched | | `TestOAuth429WeeklyOnlyRotationPreservesScheduling` | Isolated PostgreSQL: actual permanent scheduling write, real automatic rotation repository lifecycle success/failure, manual enable/disable after queueing, successful-test recovery | @@ -44,6 +51,10 @@ no paid calls or production writes occur. The repository lifecycle uses fictiona worker transitions; no real 2FA enrollment runs. The combined service and durable repository tests are separate boundaries, not a claimed end-to-end worker test. +The permanent policy receives original stream/WS headers through context before +temporary cooldown sanitization. Ordinary-model temporary cooldowns still discard +successful handshake quota headers and use their existing event/body policy. + ## Caller coverage limits The three direct entrances to the permanent policy are the common @@ -123,7 +134,7 @@ report. Line numbers refer to this change's source tree. | `openai_gateway_messages.go:641` | `handleAnthropicErrorResponse` | `handleCompatErrorResponse` | | `openai_gateway_passthrough.go:1024` | `handleFailoverErrorResponsePassthrough` | `handleOpenAIAccountUpstreamError` | | `openai_gateway_passthrough.go:1097` | `handleErrorResponsePassthrough` | `handleOpenAIAccountUpstreamError` | -| `openai_gateway_passthrough.go:1883` | `handleOpenAIStreamTerminalAccountSideEffects` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_passthrough.go:1884` | `handleOpenAIStreamTerminalAccountSideEffects` | `handleOpenAIAccountUpstreamError` | | `openai_gateway_responses_chat_fallback.go:179` | `forwardResponsesViaRawChatCompletions` | `handleErrorResponse` | | `openai_gateway_upstream_errors.go:597` | `handleFailoverSideEffects` | `handleOpenAIAccountUpstreamError` | | `openai_gateway_upstream_errors.go:599` | `handleFailoverSideEffects` | `handleOpenAIAccountUpstreamError` | @@ -139,10 +150,10 @@ report. Line numbers refer to this change's source tree. | `openai_ws_forwarder_ingress.go:1992` | `ProxyResponsesWebSocketFromClient` | `handleOpenAIWSErrorEventTransientFailure` | | `openai_ws_forwarder_ingress.go:2160` | `ProxyResponsesWebSocketFromClient` | `handleOpenAIWSTerminalTransientFailure` | | `openai_ws_forwarder_support.go:325` | `handleOpenAIWSTerminalTransientFailure` | `handleOpenAIWSFailureAccountSideEffects` | -| `openai_ws_forwarder_support.go:340` | `handleOpenAIWSErrorEventTransientFailure` | `handleOpenAIAccountUpstreamError` | -| `openai_ws_forwarder_support.go:367` | `handleOpenAIWSFailureAccountSideEffects` | `handleOpenAIAccountUpstreamError` | -| `openai_ws_forwarder_support.go:379` | `handleOpenAIWSDialTransientFailure` | `handleOpenAIAccountUpstreamError` | -| `openai_ws_forwarder_support.go:721` | `persistOpenAIWSRateLimitSignal` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:341` | `handleOpenAIWSErrorEventTransientFailure` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:368` | `handleOpenAIWSFailureAccountSideEffects` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:380` | `handleOpenAIWSDialTransientFailure` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:723` | `persistOpenAIWSRateLimitSignal` | `handleOpenAIAccountUpstreamError` | | `openai_ws_forwarder_v2.go:379` | `forwardOpenAIWSV2` | `handleOpenAIWSDialTransientFailure` | | `openai_ws_forwarder_v2.go:958` | `forwardOpenAIWSV2` | `handleOpenAIWSErrorEventTransientFailure` | | `openai_ws_forwarder_v2.go:1085` | `forwardOpenAIWSV2` | `handleOpenAIWSTerminalTransientFailure` | From b25c957218dd46ed6e3b7d569cc6f0f3b0a942ee Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:15:55 +0800 Subject: [PATCH 24/38] fix: retain validated weekly cache and expire WebSocket handshake evidence --- .../scripts/oauth429-weekly-only-evidence.py | 8 +- .github/workflows/oauth429-weekly-only.yml | 14 ++- .../oauth429_weekly_only_integration_test.go | 69 +++++++++++++ .../oauth429_weekly_only_gateway_test.go | 16 +++ .../service/oauth429_weekly_only_test.go | 27 +++++- .../service/openai_disable_scheduling_429.go | 97 ++++++++++++++++++- .../service/openai_gateway_passthrough.go | 18 ++-- .../internal/service/openai_gateway_usage.go | 5 +- .../internal/service/openai_quota_recovery.go | 3 + .../service/openai_ws_forwarder_ingress.go | 6 +- .../service/openai_ws_forwarder_support.go | 6 +- .../service/openai_ws_forwarder_v2.go | 6 +- .../openai_ws_v2_passthrough_adapter.go | 1 + docs/testing/oauth429-weekly-only.md | 8 +- 14 files changed, 255 insertions(+), 29 deletions(-) diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index 95e962f69b5c..c9099e2f4ab1 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -34,6 +34,8 @@ assert int(status) == 1 and terminal[0]["Action"] == "fail", "expected normal go test assertion failure" if mode == "red-cache": assert "TestOAuth429WeeklyOnlySequentialCache/duplicate_usage" in failed + assert "TestOAuth429WeeklyOnlySequentialCache/nan_weekly_usage" in failed + assert "TestOAuth429WeeklyOnlyNonweeklyPersistenceRetainsEvidence" in failed assert "rejected weekly headers must not poison a later headerless 429 cache" in output else: for name in ("primary_weekly_zero_neighbor", "secondary_weekly_invalid_neighbor"): @@ -50,6 +52,8 @@ "WSForward/frame_with_weekly_handshake", "WSForward/frame_low_overrides_high_cache", "WSForward/frame_invalid_overrides_high_cache", + "WSForward/frame_elapsed_handshake_reset", + "NonweeklyPersistenceRetainsEvidence", "WSClientIngress", ): assert "TestOAuth429WeeklyOnly" + name in failed, name @@ -57,9 +61,9 @@ assert "request admission denied:" not in output else: assert int(status) == 0 and not failed and terminal[0]["Action"] == "pass", "candidate failed" - required = ["RotationPreservesScheduling"] if mode == "repository" else [ + required = ["RotationPreservesScheduling", "InvalidWeeklyPersistence", "NonweeklyPersistenceRetainsEvidence"] if mode == "repository" else [ "Service", "HeaderBoundaries", "CachedIdentity", "NonweeklyHeadersAllowExplicitCache", - "CacheDoesNotRelabelUnidentifiedUsage", "SequentialCache", "PolicyGates", + "CacheDoesNotRelabelUnidentifiedUsage", "SequentialCache", "NonweeklyPersistenceRetainsEvidence", "PolicyGates", "HTTPForward", "WSForward", "WSClientIngress", "CombinedRotation", ] for name in required: diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 3edff8d5e88e..b01b8ce212f7 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -9,6 +9,10 @@ on: - 'backend/internal/service/openai_gateway_usage.go' - 'backend/internal/service/openai_gateway_passthrough.go' - 'backend/internal/service/openai_ws_forwarder_support.go' + - 'backend/internal/service/openai_ws_forwarder_v2.go' + - 'backend/internal/service/openai_ws_forwarder_ingress.go' + - 'backend/internal/service/openai_ws_v2_passthrough_adapter.go' + - 'backend/internal/service/openai_quota_recovery.go' - 'backend/internal/repository/oauth429_weekly_only*' - '.github/workflows/oauth429-weekly-only.yml' - '.github/scripts/oauth429-weekly-only-*' @@ -54,6 +58,10 @@ jobs: 9fb1903315d1f086f4f38bd73a5a0a5f69f6542a backend/internal/service/openai_gateway_usage.go 9dfffb6d6280278c5c21015ddffad12b706efa5c backend/internal/service/openai_ws_forwarder_support.go aa0c3dafdf9e9e3f5ec78467fa08899c67e9ec89 backend/internal/service/openai_gateway_passthrough.go + 3af551183471cd0ac3b2a6baa27aa506975dce96 backend/internal/service/openai_ws_forwarder_v2.go + fcff9837e12c0aa9c3ea3e22724f923890681fe1 backend/internal/service/openai_ws_forwarder_ingress.go + aee0bb83694c375d5baf431db916ea093a1658f4 backend/internal/service/openai_ws_v2_passthrough_adapter.go + 696cd27a7aa58e6503e57c0b64bb341388c6ce3e backend/internal/service/openai_quota_recovery.go BLOBS git -C "$RUNNER_TEMP/oauth429-red" diff --stat > evidence/red-diff.txt git ls-files 'backend/internal/service/*429*test.go' 'backend/internal/repository/oauth429_weekly_only*test.go' > evidence/retained-tests.txt @@ -91,7 +99,7 @@ jobs: git -C "$RUNNER_TEMP/oauth429-cache-red" diff --exit-code -- '*_test.go' git -C "$RUNNER_TEMP/oauth429-cache-red" diff --stat > evidence/cache-red-diff.txt set +e - (cd "$RUNNER_TEMP/oauth429-cache-red/backend" && go test -json -tags=unit ./internal/service -run '^TestOAuth429WeeklyOnlySequentialCache$' -count=1 -timeout=10m) > evidence/red-cache.jsonl 2> evidence/red-cache.stderr + (cd "$RUNNER_TEMP/oauth429-cache-red/backend" && go test -json -tags=unit ./internal/service -run '^TestOAuth429WeeklyOnly(SequentialCache|NonweeklyPersistenceRetainsEvidence)$' -count=1 -timeout=10m) > evidence/red-cache.jsonl 2> evidence/red-cache.stderr result=$? set -e printf '%s\n' "$result" > evidence/red-cache-exit.txt @@ -123,7 +131,7 @@ jobs: git rev-parse HEAD HEAD^{tree} > evidence/candidate.txt git diff --exit-code set +e - (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|Weekly429Threshold|TOTPRotationOn429|OpenAIStream429|CalculateOpenAI429ResetTime)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr + (cd backend && go test -race -json -tags=unit ./internal/service -run '^Test(OAuth429WeeklyOnly|DisableScheduling429|RateLimitDisableSchedulingOn429|OpenAIGatewayDisableSchedulingOn429|Managed429WeeklyPolicy|Weekly429Threshold|TOTPRotationOn429|OpenAIStream429|OpenAIQuotaRecovery|CalculateOpenAI429ResetTime)' -count=1 -timeout=10m) > evidence/green.jsonl 2> evidence/green.stderr result=$? set -e printf '%s\n' "$result" > evidence/green-exit.txt @@ -136,7 +144,7 @@ jobs: run: | set -euo pipefail set +e - (cd backend && go test -json -tags=integration ./internal/repository -run '^TestOAuth429WeeklyOnlyRotationPreservesScheduling$' -count=1 -timeout=10m) > evidence/green-repository.jsonl 2> evidence/green-repository.stderr + (cd backend && go test -json -tags=integration ./internal/repository -run '^TestOAuth429WeeklyOnly' -count=1 -timeout=10m) > evidence/green-repository.jsonl 2> evidence/green-repository.stderr result=$? set -e printf '%s\n' "$result" > evidence/green-repository-exit.txt diff --git a/backend/internal/repository/oauth429_weekly_only_integration_test.go b/backend/internal/repository/oauth429_weekly_only_integration_test.go index 72382e72b54a..3ed1b967d337 100644 --- a/backend/internal/repository/oauth429_weekly_only_integration_test.go +++ b/backend/internal/repository/oauth429_weekly_only_integration_test.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/service" @@ -65,3 +66,71 @@ func TestOAuth429WeeklyOnlyRotationPreservesScheduling(t *testing.T) { } } } + +func TestOAuth429WeeklyOnlyInvalidWeeklyPersistence(t *testing.T) { + for _, usage := range []string{"NaN", "+Inf", "duplicate"} { + t.Run(usage, func(t *testing.T) { + ctx, _, cfg := totpRotationFixture(t) + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + require.NoError(t, accounts.SetSchedulable(ctx, cfg.AccountID, true)) + old := map[string]any{ + service.OpenAIDisableSchedulingOn429ExtraKey: true, + "codex_7d_used_percent": 99.0, "codex_7d_window_minutes": 10080, + "codex_usage_updated_at": time.Now().Add(-time.Minute).Format(time.RFC3339Nano), + } + require.NoError(t, accounts.UpdateExtra(ctx, cfg.AccountID, old)) + a, err := accounts.GetByID(ctx, cfg.AccountID) + require.NoError(t, err) + h := http.Header{} + h.Set("x-codex-primary-window-minutes", "10080") + h.Set("x-codex-primary-used-percent", usage) + if usage == "duplicate" { + h["X-Codex-Primary-Used-Percent"] = []string{"99", "20"} + } + rates := service.NewRateLimitService(accounts, nil, &config.Config{}, nil, nil) + rates.HandleUpstreamError(ctx, a, 429, h, nil) + a, err = accounts.GetByID(ctx, cfg.AccountID) + require.NoError(t, err) + require.True(t, a.Schedulable) + require.Contains(t, a.Extra, "codex_7d_permanent_disable_invalid_at", "invalid weekly provenance must survive real JSONB persistence") + // A delayed earlier valid packet cannot clear newer invalid provenance. + require.NoError(t, accounts.UpdateExtra(ctx, a.ID, old)) + a, err = accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + rates.HandleUpstreamError(ctx, a, 429, nil, nil) + a, err = accounts.GetByID(ctx, cfg.AccountID) + require.NoError(t, err) + require.True(t, a.Schedulable, "a rejected weekly packet must not poison a later headerless 429") + }) + } +} + +func TestOAuth429WeeklyOnlyNonweeklyPersistenceRetainsEvidence(t *testing.T) { + ctx, _, cfg := totpRotationFixture(t) + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + require.NoError(t, accounts.SetSchedulable(ctx, cfg.AccountID, true)) + rates := service.NewRateLimitService(accounts, nil, &config.Config{}, nil, nil) + a, err := accounts.GetByID(ctx, cfg.AccountID) + require.NoError(t, err) + // Feature is initially off: persist a real explicit weekly observation + // through the parser/repository without a permanent scheduling write. + h := http.Header{} + h.Set("x-codex-primary-window-minutes", "10080") + h.Set("x-codex-primary-used-percent", "99") + rates.HandleUpstreamError(ctx, a, 429, h, nil) + a, err = accounts.GetByID(ctx, cfg.AccountID) + require.NoError(t, err) + h.Set("x-codex-primary-window-minutes", "300") + h.Set("x-codex-primary-used-percent", "100") + h.Set("x-codex-secondary-window-minutes", "0") + h.Set("x-codex-secondary-used-percent", "0") + rates.HandleUpstreamError(ctx, a, 429, h, nil) + require.NoError(t, accounts.UpdateExtra(ctx, a.ID, map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: true})) + a, err = accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + require.True(t, a.Schedulable) + rates.HandleUpstreamError(ctx, a, 429, nil, nil) + a, err = accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + require.False(t, a.Schedulable, "nonweekly JSONB updates must retain the valid weekly observation") +} diff --git a/backend/internal/service/oauth429_weekly_only_gateway_test.go b/backend/internal/service/oauth429_weekly_only_gateway_test.go index 6746304b45df..43aad89288bd 100644 --- a/backend/internal/service/oauth429_weekly_only_gateway_test.go +++ b/backend/internal/service/oauth429_weekly_only_gateway_test.go @@ -103,6 +103,7 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { {"frame_with_explicit_cache", true, true, true}, {"frame_low_overrides_high_cache", true, true, false}, {"frame_invalid_overrides_high_cache", true, true, false}, + {"frame_elapsed_handshake_reset", true, true, false}, } { t.Run(tc.name, func(t *testing.T) { h := weekly429Headers("99", "0", false) @@ -121,6 +122,10 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { if tc.name == "body_only_no_percentage" || tc.name == "frame_with_explicit_cache" { h = http.Header{} } + if tc.name == "frame_elapsed_handshake_reset" { + h.Set("x-codex-primary-reset-after-seconds", "1") + } + var poolRef atomic.Pointer[openAIWSConnPool] var peers atomic.Int64 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { peers.Add(1) @@ -144,6 +149,16 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { t.Errorf("read: %v", err) return } + if tc.name == "frame_elapsed_handshake_reset" { + // Simulate elapsed connection time after the actual peer read, + // before the error frame; no sleep or alternate helper path. + ap := poolRef.Load().getOrCreateAccountPool(42) + ap.mu.Lock() + for _, pooled := range ap.conns { + pooled.createdAtNano.Store(time.Now().Add(-time.Minute).UnixNano()) + } + ap.mu.Unlock() + } _ = conn.WriteJSON(map[string]any{"type": "error", "error": map[string]any{"type": "usage_limit_reached", "code": "rate_limit_exceeded", "message": "fictional quota rejection", "limit_window_minutes": 10080, "resets_in_seconds": 7200}}) })) defer server.Close() @@ -168,6 +183,7 @@ func TestOAuth429WeeklyOnlyWSForward(t *testing.T) { defer pool.Close() pool.setClientDialerForTest(&openAIWSQuotaLocalDialer{url: "ws" + strings.TrimPrefix(server.URL, "http")}) gateway.openaiWSPool = pool + poolRef.Store(pool) rates.SetAccountRuntimeBlocker(gateway) rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) diff --git a/backend/internal/service/oauth429_weekly_only_test.go b/backend/internal/service/oauth429_weekly_only_test.go index b1dc7a7e1911..2d3bb56a97db 100644 --- a/backend/internal/service/oauth429_weekly_only_test.go +++ b/backend/internal/service/oauth429_weekly_only_test.go @@ -4,6 +4,7 @@ package service import ( "context" + "encoding/json" "fmt" "net/http" "strconv" @@ -335,6 +336,9 @@ type weeklyOnlyPersistedRepo struct { } func (r *weeklyOnlyPersistedRepo) UpdateExtra(_ context.Context, _ int64, updates map[string]any) error { + if _, err := json.Marshal(updates); err != nil { + return err + } r.stored.Extra = mergeCodexUsageUpdates(r.stored.Extra, updates) return nil } @@ -354,10 +358,12 @@ func TestOAuth429WeeklyOnlySequentialCache(t *testing.T) { {"conflicting_window", "x-codex-primary-window-minutes", []string{"10080", "300"}}, {"conflicting_weekly_windows", "x-codex-secondary-window-minutes", []string{"10080"}}, {"invalid_weekly_usage", "x-codex-primary-used-percent", []string{"invalid"}}, + {"nan_weekly_usage", "x-codex-primary-used-percent", []string{"NaN"}}, + {"infinite_weekly_usage", "x-codex-primary-used-percent", []string{"+Inf"}}, } { t.Run(tc.name, func(t *testing.T) { a := scheduling429Account() - initial := ParseCodexRateLimitHeaders(weekly429Headers("20", "0", false)) + initial := ParseCodexRateLimitHeaders(weekly429Headers("99", "0", false)) initial.UpdatedAt = time.Now().Add(-time.Minute).Format(time.RFC3339Nano) a.Extra = mergeCodexUsageUpdates(a.Extra, buildCodexUsageExtraUpdates(initial, time.Now())) repo := &weeklyOnlyPersistedRepo{stored: a} @@ -382,3 +388,22 @@ func TestOAuth429WeeklyOnlySequentialCache(t *testing.T) { }) } } + +func TestOAuth429WeeklyOnlyNonweeklyPersistenceRetainsEvidence(t *testing.T) { + a := scheduling429Account() + weekly := ParseCodexRateLimitHeaders(weekly429Headers("99", "0", false)) + weekly.UpdatedAt = time.Now().Add(-time.Minute).Format(time.RFC3339Nano) + a.Extra = mergeCodexUsageUpdates(a.Extra, buildCodexUsageExtraUpdates(weekly, time.Now())) + repo := &weeklyOnlyPersistedRepo{stored: a} + nonweekly := http.Header{} + nonweekly.Set("x-codex-primary-window-minutes", "300") + nonweekly.Set("x-codex-primary-used-percent", "100") + nonweekly.Set("x-codex-secondary-window-minutes", "0") + nonweekly.Set("x-codex-secondary-used-percent", "0") + require.NoError(t, repo.UpdateExtra(t.Context(), a.ID, buildCodexUsageExtraUpdates(ParseCodexRateLimitHeaders(nonweekly), time.Now()))) + reloaded, err := repo.GetByID(t.Context(), a.ID) + require.NoError(t, err) + rates := NewRateLimitService(repo, nil, &config.Config{}, nil, nil) + rates.HandleUpstreamError(t.Context(), reloaded, 429, nil, nil) + require.Equal(t, []bool{false}, repo.values, "nonweekly persistence must retain independently valid weekly evidence") +} diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index 77c8935746cf..a59aa04c1b37 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -16,6 +16,7 @@ const ( OpenAIDisableSchedulingOn4297dThresholdExtraKey = "openai_disable_scheduling_on_429_7d_threshold_percent" DefaultOpenAIDisableSchedulingOn4297dThresholdPercent = 98.0 openAI429WeeklyInvalidAtKey = "codex_7d_permanent_disable_invalid_at" + openAI429WeeklyEvidenceKey = "codex_7d_permanent_disable_evidence" ) func openAI429WeeklyThreshold(account *Account) (float64, bool) { @@ -93,14 +94,61 @@ func openAI429WeeklyParsedHeaderUsage(headers http.Header, snapshot *OpenAICodex return *weekly, true, true } -func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time) (float64, bool) { +func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time, observedAt ...time.Time) (float64, bool) { if used, present, valid := openAI429WeeklyHeaderUsage(headers); present { + if valid && len(observedAt) > 0 { + observed := observedAt[0] + if observed.IsZero() || observed.After(now) || now.Sub(observed) >= openAICodexAutoPauseStaleAfter { + return 0, false + } + for _, window := range []string{"primary", "secondary"} { + prefix := "x-codex-" + window + "-" + minutes, _ := strconv.Atoi(headers.Get(prefix + "window-minutes")) + if minutes == 7*24*60 && len(headers.Values(prefix+"reset-after-seconds")) > 0 { + seconds, _ := strconv.ParseInt(headers.Get(prefix+"reset-after-seconds"), 10, 64) + if !observed.Add(time.Duration(seconds) * time.Second).After(now) { + return 0, false + } + } + } + } return used, valid } if !openAICodexSnapshotIdentityTrusted(account) { return 0, false } extra := account.Extra + if raw, exists := extra[openAI429WeeklyEvidenceKey]; exists { + evidence, ok := raw.(map[string]any) + if !ok { + return 0, false + } + // The complete validated observation is one versioned value. Legacy + // normalization of nonweekly packets cannot overwrite its identity. + proofExtra := map[string]any{ + "codex_7d_used_percent": evidence["used_percent"], + "codex_7d_window_minutes": evidence["window_minutes"], + "codex_usage_updated_at": evidence["observed_at"], + } + if reset, exists := evidence["reset_after_seconds"]; exists { + proofExtra["codex_7d_reset_after_seconds"] = reset + } + if invalidAt, exists := extra[openAI429WeeklyInvalidAtKey]; exists { + proofExtra[openAI429WeeklyInvalidAtKey] = invalidAt + } + if rawVersions, exists := extra[CodexUsageFieldVersionsKey]; exists { + versions, ok := rawVersions.(map[string]any) + stamp, err := strconv.ParseInt(fmt.Sprint(versions[openAI429WeeklyEvidenceKey]), 10, 64) + if !ok || err != nil || stamp <= 0 || !codexUpdatesTime(proofExtra).Equal(time.Unix(0, stamp)) { + return 0, false + } + proofExtra[CodexUsageFieldVersionsKey] = map[string]any{ + "codex_7d_used_percent": stamp, "codex_7d_window_minutes": stamp, + "codex_7d_reset_after_seconds": stamp, + } + } + extra = proofExtra + } // A normalized legacy primary snapshot may have no window identity. Its // "7d" field name alone is not evidence for a permanent scheduling change. minutes, ok := resolveAccountExtraNumber(extra, "codex_7d_window_minutes") @@ -174,6 +222,38 @@ func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time) return used, true } +func openAI429WeeklyEvidence(used float64, observed time.Time, reset *int) map[string]any { + evidence := map[string]any{"used_percent": used, "window_minutes": 7 * 24 * 60, "observed_at": observed.Format(time.RFC3339Nano)} + if reset != nil { + evidence["reset_after_seconds"] = *reset + } + return evidence +} + +func openAI429SnapshotWeeklyEvidence(snapshot *OpenAICodexUsageSnapshot, observed time.Time) map[string]any { + if snapshot.invalidWeekly429 { + return nil + } + var evidence map[string]any + for _, window := range []struct { + minutes, reset *int + used *float64 + }{ + {snapshot.PrimaryWindowMinutes, snapshot.PrimaryResetAfterSeconds, snapshot.PrimaryUsedPercent}, + {snapshot.SecondaryWindowMinutes, snapshot.SecondaryResetAfterSeconds, snapshot.SecondaryUsedPercent}, + } { + if window.minutes == nil || *window.minutes != 7*24*60 { + continue + } + if evidence != nil || window.used == nil || !validOpenAI429Percent(*window.used) || + (window.reset != nil && (*window.reset <= 0 || *window.reset > 7*24*60*60)) { + return nil + } + evidence = openAI429WeeklyEvidence(*window.used, observed, window.reset) + } + return evidence +} + func openAIDisableSchedulingOn429Enabled(account *Account) bool { // Evaluate the persisted owner, not a managed connection's projected type. if account == nil || account.ID <= 0 || account.Platform != PlatformOpenAI || account.Type != AccountTypeOAuth || @@ -190,6 +270,15 @@ type openAIDisableScheduling429ObservedKey struct{} // opt-in permanent weekly policy still needs that observation, including lows // and invalid evidence that must prevent fallback to an older high snapshot. type openAI429WeeklyHeadersKey struct{} +type openAI429WeeklyObservedAtKey struct{} + +func openAI429LeaseObservation(ctx context.Context, lease *openAIWSConnLease) context.Context { + var observed time.Time + if lease != nil && lease.conn != nil { + observed = lease.conn.createdAt() + } + return context.WithValue(ctx, openAI429WeeklyObservedAtKey{}, observed) +} type openAIDisableScheduling429Observation struct { accountID int64 @@ -234,7 +323,11 @@ func (s *RateLimitService) maybeDisableOpenAISchedulingOn429(ctx context.Context if evidence, ok := ctx.Value(openAI429WeeklyHeadersKey{}).(http.Header); ok { headers = evidence } - used, usageValid := openAI429WeeklyUsage(owner, headers, time.Now()) + var observedAt []time.Time + if observed, ok := ctx.Value(openAI429WeeklyObservedAtKey{}).(time.Time); ok { + observedAt = []time.Time{observed} + } + used, usageValid := openAI429WeeklyUsage(owner, headers, time.Now(), observedAt...) if !thresholdValid || !usageValid || used <= threshold { return ctx, false } diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index c7c8a79fba45..c1833fc0e65a 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -1843,16 +1843,22 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects( message string, headers http.Header, canonicalModel ...string, +) (int, bool) { + ctx := context.Background() + if c != nil && c.Request != nil { + ctx = c.Request.Context() + } + return s.handleOpenAIStreamTerminalAccountSideEffectsWithContext(ctx, account, payload, message, headers, canonicalModel...) +} + +func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffectsWithContext( + ctx context.Context, account *Account, payload []byte, message string, headers http.Header, canonicalModel ...string, ) (int, bool) { statusCode := openAIStreamFailureStatus(payload, message) if account != nil && account.IsGrok() { if isGrokContentPolicyRejection(http.StatusForbidden, payload) { return http.StatusForbidden, false } - ctx := context.Background() - if c != nil && c.Request != nil { - ctx = c.Request.Context() - } s.handleGrokAccountUpstreamError(withGrokTeamRateLimitModel(ctx, firstNonEmpty(canonicalModel...)), account, statusCode, nil, payload) return statusCode, false } @@ -1866,10 +1872,6 @@ func (s *OpenAIGatewayService) handleOpenAIStreamTerminalAccountSideEffects( } fallthrough case http.StatusUnauthorized, http.StatusTooManyRequests, http.StatusServiceUnavailable, 529: - ctx := context.Background() - if c != nil && c.Request != nil { - ctx = c.Request.Context() - } model := firstNonEmpty(canonicalModel...) if model == "" { model = firstNonEmpty(gjson.GetBytes(payload, "model").String(), gjson.GetBytes(payload, "response.model").String()) diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 1a82b648251f..073ca9710e28 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -1092,7 +1092,7 @@ func ParseCodexRateLimitHeaders(headers http.Header) *OpenAICodexUsageSnapshot { // Helper to parse float64 from header parseFloat := func(key string) *float64 { if v := headers.Get(key); v != "" { - if f, err := strconv.ParseFloat(v, 64); err == nil { + if f, err := strconv.ParseFloat(v, 64); err == nil && !math.IsNaN(f) && !math.IsInf(f, 0) { return &f } } @@ -1189,6 +1189,9 @@ func buildCodexUsageExtraUpdates(snapshot *OpenAICodexUsageSnapshot, fallbackNow if snapshot.invalidWeekly429 { updates[openAI429WeeklyInvalidAtKey] = baseTime.Format(time.RFC3339Nano) } + if evidence := openAI429SnapshotWeeklyEvidence(snapshot, baseTime); evidence != nil { + updates[openAI429WeeklyEvidenceKey] = evidence + } // 保存原始 primary/secondary 字段,便于排查问题 if snapshot.PrimaryUsedPercent != nil { diff --git a/backend/internal/service/openai_quota_recovery.go b/backend/internal/service/openai_quota_recovery.go index 696cd27a7aa5..4b50f7398b84 100644 --- a/backend/internal/service/openai_quota_recovery.go +++ b/backend/internal/service/openai_quota_recovery.go @@ -100,5 +100,8 @@ func openAIQuotaRecoveryUsageUpdates(body []byte, now time.Time) map[string]any if len(updates) != 3 { return nil } + // This body explicitly identifies a recovered weekly window. Supersede any + // older retained header evidence alongside the existing zero-usage update. + updates[openAI429WeeklyEvidenceKey] = openAI429WeeklyEvidence(0, now.Truncate(time.Second), nil) return updates } diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index fcff9837e12c..2ac3b0ec9170 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1989,7 +1989,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( s.markOpenAIWSInvalidEncryptedContentLineageFromPayload(c, payload, "ingress_ws_invalid_encrypted_lineage_mark", account.ID, turn, upstreamMessage) } if eventType == "error" { - s.handleOpenAIWSErrorEventTransientFailure(ctx, account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) + s.handleOpenAIWSErrorEventTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) errCodeRaw, errTypeRaw, errMsgRaw := parseOpenAIWSErrorEventFields(upstreamMessage) statusCode := openAIWSRejectedFieldRetryHTTPStatus(upstreamMessage) if !smartStrict && OpenAIWSAgentRecoveryCanRetry(ctx) && !wroteDownstream && statusCode == http.StatusBadRequest && rejectedFieldRetryState != nil { @@ -2015,7 +2015,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } } } - s.persistOpenAIWSRateLimitSignal(ctx, account, lease.HandshakeHeaders(), upstreamMessage, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) + s.persistOpenAIWSRateLimitSignal(openAI429LeaseObservation(ctx, lease), account, lease.HandshakeHeaders(), upstreamMessage, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) fallbackReason, _ := classifyOpenAIWSErrorEventFromRaw(errCodeRaw, errTypeRaw, errMsgRaw) if fallbackReason == openAIWSFallbackReasonInvalidEncryptedContent { // 记录被上游拒绝的密文摘要;错误照旧透传,下一轮进场时按摘要预剥离。 @@ -2157,7 +2157,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } } if isTerminalEvent { - terminalEvent := s.handleOpenAIWSTerminalTransientFailure(ctx, account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) + terminalEvent := s.handleOpenAIWSTerminalTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), upstreamMessage) // 客户端已断连时,上游连接的 session 状态不可信,标记 broken 避免回池复用。 if clientDisconnected { lease.MarkBroken() diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go index 682049cc7b36..2da08dc464fa 100644 --- a/backend/internal/service/openai_ws_forwarder_support.go +++ b/backend/internal/service/openai_ws_forwarder_support.go @@ -140,7 +140,7 @@ func (s *OpenAIGatewayService) performOpenAIWSGeneratePrewarm( if eventType == "error" { errCodeRaw, errTypeRaw, errMsgRaw := parseOpenAIWSErrorEventFields(message) prewarmModel, _ := reqBody["model"].(string) - s.persistOpenAIWSRateLimitSignal(ctx, account, lease.HandshakeHeaders(), message, errCodeRaw, errTypeRaw, errMsgRaw, prewarmModel) + s.persistOpenAIWSRateLimitSignal(openAI429LeaseObservation(ctx, lease), account, lease.HandshakeHeaders(), message, errCodeRaw, errTypeRaw, errMsgRaw, prewarmModel) errMsg := strings.TrimSpace(errMsgRaw) if errMsg == "" { errMsg = "OpenAI websocket prewarm error" @@ -351,13 +351,13 @@ func (s *OpenAIGatewayService) handleOpenAIWSFailureAccountSideEffects(ctx conte s.rateLimitService.observeQualityStatus(ctx, account, status) switch status { case http.StatusUnauthorized, http.StatusTooManyRequests, 529: - s.handleOpenAIStreamTerminalAccountSideEffects(nil, account, payload, message, headers, canonicalModel) + s.handleOpenAIStreamTerminalAccountSideEffectsWithContext(ctx, account, payload, message, headers, canonicalModel) return true case http.StatusForbidden: if !openAIStream403AccountFailure(payload, message) { return false } - s.handleOpenAIStreamTerminalAccountSideEffects(nil, account, payload, message, headers, canonicalModel) + s.handleOpenAIStreamTerminalAccountSideEffectsWithContext(ctx, account, payload, message, headers, canonicalModel) return true } diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index 3af551183471..3f70a8a5527c 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -955,9 +955,9 @@ readLoop: // account failover for a request the provider already received. flushBufferedStreamEvents("error_event") } - s.handleOpenAIWSErrorEventTransientFailure(ctx, account, mappedModel, lease.HandshakeHeaders(), message) + s.handleOpenAIWSErrorEventTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), message) errCodeRaw, errTypeRaw, errMsgRaw := parseOpenAIWSErrorEventFields(message) - s.persistOpenAIWSRateLimitSignal(ctx, account, lease.HandshakeHeaders(), message, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) + s.persistOpenAIWSRateLimitSignal(openAI429LeaseObservation(ctx, lease), account, lease.HandshakeHeaders(), message, errCodeRaw, errTypeRaw, errMsgRaw, mappedModel) errMsg := sanitizeUpstreamErrorMessage(strings.TrimSpace(errMsgRaw)) if errMsg == "" { errMsg = "Upstream websocket error" @@ -1082,7 +1082,7 @@ readLoop: if !clientDisconnected { markOpenAIWSClientVisibleFailure(c, eventType, message) } - upstreamTerminalEvent = s.handleOpenAIWSTerminalTransientFailure(ctx, account, mappedModel, lease.HandshakeHeaders(), message) + upstreamTerminalEvent = s.handleOpenAIWSTerminalTransientFailure(openAI429LeaseObservation(ctx, lease), account, mappedModel, lease.HandshakeHeaders(), message) // A terminal event must be the final JSON document in its WS message. // Ignore any tail for the completed client turn, but never reuse the // ambiguous upstream connection for another request. diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index aee0bb83694c..621f28013de9 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -988,6 +988,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( defer func() { _ = upstreamConn.Close() }() + ctx = context.WithValue(ctx, openAI429WeeklyObservedAtKey{}, time.Now()) handshakeBinding := s.bindOpenAIWSHandshake(account, gjson.GetBytes(firstClientMessage, "model").String(), headers) logOpenAIWSV2Passthrough( "relay_dial_ok account_id=%d status_code=%d upstream_request_id=%s", diff --git a/docs/testing/oauth429-weekly-only.md b/docs/testing/oauth429-weekly-only.md index 2a8515a960f6..4a864199fd5d 100644 --- a/docs/testing/oauth429-weekly-only.md +++ b/docs/testing/oauth429-weekly-only.md @@ -2,7 +2,7 @@ Baseline: `f895ea743f34a4c4ab6c9d01c01e13c931625a6e`. Production scope: weekly policy, quota snapshot header provenance, and the three -stream/WS sites that separate permanent-policy evidence from temporary cooldown headers. +stream/WS sites that separate permanent-policy evidence from temporary cooldown headers, retained handshake observation time, and explicit zero-quota recovery evidence. All public fixtures are fictional. Local work is static only; dynamic evidence is produced by `.github/workflows/oauth429-weekly-only.yml` on GitHub Actions. @@ -22,7 +22,7 @@ exist, both usage and window identity must have valid fresh versions from the sa source observation. A partial packet cannot borrow another packet's weekly identity. Rejected weekly headers carry an observation timestamp through parser/persistence; a later headerless 429 cannot trust usage from that packet. A newer valid weekly -observation may supply fresh evidence again. Temporary quota normalization is unchanged. Legacy +observation may supply fresh evidence again. Validated weekly usage is also retained as one versioned observation, independently of legacy normalized windows. Nonweekly updates cannot erase it; explicit weekly zero recovery supersedes it. Temporary quota normalization is unchanged. Legacy snapshots without an explicit window no longer authorize a permanent disable. Nonweekly or unidentified headers do not veto independently valid weekly cache; unidentified percentages themselves never count as weekly evidence. @@ -37,9 +37,11 @@ unidentified percentages themselves never count as weekly evidence. | `TestOAuth429WeeklyOnlyCacheDoesNotRelabelUnidentifiedUsage` | Actual parser/normalizer/merge; partial usage-only and window-only packets cannot combine into weekly evidence | | `TestOAuth429WeeklyOnlyNonweeklyHeadersAllowExplicitCache` | Public RateLimitService: explicit fresh cached 99 with only 300-minute 100 and zero/invalid neighbor; absent/unidentified cache and equality remain closed | | `TestOAuth429WeeklyOnlySequentialCache` | Public error service → actual parser → per-field persist/merge → reload → headerless 429; duplicate/conflicting/invalid weekly packets cannot poison cache | +| `TestOAuth429WeeklyOnlyInvalidWeeklyPersistence` | Real PostgreSQL JSONB: NaN/Inf/duplicate weekly headers, prior-high cache, reload, delayed older snapshot, headerless 429 | +| `TestOAuth429WeeklyOnlyNonweeklyPersistenceRetainsEvidence` | Parser/merge and production PostgreSQL variants preserve weekly 99 across subsequent 5h/zero persistence and reload | | `TestOAuth429WeeklyOnlyPolicyGates` | Own threshold, strict equality, invalid threshold, opt-out, non429, body-only weekly classification | | `TestOAuth429WeeklyOnlyHTTPForward` | Actual `Forward` entry, native and OAuth passthrough HTTP paths, mocked transport response, primary/secondary weekly zero-neighbor and negative cases | -| `TestOAuth429WeeklyOnlyWSForward` | Actual `Forward` entry, real loopback WS upstream handshake 429 and error frames, handshake quota, fresh low/invalid versus high cache, and explicit-cache/body-only controls; observes upstream peer and retains event-reset temporary cooldown | +| `TestOAuth429WeeklyOnlyWSForward` | Actual `Forward` entry, real loopback WS upstream handshake 429 and error frames, handshake quota, elapsed handshake reset (simulated on an actual connection after peer read), fresh low/invalid versus high cache, and explicit-cache/body-only controls; observes upstream peer and retains event-reset temporary cooldown | | `TestOAuth429WeeklyOnlyWSClientIngress` | Real loopback client socket → `ProxyResponsesWebSocketFromClient` ctx_pool path → upstream adapter fixture → secondary weekly error frame | | `TestOAuth429WeeklyOnlyCombinedRotation` | Actual RateLimitService and auto2FA service together, real queue method with spy storage, manual snapshot untouched | | `TestOAuth429WeeklyOnlyRotationPreservesScheduling` | Isolated PostgreSQL: actual permanent scheduling write, real automatic rotation repository lifecycle success/failure, manual enable/disable after queueing, successful-test recovery | From d93943307125aa239fae94a6cc719e03c1c1b3ff Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:20:57 +0800 Subject: [PATCH 25/38] ci: keep parser-only RED compatible with candidate evidence fields --- .github/workflows/oauth429-weekly-only.yml | 1 - docs/testing/oauth429-weekly-only.md | 7 +++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index b01b8ce212f7..6491b8ef4f3e 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -93,7 +93,6 @@ jobs: test "$(git hash-object "$RUNNER_TEMP/oauth429-cache-red/$target")" = "$expected" printf '%s %s %s\n' "$BASELINE" "$expected" "$target" >> evidence/cache-restored-blobs.txt done <<'BLOBS' - 849aec6c598b9ca5e94f218f76e7d7266505ae57 backend/internal/service/openai_gateway_service.go 9fb1903315d1f086f4f38bd73a5a0a5f69f6542a backend/internal/service/openai_gateway_usage.go BLOBS git -C "$RUNNER_TEMP/oauth429-cache-red" diff --exit-code -- '*_test.go' diff --git a/docs/testing/oauth429-weekly-only.md b/docs/testing/oauth429-weekly-only.md index 4a864199fd5d..a847deb62bf2 100644 --- a/docs/testing/oauth429-weekly-only.md +++ b/docs/testing/oauth429-weekly-only.md @@ -136,7 +136,8 @@ report. Line numbers refer to this change's source tree. | `openai_gateway_messages.go:641` | `handleAnthropicErrorResponse` | `handleCompatErrorResponse` | | `openai_gateway_passthrough.go:1024` | `handleFailoverErrorResponsePassthrough` | `handleOpenAIAccountUpstreamError` | | `openai_gateway_passthrough.go:1097` | `handleErrorResponsePassthrough` | `handleOpenAIAccountUpstreamError` | -| `openai_gateway_passthrough.go:1884` | `handleOpenAIStreamTerminalAccountSideEffects` | `handleOpenAIAccountUpstreamError` | +| `openai_gateway_passthrough.go:1851` | `handleOpenAIStreamTerminalAccountSideEffects` | `handleOpenAIStreamTerminalAccountSideEffectsWithContext` | +| `openai_gateway_passthrough.go:1886` | `handleOpenAIStreamTerminalAccountSideEffectsWithContext` | `handleOpenAIAccountUpstreamError` | | `openai_gateway_responses_chat_fallback.go:179` | `forwardResponsesViaRawChatCompletions` | `handleErrorResponse` | | `openai_gateway_upstream_errors.go:597` | `handleFailoverSideEffects` | `handleOpenAIAccountUpstreamError` | | `openai_gateway_upstream_errors.go:599` | `handleFailoverSideEffects` | `handleOpenAIAccountUpstreamError` | @@ -153,6 +154,8 @@ report. Line numbers refer to this change's source tree. | `openai_ws_forwarder_ingress.go:2160` | `ProxyResponsesWebSocketFromClient` | `handleOpenAIWSTerminalTransientFailure` | | `openai_ws_forwarder_support.go:325` | `handleOpenAIWSTerminalTransientFailure` | `handleOpenAIWSFailureAccountSideEffects` | | `openai_ws_forwarder_support.go:341` | `handleOpenAIWSErrorEventTransientFailure` | `handleOpenAIAccountUpstreamError` | +| `openai_ws_forwarder_support.go:354` | `handleOpenAIWSFailureAccountSideEffects` | `handleOpenAIStreamTerminalAccountSideEffectsWithContext` | +| `openai_ws_forwarder_support.go:360` | `handleOpenAIWSFailureAccountSideEffects` | `handleOpenAIStreamTerminalAccountSideEffectsWithContext` | | `openai_ws_forwarder_support.go:368` | `handleOpenAIWSFailureAccountSideEffects` | `handleOpenAIAccountUpstreamError` | | `openai_ws_forwarder_support.go:380` | `handleOpenAIWSDialTransientFailure` | `handleOpenAIAccountUpstreamError` | | `openai_ws_forwarder_support.go:723` | `persistOpenAIWSRateLimitSignal` | `handleOpenAIAccountUpstreamError` | @@ -164,6 +167,6 @@ report. Line numbers refer to this change's source tree. | `openai_ws_http_bridge.go:980` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSFailureAccountSideEffects` | | `openai_ws_http_bridge.go:1088` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSTerminalTransientFailure` | | `openai_ws_v2_passthrough_adapter.go:981` | `proxyResponsesWebSocketV2Passthrough` | `handleOpenAIWSDialTransientFailure` | -| `openai_ws_v2_passthrough_adapter.go:1596` | `proxyResponsesWebSocketV2Passthrough` | `handleOpenAIWSFailureAccountSideEffects` | +| `openai_ws_v2_passthrough_adapter.go:1597` | `proxyResponsesWebSocketV2Passthrough` | `handleOpenAIWSFailureAccountSideEffects` | | `ratelimit_service.go:354` | `HandleUpstreamError` | `handleUpstreamErrorAfterStreakReset` | | `ratelimit_service.go:360` | `handleUpstreamErrorAfterStreakReset` | `maybeDisableOpenAISchedulingOn429` | From 12b1e4945bde071e9425a7828b23843104af7ec2 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:30:04 +0800 Subject: [PATCH 26/38] fix: supersede weekly proof on quota queries and timestamp HTTP stream evidence --- .../scripts/oauth429-weekly-only-evidence.py | 18 +++- .github/workflows/oauth429-weekly-only.yml | 35 +++++++- .../oauth429_weekly_only_integration_test.go | 87 +++++++++++++++++++ .../oauth429_weekly_only_gateway_test.go | 73 ++++++++++++++++ .../service/openai_disable_scheduling_429.go | 21 +++++ .../service/openai_gateway_passthrough.go | 2 + .../openai_gateway_response_handling.go | 2 + .../service/openai_plugin_transport.go | 4 + .../internal/service/openai_quota_recovery.go | 3 - .../internal/service/openai_quota_service.go | 5 ++ .../service/openai_quota_usage_snapshot.go | 7 ++ .../internal/service/openai_ws_http_bridge.go | 1 + docs/testing/oauth429-weekly-only.md | 15 ++-- 13 files changed, 257 insertions(+), 16 deletions(-) diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index c9099e2f4ab1..759e8585ad9f 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -24,7 +24,7 @@ finished = {(event.get("Package"), event["Test"]) for event in events if event["Action"] in ("pass", "fail") and event.get("Test")} assert started and started == finished, "test execution did not finish" -package = "github.com/Wei-Shaw/sub2api/internal/" + ("repository" if mode == "repository" else "service") +package = "github.com/Wei-Shaw/sub2api/internal/" + ("repository" if mode in ("repository", "red-query") else "service") terminal = [event for event in events if event.get("Package") == package and not event.get("Test") and event["Action"] in ("pass", "fail")] assert len(terminal) == 1, "missing completed package result" @@ -32,7 +32,12 @@ passed = {event.get("Test") for event in events if event["Action"] == "pass"} if mode.startswith("red"): assert int(status) == 1 and terminal[0]["Action"] == "fail", "expected normal go test assertion failure" - if mode == "red-cache": + if mode == "red-query": + for name in ("new_weekly_zero", "new_weekly_low"): + assert "TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence/" + name in failed + assert "TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence/older_query_cannot_replace_newer_high" in passed + assert "actual QueryUsage persistence must supersede older weekly high" in output + elif mode == "red-cache": assert "TestOAuth429WeeklyOnlySequentialCache/duplicate_usage" in failed assert "TestOAuth429WeeklyOnlySequentialCache/nan_weekly_usage" in failed assert "TestOAuth429WeeklyOnlyNonweeklyPersistenceRetainsEvidence" in failed @@ -55,16 +60,21 @@ "WSForward/frame_elapsed_handshake_reset", "NonweeklyPersistenceRetainsEvidence", "WSClientIngress", + "HTTPStreamExpiredObservation/native_stream", + "HTTPStreamExpiredObservation/passthrough_stream", + "HTTPStreamExpiredObservation/native_buffered", + "HTTPStreamExpiredObservation/passthrough_buffered", + "HTTPStreamExpiredObservation/ws_http_bridge", ): assert "TestOAuth429WeeklyOnly" + name in failed, name assert "TestOAuth429WeeklyOnlyWSForward/body_only_no_percentage" in passed assert "request admission denied:" not in output else: assert int(status) == 0 and not failed and terminal[0]["Action"] == "pass", "candidate failed" - required = ["RotationPreservesScheduling", "InvalidWeeklyPersistence", "NonweeklyPersistenceRetainsEvidence"] if mode == "repository" else [ + required = ["RotationPreservesScheduling", "InvalidWeeklyPersistence", "NonweeklyPersistenceRetainsEvidence", "QueryUsageSupersedesEvidence"] if mode == "repository" else [ "Service", "HeaderBoundaries", "CachedIdentity", "NonweeklyHeadersAllowExplicitCache", "CacheDoesNotRelabelUnidentifiedUsage", "SequentialCache", "NonweeklyPersistenceRetainsEvidence", "PolicyGates", - "HTTPForward", "WSForward", "WSClientIngress", "CombinedRotation", + "HTTPForward", "HTTPStreamExpiredObservation", "WSForward", "WSClientIngress", "CombinedRotation", ] for name in required: assert "TestOAuth429WeeklyOnly" + name in passed, "missing regression: " + name diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 6491b8ef4f3e..04cfd2effba7 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -12,7 +12,11 @@ on: - 'backend/internal/service/openai_ws_forwarder_v2.go' - 'backend/internal/service/openai_ws_forwarder_ingress.go' - 'backend/internal/service/openai_ws_v2_passthrough_adapter.go' - - 'backend/internal/service/openai_quota_recovery.go' + - 'backend/internal/service/openai_plugin_transport.go' + - 'backend/internal/service/openai_gateway_response_handling.go' + - 'backend/internal/service/openai_ws_http_bridge.go' + - 'backend/internal/service/openai_quota_service.go' + - 'backend/internal/service/openai_quota_usage_snapshot.go' - 'backend/internal/repository/oauth429_weekly_only*' - '.github/workflows/oauth429-weekly-only.yml' - '.github/scripts/oauth429-weekly-only-*' @@ -27,7 +31,7 @@ env: jobs: red: runs-on: ubuntu-latest - timeout-minutes: 25 + timeout-minutes: 35 steps: - uses: actions/checkout@v6 with: @@ -61,7 +65,11 @@ jobs: 3af551183471cd0ac3b2a6baa27aa506975dce96 backend/internal/service/openai_ws_forwarder_v2.go fcff9837e12c0aa9c3ea3e22724f923890681fe1 backend/internal/service/openai_ws_forwarder_ingress.go aee0bb83694c375d5baf431db916ea093a1658f4 backend/internal/service/openai_ws_v2_passthrough_adapter.go - 696cd27a7aa58e6503e57c0b64bb341388c6ce3e backend/internal/service/openai_quota_recovery.go + 0f83bd1fcfcf9d585c4fda999cce71bb7154451f backend/internal/service/openai_plugin_transport.go + fc1490884a556ef7518786c770fbd73a237155da backend/internal/service/openai_gateway_response_handling.go + ed1708f3c2ee470d80ab97b377ff610050e383fc backend/internal/service/openai_ws_http_bridge.go + 0e4455ea613b07f2775c793346bd0b8fa0257fd5 backend/internal/service/openai_quota_service.go + 26744ab312ed9552b375487d34052fd8b7f28da1 backend/internal/service/openai_quota_usage_snapshot.go BLOBS git -C "$RUNNER_TEMP/oauth429-red" diff --stat > evidence/red-diff.txt git ls-files 'backend/internal/service/*429*test.go' 'backend/internal/repository/oauth429_weekly_only*test.go' > evidence/retained-tests.txt @@ -103,6 +111,27 @@ jobs: set -e printf '%s\n' "$result" > evidence/red-cache-exit.txt python3 .github/scripts/oauth429-weekly-only-evidence.py red-cache evidence/red-cache.jsonl "$result" + - name: Original quota-query persistence must fail against real PostgreSQL + shell: bash + env: + CI: 'true' + run: | + set -euo pipefail + git worktree add --detach "$RUNNER_TEMP/oauth429-query-red" "$CANDIDATE" + target=backend/internal/service/openai_quota_usage_snapshot.go + expected=26744ab312ed9552b375487d34052fd8b7f28da1 + test "$(git rev-parse "$BASELINE:$target")" = "$expected" + git show "$BASELINE:$target" > "$RUNNER_TEMP/oauth429-query-red/$target" + test "$(git hash-object "$RUNNER_TEMP/oauth429-query-red/$target")" = "$expected" + printf '%s %s %s\n' "$BASELINE" "$expected" "$target" > evidence/query-restored-blobs.txt + git -C "$RUNNER_TEMP/oauth429-query-red" diff --exit-code -- '*_test.go' + git -C "$RUNNER_TEMP/oauth429-query-red" diff --stat > evidence/query-red-diff.txt + set +e + (cd "$RUNNER_TEMP/oauth429-query-red/backend" && go test -json -tags=integration ./internal/repository -run '^TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence$' -count=1 -timeout=10m) > evidence/red-query.jsonl 2> evidence/red-query.stderr + result=$? + set -e + printf '%s\n' "$result" > evidence/red-query-exit.txt + python3 .github/scripts/oauth429-weekly-only-evidence.py red-query evidence/red-query.jsonl "$result" - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/repository/oauth429_weekly_only_integration_test.go b/backend/internal/repository/oauth429_weekly_only_integration_test.go index 3ed1b967d337..553c54b740ae 100644 --- a/backend/internal/repository/oauth429_weekly_only_integration_test.go +++ b/backend/internal/repository/oauth429_weekly_only_integration_test.go @@ -5,11 +5,15 @@ package repository import ( "fmt" "net/http" + "net/http/httptest" + "net/url" + "sync/atomic" "testing" "time" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/imroc/req/v3" "github.com/stretchr/testify/require" ) @@ -134,3 +138,86 @@ func TestOAuth429WeeklyOnlyNonweeklyPersistenceRetainsEvidence(t *testing.T) { require.NoError(t, err) require.False(t, a.Schedulable, "nonweekly JSONB updates must retain the valid weekly observation") } + +func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { + for _, tc := range []struct { + name string + used int + newerHeader bool + }{ + {"new_weekly_zero", 0, false}, {"new_weekly_low", 20, false}, {"older_query_cannot_replace_newer_high", 20, true}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, _, cfg := totpRotationFixture(t) + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + require.NoError(t, accounts.SetSchedulable(ctx, cfg.AccountID, true)) + require.NoError(t, accounts.UpdateCredentials(ctx, cfg.AccountID, map[string]any{"email": "owner@example.test", "chatgpt_account_id": "fictional-owner", "access_token": "fictional-token", "expires_at": time.Now().Add(time.Hour).Format(time.RFC3339)})) + rates := service.NewRateLimitService(accounts, nil, &config.Config{}, nil, nil) + h := http.Header{} + h.Set("x-codex-primary-window-minutes", "10080") + h.Set("x-codex-primary-used-percent", "99") + a, err := accounts.GetByID(ctx, cfg.AccountID) + require.NoError(t, err) + rates.HandleUpstreamError(ctx, a, 429, h, nil) + old, err := accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + var peers atomic.Int64 + peerErrors := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path != "/backend-api/wham/usage" { + _, _ = w.Write([]byte(`{}`)) + return + } + peers.Add(1) + if tc.newerHeader { + latest, readErr := accounts.GetByID(ctx, a.ID) + if readErr != nil { + peerErrors <- readErr + w.WriteHeader(500) + return + } + rates.HandleUpstreamError(ctx, latest, 429, h, nil) + } + _, _ = fmt.Fprintf(w, `{"account_id":"fictional-owner","email":"owner@example.test","rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"used_percent":%d,"limit_window_seconds":604800,"reset_after_seconds":7200},"secondary_window":{"used_percent":0,"limit_window_seconds":18000,"reset_after_seconds":3600}}}`, tc.used) + })) + defer server.Close() + target, err := url.Parse(server.URL) + require.NoError(t, err) + factory := func(string) (*req.Client, error) { + client := req.C().WrapRoundTripFunc(func(rt req.RoundTripper) req.RoundTripFunc { + return func(request *req.Request) (*req.Response, error) { + request.URL.Scheme = target.Scheme + request.URL.Host = target.Host + return rt.RoundTrip(request) + } + }) + return client, nil + } + quota := service.NewOpenAIQuotaService(accounts, nil, service.NewOpenAITokenProvider(accounts, nil, nil), factory, nil) + _, err = quota.QueryUsage(ctx, a.ID) + require.NoError(t, err) + select { + case peerErr := <-peerErrors: + require.NoError(t, peerErr) + default: + } + require.Positive(t, peers.Load()) + // Simulate a delayed pre-query observation after query persistence. + delayed := map[string]any{} + for key, value := range old.Extra { + if service.IsCodexUsageExtraKey(key) { + delayed[key] = value + } + } + require.NoError(t, accounts.UpdateExtra(ctx, a.ID, delayed)) + require.NoError(t, accounts.UpdateExtra(ctx, a.ID, map[string]any{service.OpenAIDisableSchedulingOn429ExtraKey: true})) + a, err = accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + rates.HandleUpstreamError(ctx, a, 429, nil, nil) + a, err = accounts.GetByID(ctx, a.ID) + require.NoError(t, err) + require.Equal(t, !tc.newerHeader, a.Schedulable, "actual QueryUsage persistence must supersede older weekly high without overwriting a newer observation") + }) + } +} diff --git a/backend/internal/service/oauth429_weekly_only_gateway_test.go b/backend/internal/service/oauth429_weekly_only_gateway_test.go index 43aad89288bd..066576497653 100644 --- a/backend/internal/service/oauth429_weekly_only_gateway_test.go +++ b/backend/internal/service/oauth429_weekly_only_gateway_test.go @@ -4,15 +4,18 @@ package service import ( "context" + "fmt" "io" "net/http" "net/http/httptest" + "net/url" "strings" "sync/atomic" "testing" "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" coderws "github.com/coder/websocket" "github.com/gin-gonic/gin" "github.com/gorilla/websocket" @@ -266,3 +269,73 @@ func TestOAuth429WeeklyOnlyWSClientIngress(t *testing.T) { t.Fatal("client ingress did not finish") } } + +type weeklyOnlyLoopbackHTTP struct { + client *http.Client + target string +} + +func (u *weeklyOnlyLoopbackHTTP) Do(request *http.Request, _ string, _ int64, _ int) (*http.Response, error) { + local := request.Clone(request.Context()) + parsed, err := url.Parse(u.target) + if err != nil { + return nil, err + } + local.URL.Scheme, local.URL.Host = parsed.Scheme, parsed.Host + local.Host = parsed.Host + return u.client.Do(local) +} + +func (u *weeklyOnlyLoopbackHTTP) DoWithTLS(request *http.Request, proxy string, id int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(request, proxy, id, concurrency) +} + +func TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, mode := range []string{"native_stream", "passthrough_stream", "native_buffered", "passthrough_buffered", "ws_http_bridge"} { + t.Run(mode, func(t *testing.T) { + var peers atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + peers.Add(1) + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("x-codex-primary-window-minutes", "10080") + w.Header().Set("x-codex-primary-used-percent", "99") + w.Header().Set("x-codex-primary-reset-after-seconds", "1") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, ": fictional keepalive\n\n") + w.(http.Flusher).Flush() + // A real HTTP transport receives headers before this reset elapses. + time.Sleep(1500 * time.Millisecond) + _, _ = io.WriteString(w, "data: {\"type\":\"response.failed\",\"response\":{\"id\":\"fictional-response\",\"error\":{\"type\":\"usage_limit_reached\",\"code\":\"rate_limit_exceeded\",\"message\":\"fictional quota rejection\",\"resets_in_seconds\":7200}}}\n\n") + })) + defer server.Close() + a := scheduling429Account() + a.Status, a.Concurrency = StatusActive, 1 + a.Credentials = map[string]any{"access_token": "fictional-token", "chatgpt_account_id": "fictional-owner"} + a.Extra["codex_7d_used_percent"] = 20.0 + a.Extra["openai_passthrough"] = strings.HasPrefix(mode, "passthrough") + a.Extra["openai_oauth_responses_websockets_v2_mode"] = OpenAIWSIngressModeOff + repo := &weeklyOnly429Repo{} + cfg := &config.Config{} + rates := NewRateLimitService(repo, nil, cfg, nil, nil) + gateway := &OpenAIGatewayService{cfg: cfg, httpUpstream: &weeklyOnlyLoopbackHTTP{client: server.Client(), target: server.URL}, rateLimitService: rates, cache: &stubGatewayCache{}, toolCorrector: NewCodexToolCorrector()} + rates.SetAccountRuntimeBlocker(gateway) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + c.Request.Header.Set("User-Agent", "codex_cli_rs/0.1.0") + var err error + if mode == "ws_http_bridge" { + payload := []byte(`{"type":"response.create","model":"gpt-5.2","stream":true,"input":"fictional test"}`) + _, err = gateway.proxyOpenAIWSHTTPBridgeTurn(t.Context(), c, a, "fictional-token", payload, len(payload), "gpt-5.2", "", "", "", "", 1, func([]byte) error { return nil }) + } else { + stream := !strings.HasSuffix(mode, "buffered") + _, err = gateway.Forward(t.Context(), c, a, []byte(fmt.Sprintf(`{"model":"gpt-5.2","stream":%t,"input":"fictional test"}`, stream))) + } + require.Error(t, err) + require.Positive(t, peers.Load(), "must reach the real loopback HTTP peer") + require.Empty(t, repo.ids, "expired HTTP response quota must not permanently disable on a later stream 429") + require.Positive(t, repo.rateLimitedCalls, "semantic 429 must preserve temporary cooldown handling") + require.WithinDuration(t, time.Now().Add(2*time.Hour), repo.lastRateLimitedAt, 10*time.Second, "temporary cooldown must use event reset") + }) + } +} diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index a59aa04c1b37..edb70ea5bd30 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -9,6 +9,8 @@ import ( "strconv" "strings" "time" + + "github.com/gin-gonic/gin" ) const ( @@ -133,6 +135,9 @@ func openAI429WeeklyUsage(account *Account, headers http.Header, now time.Time, if reset, exists := evidence["reset_after_seconds"]; exists { proofExtra["codex_7d_reset_after_seconds"] = reset } + if reset, exists := evidence["reset_at"]; exists { + proofExtra["codex_7d_reset_at"] = reset + } if invalidAt, exists := extra[openAI429WeeklyInvalidAtKey]; exists { proofExtra[openAI429WeeklyInvalidAtKey] = invalidAt } @@ -272,6 +277,22 @@ type openAIDisableScheduling429ObservedKey struct{} type openAI429WeeklyHeadersKey struct{} type openAI429WeeklyObservedAtKey struct{} +// Bind the receipt time before any body buffering/streaming. Downstream +// failover helpers read the same request context as direct stream side effects. +func bindOpenAI429ResponseObservation(ctx context.Context, resp *http.Response, c *gin.Context) context.Context { + observed := time.Now() + if resp != nil && resp.Request != nil { + if stamp, ok := resp.Request.Context().Value(openAI429WeeklyObservedAtKey{}).(time.Time); ok { + observed = stamp + } + } + ctx = context.WithValue(ctx, openAI429WeeklyObservedAtKey{}, observed) + if c != nil && c.Request != nil { + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), openAI429WeeklyObservedAtKey{}, observed)) + } + return ctx +} + func openAI429LeaseObservation(ctx context.Context, lease *openAIWSConnLease) context.Context { var observed time.Time if lease != nil && lease.conn != nil { diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index c1833fc0e65a..cd07bd95d461 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -2121,6 +2121,7 @@ func (s *OpenAIGatewayService) handleStreamingResponsePassthroughWithImage( imageBillingModel string, reasoningEfforts ...string, ) (*openaiStreamingResultPassthrough, error) { + ctx = bindOpenAI429ResponseObservation(ctx, resp, c) earlyPluginEvents := s.openAIPluginSSEEarlyEvents(resp, account) pluginEarlyCommitted := false earlyMetadataPending := false @@ -2751,6 +2752,7 @@ func (s *OpenAIGatewayService) handleNonStreamingResponsePassthrough( originalModel string, mappedModel string, ) (*openaiNonStreamingResultPassthrough, error) { + ctx = bindOpenAI429ResponseObservation(ctx, resp, c) body, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError) if err != nil { return nil, err diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index fc1490884a55..671c489a8d25 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -55,6 +55,7 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp } func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, startTime time.Time, originalModel, mappedModel, reasoningEffort string) (*openaiStreamingResult, error) { + ctx = bindOpenAI429ResponseObservation(ctx, resp, c) observer := upstreamResponseModelObserverFromContext(c) if observer == nil { observer = beginUpstreamResponseModelObservation(c) @@ -1918,6 +1919,7 @@ func openAICacheCreationTTLTokensFromUsage(value gjson.Result, aggregate int) (i } func (s *OpenAIGatewayService) handleNonStreamingResponse(ctx context.Context, resp *http.Response, c *gin.Context, account *Account, originalModel, mappedModel string) (*openaiNonStreamingResult, error) { + ctx = bindOpenAI429ResponseObservation(ctx, resp, c) body, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError) if err != nil { return nil, err diff --git a/backend/internal/service/openai_plugin_transport.go b/backend/internal/service/openai_plugin_transport.go index 0f83bd1fcfcf..753844218f21 100644 --- a/backend/internal/service/openai_plugin_transport.go +++ b/backend/internal/service/openai_plugin_transport.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "strings" + "time" ) func (s *OpenAIGatewayService) SetPluginManager(manager *PluginManager) { @@ -34,6 +35,9 @@ func (s *OpenAIGatewayService) doOpenAIUpstream(request *http.Request, proxyURL if result != nil && result.Request == nil { result.Request = request } + if result != nil && result.Request != nil { + result.Request = result.Request.WithContext(context.WithValue(result.Request.Context(), openAI429WeeklyObservedAtKey{}, time.Now())) + } result, resultErr = phaseGuard.finish(result, resultErr) resultErr = finishHeaderTimeout(result, resultErr) }() diff --git a/backend/internal/service/openai_quota_recovery.go b/backend/internal/service/openai_quota_recovery.go index 4b50f7398b84..696cd27a7aa5 100644 --- a/backend/internal/service/openai_quota_recovery.go +++ b/backend/internal/service/openai_quota_recovery.go @@ -100,8 +100,5 @@ func openAIQuotaRecoveryUsageUpdates(body []byte, now time.Time) map[string]any if len(updates) != 3 { return nil } - // This body explicitly identifies a recovered weekly window. Supersede any - // older retained header evidence alongside the existing zero-usage update. - updates[openAI429WeeklyEvidenceKey] = openAI429WeeklyEvidence(0, now.Truncate(time.Second), nil) return updates } diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 0e4455ea613b..44f00d1bbd47 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -254,6 +254,11 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* // Order by request observation, so a slow earlier query cannot undo // a later response/header snapshot. Resets use response receipt time. updates["codex_usage_updated_at"] = queryStartedAt.UTC().Format(time.RFC3339Nano) + if evidence, ok := updates[openAI429WeeklyEvidenceKey].(map[string]any); ok { + // Bind the proof to the same ordering version as its atomic field. + // Absolute resets above still use response receipt time. + evidence["observed_at"] = updates["codex_usage_updated_at"] + } payload.schedulingUpdates = updates written, writeErr := persistCodexUsageUpdates(callCtx, s.accountRepo, accountID, updates) payload.UsageCachePersisted = written && writeErr == nil diff --git a/backend/internal/service/openai_quota_usage_snapshot.go b/backend/internal/service/openai_quota_usage_snapshot.go index 26744ab312ed..5d77621dd722 100644 --- a/backend/internal/service/openai_quota_usage_snapshot.go +++ b/backend/internal/service/openai_quota_usage_snapshot.go @@ -79,5 +79,12 @@ func openAIQuotaSchedulingUpdates(body []byte, shadow bool, expectedAccountID st return nil } updates["codex_usage_updated_at"] = now.UTC().Format(time.RFC3339Nano) + if used, ok := resolveAccountExtraNumber(updates, "codex_7d_used_percent"); ok && validOpenAI429Percent(used) { + evidence := openAI429WeeklyEvidence(used, now, nil) + if reset, exists := updates["codex_7d_reset_at"]; exists { + evidence["reset_at"] = reset + } + updates[openAI429WeeklyEvidenceKey] = evidence + } return updates } diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index ed1708f3c2ee..fa47c470055e 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -707,6 +707,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( } return nil, fmt.Errorf("upstream http bridge error: status=%d message=%s", resp.StatusCode, upstreamMsg) } + ctx = bindOpenAI429ResponseObservation(ctx, resp, c) defer func() { _ = resp.Body.Close() }() // upstreamCtx cancellation interrupts the transport read. Keep Body.Close // on this reader's goroutine: compressed bodies cannot close during Read. diff --git a/docs/testing/oauth429-weekly-only.md b/docs/testing/oauth429-weekly-only.md index a847deb62bf2..7d16d22e9583 100644 --- a/docs/testing/oauth429-weekly-only.md +++ b/docs/testing/oauth429-weekly-only.md @@ -2,7 +2,7 @@ Baseline: `f895ea743f34a4c4ab6c9d01c01e13c931625a6e`. Production scope: weekly policy, quota snapshot header provenance, and the three -stream/WS sites that separate permanent-policy evidence from temporary cooldown headers, retained handshake observation time, and explicit zero-quota recovery evidence. +stream/WS sites that separate permanent-policy evidence from temporary cooldown headers, retained handshake observation time, and persisted quota-query observations (including low/zero recovery). All public fixtures are fictional. Local work is static only; dynamic evidence is produced by `.github/workflows/oauth429-weekly-only.yml` on GitHub Actions. @@ -22,7 +22,7 @@ exist, both usage and window identity must have valid fresh versions from the sa source observation. A partial packet cannot borrow another packet's weekly identity. Rejected weekly headers carry an observation timestamp through parser/persistence; a later headerless 429 cannot trust usage from that packet. A newer valid weekly -observation may supply fresh evidence again. Validated weekly usage is also retained as one versioned observation, independently of legacy normalized windows. Nonweekly updates cannot erase it; explicit weekly zero recovery supersedes it. Temporary quota normalization is unchanged. Legacy +observation may supply fresh evidence again. Validated weekly usage is also retained as one versioned observation, independently of legacy normalized windows. Nonweekly updates cannot erase it; newer explicit quota-query low/zero usage supersedes it in the same repository write. Temporary quota normalization is unchanged. Legacy snapshots without an explicit window no longer authorize a permanent disable. Nonweekly or unidentified headers do not veto independently valid weekly cache; unidentified percentages themselves never count as weekly evidence. @@ -39,6 +39,8 @@ unidentified percentages themselves never count as weekly evidence. | `TestOAuth429WeeklyOnlySequentialCache` | Public error service → actual parser → per-field persist/merge → reload → headerless 429; duplicate/conflicting/invalid weekly packets cannot poison cache | | `TestOAuth429WeeklyOnlyInvalidWeeklyPersistence` | Real PostgreSQL JSONB: NaN/Inf/duplicate weekly headers, prior-high cache, reload, delayed older snapshot, headerless 429 | | `TestOAuth429WeeklyOnlyNonweeklyPersistenceRetainsEvidence` | Parser/merge and production PostgreSQL variants preserve weekly 99 across subsequent 5h/zero persistence and reload | +| `TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence` | Actual QueryUsage via loopback HTTP → PostgreSQL update/reload → headerless 429; low/zero supersedes high, delayed observations cannot overwrite newer evidence | +| `TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation` | Real loopback HTTP flushes weekly headers, waits beyond reset, then sends semantic 429 through native/passthrough streamed and buffered paths plus WS HTTP bridge; temporary cooldown retained | | `TestOAuth429WeeklyOnlyPolicyGates` | Own threshold, strict equality, invalid threshold, opt-out, non429, body-only weekly classification | | `TestOAuth429WeeklyOnlyHTTPForward` | Actual `Forward` entry, native and OAuth passthrough HTTP paths, mocked transport response, primary/secondary weekly zero-neighbor and negative cases | | `TestOAuth429WeeklyOnlyWSForward` | Actual `Forward` entry, real loopback WS upstream handshake 429 and error frames, handshake quota, elapsed handshake reset (simulated on an actual connection after peer read), fresh low/invalid versus high cache, and explicit-cache/body-only controls; observes upstream peer and retains event-reset temporary cooldown | @@ -53,6 +55,7 @@ no paid calls or production writes occur. The repository lifecycle uses fictiona worker transitions; no real 2FA enrollment runs. The combined service and durable repository tests are separate boundaries, not a claimed end-to-end worker test. +HTTP response receipt and WS handshake times accompany retained headers through all stream and buffered-event policy paths. The permanent policy receives original stream/WS headers through context before temporary cooldown sanitization. Ordinary-model temporary cooldowns still discard successful handshake quota headers and use their existing event/body policy. @@ -65,7 +68,7 @@ The three direct entrances to the permanent policy are the common its observation context with the common handler, avoiding duplicate permanent writes. Native HTTP/passthrough and WS Forward/client ctx_pool have entry-point execution above. Existing image/BPS/managed/SIWC tests call shared handlers; they -are not full image/BPS transport acceptance. WS passthrough and HTTP bridge, +are not full image/BPS transport acceptance. WS passthrough, images, embeddings, count tokens, model listing, alpha search, chat/messages compatibility and BPS repair variants are statically mapped below, not all individually executed by this focused suite. @@ -163,9 +166,9 @@ report. Line numbers refer to this change's source tree. | `openai_ws_forwarder_v2.go:958` | `forwardOpenAIWSV2` | `handleOpenAIWSErrorEventTransientFailure` | | `openai_ws_forwarder_v2.go:1085` | `forwardOpenAIWSV2` | `handleOpenAIWSTerminalTransientFailure` | | `openai_ws_http_bridge.go:696` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIAccountUpstreamError` | -| `openai_ws_http_bridge.go:816` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSFailureAccountSideEffects` | -| `openai_ws_http_bridge.go:980` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSFailureAccountSideEffects` | -| `openai_ws_http_bridge.go:1088` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSTerminalTransientFailure` | +| `openai_ws_http_bridge.go:817` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSFailureAccountSideEffects` | +| `openai_ws_http_bridge.go:981` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSFailureAccountSideEffects` | +| `openai_ws_http_bridge.go:1089` | `proxyOpenAIWSHTTPBridgeTurn` | `handleOpenAIWSTerminalTransientFailure` | | `openai_ws_v2_passthrough_adapter.go:981` | `proxyResponsesWebSocketV2Passthrough` | `handleOpenAIWSDialTransientFailure` | | `openai_ws_v2_passthrough_adapter.go:1597` | `proxyResponsesWebSocketV2Passthrough` | `handleOpenAIWSFailureAccountSideEffects` | | `ratelimit_service.go:354` | `HandleUpstreamError` | `handleUpstreamErrorAfterStreakReset` | From addea37092c4fffdead3b6eeeb39cddff9842610 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:34:37 +0800 Subject: [PATCH 27/38] fix: keep query weekly evidence independent of unrelated quota windows --- .../scripts/oauth429-weekly-only-evidence.py | 1 + .../oauth429_weekly_only_integration_test.go | 12 +++- .../oauth429_weekly_only_gateway_test.go | 3 +- .../internal/service/openai_quota_service.go | 3 + .../service/openai_quota_usage_snapshot.go | 55 ++++++++++++++----- 5 files changed, 55 insertions(+), 19 deletions(-) diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index 759e8585ad9f..79e4ef2191a9 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -36,6 +36,7 @@ for name in ("new_weekly_zero", "new_weekly_low"): assert "TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence/" + name in failed assert "TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence/older_query_cannot_replace_newer_high" in passed + assert "TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence/new_weekly_high" in passed assert "actual QueryUsage persistence must supersede older weekly high" in output elif mode == "red-cache": assert "TestOAuth429WeeklyOnlySequentialCache/duplicate_usage" in failed diff --git a/backend/internal/repository/oauth429_weekly_only_integration_test.go b/backend/internal/repository/oauth429_weekly_only_integration_test.go index 553c54b740ae..41481a558a42 100644 --- a/backend/internal/repository/oauth429_weekly_only_integration_test.go +++ b/backend/internal/repository/oauth429_weekly_only_integration_test.go @@ -145,7 +145,9 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { used int newerHeader bool }{ - {"new_weekly_zero", 0, false}, {"new_weekly_low", 20, false}, {"older_query_cannot_replace_newer_high", 20, true}, + {"new_weekly_zero", 0, false}, {"new_weekly_low", 20, false}, {"new_weekly_high", 99, false}, + {"invalid_weekly_usage", 101, false}, {"negative_weekly_usage", -1, false}, {"unrelated_zero_window", 20, false}, + {"older_query_cannot_replace_newer_high", 20, true}, } { t.Run(tc.name, func(t *testing.T) { ctx, _, cfg := totpRotationFixture(t) @@ -179,7 +181,11 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { } rates.HandleUpstreamError(ctx, latest, 429, h, nil) } - _, _ = fmt.Fprintf(w, `{"account_id":"fictional-owner","email":"owner@example.test","rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"used_percent":%d,"limit_window_seconds":604800,"reset_after_seconds":7200},"secondary_window":{"used_percent":0,"limit_window_seconds":18000,"reset_after_seconds":3600}}}`, tc.used) + shortSeconds := 18000 + if tc.name == "unrelated_zero_window" { + shortSeconds = 0 + } + _, _ = fmt.Fprintf(w, `{"account_id":"fictional-owner","email":"owner@example.test","rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"used_percent":%d,"limit_window_seconds":604800,"reset_after_seconds":7200},"secondary_window":{"used_percent":0,"limit_window_seconds":%d,"reset_after_seconds":3600}}}`, tc.used, shortSeconds) })) defer server.Close() target, err := url.Parse(server.URL) @@ -217,7 +223,7 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { rates.HandleUpstreamError(ctx, a, 429, nil, nil) a, err = accounts.GetByID(ctx, a.ID) require.NoError(t, err) - require.Equal(t, !tc.newerHeader, a.Schedulable, "actual QueryUsage persistence must supersede older weekly high without overwriting a newer observation") + require.Equal(t, !(tc.newerHeader || (tc.used > 98 && tc.used <= 100)), a.Schedulable, "actual QueryUsage persistence must supersede older weekly high without overwriting a newer observation") }) } } diff --git a/backend/internal/service/oauth429_weekly_only_gateway_test.go b/backend/internal/service/oauth429_weekly_only_gateway_test.go index 066576497653..1de15c5ff246 100644 --- a/backend/internal/service/oauth429_weekly_only_gateway_test.go +++ b/backend/internal/service/oauth429_weekly_only_gateway_test.go @@ -320,6 +320,7 @@ func TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation(t *testing.T) { rates := NewRateLimitService(repo, nil, cfg, nil, nil) gateway := &OpenAIGatewayService{cfg: cfg, httpUpstream: &weeklyOnlyLoopbackHTTP{client: server.Client(), target: server.URL}, rateLimitService: rates, cache: &stubGatewayCache{}, toolCorrector: NewCodexToolCorrector()} rates.SetAccountRuntimeBlocker(gateway) + gateway.openaiOAuth429RetryStartedAt.Store(a.ID, time.Now().Add(-openAIOAuth429RetryWindow-time.Second)) c, _ := gin.CreateTestContext(httptest.NewRecorder()) c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) c.Request.Header.Set("User-Agent", "codex_cli_rs/0.1.0") @@ -335,7 +336,7 @@ func TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation(t *testing.T) { require.Positive(t, peers.Load(), "must reach the real loopback HTTP peer") require.Empty(t, repo.ids, "expired HTTP response quota must not permanently disable on a later stream 429") require.Positive(t, repo.rateLimitedCalls, "semantic 429 must preserve temporary cooldown handling") - require.WithinDuration(t, time.Now().Add(2*time.Hour), repo.lastRateLimitedAt, 10*time.Second, "temporary cooldown must use event reset") + require.Less(t, time.Until(repo.lastRateLimitedAt), time.Minute, "nested-event fallback cooldown must remain bounded") }) } } diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 44f00d1bbd47..eaa553459dba 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -259,6 +259,9 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* // Absolute resets above still use response receipt time. evidence["observed_at"] = updates["codex_usage_updated_at"] } + if _, invalid := updates[openAI429WeeklyInvalidAtKey]; invalid { + updates[openAI429WeeklyInvalidAtKey] = updates["codex_usage_updated_at"] + } payload.schedulingUpdates = updates written, writeErr := persistCodexUsageUpdates(callCtx, s.accountRepo, accountID, updates) payload.UsageCachePersisted = written && writeErr == nil diff --git a/backend/internal/service/openai_quota_usage_snapshot.go b/backend/internal/service/openai_quota_usage_snapshot.go index 5d77621dd722..1ae0127781ad 100644 --- a/backend/internal/service/openai_quota_usage_snapshot.go +++ b/backend/internal/service/openai_quota_usage_snapshot.go @@ -43,13 +43,49 @@ func openAIQuotaSchedulingUpdates(body []byte, shadow bool, expectedAccountID st if selected == nil { return nil } + // Keep permanent-policy evidence independent of unrelated window parsing. + // It is still persisted atomically with the normal scheduling snapshot. + weekly := make(map[string]any) + weeklyCount := 0 + for _, w := range []*window{selected.Primary, selected.Secondary} { + if w == nil || w.Seconds != 7*24*60*60 { + continue + } + weeklyCount++ + if weeklyCount > 1 || w.Used == nil || !validOpenAI429Percent(*w.Used) || + (w.ResetAfter != nil && (*w.ResetAfter <= 0 || *w.ResetAfter > 7*24*60*60)) || + (w.ResetAt != nil && !time.Unix(*w.ResetAt, 0).After(now)) { + weekly = map[string]any{openAI429WeeklyInvalidAtKey: now.UTC().Format(time.RFC3339Nano)} + break + } + evidence := openAI429WeeklyEvidence(*w.Used, now, nil) + if w.ResetAt != nil { + evidence["reset_at"] = time.Unix(*w.ResetAt, 0).UTC().Format(time.RFC3339Nano) + } else if w.ResetAfter != nil { + evidence["reset_at"] = now.Add(time.Duration(*w.ResetAfter) * time.Second).UTC().Format(time.RFC3339Nano) + } + weekly[openAI429WeeklyEvidenceKey] = evidence + } + finish := func(updates map[string]any) map[string]any { + if updates == nil { + updates = make(map[string]any) + } + for key, value := range weekly { + updates[key] = value + } + if len(updates) == 0 { + return nil + } + updates["codex_usage_updated_at"] = now.UTC().Format(time.RFC3339Nano) + return updates + } updates := make(map[string]any) for _, w := range []*window{selected.Primary, selected.Secondary} { if w == nil || w.Used == nil { continue } if math.IsNaN(*w.Used) || math.IsInf(*w.Used, 0) || *w.Used < 0 { - return nil + return finish(nil) } var name string switch w.Seconds { @@ -58,11 +94,11 @@ func openAIQuotaSchedulingUpdates(body []byte, shadow bool, expectedAccountID st case 7 * 24 * 60 * 60: name = "7d" default: - return nil + return finish(nil) } prefix := "codex_" + name if _, exists := updates[prefix+"_used_percent"]; exists { - return nil + return finish(nil) } updates[prefix+"_used_percent"] = *w.Used updates[prefix+"_window_minutes"] = int(w.Seconds / 60) @@ -75,16 +111,5 @@ func openAIQuotaSchedulingUpdates(body []byte, shadow bool, expectedAccountID st updates[prefix+"_reset_after_seconds"] = int(*w.ResetAfter) } } - if len(updates) == 0 { - return nil - } - updates["codex_usage_updated_at"] = now.UTC().Format(time.RFC3339Nano) - if used, ok := resolveAccountExtraNumber(updates, "codex_7d_used_percent"); ok && validOpenAI429Percent(used) { - evidence := openAI429WeeklyEvidence(used, now, nil) - if reset, exists := updates["codex_7d_reset_at"]; exists { - evidence["reset_at"] = reset - } - updates[openAI429WeeklyEvidenceKey] = evidence - } - return updates + return finish(updates) } From 6937e00e27e22a38d21da57376bffb3735bfb0ca Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:39:23 +0800 Subject: [PATCH 28/38] test: isolate retained-header expiry RED and invalid query reset persistence --- .../scripts/oauth429-weekly-only-evidence.py | 11 +++++---- .github/workflows/oauth429-weekly-only.yml | 24 +++++++++++++++++++ .../oauth429_weekly_only_integration_test.go | 12 ++++++++-- 3 files changed, 40 insertions(+), 7 deletions(-) diff --git a/.github/scripts/oauth429-weekly-only-evidence.py b/.github/scripts/oauth429-weekly-only-evidence.py index 79e4ef2191a9..8d0308f89bd3 100644 --- a/.github/scripts/oauth429-weekly-only-evidence.py +++ b/.github/scripts/oauth429-weekly-only-evidence.py @@ -38,6 +38,11 @@ assert "TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence/older_query_cannot_replace_newer_high" in passed assert "TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence/new_weekly_high" in passed assert "actual QueryUsage persistence must supersede older weekly high" in output + elif mode == "red-http-expiry": + for name in ("native_stream", "passthrough_stream", "native_buffered", "passthrough_buffered", "ws_http_bridge"): + test = "TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation/" + name + assert test in failed, name + assert any(event.get("Test") == test and "expired HTTP response quota must not permanently disable" in event.get("Output", "") for event in events), "wrong expiry failure: " + name elif mode == "red-cache": assert "TestOAuth429WeeklyOnlySequentialCache/duplicate_usage" in failed assert "TestOAuth429WeeklyOnlySequentialCache/nan_weekly_usage" in failed @@ -61,14 +66,10 @@ "WSForward/frame_elapsed_handshake_reset", "NonweeklyPersistenceRetainsEvidence", "WSClientIngress", - "HTTPStreamExpiredObservation/native_stream", - "HTTPStreamExpiredObservation/passthrough_stream", - "HTTPStreamExpiredObservation/native_buffered", - "HTTPStreamExpiredObservation/passthrough_buffered", - "HTTPStreamExpiredObservation/ws_http_bridge", ): assert "TestOAuth429WeeklyOnly" + name in failed, name assert "TestOAuth429WeeklyOnlyWSForward/body_only_no_percentage" in passed + assert "TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation" in passed assert "request admission denied:" not in output else: assert int(status) == 0 and not failed and terminal[0]["Action"] == "pass", "candidate failed" diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 04cfd2effba7..946debfb7118 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -111,6 +111,30 @@ jobs: set -e printf '%s\n' "$result" > evidence/red-cache-exit.txt python3 .github/scripts/oauth429-weekly-only-evidence.py red-cache evidence/red-cache.jsonl "$result" + - name: Retained HTTP evidence without receipt-time binding must fail expiry regression + shell: bash + run: | + set -euo pipefail + before=d93943307125aa239fae94a6cc719e03c1c1b3ff + git worktree add --detach "$RUNNER_TEMP/oauth429-expiry-red" "$CANDIDATE" + while read -r expected target; do + test "$(git rev-parse "$before:$target")" = "$expected" + git show "$before:$target" > "$RUNNER_TEMP/oauth429-expiry-red/$target" + test "$(git hash-object "$RUNNER_TEMP/oauth429-expiry-red/$target")" = "$expected" + printf '%s %s %s\n' "$before" "$expected" "$target" >> evidence/expiry-restored-blobs.txt + done <<'BLOBS' + fc1490884a556ef7518786c770fbd73a237155da backend/internal/service/openai_gateway_response_handling.go + c1833fc0e65a9e4951418de52658e343f14593f0 backend/internal/service/openai_gateway_passthrough.go + ed1708f3c2ee470d80ab97b377ff610050e383fc backend/internal/service/openai_ws_http_bridge.go + BLOBS + git -C "$RUNNER_TEMP/oauth429-expiry-red" diff --exit-code -- '*_test.go' + git -C "$RUNNER_TEMP/oauth429-expiry-red" diff --stat > evidence/expiry-red-diff.txt + set +e + (cd "$RUNNER_TEMP/oauth429-expiry-red/backend" && go test -json -tags=unit ./internal/service -run '^TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation$' -count=1 -timeout=10m) > evidence/red-http-expiry.jsonl 2> evidence/red-http-expiry.stderr + result=$? + set -e + printf '%s\n' "$result" > evidence/red-http-expiry-exit.txt + python3 .github/scripts/oauth429-weekly-only-evidence.py red-http-expiry evidence/red-http-expiry.jsonl "$result" - name: Original quota-query persistence must fail against real PostgreSQL shell: bash env: diff --git a/backend/internal/repository/oauth429_weekly_only_integration_test.go b/backend/internal/repository/oauth429_weekly_only_integration_test.go index 41481a558a42..b30c80a26f65 100644 --- a/backend/internal/repository/oauth429_weekly_only_integration_test.go +++ b/backend/internal/repository/oauth429_weekly_only_integration_test.go @@ -146,6 +146,7 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { newerHeader bool }{ {"new_weekly_zero", 0, false}, {"new_weekly_low", 20, false}, {"new_weekly_high", 99, false}, + {"invalid_weekly_reset", 99, false}, {"expired_weekly_reset", 99, false}, {"invalid_weekly_usage", 101, false}, {"negative_weekly_usage", -1, false}, {"unrelated_zero_window", 20, false}, {"older_query_cannot_replace_newer_high", 20, true}, } { @@ -185,7 +186,14 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { if tc.name == "unrelated_zero_window" { shortSeconds = 0 } - _, _ = fmt.Fprintf(w, `{"account_id":"fictional-owner","email":"owner@example.test","rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"used_percent":%d,"limit_window_seconds":604800,"reset_after_seconds":7200},"secondary_window":{"used_percent":0,"limit_window_seconds":%d,"reset_after_seconds":3600}}}`, tc.used, shortSeconds) + resetSeconds, resetAt := 7200, "" + if tc.name == "invalid_weekly_reset" { + resetSeconds = -1 + } + if tc.name == "expired_weekly_reset" { + resetAt = fmt.Sprintf(",\"reset_at\":%d", time.Now().Add(-time.Minute).Unix()) + } + _, _ = fmt.Fprintf(w, `{"account_id":"fictional-owner","email":"owner@example.test","rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"used_percent":%d,"limit_window_seconds":604800,"reset_after_seconds":%d%s},"secondary_window":{"used_percent":0,"limit_window_seconds":%d,"reset_after_seconds":3600}}}`, tc.used, resetSeconds, resetAt, shortSeconds) })) defer server.Close() target, err := url.Parse(server.URL) @@ -223,7 +231,7 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { rates.HandleUpstreamError(ctx, a, 429, nil, nil) a, err = accounts.GetByID(ctx, a.ID) require.NoError(t, err) - require.Equal(t, !(tc.newerHeader || (tc.used > 98 && tc.used <= 100)), a.Schedulable, "actual QueryUsage persistence must supersede older weekly high without overwriting a newer observation") + require.Equal(t, !(tc.newerHeader || (tc.used > 98 && tc.used <= 100 && tc.name != "invalid_weekly_reset" && tc.name != "expired_weekly_reset")), a.Schedulable, "actual QueryUsage persistence must supersede older weekly high without overwriting a newer observation") }) } } From 78974f13ab497d8dc74657979b663a187ce89269 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:41:08 +0800 Subject: [PATCH 29/38] test: use concrete account repository for query fixture credentials --- .../repository/oauth429_weekly_only_integration_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/repository/oauth429_weekly_only_integration_test.go b/backend/internal/repository/oauth429_weekly_only_integration_test.go index b30c80a26f65..0626cdf92cfb 100644 --- a/backend/internal/repository/oauth429_weekly_only_integration_test.go +++ b/backend/internal/repository/oauth429_weekly_only_integration_test.go @@ -152,7 +152,7 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { } { t.Run(tc.name, func(t *testing.T) { ctx, _, cfg := totpRotationFixture(t) - accounts := NewAccountRepository(integrationEntClient, integrationDB, nil) + accounts := NewAccountRepository(integrationEntClient, integrationDB, nil).(*accountRepository) require.NoError(t, accounts.SetSchedulable(ctx, cfg.AccountID, true)) require.NoError(t, accounts.UpdateCredentials(ctx, cfg.AccountID, map[string]any{"email": "owner@example.test", "chatgpt_account_id": "fictional-owner", "access_token": "fictional-token", "expires_at": time.Now().Add(time.Hour).Format(time.RFC3339)})) rates := service.NewRateLimitService(accounts, nil, &config.Config{}, nil, nil) From e314dba1fb30120493ada3058cc2186ac731da79 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:45:24 +0800 Subject: [PATCH 30/38] fix: decode quota windows independently before persisting weekly evidence --- .../oauth429_weekly_only_integration_test.go | 16 ++++++- .../internal/service/openai_quota_service.go | 29 +++++++++++- .../service/openai_quota_usage_snapshot.go | 46 +++++++++++++++---- 3 files changed, 78 insertions(+), 13 deletions(-) diff --git a/backend/internal/repository/oauth429_weekly_only_integration_test.go b/backend/internal/repository/oauth429_weekly_only_integration_test.go index 0626cdf92cfb..ca2f84ec6b7a 100644 --- a/backend/internal/repository/oauth429_weekly_only_integration_test.go +++ b/backend/internal/repository/oauth429_weekly_only_integration_test.go @@ -146,6 +146,8 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { newerHeader bool }{ {"new_weekly_zero", 0, false}, {"new_weekly_low", 20, false}, {"new_weekly_high", 99, false}, + {"malformed_weekly_usage", 20, false}, {"malformed_nonweekly_window", 20, false}, + {"malformed_weekly_reset", 99, false}, {"invalid_weekly_reset", 99, false}, {"expired_weekly_reset", 99, false}, {"invalid_weekly_usage", 101, false}, {"negative_weekly_usage", -1, false}, {"unrelated_zero_window", 20, false}, {"older_query_cannot_replace_newer_high", 20, true}, @@ -193,7 +195,17 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { if tc.name == "expired_weekly_reset" { resetAt = fmt.Sprintf(",\"reset_at\":%d", time.Now().Add(-time.Minute).Unix()) } - _, _ = fmt.Fprintf(w, `{"account_id":"fictional-owner","email":"owner@example.test","rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"used_percent":%d,"limit_window_seconds":604800,"reset_after_seconds":%d%s},"secondary_window":{"used_percent":0,"limit_window_seconds":%d,"reset_after_seconds":3600}}}`, tc.used, resetSeconds, resetAt, shortSeconds) + usedJSON, shortJSON, resetJSON := fmt.Sprint(tc.used), fmt.Sprint(shortSeconds), fmt.Sprint(resetSeconds) + if tc.name == "malformed_weekly_usage" { + usedJSON = `"invalid"` + } + if tc.name == "malformed_nonweekly_window" { + shortJSON = `"invalid"` + } + if tc.name == "malformed_weekly_reset" { + resetJSON = `"invalid"` + } + _, _ = fmt.Fprintf(w, `{"account_id":"fictional-owner","email":"owner@example.test","rate_limit":{"allowed":true,"limit_reached":false,"primary_window":{"used_percent":%s,"limit_window_seconds":604800,"reset_after_seconds":%s%s},"secondary_window":{"used_percent":0,"limit_window_seconds":%s,"reset_after_seconds":3600}}}`, usedJSON, resetJSON, resetAt, shortJSON) })) defer server.Close() target, err := url.Parse(server.URL) @@ -231,7 +243,7 @@ func TestOAuth429WeeklyOnlyQueryUsageSupersedesEvidence(t *testing.T) { rates.HandleUpstreamError(ctx, a, 429, nil, nil) a, err = accounts.GetByID(ctx, a.ID) require.NoError(t, err) - require.Equal(t, !(tc.newerHeader || (tc.used > 98 && tc.used <= 100 && tc.name != "invalid_weekly_reset" && tc.name != "expired_weekly_reset")), a.Schedulable, "actual QueryUsage persistence must supersede older weekly high without overwriting a newer observation") + require.Equal(t, !(tc.newerHeader || (tc.used > 98 && tc.used <= 100 && tc.name != "invalid_weekly_reset" && tc.name != "expired_weekly_reset" && tc.name != "malformed_weekly_reset")), a.Schedulable, "actual QueryUsage persistence must supersede older weekly high without overwriting a newer observation") }) } } diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index eaa553459dba..6c73387571f8 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -79,6 +79,28 @@ type OpenAIRateLimit struct { SecondaryWindow *OpenAIRateLimitWindow `json:"secondary_window,omitempty"` } +func (r *OpenAIRateLimit) UnmarshalJSON(data []byte) error { + var raw struct { + Allowed bool `json:"allowed"` + LimitReached bool `json:"limit_reached"` + Primary json.RawMessage `json:"primary_window"` + Secondary json.RawMessage `json:"secondary_window"` + } + if err := json.Unmarshal(data, &raw); err != nil { + return err + } + *r = OpenAIRateLimit{Allowed: raw.Allowed, LimitReached: raw.LimitReached} + // One malformed slot is unavailable display data, not a reason to lose + // another slot. Scheduling validates the original raw fields separately. + if err := json.Unmarshal(raw.Primary, &r.PrimaryWindow); err != nil { + r.PrimaryWindow = nil + } + if err := json.Unmarshal(raw.Secondary, &r.SecondaryWindow); err != nil { + r.SecondaryWindow = nil + } + return nil +} + // OpenAIAdditionalRateLimit describes a per-feature rate limit (e.g. Codex Spark). type OpenAIAdditionalRateLimit struct { LimitName string `json:"limit_name"` @@ -221,7 +243,6 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* resp, err := client.R(). SetContext(callCtx). SetHeaders(quotaHeaders). - SetSuccessResult(&payload). Get(chatGPTUsageURL) if err != nil { return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_REQUEST_FAILED", "upstream request failed: %v", err) @@ -243,6 +264,9 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "body", body) return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) } + // Decode display data independently: its unrelated malformed fields + // must not prevent raw weekly evidence/invalidation from being stored. + decodeErr := json.Unmarshal(resp.Bytes(), &payload) payload.schedulingObserved = true payload.UsageCachePersisted = false // A failed row read cannot safely choose global vs Spark windows. @@ -273,6 +297,9 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* recoverOpenAIQuotaRateLimit(callCtx, s.accountRepo, observed, openAIQuotaRecoveryUsageUpdates(resp.Bytes(), time.Now())) } } + if decodeErr != nil { + return nil, infraerrors.New(http.StatusBadGateway, "OPENAI_QUOTA_RESPONSE_INVALID", "upstream quota response has invalid fields") + } break } diff --git a/backend/internal/service/openai_quota_usage_snapshot.go b/backend/internal/service/openai_quota_usage_snapshot.go index 1ae0127781ad..804df6047c75 100644 --- a/backend/internal/service/openai_quota_usage_snapshot.go +++ b/backend/internal/service/openai_quota_usage_snapshot.go @@ -10,14 +10,15 @@ import ( // unknown/duplicate windows and absent reset timestamps must not invent a reset. func openAIQuotaSchedulingUpdates(body []byte, shadow bool, expectedAccountID string, now time.Time) map[string]any { type window struct { - Used *float64 `json:"used_percent"` - Seconds int64 `json:"limit_window_seconds"` - ResetAfter *int64 `json:"reset_after_seconds"` - ResetAt *int64 `json:"reset_at"` + Used *float64 + Seconds int64 + ResetAfter *int64 + ResetAt *int64 + malformed bool } type limit struct { - Primary *window `json:"primary_window"` - Secondary *window `json:"secondary_window"` + Primary json.RawMessage `json:"primary_window"` + Secondary json.RawMessage `json:"secondary_window"` } var payload struct { AccountID string `json:"account_id"` @@ -43,16 +44,41 @@ func openAIQuotaSchedulingUpdates(body []byte, shadow bool, expectedAccountID st if selected == nil { return nil } + decodeWindow := func(raw json.RawMessage) *window { + var fields map[string]json.RawMessage + if len(raw) == 0 || string(raw) == "null" || json.Unmarshal(raw, &fields) != nil { + return nil + } + w := &window{} + // The identity is decoded separately, so malformed usage/reset fields + // in a known weekly slot remain an invalidating weekly observation. + _ = json.Unmarshal(fields["limit_window_seconds"], &w.Seconds) + if value, exists := fields["used_percent"]; exists { + if json.Unmarshal(value, &w.Used) != nil { + w.Used = nil + w.malformed = true + } + } + for key, target := range map[string]**int64{"reset_after_seconds": &w.ResetAfter, "reset_at": &w.ResetAt} { + if value, exists := fields[key]; exists { + if string(value) == "null" || json.Unmarshal(value, target) != nil { + w.malformed = true + } + } + } + return w + } + windows := []*window{decodeWindow(selected.Primary), decodeWindow(selected.Secondary)} // Keep permanent-policy evidence independent of unrelated window parsing. // It is still persisted atomically with the normal scheduling snapshot. weekly := make(map[string]any) weeklyCount := 0 - for _, w := range []*window{selected.Primary, selected.Secondary} { + for _, w := range windows { if w == nil || w.Seconds != 7*24*60*60 { continue } weeklyCount++ - if weeklyCount > 1 || w.Used == nil || !validOpenAI429Percent(*w.Used) || + if weeklyCount > 1 || w.malformed || w.Used == nil || !validOpenAI429Percent(*w.Used) || (w.ResetAfter != nil && (*w.ResetAfter <= 0 || *w.ResetAfter > 7*24*60*60)) || (w.ResetAt != nil && !time.Unix(*w.ResetAt, 0).After(now)) { weekly = map[string]any{openAI429WeeklyInvalidAtKey: now.UTC().Format(time.RFC3339Nano)} @@ -80,11 +106,11 @@ func openAIQuotaSchedulingUpdates(body []byte, shadow bool, expectedAccountID st return updates } updates := make(map[string]any) - for _, w := range []*window{selected.Primary, selected.Secondary} { + for _, w := range windows { if w == nil || w.Used == nil { continue } - if math.IsNaN(*w.Used) || math.IsInf(*w.Used, 0) || *w.Used < 0 { + if w.malformed || math.IsNaN(*w.Used) || math.IsInf(*w.Used, 0) || *w.Used < 0 { return finish(nil) } var name string From ca9153157d8d421e299ea070e719b43cfa263c34 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 00:57:21 +0800 Subject: [PATCH 31/38] ci: scope HTTP2 historical overlays to the reviewed transport repair --- .github/workflows/http2-stream-reset.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml index 381b70f5e26f..95885e48a1cf 100644 --- a/.github/workflows/http2-stream-reset.yml +++ b/.github/workflows/http2-stream-reset.yml @@ -57,13 +57,19 @@ jobs: mkdir -p "$RUNNER_TEMP/http2-evidence" git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/http2-evidence/head.txt" baseline=ccf997c73868083d96c0bec56e71c1a34d26c98a - mapfile -t targets < <(git diff --name-only "$baseline" HEAD -- 'backend/**/*.go' ':!backend/**/*_test.go' ':!backend/**/*_test_support.go') + # Freeze the transport repair's source set. A later production merge + # must not roll back unrelated schemas while retaining their new tests. + reviewed=f177caec5510f502270ff3ceb36fe43295f405f1 + mapfile -t targets < <(git diff --name-only "$baseline" "$reviewed" -- 'backend/**/*.go' ':!backend/**/*_test.go' ':!backend/**/*_test_support.go') restore_head() { for target in "${targets[@]}"; do git show "HEAD:$target" > "$target"; done } trap restore_head EXIT for target in "${targets[@]}"; do - if git cat-file -e "$baseline:$target" 2>/dev/null; then git show "$baseline:$target" > "$target"; fi + if git cat-file -e "$baseline:$target" 2>/dev/null; then + git show "$baseline:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" + fi done git diff --stat > "$RUNNER_TEMP/http2-evidence/overlay.txt" set +e From 387d0774aee30d9c3abfdd8af201d511af12d963 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 01:10:19 +0800 Subject: [PATCH 32/38] ci: isolate weekly quota provenance from historical recovery fixture --- .github/workflows/issue715-agent-recovery.yml | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml index 961d1eadd5ed..b4c77bb06015 100644 --- a/.github/workflows/issue715-agent-recovery.yml +++ b/.github/workflows/issue715-agent-recovery.yml @@ -108,13 +108,26 @@ jobs: # Retain the pre-TTL billing leaf without changing recovery behavior. billing_compat=6fa7fb86eae7c732794450646dc13831dce87ff1 billing_leaf=backend/internal/service/openai_gateway_usage.go + # The original snapshot type has no weekly provenance field. Restore + # the unrelated quota policy and its callers together, preserving the + # exact Issue715 recovery blobs and all retained handler assertions. + weekly_compat=f895ea743f34a4c4ab6c9d01c01e13c931625a6e + weekly_leaves=(backend/internal/service/openai_disable_scheduling_429.go backend/internal/service/openai_gateway_passthrough.go backend/internal/service/openai_plugin_transport.go backend/internal/service/openai_quota_service.go backend/internal/service/openai_quota_usage_snapshot.go backend/internal/service/openai_ws_forwarder_support.go backend/internal/service/openai_ws_forwarder_v2.go) git fetch --no-tags --depth=1 origin "$original" git fetch --no-tags --depth=1 origin "$analysis_compat" git fetch --no-tags --depth=1 origin "$billing_compat" - trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}"; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" git restore --source="$analysis_compat" -- "$analysis_leaf" git restore --source="$billing_compat" -- "$billing_leaf" + git fetch --no-tags --depth=1 origin "$weekly_compat" + git restore --source="$weekly_compat" -- "${weekly_leaves[@]}" + for leaf in "${weekly_leaves[@]}"; do + expected=$(git rev-parse "$weekly_compat:$leaf") + actual=$(git hash-object "$leaf") + echo "compatibility_leaf_baseline=$weekly_compat path=$leaf expected_blob=$expected tested_blob=$actual" + test "$expected" = "$actual" + done expected=$(git rev-parse "$billing_compat:$billing_leaf") actual=$(git hash-object "$billing_leaf") echo "compatibility_leaf_baseline=$billing_compat path=$billing_leaf expected_blob=$expected tested_blob=$actual" From 1b8378f8130e0b4454685bb820e44193735e7c6f Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 01:10:54 +0800 Subject: [PATCH 33/38] fix: keep invalid weekly provenance guard at snapshot persistence boundary --- backend/internal/service/openai_disable_scheduling_429.go | 3 --- backend/internal/service/openai_gateway_usage.go | 3 +-- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/backend/internal/service/openai_disable_scheduling_429.go b/backend/internal/service/openai_disable_scheduling_429.go index edb70ea5bd30..7346c30e0333 100644 --- a/backend/internal/service/openai_disable_scheduling_429.go +++ b/backend/internal/service/openai_disable_scheduling_429.go @@ -236,9 +236,6 @@ func openAI429WeeklyEvidence(used float64, observed time.Time, reset *int) map[s } func openAI429SnapshotWeeklyEvidence(snapshot *OpenAICodexUsageSnapshot, observed time.Time) map[string]any { - if snapshot.invalidWeekly429 { - return nil - } var evidence map[string]any for _, window := range []struct { minutes, reset *int diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 073ca9710e28..e79afa8e32f5 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -1188,8 +1188,7 @@ func buildCodexUsageExtraUpdates(snapshot *OpenAICodexUsageSnapshot, fallbackNow updates := make(map[string]any) if snapshot.invalidWeekly429 { updates[openAI429WeeklyInvalidAtKey] = baseTime.Format(time.RFC3339Nano) - } - if evidence := openAI429SnapshotWeeklyEvidence(snapshot, baseTime); evidence != nil { + } else if evidence := openAI429SnapshotWeeklyEvidence(snapshot, baseTime); evidence != nil { updates[openAI429WeeklyEvidenceKey] = evidence } From b6c188bbef4aa17cfa2ab19a93dc01fdcae17d46 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 01:35:56 +0800 Subject: [PATCH 34/38] ci: provide Redis for HTTP replay seams --- .github/workflows/priority-observation.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/priority-observation.yml b/.github/workflows/priority-observation.yml index b6f91cfcd13a..f7a777c72e07 100644 --- a/.github/workflows/priority-observation.yml +++ b/.github/workflows/priority-observation.yml @@ -145,6 +145,14 @@ jobs: cat "$RUNNER_TEMP/priority-logs/review-red.log" test "$result" -ne 0 python3 .github/scripts/priority-penalty-review-red.py "$RUNNER_TEMP/priority-logs/review-red.log" + - name: Install Redis for retained HTTP replay regressions + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + redis-server --version - name: New transport scheduler history and handler seams id: green if: ${{ !cancelled() }} From 37460fe8d5135fe7238b4d2b9b57f2b5dab82028 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 01:35:57 +0800 Subject: [PATCH 35/38] ci: provide Redis for HTTP replay seams --- .github/workflows/priority-observation.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/priority-observation.yml b/.github/workflows/priority-observation.yml index b6f91cfcd13a..f7a777c72e07 100644 --- a/.github/workflows/priority-observation.yml +++ b/.github/workflows/priority-observation.yml @@ -145,6 +145,14 @@ jobs: cat "$RUNNER_TEMP/priority-logs/review-red.log" test "$result" -ne 0 python3 .github/scripts/priority-penalty-review-red.py "$RUNNER_TEMP/priority-logs/review-red.log" + - name: Install Redis for retained HTTP replay regressions + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + redis-server --version - name: New transport scheduler history and handler seams id: green if: ${{ !cancelled() }} From eff2729247f2d5f1a4f28c561515701487e02f25 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 01:47:39 +0800 Subject: [PATCH 36/38] ci: retain additive Ops diagnostic DTO in historical reset fixtures --- .github/workflows/http2-stream-reset.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml index 95885e48a1cf..2c535db01a9d 100644 --- a/.github/workflows/http2-stream-reset.yml +++ b/.github/workflows/http2-stream-reset.yml @@ -60,7 +60,10 @@ jobs: # Freeze the transport repair's source set. A later production merge # must not roll back unrelated schemas while retaining their new tests. reviewed=f177caec5510f502270ff3ceb36fe43295f405f1 - mapfile -t targets < <(git diff --name-only "$baseline" "$reviewed" -- 'backend/**/*.go' ':!backend/**/*_test.go' ':!backend/**/*_test_support.go') + # Keep the additive Ops event DTO at HEAD: later 400 recovery code + # needs its diagnostic fields. This file only adds the reset marker + # field; old transport producers below still cannot populate it. + mapfile -t targets < <(git diff --name-only "$baseline" "$reviewed" -- 'backend/**/*.go' ':!backend/**/*_test.go' ':!backend/**/*_test_support.go' ':!backend/internal/service/ops_upstream_context.go') restore_head() { for target in "${targets[@]}"; do git show "HEAD:$target" > "$target"; done } From 118755379ebbdea9ab93977272551c7e680a2225 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 01:53:37 +0800 Subject: [PATCH 37/38] ci: supply only the additive transport DTO to original-source RED --- .github/workflows/http2-stream-reset.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml index 2c535db01a9d..f7b2d5626606 100644 --- a/.github/workflows/http2-stream-reset.yml +++ b/.github/workflows/http2-stream-reset.yml @@ -64,10 +64,23 @@ jobs: # needs its diagnostic fields. This file only adds the reset marker # field; old transport producers below still cannot populate it. mapfile -t targets < <(git diff --name-only "$baseline" "$reviewed" -- 'backend/**/*.go' ':!backend/**/*_test.go' ':!backend/**/*_test_support.go' ':!backend/internal/service/ops_upstream_context.go') + dto_leaf=backend/internal/service/http2_historical_dto_compat.go + test ! -e "$dto_leaf" restore_head() { + rm -f -- "$dto_leaf" for target in "${targets[@]}"; do git show "HEAD:$target" > "$target"; done } trap restore_head EXIT + # The retained event DTO references only this additive data type. + # Extract its exact candidate declaration; no classifier or producer + # implementation is carried into the original-source RED. + python3 - <<'PY' + import pathlib, re, subprocess + source = subprocess.check_output(['git', 'show', 'HEAD:backend/internal/service/openai_stream_read_error.go'], text=True) + declaration = re.search(r'type OpsTransportFailure struct \{\n.*?\n\}', source, re.S) + assert declaration is not None + pathlib.Path('backend/internal/service/http2_historical_dto_compat.go').write_text('package service\n\n' + declaration.group(0) + '\n') + PY for target in "${targets[@]}"; do if git cat-file -e "$baseline:$target" 2>/dev/null; then git show "$baseline:$target" > "$target" @@ -100,6 +113,8 @@ jobs: done # Semantic spoofing was introduced by the first patch; reproduce it # against the compiling pre-review candidate, retaining these tests. + # These later candidates already declare the additive DTO themselves. + rm -- "$dto_leaf" vulnerable=c351ebea9bf144c710780da5e4db0e264e6ebb9c for target in "${targets[@]}"; do git show "$vulnerable:$target" > "$target"; done set +e From 358d5ef7bba9bbde30afa2a8b4233ddf6d0232fc Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 14 Nov 2026 01:54:14 +0800 Subject: [PATCH 38/38] ci: run historical HTTP2 counterexamples in a pinned dependency tree --- .github/workflows/http2-stream-reset.yml | 40 +++++++++++------------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/.github/workflows/http2-stream-reset.yml b/.github/workflows/http2-stream-reset.yml index f7b2d5626606..de800ae7d11a 100644 --- a/.github/workflows/http2-stream-reset.yml +++ b/.github/workflows/http2-stream-reset.yml @@ -57,30 +57,27 @@ jobs: mkdir -p "$RUNNER_TEMP/http2-evidence" git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/http2-evidence/head.txt" baseline=ccf997c73868083d96c0bec56e71c1a34d26c98a - # Freeze the transport repair's source set. A later production merge - # must not roll back unrelated schemas while retaining their new tests. + # Keep the historical source/test dependencies on the last fully + # validated pre-integration checkpoint. Copy the exact current HTTP2 + # regressions into this disposable tree; GREEN below runs full HEAD. reviewed=f177caec5510f502270ff3ceb36fe43295f405f1 - # Keep the additive Ops event DTO at HEAD: later 400 recovery code - # needs its diagnostic fields. This file only adds the reset marker - # field; old transport producers below still cannot populate it. - mapfile -t targets < <(git diff --name-only "$baseline" "$reviewed" -- 'backend/**/*.go' ':!backend/**/*_test.go' ':!backend/**/*_test_support.go' ':!backend/internal/service/ops_upstream_context.go') - dto_leaf=backend/internal/service/http2_historical_dto_compat.go - test ! -e "$dto_leaf" + candidate=$(git rev-parse HEAD) + red_tree="$RUNNER_TEMP/http2-historical-red" + git worktree add --detach "$red_tree" "$reviewed" + while IFS= read -r test_source; do + git show "$candidate:$test_source" > "$red_tree/$test_source" + expected=$(git rev-parse "$candidate:$test_source") + actual=$(git hash-object "$red_tree/$test_source") + test "$expected" = "$actual" + echo "candidate_test=$test_source expected=$expected actual=$actual" >> "$RUNNER_TEMP/http2-evidence/red-tests.txt" + done < <(git ls-files 'backend/internal/handler/http2*_test.go' 'backend/internal/service/http2*_test.go' 'backend/internal/repository/http2*_test.go') + cd "$red_tree" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/http2-evidence/red-source-checkpoint.txt" + mapfile -t targets < <(git diff --name-only "$baseline" "$reviewed" -- 'backend/**/*.go' ':!backend/**/*_test.go' ':!backend/**/*_test_support.go') restore_head() { - rm -f -- "$dto_leaf" for target in "${targets[@]}"; do git show "HEAD:$target" > "$target"; done } trap restore_head EXIT - # The retained event DTO references only this additive data type. - # Extract its exact candidate declaration; no classifier or producer - # implementation is carried into the original-source RED. - python3 - <<'PY' - import pathlib, re, subprocess - source = subprocess.check_output(['git', 'show', 'HEAD:backend/internal/service/openai_stream_read_error.go'], text=True) - declaration = re.search(r'type OpsTransportFailure struct \{\n.*?\n\}', source, re.S) - assert declaration is not None - pathlib.Path('backend/internal/service/http2_historical_dto_compat.go').write_text('package service\n\n' + declaration.group(0) + '\n') - PY for target in "${targets[@]}"; do if git cat-file -e "$baseline:$target" 2>/dev/null; then git show "$baseline:$target" > "$target" @@ -113,8 +110,6 @@ jobs: done # Semantic spoofing was introduced by the first patch; reproduce it # against the compiling pre-review candidate, retaining these tests. - # These later candidates already declare the additive DTO themselves. - rm -- "$dto_leaf" vulnerable=c351ebea9bf144c710780da5e4db0e264e6ebb9c for target in "${targets[@]}"; do git show "$vulnerable:$target" > "$target"; done set +e @@ -150,6 +145,9 @@ jobs: grep -q 'incomplete raw error event must not suppress reset classification' "$RUNNER_TEMP/http2-evidence/terminal-red.log" restore_head trap - EXIT + git diff --exit-code -- "${targets[@]}" + cd "$GITHUB_WORKSPACE" + git worktree remove --force "$red_tree" git diff --exit-code - name: GREEN boundary and existing stream regressions shell: bash