From 9f5a704630537dfec4e77a9142c52c06fcbd8594 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:00:59 +0800 Subject: [PATCH 01/38] =?UTF-8?q?fix:=20=E5=9C=A8=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E5=AF=86=E6=96=87=E5=8E=86=E5=8F=B2=E5=BF=AB=E7=85=A7=E5=89=8D?= =?UTF-8?q?=E8=A7=84=E8=8C=83=E5=8C=96=E5=9B=9E=E6=94=BE=E5=85=83=E6=95=B0?= =?UTF-8?q?=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workflows/issue842-replay-metadata.yml | 108 +++++++++++ .../handler/openai_gateway_handler.go | 9 + .../handler/openai_issue842_replay_test.go | 167 ++++++++++++++++++ .../service/openai_409_omit_history.go | 2 +- .../service/openai_agent_replay_metadata.go | 70 ++++++++ 5 files changed, 355 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/issue842-replay-metadata.yml create mode 100644 backend/internal/handler/openai_issue842_replay_test.go create mode 100644 backend/internal/service/openai_agent_replay_metadata.go diff --git a/.github/workflows/issue842-replay-metadata.yml b/.github/workflows/issue842-replay-metadata.yml new file mode 100644 index 000000000000..5d291616cd9f --- /dev/null +++ b/.github/workflows/issue842-replay-metadata.yml @@ -0,0 +1,108 @@ +name: Issue842 protected replay metadata + +on: + pull_request: + branches: [production] + paths: ['backend/**', '.github/workflows/issue842-replay-metadata.yml'] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: issue842-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + +jobs: + evidence: + runs-on: ubuntu-latest + timeout-minutes: 35 + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: fixture + POSTGRES_PASSWORD: fixture + POSTGRES_DB: issue842 + ports: ['15432:5432'] + options: >- + --health-cmd "pg_isready -U fixture -d issue842" + --health-interval 5s --health-timeout 5s --health-retries 10 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated Redis fixture + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + - name: Candidate GREEN at exact head + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/issue842" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue842/candidate.txt" + cd backend + go test -race -json -tags=unit ./internal/handler -run '^TestIssue842' -count=1 -timeout=10m 2>&1 | tee "$RUNNER_TEMP/issue842/green.jsonl" + ! grep -Eiq '"Action":"skip"|no tests to run|panic:|WARNING: DATA RACE' "$RUNNER_TEMP/issue842/green.jsonl" + - name: Isolated pinned defect RED with candidate fixtures + shell: bash + run: | + set -euo pipefail + baseline=aa8e596e6d6f3e4648d6beba73b39b240dd5357a + git fetch --no-tags --depth=1 origin "$baseline" + git worktree add --detach "$RUNNER_TEMP/issue842-red" "$EXPECTED_HEAD_SHA" + cd "$RUNNER_TEMP/issue842-red" + # Only the production paths of this repair are restored. Candidate + # fixtures stay exact, and the original GREEN tree stays untouched. + for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go; do + git show "$baseline:$target" > "$target" + expected=$(git rev-parse "$baseline:$target") + actual=$(git hash-object "$target") + echo "$target expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue842/red-blobs.txt" + test "$expected" = "$actual" + done + target=backend/internal/service/openai_agent_replay_metadata.go + ! git cat-file -e "$baseline:$target" 2>/dev/null + rm -- "$target" + test ! -e "$target" + echo "$target baseline=absent actual=absent" >> "$RUNNER_TEMP/issue842/red-blobs.txt" + target=backend/internal/handler/openai_issue842_replay_test.go + test "$(git hash-object "$target")" = "$(git rev-parse "$EXPECTED_HEAD_SHA:$target")" + git diff --stat > "$RUNNER_TEMP/issue842/red-diff.txt" + set +e + (cd backend && go test -json -tags=unit ./internal/handler -run '^TestIssue842HTTPReplayMetadata$' -count=1 -timeout=5m) > "$RUNNER_TEMP/issue842/red.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/issue842/red.jsonl" + test "$result" -ne 0 + ! grep -Eiq 'build failed|no tests to run|undefined:|panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|"Action":"skip"' "$RUNNER_TEMP/issue842/red.jsonl" + python3 - "$RUNNER_TEMP/issue842/red.jsonl" <<'PY' + import itertools, json, sys + events = [json.loads(line) for line in open(sys.argv[1])] + failed = {e.get('Test') for e in events if e.get('Action') == 'fail'} + for kind, stream, variant in itertools.product(('apikey', 'oauth'), ('false', 'true'), ('reasoning_status', 'reasoning_id', 'invalid_replay_id', 'message_call_id')): + name = f'TestIssue842HTTPReplayMetadata/{kind}/stream={stream}/{variant}' + assert name in failed, f'missing business RED: {name}' + output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name) + assert 'Issue842 benign replay metadata must reach B once' in output, name + assert 'encrypted_agent_recovery_wire_changed' in output, name + PY + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue842-${{ env.EXPECTED_HEAD_SHA }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/issue842/ + if-no-files-found: error diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 3b15d85be21f..923d02b87251 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -894,6 +894,15 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } } + // Normalize the finite replay metadata before either immutable body copy or + // the recovery digest is frozen. Each attempt derives from these same bytes. + if prepared, err := h.gatewayService.PrepareOpenAIAgentReplayBody(body); err != nil { + h.handleOpenAIAgentRecoveryError(c, err, streamStarted) + return + } else { + body = prepared + } + // 解析渠道级模型映射 channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel) forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody) diff --git a/backend/internal/handler/openai_issue842_replay_test.go b/backend/internal/handler/openai_issue842_replay_test.go new file mode 100644 index 000000000000..afcf8b7cc60c --- /dev/null +++ b/backend/internal/handler/openai_issue842_replay_test.go @@ -0,0 +1,167 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// The real native OAuth builder has a fixed URL. Redirect only its final +// transport to loopback; never dial a provider or change its body/credentials. +type issue842Transport struct { + service.HTTPUpstream + target *url.URL +} + +func (u *issue842Transport) Do(req *http.Request, proxy string, account int64, concurrency int) (*http.Response, error) { + if proxy != "" || (req.URL.String() != "https://chatgpt.com/backend-api/codex/responses" && req.URL.String() != u.target.String()+"/v1/responses") { + return nil, fmt.Errorf("Issue842 refuses non-fixture transport") + } + local := req.Clone(req.Context()) + address := *req.URL + address.Scheme, address.Host = u.target.Scheme, u.target.Host + local.URL = &address + return u.HTTPUpstream.Do(local, "", account, concurrency) +} + +func (u *issue842Transport) DoWithTLS(req *http.Request, proxy string, account int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxy, account, concurrency) +} + +// This uses the existing setting's literal key so historical RED assemblies +// predating Beta can still compile these otherwise independent fixtures. +type issue842Settings struct { + service.SettingRepository + beta bool +} + +func (s *issue842Settings) GetValue(context.Context, string) (string, error) { + return fmt.Sprint(s.beta), nil +} + +func (s *issue842Settings) GetMultiple(context.Context, []string) (map[string]string, error) { + return map[string]string{"openai_409_omit_encrypted_history_enabled": fmt.Sprint(s.beta)}, nil +} + +func issue842History(t *testing.T, stream bool, variant string) (string, string) { + t.Helper() + body := issue715Body(true, stream) + var err error + body, err = sjson.Set(body, "store", false) + require.NoError(t, err) + body, err = sjson.SetRaw(body, "input.1.sequence", "9007199254740993") + require.NoError(t, err) + reasoning := `{"type":"reasoning","encrypted_content":"fixture-842-reasoning-cipher","summary":[]}` + switch variant { + case "reasoning_status": + reasoning, err = sjson.Set(reasoning, "status", "completed") + case "reasoning_id": + reasoning, err = sjson.Set(reasoning, "id", "rs_fixture842") + case "invalid_replay_id": + body, err = sjson.Set(body, "input.1.id", "invalid-provider-item842") + case "message_call_id": + body, err = sjson.Set(body, "input.1.call_id", "unpaired-output-metadata842") + } + require.NoError(t, err) + body, err = sjson.SetRaw(body, "input.-1", reasoning) + require.NoError(t, err) + // Independent expected representation: exactly the metadata permitted by + // the pre-freeze contract; no production normalizer is used as the oracle. + want := body + for _, path := range []string{"input.5.status", "input.5.id", "input.1.id", "input.1.call_id"} { + want, err = sjson.Delete(want, path) + require.NoError(t, err) + } + return body, want +} + +func TestIssue842HTTPReplayMetadata(t *testing.T) { + for _, kind := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, variant := range []string{"reasoning_status", "reasoning_id", "invalid_replay_id", "message_call_id"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", kind, stream, variant), func(t *testing.T) { + clients := issue805Redis(t) + var mu sync.Mutex + var bodies [][]byte + var identities []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + mu.Lock() + bodies = append(bodies, body) + identities = append(identities, r.Header.Get("Authorization")) + n := len(bodies) + mu.Unlock() + output := "[" + issue715Agent + "]" + if n > 1 { + output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"recorded result retained once"}]}]` + } + response := fmt.Sprintf(`{"id":"resp_842_%d","status":"completed","error":null,"model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, n, output) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, response) + } + })) + defer srv.Close() + target, err := url.Parse(srv.URL) + require.NoError(t, err) + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = kind + accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture842-%d", i+1), "access_token": fmt.Sprintf("fixture842-%d", i+1), "base_url": srv.URL} + } + newNode := func(disabled bool) *OpenAIGatewayHandler { + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + settings := service.NewSettingService(&issue842Settings{}, cfg) + h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, repository.NewGatewayCache(clients()), settings, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue805Policy(t, h.cfg, disabled) + return h + } + first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + require.JSONEq(t, issue715Agent, issue758CompletedResponse(t, first.Body.String(), stream).Get("output.0").Raw) + original := issue805Owners(t, clients()) + require.Len(t, original, 1, "A must actually complete delivery") + accounts[0].Schedulable = false + body, want := issue842History(t, stream, variant) + answer := issue758Request(t, newNode(true), body) + require.Equal(t, http.StatusOK, answer.Code, "Issue842 benign replay metadata must reach B once: %s", answer.Body.String()) + issue758CompletedResponse(t, answer.Body.String(), stream) + mu.Lock() + defer mu.Unlock() + require.Equal(t, []string{"Bearer fixture842-1", "Bearer fixture842-2"}, identities) + require.Len(t, bodies, 2, "one A generation and one intact B continuation") + require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(bodies[1], "input").Raw) + require.Equal(t, "9007199254740993", gjson.GetBytes(bodies[1], "input.1.sequence").Raw) + require.Equal(t, original, issue805Owners(t, clients()), "consuming A on B must not republish its owner") + }) + } + } + } +} diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 94f9df00cf46..e31d129bbb98 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -407,7 +407,7 @@ func openAI409ReadableMetadata(value any) any { } func prepareOpenAI409KnownReadableReplay(raw []byte) ([]byte, error) { - clean, _, err := sanitizeOpenAIResponsesInputItemIDs(raw) + clean, err := normalizeOpenAIReplayMetadata(raw) if err != nil { return nil, err } diff --git a/backend/internal/service/openai_agent_replay_metadata.go b/backend/internal/service/openai_agent_replay_metadata.go new file mode 100644 index 000000000000..5669aa67a3c3 --- /dev/null +++ b/backend/internal/service/openai_agent_replay_metadata.go @@ -0,0 +1,70 @@ +package service + +import ( + "encoding/json" + "strings" + "unicode/utf8" + + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// PrepareOpenAIAgentReplayBody is a pre-snapshot stage, never a final-wire +// exemption. Only output metadata is portable here. Readable reasoning, +// ciphertext, tool relationships, array order and JSON numbers remain intact. +// The caller must forward these bytes and freeze them before account builders. +func (s *OpenAIGatewayService) PrepareOpenAIAgentReplayBody(body []byte) ([]byte, error) { + if !s.preserveOpenAIAgentHistory(body) { + return body, nil + } + if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { + return nil, openAIAgentRecoveryError("wire_changed") + } + return normalizeOpenAIReplayMetadata(body) +} + +// Shared with readable Beta preparation. This deliberately excludes OAuth +// system promotion, namespace flattening, timezone and call reconstruction. +func normalizeOpenAIReplayMetadata(body []byte) ([]byte, error) { + clean, _, err := sanitizeOpenAIResponsesInputItemIDs(body) + if err != nil { + return nil, err + } + var source map[string]any + if err := decodeOpenAIJSONUseNumber(clean, &source); err != nil { + return nil, err + } + input, _ := source["input"].([]any) + storeFalse := gjson.GetBytes(clean, "store").Type == gjson.False + changed := false + for _, value := range input { + item, ok := value.(map[string]any) + if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "reasoning" { + continue + } + if _, exists := item["status"]; exists { + delete(item, "status") + changed = true + } + encrypted, _ := item["encrypted_content"].(string) + if !storeFalse || strings.TrimSpace(encrypted) == "" { + continue + } + if strings.HasPrefix(strings.TrimSpace(firstNonEmptyString(item["id"])), "rs_") { + delete(item, "id") + changed = true + } + if item["summary"] == nil { + item["summary"] = []any{} + changed = true + } + } + if !changed { + return clean, nil + } + encoded, err := json.Marshal(input) + if err != nil { + return nil, err + } + return sjson.SetRawBytes(clean, "input", encoded) +} From 1f9e947dd377e968c7389bf382f93567ddf98139 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:19:09 +0800 Subject: [PATCH 02/38] =?UTF-8?q?fix:=20=E5=86=BB=E7=BB=93=E6=AF=8F?= =?UTF-8?q?=E8=BD=AE=20WS=20=E5=9B=9E=E6=94=BE=E5=B9=B6=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E5=AE=8C=E6=95=B4=20reasoning=20=E5=8E=86=E5=8F=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workflows/issue842-replay-metadata.yml | 8 +- .../handler/openai_gateway_handler.go | 4 + .../openai_issue842_boundaries_test.go | 136 ++++++++++++++++ .../handler/openai_issue842_replay_test.go | 149 ++++++++++-------- .../handler/openai_issue842_ws_test.go | 96 +++++++++++ .../service/openai_agent_message_recovery.go | 14 +- .../service/openai_agent_replay_metadata.go | 31 ++++ .../service/openai_gateway_forward.go | 8 +- .../service/openai_gateway_request_body.go | 30 ++-- .../service/openai_issue842_replay_test.go | 113 +++++++++++++ .../service/openai_ws_agent_recovery.go | 39 ++++- 11 files changed, 536 insertions(+), 92 deletions(-) create mode 100644 backend/internal/handler/openai_issue842_boundaries_test.go create mode 100644 backend/internal/handler/openai_issue842_ws_test.go create mode 100644 backend/internal/service/openai_issue842_replay_test.go diff --git a/.github/workflows/issue842-replay-metadata.yml b/.github/workflows/issue842-replay-metadata.yml index 5d291616cd9f..bea47b363f54 100644 --- a/.github/workflows/issue842-replay-metadata.yml +++ b/.github/workflows/issue842-replay-metadata.yml @@ -55,7 +55,7 @@ jobs: mkdir -p "$RUNNER_TEMP/issue842" git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue842/candidate.txt" cd backend - go test -race -json -tags=unit ./internal/handler -run '^TestIssue842' -count=1 -timeout=10m 2>&1 | tee "$RUNNER_TEMP/issue842/green.jsonl" + go test -race -json -tags=unit ./internal/handler ./internal/service -run '^TestIssue(842|805)' -count=1 -timeout=10m 2>&1 | tee "$RUNNER_TEMP/issue842/green.jsonl" ! grep -Eiq '"Action":"skip"|no tests to run|panic:|WARNING: DATA RACE' "$RUNNER_TEMP/issue842/green.jsonl" - name: Isolated pinned defect RED with candidate fixtures shell: bash @@ -67,7 +67,7 @@ jobs: cd "$RUNNER_TEMP/issue842-red" # Only the production paths of this repair are restored. Candidate # fixtures stay exact, and the original GREEN tree stays untouched. - for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go; do + for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_gateway_request_body.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_agent_message_recovery.go; do git show "$baseline:$target" > "$target" expected=$(git rev-parse "$baseline:$target") actual=$(git hash-object "$target") @@ -93,8 +93,8 @@ jobs: import itertools, json, sys events = [json.loads(line) for line in open(sys.argv[1])] failed = {e.get('Test') for e in events if e.get('Action') == 'fail'} - for kind, stream, variant in itertools.product(('apikey', 'oauth'), ('false', 'true'), ('reasoning_status', 'reasoning_id', 'invalid_replay_id', 'message_call_id')): - name = f'TestIssue842HTTPReplayMetadata/{kind}/stream={stream}/{variant}' + for kind, stream, variant, known in itertools.product(('apikey', 'oauth'), ('false', 'true'), ('reasoning_status', 'reasoning_id', 'invalid_replay_id', 'message_call_id'), ('true', 'false')): + name = f'TestIssue842HTTPReplayMetadata/{kind}/stream={stream}/{variant}/known={known}' assert name in failed, f'missing business RED: {name}' output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name) assert 'Issue842 benign replay metadata must reach B once' in output, name diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 923d02b87251..e48ebe0ea99e 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -1217,6 +1217,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { // 从不可变的 canonical forwardBody 派生本次尝试 body 并整块剔除上游私有的加密 // reasoning item(含耦合的 id/summary),避免非透传上游 400 拒绝 Kiro reasoning 形态。 attemptBody := h.deriveOpenAIForwardAttemptBody(reqLog, forwardBody, account, &passthroughFailoverState) + if h.cfg != nil && h.cfg.Gateway.DisableEncryptedAgentOwnerBinding { + // Account-specific builders/retries never own the frozen source slice. + attemptBody = append([]byte(nil), attemptBody...) + } result, err := func() (*service.OpenAIForwardResult, error) { defer func() { if accountReleaseFunc != nil { diff --git a/backend/internal/handler/openai_issue842_boundaries_test.go b/backend/internal/handler/openai_issue842_boundaries_test.go new file mode 100644 index 000000000000..45c8064f683f --- /dev/null +++ b/backend/internal/handler/openai_issue842_boundaries_test.go @@ -0,0 +1,136 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type issue842FaultCache struct { + service.GatewayCache + issue715WSDeliveryCache + fault string + reads atomic.Int64 + client *redis.Client +} + +func (c *issue842FaultCache) GetOpenAIAgentRecovery(ctx context.Context, key string) (string, error) { + reads := c.reads.Add(1) + if c.fault == "redis_error" { + _ = c.client.Close() + return c.issue715WSDeliveryCache.GetOpenAIAgentRecovery(ctx, key) + } + if c.fault == "lost_after_snapshot" && reads > 1 { + if err := c.client.Del(ctx, "openai_agent_owner:v1:"+key).Err(); err != nil { + return "", err + } + } + return c.issue715WSDeliveryCache.GetOpenAIAgentRecovery(ctx, key) +} + +func TestIssue842HTTPPolicyAndDeliveryBoundaries(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, state := range []string{"complete", "pending", "failed", "conflict", "redis_error", "lost_after_snapshot", "canceled", "pointer"} { + for _, disabled := range []bool{false, true} { + for _, beta := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t/%s/optout=%t/beta=%t", stream, state, disabled, beta), func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + accounts := issue715AccountsOfType(service.AccountTypeAPIKey) + for i := range accounts { + accounts[i].Credentials = map[string]any{"api_key": []string{"fixture-ws-one", "fixture-ws-two"}[i], "base_url": srv.URL} + } + newNode := func(relaxed, lossy bool, fault string) *OpenAIGatewayHandler { + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + client := clients() + cache := repository.NewGatewayCache(client) + if fault != "" { + cache = &issue842FaultCache{GatewayCache: cache, issue715WSDeliveryCache: cache.(issue715WSDeliveryCache), fault: fault, client: client} + } + settings := service.NewSettingService(&issue842Settings{beta: lossy}, cfg) + h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, testutil.NewRealHTTPUpstream(cfg), cache, settings, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue805Policy(t, h.cfg, relaxed) + return h + } + first := issue758Request(t, newNode(false, false, ""), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + original := issue805Owners(t, clients()) + require.Len(t, original, 1) + probe := clients() + if state == "pending" || state == "failed" || state == "conflict" { + for key, raw := range original { + value := state + if state == "pending" { + value = "pending:fixture842:" + raw + } + require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err()) + } + } + before := issue805Owners(t, clients()) + accounts[0].Schedulable = false + body, want := issue842History(t, stream, "reasoning_status") + if state == "pointer" { + body = strings.TrimSuffix(body, "}") + fmt.Sprintf(`,"previous_response_id":%q}`, issue758CompletedResponse(t, first.Body.String(), stream).Get("id").String()) + } + fault := "" + if state == "redis_error" || state == "lost_after_snapshot" { + fault = state + } + h := newNode(disabled, beta, fault) + var code int + var response string + if state == "canceled" { + code, response = issue715Request(t, h, body, 715, "fixture-758-thread", true) + } else { + answer := issue758Request(t, h, body) + code, response = answer.Code, answer.Body.String() + } + allowed := state == "complete" && (disabled || beta) + // Beta explicitly detaches an old provider pointer before any + // send; ordinary opt-out cannot grant this lossy behavior. + allowed = allowed || (state == "pointer" && beta) + u.mu.Lock() + defer u.mu.Unlock() + if allowed { + require.Equal(t, http.StatusOK, code, response) + require.Len(t, u.frames, 2) + if disabled && state == "complete" { + require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw) + } + } else { + require.Len(t, u.frames, 1, "unsafe history must stop before B, regardless of metadata or Beta: %s", response) + if state != "canceled" { + require.GreaterOrEqual(t, code, http.StatusBadRequest, response) + } + } + for key, raw := range before { + if state == "lost_after_snapshot" { + current := issue805Owners(t, clients())[key] + require.True(t, current == "" || current == raw, "lost records cannot be republished") + continue + } + require.Equal(t, raw, issue805Owners(t, clients())[key]) + } + }) + } + } + } + } +} diff --git a/backend/internal/handler/openai_issue842_replay_test.go b/backend/internal/handler/openai_issue842_replay_test.go index afcf8b7cc60c..5fde2ca463b9 100644 --- a/backend/internal/handler/openai_issue842_replay_test.go +++ b/backend/internal/handler/openai_issue842_replay_test.go @@ -52,8 +52,11 @@ type issue842Settings struct { beta bool } -func (s *issue842Settings) GetValue(context.Context, string) (string, error) { - return fmt.Sprint(s.beta), nil +func (s *issue842Settings) GetValue(_ context.Context, key string) (string, error) { + if key == "openai_409_omit_encrypted_history_enabled" { + return fmt.Sprint(s.beta), nil + } + return "", service.ErrSettingNotFound } func (s *issue842Settings) GetMultiple(context.Context, []string) (map[string]string, error) { @@ -72,6 +75,10 @@ func issue842History(t *testing.T, stream bool, variant string) (string, string) switch variant { case "reasoning_status": reasoning, err = sjson.Set(reasoning, "status", "completed") + case "reasoning_content": + reasoning, err = sjson.SetRaw(reasoning, "content", `[{"type":"reasoning_text","text":"Retain this readable reasoning exactly"}]`) + case "plaintext_reasoning": + reasoning = `{"type":"reasoning","summary":[{"type":"summary_text","text":"retain plaintext summary"}],"content":[{"type":"reasoning_text","text":"Retain this readable reasoning exactly"}]}` case "reasoning_id": reasoning, err = sjson.Set(reasoning, "id", "rs_fixture842") case "invalid_replay_id": @@ -95,72 +102,84 @@ func issue842History(t *testing.T, stream bool, variant string) (string, string) func TestIssue842HTTPReplayMetadata(t *testing.T) { for _, kind := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { for _, stream := range []bool{false, true} { - for _, variant := range []string{"reasoning_status", "reasoning_id", "invalid_replay_id", "message_call_id"} { - t.Run(fmt.Sprintf("%s/stream=%t/%s", kind, stream, variant), func(t *testing.T) { - clients := issue805Redis(t) - var mu sync.Mutex - var bodies [][]byte - var identities []string - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := io.ReadAll(r.Body) - if err != nil { - t.Error(err) - return + for _, variant := range []string{"reasoning_status", "reasoning_content", "plaintext_reasoning", "reasoning_id", "invalid_replay_id", "message_call_id"} { + for _, known := range []bool{true, false} { + t.Run(fmt.Sprintf("%s/stream=%t/%s/known=%t", kind, stream, variant, known), func(t *testing.T) { + clients := issue805Redis(t) + var mu sync.Mutex + var bodies [][]byte + var identities []string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + mu.Lock() + bodies = append(bodies, body) + identities = append(identities, r.Header.Get("Authorization")) + n := len(bodies) + mu.Unlock() + output := "[" + issue715Agent + "]" + if n > 1 || gjson.GetBytes(body, "input.#(type==function_call_output)").Exists() { + output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"recorded result retained once"}]}]` + } + response := fmt.Sprintf(`{"id":"resp_842_%d","status":"completed","error":null,"model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, n, output) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, response) + } + })) + defer srv.Close() + target, err := url.Parse(srv.URL) + require.NoError(t, err) + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = kind + accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture842-%d", i+1), "access_token": fmt.Sprintf("fixture842-%d", i+1), "base_url": srv.URL} } - mu.Lock() - bodies = append(bodies, body) - identities = append(identities, r.Header.Get("Authorization")) - n := len(bodies) - mu.Unlock() - output := "[" + issue715Agent + "]" - if n > 1 { - output = `[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"recorded result retained once"}]}]` + newNode := func(disabled bool) *OpenAIGatewayHandler { + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + settings := service.NewSettingService(&issue842Settings{}, cfg) + h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, repository.NewGatewayCache(clients()), settings, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue805Policy(t, h.cfg, disabled) + return h + } + if known { + first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) + require.Equal(t, http.StatusOK, first.Code, first.Body.String()) + require.JSONEq(t, issue715Agent, issue758CompletedResponse(t, first.Body.String(), stream).Get("output.0").Raw) } - response := fmt.Sprintf(`{"id":"resp_842_%d","status":"completed","error":null,"model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, n, output) - if gjson.GetBytes(body, "stream").Bool() { - w.Header().Set("Content-Type", "text/event-stream") - _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response) - } else { - w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, response) + original := issue805Owners(t, clients()) + offset := 0 + if known { + offset = 1 + } + require.Len(t, original, offset, "A must actually complete delivery") + accounts[0].Schedulable = false + body, want := issue842History(t, stream, variant) + answer := issue758Request(t, newNode(true), body) + require.Equal(t, http.StatusOK, answer.Code, "Issue842 benign replay metadata must reach B once: %s", answer.Body.String()) + issue758CompletedResponse(t, answer.Body.String(), stream) + mu.Lock() + defer mu.Unlock() + expectedIDs := []string{"Bearer fixture842-2"} + if known { + expectedIDs = append([]string{"Bearer fixture842-1"}, expectedIDs...) } - })) - defer srv.Close() - target, err := url.Parse(srv.URL) - require.NoError(t, err) - accounts := issue715Accounts() - for i := range accounts { - accounts[i].Type = kind - accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture842-%d", i+1), "access_token": fmt.Sprintf("fixture842-%d", i+1), "base_url": srv.URL} - } - newNode := func(disabled bool) *OpenAIGatewayHandler { - cfg := &config.Config{RunMode: config.RunModeSimple} - cfg.Security.URLAllowlist.AllowInsecureHTTP = true - upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} - settings := service.NewSettingService(&issue842Settings{}, cfg) - h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, repository.NewGatewayCache(clients()), settings, accounts...) - h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true - issue805Policy(t, h.cfg, disabled) - return h - } - first := issue758Request(t, newNode(false), strings.Replace(issue715Body(false, stream), issue715Agent+",", "", 1)) - require.Equal(t, http.StatusOK, first.Code, first.Body.String()) - require.JSONEq(t, issue715Agent, issue758CompletedResponse(t, first.Body.String(), stream).Get("output.0").Raw) - original := issue805Owners(t, clients()) - require.Len(t, original, 1, "A must actually complete delivery") - accounts[0].Schedulable = false - body, want := issue842History(t, stream, variant) - answer := issue758Request(t, newNode(true), body) - require.Equal(t, http.StatusOK, answer.Code, "Issue842 benign replay metadata must reach B once: %s", answer.Body.String()) - issue758CompletedResponse(t, answer.Body.String(), stream) - mu.Lock() - defer mu.Unlock() - require.Equal(t, []string{"Bearer fixture842-1", "Bearer fixture842-2"}, identities) - require.Len(t, bodies, 2, "one A generation and one intact B continuation") - require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(bodies[1], "input").Raw) - require.Equal(t, "9007199254740993", gjson.GetBytes(bodies[1], "input.1.sequence").Raw) - require.Equal(t, original, issue805Owners(t, clients()), "consuming A on B must not republish its owner") - }) + require.Equal(t, expectedIDs, identities) + require.Len(t, bodies, offset+1, "one A generation and one intact B continuation") + require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(bodies[offset], "input").Raw) + require.Equal(t, "9007199254740993", gjson.GetBytes(bodies[offset], "input.1.sequence").Raw) + require.Equal(t, original, issue805Owners(t, clients()), "consuming A on B must not republish its owner") + }) + } } } } diff --git a/backend/internal/handler/openai_issue842_ws_test.go b/backend/internal/handler/openai_issue842_ws_test.go new file mode 100644 index 000000000000..06848d7437a0 --- /dev/null +++ b/backend/internal/handler/openai_issue842_ws_test.go @@ -0,0 +1,96 @@ +//go:build unit + +package handler + +import ( + "fmt" + "net/http" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +func issue842WSHistory(t *testing.T, variant string) (string, string) { + t.Helper() + body, want := issue842History(t, true, variant) + var err error + body, err = sjson.Set(body, "type", "response.create") + require.NoError(t, err) + body, err = sjson.Set(body, "client_metadata.thread_id", "fixture-ws715-thread") + require.NoError(t, err) + return body, want +} + +func TestIssue842WSReplayMetadata(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + for _, variant := range []string{"reasoning_status", "reasoning_content", "plaintext_reasoning", "reasoning_id", "invalid_replay_id", "message_call_id"} { + for _, known := range []bool{false, true} { + t.Run(fmt.Sprintf("%s/%s/known=%t", mode, variant, known), func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + original := map[string]string{} + if known { + producer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), false, false) + issue715WSSend(t, producer.clientConn, issue715WSCreate("", false)) + require.Contains(t, string(issue715WSRead(t, producer.clientConn)), "fixture-task-reference-715") + probe := clients() + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 1 { + return false + } + for _, raw := range owners { + if !issue805CompletedOwner(raw, 1) { + return false + } + } + return true + }, time.Second, 5*time.Millisecond) + original = issue805Owners(t, probe) + issue600Finish(t, producer, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + } + consumer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), true, true) + body, want := issue842WSHistory(t, variant) + for turn := 0; turn < 2; turn++ { + issue715WSSend(t, consumer.clientConn, body) + answer := issue715WSRead(t, consumer.clientConn) + require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), "Issue842 WS benign metadata must reach the actual adapter once: %s", answer) + require.Contains(t, string(answer), "existing ledger balance 18") + } + issue600Finish(t, consumer, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + u.mu.Lock() + defer u.mu.Unlock() + offset := 0 + if known { + offset = 1 + } + ids := []string{"Bearer fixture-ws-two", "Bearer fixture-ws-two"} + if known { + ids = append([]string{"Bearer fixture-ws-one"}, ids...) + } + require.Equal(t, ids, u.ids, "no warmup or executed tool replay") + for _, frame := range u.frames[offset:] { + require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(frame, "input").Raw) + require.Equal(t, "9007199254740993", gjson.GetBytes(frame, "input.1.sequence").Raw) + } + if mode == service.OpenAIWSIngressModeHTTPBridge { + require.Equal(t, len(ids), u.http) + require.Zero(t, u.ws) + } else { + require.Equal(t, len(ids), u.ws) + require.Zero(t, u.http) + } + for key, raw := range original { + require.Equal(t, raw, issue805Owners(t, clients())[key], "A remains the original producer") + } + }) + } + } + } +} diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index aa794ad13cc7..492bb4151868 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -384,7 +384,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con if !account.IsOpenAI() || account.HasManagedOpenAIConnections() || account.AuthConnectionID != "" || account.IsOpenAIPassthroughEnabled() || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() { if request.owner != nil || request.preservesHistory() { - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIAgentRecoveryRefusal(ctx, "unsupported_adapter") } return noop, nil } @@ -392,14 +392,14 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable") } reader, err := req.GetBody() if err != nil { if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable") } body, err := io.ReadAll(reader) _ = reader.Close() @@ -407,13 +407,13 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable") } if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIAgentRecoveryRefusal(ctx, "body_unreadable") } expectedInput, expectedControls := request.inputDigest, request.replayControlsDigest if request.omittedHistory && account.IsOpenAIApiKey() && request.apiReplayPrepared { @@ -429,7 +429,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con if request.omittedHistory { logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", zap.String("stage", "input_integrity")) } - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIAgentRecoveryRefusal(ctx, "input_integrity") } if request.omittedHistory && (gjson.GetBytes(body, "previous_response_id").Exists() || gjson.GetBytes(body, "conversation").Exists() || openAI409ControlsDigest(body) != expectedControls) { @@ -459,7 +459,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, openAIAgentRecoveryError("wire_changed") } if request.ownerBindingRequired() && !sameOpenAIAgentRecoveryRoute(*request.owner, binding) { - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIAgentRecoveryRefusal(ctx, "route_identity") } if err := s.checkOpenAIAgentRecoveryRecords(ctx, request, binding); err != nil { return noop, err diff --git a/backend/internal/service/openai_agent_replay_metadata.go b/backend/internal/service/openai_agent_replay_metadata.go index 5669aa67a3c3..27f1dca8e31a 100644 --- a/backend/internal/service/openai_agent_replay_metadata.go +++ b/backend/internal/service/openai_agent_replay_metadata.go @@ -1,12 +1,15 @@ package service import ( + "context" "encoding/json" "strings" "unicode/utf8" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/tidwall/gjson" "github.com/tidwall/sjson" + "go.uber.org/zap" ) // PrepareOpenAIAgentReplayBody is a pre-snapshot stage, never a final-wire @@ -23,6 +26,34 @@ func (s *OpenAIGatewayService) PrepareOpenAIAgentReplayBody(body []byte) ([]byte return normalizeOpenAIReplayMetadata(body) } +func normalizeOpenAIResponsesReasoningContentReplayProtected(body []byte, protected bool) ([]byte, bool, error) { + if protected { + return body, false, nil + } + return normalizeOpenAIResponsesReasoningContentReplay(body) +} + +func normalizeOpenAIAPIKeyStoreFalseReasoningReplayProtected(body []byte, knownStoreFalse, protected bool) ([]byte, bool, error) { + if protected { + return body, false, nil + } + return normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, knownStoreFalse) +} + +// The allowlist is internal and fixed. Never attach bodies, ciphertext, item +// digests, route URLs or credentials, including in unexpected-stage fallback. +func openAIAgentRecoveryRefusal(ctx context.Context, stage string) error { + switch stage { + case "input_integrity", "body_unreadable", "unsupported_adapter", "route_identity": + default: + stage = "route_identity" + } + if r := openAIAgentRecoveryFromContext(ctx); r != nil && r.disableOwnerBinding { + logger.FromContext(ctx).Warn("openai.encrypted_agent_recovery_refused", zap.String("stage", stage)) + } + return openAIAgentRecoveryError("wire_changed") +} + // Shared with readable Beta preparation. This deliberately excludes OAuth // system promotion, namespace flattening, timezone and call reconstruction. func normalizeOpenAIReplayMetadata(body []byte) ([]byte, error) { diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 9e2e7098f714..643c23c7a6ea 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -373,7 +373,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco body = normalized originalBody = normalized } - if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(body, isOpenAIResponsesCompactPath(c)); normalizeErr != nil { + if normalized, changed, normalizeErr := normalizeOpenAIAPIKeyStoreFalseReasoningReplayProtected(body, isOpenAIResponsesCompactPath(c), s.preserveOpenAIAgentHistory(body)); normalizeErr != nil { return nil, normalizeErr } else if changed { body = normalized @@ -405,7 +405,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } SetActualOpenAIUpstreamEndpoint(c, openAIResponsesUpstreamEndpoint) if account.IsOpenAI() && (account.IsOpenAIApiKey() || account.IsOpenAIOAuthLike()) { - normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplay(body) + normalizedReasoningBody, reasoningChanged, reasoningErr := normalizeOpenAIResponsesReasoningContentReplayProtected(body, s.preserveOpenAIAgentHistory(body)) if reasoningErr != nil { return nil, fmt.Errorf("normalize OpenAI Responses reasoning content replay: %w", reasoningErr) } @@ -727,7 +727,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco IsCompact: isCompactRequest, SkipDefaultInstructions: true, PreserveToolCallIDs: true, - PreserveReadableReplay: readableReplay, + PreserveReadableReplay: readableReplay || openAIAgentRecoveryPreservesHistory(ctx), OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages, ResponsesLite: responsesLite, }) @@ -738,7 +738,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco IsCodexCLI: isCodexCLI, IsCompact: isCompactRequest, SkipDefaultInstructions: readableReplay, - PreserveReadableReplay: readableReplay, + PreserveReadableReplay: readableReplay || openAIAgentRecoveryPreservesHistory(ctx), OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages, ResponsesLite: responsesLite, }) diff --git a/backend/internal/service/openai_gateway_request_body.go b/backend/internal/service/openai_gateway_request_body.go index a62083f8eec6..10a55f79e051 100644 --- a/backend/internal/service/openai_gateway_request_body.go +++ b/backend/internal/service/openai_gateway_request_body.go @@ -1474,7 +1474,8 @@ func normalizeOpenAIResponsesWebSocketCompatibilityBody(body []byte, account *Ac } func normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(cfg *config.Config, body []byte, account *Account, responsesLite bool) ([]byte, bool, error) { - return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{Config: cfg, ResponsesLite: responsesLite}) + protected := cfg != nil && cfg.Gateway.DisableEncryptedAgentOwnerBinding && len(openAIAgentRecoveryItemDigests(body)) > 0 + return normalizeOpenAIResponsesCompatibilityBodyWithOptions(body, account, openAIResponsesCompatibilityOptions{Config: cfg, ResponsesLite: responsesLite, PreserveInput: protected}) } type openAIResponsesCompatibilityOptions struct { @@ -1483,6 +1484,9 @@ type openAIResponsesCompatibilityOptions struct { // Compact marks the /responses/compact wire shape, which is left as-is // by request-shape compatibility rewrites such as web_search history. Compact bool + // The pre-builder metadata stage already prepared this complete history. + // Never drop readable reasoning or whole items in ordinary opt-out mode. + PreserveInput bool } func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account *Account, opts openAIResponsesCompatibilityOptions) ([]byte, bool, error) { @@ -1499,11 +1503,13 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * return body, false, err } } - if next, normalizedReasoningContent, err := normalizeOpenAIResponsesReasoningContentReplay(normalized); err != nil { - return body, false, err - } else if normalizedReasoningContent { - normalized = next - changed = true + if !opts.PreserveInput { + if next, normalizedReasoningContent, err := normalizeOpenAIResponsesReasoningContentReplay(normalized); err != nil { + return body, false, err + } else if normalizedReasoningContent { + normalized = next + changed = true + } } if account.IsOpenAIApiKey() { if next, normalizedParallel, err := normalizeOpenAIParallelToolCallsWithoutTools(normalized, responsesLite); err != nil { @@ -1512,11 +1518,13 @@ func normalizeOpenAIResponsesCompatibilityBodyWithOptions(body []byte, account * normalized = next changed = true } - if next, normalizedReasoning, err := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(normalized, false); err != nil { - return body, false, err - } else if normalizedReasoning { - normalized = next - changed = true + if !opts.PreserveInput { + if next, normalizedReasoning, err := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(normalized, false); err != nil { + return body, false, err + } else if normalizedReasoning { + normalized = next + changed = true + } } } if sanitized, idsChanged, err := sanitizeOpenAIResponsesInputItemIDs(normalized); err != nil { diff --git a/backend/internal/service/openai_issue842_replay_test.go b/backend/internal/service/openai_issue842_replay_test.go new file mode 100644 index 000000000000..af1482bdb442 --- /dev/null +++ b/backend/internal/service/openai_issue842_replay_test.go @@ -0,0 +1,113 @@ +package service + +import ( + "bytes" + "context" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +const issue842Source = `{"model":"gpt-6-astra","store":false,"input":[{"type":"agent_message","author":"fixture-parent","recipient":"fixture-worker","encrypted_content":"fixture-agent842"},{"type":"reasoning","status":"completed","id":"rs_fixture842","summary":[],"content":[{"type":"reasoning_text","text":"readable reasoning842"}],"encrypted_content":"fixture-reasoning842"},{"type":"message","role":"user","content":"keep task842","sequence":9007199254740993},{"type":"function_call","name":"record","call_id":"fc_fixture842","arguments":"{\"n\":9007199254740993}"},{"type":"function_call_output","call_id":"fc_fixture842","output":"already recorded842"}]}` + +func TestIssue842FrozenWSInputRejectsSemanticMutation(t *testing.T) { + for _, mutation := range []string{"intact", "agent_cipher", "author", "reasoning_cipher", "readable_reasoning", "task", "arguments", "result", "pair", "order", "precision", "drop_reasoning", "inject_status", "mutate_source"} { + t.Run(mutation, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + manager, _, account := issue715WSManager(t, svc, context.Background()) + defer manager.abort() + source := []byte(issue842Source) + original := append([]byte(nil), source...) + // Keep historical production-overlay assemblies compilable. The + // exact candidate must provide the pre-builder preparation method. + preparer, ok := any(manager).(interface { + prepareReadable(*Account, []byte) ([]byte, error) + }) + require.True(t, ok) + payload, err := preparer.prepareReadable(account, source) + require.NoError(t, err) + require.Equal(t, original, source, "preparation must not mutate the original frame") + path, value := "", "changed842" + switch mutation { + case "agent_cipher": + path = "input.0.encrypted_content" + case "author": + path = "input.0.author" + case "reasoning_cipher": + path = "input.1.encrypted_content" + case "readable_reasoning": + path = "input.1.content.0.text" + case "task", "mutate_source": + path = "input.2.content" + case "arguments": + path = "input.3.arguments" + case "result": + path = "input.4.output" + case "pair": + path = "input.4.call_id" + case "inject_status": + path, value = "input.1.status", "completed" + case "precision": + payload, err = sjson.SetRawBytes(payload, "input.2.sequence", []byte("9007199254740992")) + case "drop_reasoning": + payload, err = sjson.DeleteBytes(payload, "input.1") + case "order": + items := gjson.GetBytes(payload, "input").Array() + items[0], items[2] = items[2], items[0] + var raw []string + for _, item := range items { + raw = append(raw, item.Raw) + } + payload, err = sjson.SetRawBytes(payload, "input", []byte("["+strings.Join(raw, ",")+"]")) + } + require.NoError(t, err) + if path != "" { + payload, err = sjson.SetBytes(payload, path, value) + require.NoError(t, err) + } + if mutation == "mutate_source" { + source = append([]byte(nil), payload...) + } + err = manager.beginSocket(account, source, payload, "wss://native.example/v1/responses", http.Header{"Authorization": {"Bearer fixture"}}, "ctx_pool") + if mutation == "intact" { + require.NoError(t, err) + require.Contains(t, string(payload), "readable reasoning842") + require.Contains(t, string(payload), "9007199254740993") + } else { + var refusal *OpenAIAgentRecoveryError + require.ErrorAs(t, err, &refusal, "a frozen snapshot cannot trust later source or wire mutation") + require.Equal(t, "wire_changed", refusal.Reason) + } + }) + } +} + +func TestIssue842FrozenHTTPInputRejectsSemanticMutation(t *testing.T) { + for _, replacement := range []string{"fixture-agent842", "readable reasoning842", "keep task842", "9007199254740993", "already recorded842"} { + t.Run(replacement, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}} + svc.cfg.Gateway.DisableEncryptedAgentOwnerBinding = true + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + // Explicit expected metadata normalization, independent of helper. + body := strings.ReplaceAll(strings.ReplaceAll(issue842Source, `,"status":"completed"`, ""), `,"id":"rs_fixture842"`, "") + ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra") + mutated := strings.Replace(body, replacement, replacement+"-changed", 1) + if replacement == "9007199254740993" { + mutated = strings.Replace(body, replacement, "9007199254740992", 1) + } + req, err := http.NewRequest(http.MethodPost, "https://fixture.example/v1/responses", bytes.NewBufferString(mutated)) + require.NoError(t, err) + _, err = svc.prepareOpenAIAgentRecoveryAttempt(ctx, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req) + var refusal *OpenAIAgentRecoveryError + require.ErrorAs(t, err, &refusal) + require.Equal(t, "wire_changed", refusal.Reason) + }) + } +} diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index d26560e52b10..163dcb63e096 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -52,6 +52,8 @@ type openAIWSAgentRecovery struct { readable *openAIAgentRecoveryRequest readableSource, readableControls [32]byte bridgeSource []byte // verified pre-builder bytes, bounded by the current frame + protected *openAIAgentRecoveryRequest + protectedSource [32]byte } func newOpenAIWSAgentRecovery(s *OpenAIGatewayService, ctx context.Context, c *gin.Context) *openAIWSAgentRecovery { @@ -110,9 +112,25 @@ func (r *openAIWSAgentRecovery) prepareReadable(account *Account, source []byte) defer r.mu.Unlock() r.readable = nil r.bridgeSource = nil + r.protected = nil initial := openAIAgentRecoveryFromContext(r.ctx) if initial == nil || !initial.omittedHistory { - return source, nil + clean, err := r.service.PrepareOpenAIAgentReplayBody(source) + if err != nil { + return nil, err + } + if r.service.preserveOpenAIAgentHistory(source) { + // Freeze before compatibility, timezone, OAuth or tool builders. + // begin may refresh owner records, but cannot trust a new input. + model := gjson.GetBytes(source, "model").String() + if initial != nil { + model = initial.model + } + ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, clean, r.session, model) + r.protected = openAIAgentRecoveryFromContext(ctx) + r.protectedSource = openAIAgentRecoveryInputDigest(source) + } + return clean, nil } ctx, clean := r.ctx, source if openAIAgentRecoveryInputDigest(source) != initial.inputDigest || openAI409ControlsDigest(source) != initial.replayControlsDigest { @@ -228,6 +246,25 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, model = initial.model } ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, source, r.session, model) + if r.protected != nil { + if openAIAgentRecoveryInputDigest(source) != r.protectedSource { + return openAIAgentRecoveryRefusal(ctx, "input_integrity") + } + // Keep fresh authoritative lookup/fences; the trusted input remains + // the immutable pre-builder snapshot, never the final source/payload. + fresh := openAIAgentRecoveryFromContext(ctx) + fresh.inputDigest = r.protected.inputDigest + if fresh.known == nil { + fresh.known = make(map[[32]byte]bool) + } + for key := range r.protected.known { + fresh.known[key] = true + } + if r.protected.lookupErr != nil { + fresh.lookupErr = r.protected.lookupErr + } + fresh.conflict = fresh.conflict || r.protected.conflict + } if r.readable != nil { if openAIAgentRecoveryInputDigest(source) != r.readableSource || openAI409ControlsDigest(source) != r.readableControls { return openAIAgentRecoveryError("wire_changed") From e357dcf9843852c392586c1b3fd0e917474336a3 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:37:09 +0800 Subject: [PATCH 03/38] =?UTF-8?q?test:=20=E8=A1=A5=E9=BD=90=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=20builder=20=E6=8B=92=E7=BB=9D=E4=B8=8E=20WS=20?= =?UTF-8?q?=E6=9C=AA=E7=9F=A5=E4=BA=A4=E4=BB=98=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue715-agent-recovery.yml | 21 ++++- .../workflows/issue842-replay-metadata.yml | 18 +++- .../openai_issue842_boundaries_test.go | 52 ++++++++++++ .../handler/openai_issue842_replay_test.go | 13 ++- .../handler/openai_issue842_ws_test.go | 85 ++++++++++++++++++- .../service/openai_ws_agent_recovery.go | 2 +- 6 files changed, 182 insertions(+), 9 deletions(-) diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml index c1cfe5ab849a..1fd15227c5cc 100644 --- a/.github/workflows/issue715-agent-recovery.yml +++ b/.github/workflows/issue715-agent-recovery.yml @@ -100,9 +100,13 @@ jobs: targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_gateway_response_handling.go backend/internal/service/openai_gateway_service.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go) added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_agent_message_recovery_wait.go backend/internal/service/openai_ws_search_activation.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go) # The exact original gateway struct predates analysis admission state. - added+=(backend/internal/service/openai_ws_readable_continuation.go) + added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_replay_metadata.go) # Pin this unrelated leaf to its pre-admission version, preserving all # Issue715 business-chain blobs and the retained handler regressions. + # Issue842 compatibility-body callers depend on the later recovery + # helper. Keep its exact pre-Issue842 blob in this historical assembly. + metadata_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a + metadata_leaf=backend/internal/service/openai_gateway_request_body.go analysis_compat=e395038e98fbc5a0c44944f0edcfbfe714570f71 analysis_leaf=backend/internal/service/priority_analysis.go # The restored usage struct also predates the 30m/12h counters. @@ -115,10 +119,14 @@ jobs: weekly_compat=f895ea743f34a4c4ab6c9d01c01e13c931625a6e weekly_leaves=(backend/internal/service/openai_disable_scheduling_429.go backend/internal/service/openai_gateway_passthrough.go backend/internal/service/openai_plugin_transport.go backend/internal/service/openai_quota_service.go backend/internal/service/openai_quota_usage_snapshot.go backend/internal/service/openai_ws_forwarder_support.go backend/internal/service/openai_ws_forwarder_v2.go) git fetch --no-tags --depth=1 origin "$original" + git fetch --no-tags --depth=1 origin "$metadata_compat" git fetch --no-tags --depth=1 origin "$analysis_compat" git fetch --no-tags --depth=1 origin "$billing_compat" - trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "$metadata_leaf" "${weekly_leaves[@]}"; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" + git restore --source="$metadata_compat" -- "$metadata_leaf" + test "$(git hash-object "$metadata_leaf")" = "$(git rev-parse "$metadata_compat:$metadata_leaf")" + echo "compatibility_leaf_baseline=$metadata_compat path=$metadata_leaf blob=$(git hash-object "$metadata_leaf")" git restore --source="$analysis_compat" -- "$analysis_leaf" git restore --source="$billing_compat" -- "$billing_leaf" git fetch --no-tags --depth=1 origin "$weekly_compat" @@ -260,12 +268,19 @@ jobs: wait_added=backend/internal/service/openai_agent_message_recovery_wait.go # The Beta helper depends on fields absent in this historical recovery struct. omission_added=(backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go) + omission_added+=(backend/internal/service/openai_agent_replay_metadata.go) + metadata_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a + metadata_leaf=backend/internal/service/openai_gateway_request_body.go git fetch --no-tags --depth=1 origin "$original" git fetch --no-tags --depth=1 origin "$ws_original" git fetch --no-tags --depth=1 origin "$scheduler_compat" - trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "${omission_added[@]}"; git diff --exit-code' EXIT + git fetch --no-tags --depth=1 origin "$metadata_compat" + trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "$metadata_leaf" "${omission_added[@]}"; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" git restore --source="$ws_original" -- "${ws_targets[@]}" + git restore --source="$metadata_compat" -- "$metadata_leaf" + test "$(git hash-object "$metadata_leaf")" = "$(git rev-parse "$metadata_compat:$metadata_leaf")" + echo "compatibility_leaf_baseline=$metadata_compat path=$metadata_leaf blob=$(git hash-object "$metadata_leaf")" git restore --source="$scheduler_compat" -- "$scheduler_leaf" expected=$(git rev-parse "$scheduler_compat:$scheduler_leaf") actual=$(git hash-object "$scheduler_leaf") diff --git a/.github/workflows/issue842-replay-metadata.yml b/.github/workflows/issue842-replay-metadata.yml index bea47b363f54..4b4fa28af3e6 100644 --- a/.github/workflows/issue842-replay-metadata.yml +++ b/.github/workflows/issue842-replay-metadata.yml @@ -54,8 +54,11 @@ jobs: test -z "$(git status --porcelain)" mkdir -p "$RUNNER_TEMP/issue842" git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue842/candidate.txt" + # Formatting is verified remotely as well; no local toolchain runs. + gofmt -d backend/internal/handler/openai_issue842*_test.go backend/internal/service/openai_issue842_replay_test.go backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_ws_agent_recovery.go > "$RUNNER_TEMP/issue842/format.patch" + cat "$RUNNER_TEMP/issue842/format.patch" cd backend - go test -race -json -tags=unit ./internal/handler ./internal/service -run '^TestIssue(842|805)' -count=1 -timeout=10m 2>&1 | tee "$RUNNER_TEMP/issue842/green.jsonl" + go test -race -json -tags=unit ./internal/handler ./internal/service -run '^Test(Issue(842|805)|OpenAIAgentRecoveryCompaction|WithoutOpenAIRemoteCompaction)' -count=1 -timeout=10m 2>&1 | tee "$RUNNER_TEMP/issue842/green.jsonl" ! grep -Eiq '"Action":"skip"|no tests to run|panic:|WARNING: DATA RACE' "$RUNNER_TEMP/issue842/green.jsonl" - name: Isolated pinned defect RED with candidate fixtures shell: bash @@ -83,7 +86,7 @@ jobs: test "$(git hash-object "$target")" = "$(git rev-parse "$EXPECTED_HEAD_SHA:$target")" git diff --stat > "$RUNNER_TEMP/issue842/red-diff.txt" set +e - (cd backend && go test -json -tags=unit ./internal/handler -run '^TestIssue842HTTPReplayMetadata$' -count=1 -timeout=5m) > "$RUNNER_TEMP/issue842/red.jsonl" 2>&1 + (cd backend && go test -json -tags=unit ./internal/handler -run '^TestIssue842(HTTP|WS)ReplayMetadata$' -count=1 -timeout=5m) > "$RUNNER_TEMP/issue842/red.jsonl" 2>&1 result=$? set -e cat "$RUNNER_TEMP/issue842/red.jsonl" @@ -93,13 +96,22 @@ jobs: import itertools, json, sys events = [json.loads(line) for line in open(sys.argv[1])] failed = {e.get('Test') for e in events if e.get('Action') == 'fail'} - for kind, stream, variant, known in itertools.product(('apikey', 'oauth'), ('false', 'true'), ('reasoning_status', 'reasoning_id', 'invalid_replay_id', 'message_call_id'), ('true', 'false')): + variants = ('reasoning_status', 'reasoning_content', 'plaintext_reasoning', 'reasoning_id', 'invalid_replay_id', 'message_call_id') + for kind, stream, variant, known in itertools.product(('apikey', 'oauth'), ('false', 'true'), variants, ('true', 'false')): name = f'TestIssue842HTTPReplayMetadata/{kind}/stream={stream}/{variant}/known={known}' assert name in failed, f'missing business RED: {name}' output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name) assert 'Issue842 benign replay metadata must reach B once' in output, name assert 'encrypted_agent_recovery_wire_changed' in output, name + for mode, variant, known in itertools.product(('ctx_pool', 'passthrough', 'http_bridge'), variants, ('true', 'false')): + name = f'TestIssue842WSReplayMetadata/{mode}/{variant}/known={known}' + assert name in failed, f'missing WS business RED: {name}' + output = ''.join(e.get('Output', '') for e in events if e.get('Test') == name) + assert 'Issue842 WS benign metadata must reach the actual adapter once' in output, name + assert 'encrypted_agent_recovery_wire_changed' in output or 'Issue842 metadata policy refusal before frame' in output, name PY + - name: Remote formatting gate + run: test ! -s "$RUNNER_TEMP/issue842/format.patch" - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_issue842_boundaries_test.go b/backend/internal/handler/openai_issue842_boundaries_test.go index 45c8064f683f..de65f7decfa7 100644 --- a/backend/internal/handler/openai_issue842_boundaries_test.go +++ b/backend/internal/handler/openai_issue842_boundaries_test.go @@ -6,6 +6,7 @@ import ( "context" "fmt" "net/http" + "net/url" "strings" "sync/atomic" "testing" @@ -18,6 +19,7 @@ import ( "github.com/redis/go-redis/v9" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) type issue842FaultCache struct { @@ -28,6 +30,56 @@ type issue842FaultCache struct { client *redis.Client } +// Exercise actual account builders after the handler has frozen the complete +// input. These rewrites have semantics and are outside the metadata allowlist. +func TestIssue842HTTPBuilderChangesStopBeforeNetwork(t *testing.T) { + for _, kind := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, change := range []string{"namespace", "timezone", "system_promotion"} { + if kind == service.AccountTypeAPIKey && change == "system_promotion" { + continue + } + t.Run(kind+"/"+change, func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + target, err := url.Parse(srv.URL) + require.NoError(t, err) + accounts := issue715Accounts() + for i := range accounts { + accounts[i].Type = kind + accounts[i].Credentials = map[string]any{"api_key": "fixture842", "access_token": "fixture842", "base_url": srv.URL} + } + body, _ := issue842History(t, false, "reasoning_status") + settingsRepo := &issue842Settings{values: map[string]string{}} + switch change { + case "namespace": + body, err = sjson.Set(body, "input.1.namespace", "semantic-namespace842") + case "system_promotion": + body, err = sjson.Set(body, "input.1.role", "system") + case "timezone": + body, err = sjson.Set(body, "input.1.content", "\nUTC\n") + settingsRepo.values["openai_request_timezone_enabled"] = "true" + settingsRepo.values["openai_request_timezone_auto"] = "false" + } + require.NoError(t, err) + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, repository.NewGatewayCache(clients()), service.NewSettingService(settingsRepo, cfg), accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + issue805Policy(t, h.cfg, true) + answer := issue758Request(t, h, body) + require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String()) + require.Contains(t, answer.Body.String(), "encrypted_agent_recovery_wire_changed") + u.mu.Lock() + defer u.mu.Unlock() + require.Empty(t, u.frames, "a gateway builder cannot rebase trust onto its changed input") + require.Empty(t, issue805Owners(t, clients())) + }) + } + } +} + func (c *issue842FaultCache) GetOpenAIAgentRecovery(ctx context.Context, key string) (string, error) { reads := c.reads.Add(1) if c.fault == "redis_error" { diff --git a/backend/internal/handler/openai_issue842_replay_test.go b/backend/internal/handler/openai_issue842_replay_test.go index 5fde2ca463b9..9daaacd76b08 100644 --- a/backend/internal/handler/openai_issue842_replay_test.go +++ b/backend/internal/handler/openai_issue842_replay_test.go @@ -49,10 +49,14 @@ func (u *issue842Transport) DoWithTLS(req *http.Request, proxy string, account i // predating Beta can still compile these otherwise independent fixtures. type issue842Settings struct { service.SettingRepository - beta bool + beta bool + values map[string]string } func (s *issue842Settings) GetValue(_ context.Context, key string) (string, error) { + if value, ok := s.values[key]; ok { + return value, nil + } if key == "openai_409_omit_encrypted_history_enabled" { return fmt.Sprint(s.beta), nil } @@ -110,6 +114,7 @@ func TestIssue842HTTPReplayMetadata(t *testing.T) { var bodies [][]byte var identities []string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Empty(t, r.Header.Get("Upgrade"), "count the actual HTTP adapter, including configured SSE acceleration") body, err := io.ReadAll(r.Body) if err != nil { t.Error(err) @@ -142,12 +147,18 @@ func TestIssue842HTTPReplayMetadata(t *testing.T) { accounts[i].Credentials = map[string]any{"api_key": fmt.Sprintf("fixture842-%d", i+1), "access_token": fmt.Sprintf("fixture842-%d", i+1), "base_url": srv.URL} } newNode := func(disabled bool) *OpenAIGatewayHandler { + if disabled && kind == service.AccountTypeOAuth { + accounts[1].Extra = map[string]any{"openai_oauth_responses_websockets_v2_enabled": true, "openai_oauth_responses_websockets_v2_mode": service.OpenAIWSIngressModeCtxPool, "openai_oauth_ws_sse_acceleration": true} + } cfg := &config.Config{RunMode: config.RunModeSimple} cfg.Security.URLAllowlist.AllowInsecureHTTP = true upstream := &issue842Transport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} settings := service.NewSettingService(&issue842Settings{}, cfg) h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, upstream, repository.NewGatewayCache(clients()), settings, accounts...) h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + h.cfg.Gateway.OpenAIWS.Enabled = disabled + h.cfg.Gateway.OpenAIWS.OAuthEnabled = disabled + h.cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = disabled issue805Policy(t, h.cfg, disabled) return h } diff --git a/backend/internal/handler/openai_issue842_ws_test.go b/backend/internal/handler/openai_issue842_ws_test.go index 06848d7437a0..32d3abc85c55 100644 --- a/backend/internal/handler/openai_issue842_ws_test.go +++ b/backend/internal/handler/openai_issue842_ws_test.go @@ -3,6 +3,7 @@ package handler import ( + "context" "fmt" "net/http" "testing" @@ -10,6 +11,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/repository" "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/tidwall/sjson" @@ -26,6 +28,78 @@ func issue842WSHistory(t *testing.T, variant string) (string, string) { return body, want } +func TestIssue842WSDeliveryAndUnknownOutcome(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { + for _, state := range []string{"pending", "failed", "conflict", "foreign_pointer", "unknown"} { + t.Run(mode+"/"+state, func(t *testing.T) { + clients := issue805Redis(t) + u := &issue805Oracle{} + srv := u.server(t) + producer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), false, false) + issue715WSSend(t, producer.clientConn, issue715WSCreate("", false)) + require.Contains(t, string(issue715WSRead(t, producer.clientConn)), "fixture-task-reference-715") + probe := clients() + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 1 { + return false + } + for _, raw := range owners { + if !issue805CompletedOwner(raw, 1) { + return false + } + } + return true + }, time.Second, 5*time.Millisecond) + original := issue805Owners(t, probe) + body, want := issue842WSHistory(t, "reasoning_status") + if state == "foreign_pointer" { + body, _ = sjson.Set(body, "previous_response_id", "resp_fixture_foreign842") + require.NoError(t, service.NewOpenAIWSStateStore(repository.NewGatewayCache(clients())).BindResponseAccount(context.Background(), 4301, "resp_fixture_foreign842", 1, time.Minute)) + } else if state != "unknown" { + for key, raw := range original { + value := state + if state == "pending" { + value = "pending:fixture842:" + raw + } + require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err()) + } + } + if state == "unknown" { + u.mu.Lock() + u.disconnect = true + u.mu.Unlock() + } + consumer := issue805WSNode(t, mode, srv.URL, repository.NewGatewayCache(clients()), true, true) + issue715WSSend(t, consumer.clientConn, body) + if state == "unknown" { + issue805WSAmbiguousTermination(t, consumer.clientConn) + } else { + code := "encrypted_agent_recovery_owner_unavailable" + if state == "pending" { + code = "encrypted_agent_recovery_delivery_pending" + } else if state == "conflict" { + code = "encrypted_agent_recovery_owner_conflict" + } + issue805WSRefusal(t, consumer.clientConn, code) + } + for _, node := range []*openAIWSPassthroughHandlerHarness{consumer, producer} { + issue600Finish(t, node, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) + } + u.mu.Lock() + defer u.mu.Unlock() + if state == "unknown" { + require.Equal(t, []string{"Bearer fixture-ws-one", "Bearer fixture-ws-two"}, u.ids, "unknown B write cannot replay warmup, generation or tool results") + require.JSONEq(t, gjson.Get(want, "input").Raw, gjson.GetBytes(u.frames[1], "input").Raw) + require.Equal(t, original, issue805Owners(t, probe)) + } else { + require.Len(t, u.frames, 1, "unsafe metadata-bearing history never reaches B") + } + }) + } + } +} + func TestIssue842WSReplayMetadata(t *testing.T) { for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeHTTPBridge} { for _, variant := range []string{"reasoning_status", "reasoning_content", "plaintext_reasoning", "reasoning_id", "invalid_replay_id", "message_call_id"} { @@ -59,7 +133,16 @@ func TestIssue842WSReplayMetadata(t *testing.T) { body, want := issue842WSHistory(t, variant) for turn := 0; turn < 2; turn++ { issue715WSSend(t, consumer.clientConn, body) - answer := issue715WSRead(t, consumer.clientConn) + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + _, answer, err := consumer.clientConn.Read(ctx) + cancel() + if err != nil { + require.NotErrorIs(t, err, context.DeadlineExceeded) + if coderws.CloseStatus(err) == coderws.StatusPolicyViolation { + t.Log("Issue842 metadata policy refusal before frame") + } + } + require.NoError(t, err, "Issue842 WS benign metadata must reach the actual adapter once") require.Equal(t, "response.completed", gjson.GetBytes(answer, "type").String(), "Issue842 WS benign metadata must reach the actual adapter once: %s", answer) require.Contains(t, string(answer), "existing ledger balance 18") } diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index 163dcb63e096..626548a38601 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -130,7 +130,7 @@ func (r *openAIWSAgentRecovery) prepareReadable(account *Account, source []byte) r.protected = openAIAgentRecoveryFromContext(ctx) r.protectedSource = openAIAgentRecoveryInputDigest(source) } - return clean, nil + return append([]byte(nil), clean...), nil } ctx, clean := r.ctx, source if openAIAgentRecoveryInputDigest(source) != initial.inputDigest || openAI409ControlsDigest(source) != initial.replayControlsDigest { From 00d2e9be01404c6e85c0560fa196e4650ef5d0fb Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:43:15 +0800 Subject: [PATCH 04/38] =?UTF-8?q?style:=20=E5=AF=B9=E9=BD=90=E8=BF=9C?= =?UTF-8?q?=E7=A8=8B=E6=A0=BC=E5=BC=8F=E6=A3=80=E6=9F=A5=E8=A6=81=E6=B1=82?= =?UTF-8?q?=E7=9A=84=20WS=20=E5=9B=9E=E5=BD=92=E7=BC=A9=E8=BF=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/openai_issue842_ws_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/handler/openai_issue842_ws_test.go b/backend/internal/handler/openai_issue842_ws_test.go index 32d3abc85c55..0a38979f3699 100644 --- a/backend/internal/handler/openai_issue842_ws_test.go +++ b/backend/internal/handler/openai_issue842_ws_test.go @@ -125,7 +125,7 @@ func TestIssue842WSReplayMetadata(t *testing.T) { } } return true - }, time.Second, 5*time.Millisecond) + }, time.Second, 5*time.Millisecond) original = issue805Owners(t, probe) issue600Finish(t, producer, http.Header{"Session_id": {"fixture-ws715-session"}, "Thread-Id": {"fixture-ws715-thread"}}) } From bf91b6fc6dfdb5e3754586cde200d2463e27127a Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:44:12 +0800 Subject: [PATCH 05/38] test: reproduce owner guard continuation on live websocket --- .github/workflows/backend-ci.yml | 65 +++++++++++++++++++ .../handler/openai_409_ws_oracle_test.go | 9 ++- .../handler/openai_409_ws_rebuild_test.go | 37 ++++++++++- .../openai_issue854_continuation_test.go | 18 +++++ .../openai_ws_v2_passthrough_cyber_test.go | 14 +++- 5 files changed, 137 insertions(+), 6 deletions(-) create mode 100644 backend/internal/handler/openai_issue854_continuation_test.go diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index c99365638d6a..e45b0ae7d34f 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -11,6 +11,71 @@ env: EXPECTED_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} jobs: + issue854-behavior: + if: github.event_name == 'pull_request' && github.head_ref == 'fix/issue854-ws-owner-continuation' + runs-on: ubuntu-latest + timeout-minutes: 35 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + - name: Assert exact candidate + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + git diff --exit-code + mkdir -p "$RUNNER_TEMP/issue854-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/issue854-evidence/candidate.txt" + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Validate evidence parser mutations + run: python3 -m unittest discover -s .github/scripts -p 'test_issue854_evidence.py' + - name: RED exact baseline production blobs with candidate tests + shell: bash + run: | + set -euo pipefail + baseline=aa8e596e6d6f3e4648d6beba73b39b240dd5357a + git worktree add --detach "$RUNNER_TEMP/issue854-red" "$EXPECTED_HEAD_SHA" + git diff --name-only "$baseline" "$EXPECTED_HEAD_SHA" -- backend | while IFS= read -r target; do + case "$target" in + *_test.go) continue ;; + *.go) + if git cat-file -e "$baseline:$target" 2>/dev/null; then + git rev-parse "$baseline:$target" >> "$RUNNER_TEMP/issue854-evidence/baseline-blobs.txt" + git show "$baseline:$target" > "$RUNNER_TEMP/issue854-red/$target" + else + rm -- "$RUNNER_TEMP/issue854-red/$target" + fi ;; + esac + done + cd "$RUNNER_TEMP/issue854-red" + git diff --stat > "$RUNNER_TEMP/issue854-evidence/red-diff.txt" + set +e + (cd backend && go test -tags=unit ./internal/handler -run '^TestIssue854OwnerContinuation$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/red.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/issue854-evidence/red.jsonl" + python3 .github/scripts/issue854-evidence.py RED "$status" "$RUNNER_TEMP/issue854-evidence/red.jsonl" + - name: GREEN clean candidate and lifecycle race checks + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" + git diff --exit-code + set +e + (cd backend && go test -race -tags=unit ./internal/handler -run '^TestIssue854OwnerContinuation$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/green.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/issue854-evidence/green.jsonl" + python3 .github/scripts/issue854-evidence.py GREEN "$status" "$RUNNER_TEMP/issue854-evidence/green.jsonl" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue854-evidence-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/issue854-evidence/ + pelican-round-evidence: if: github.event_name == 'pull_request' && github.head_ref == 'fix/issue795-round-evidence-followup-20261112' runs-on: ubuntu-latest diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index 3a0b5c5cf473..2d1a4f99f47d 100644 --- a/backend/internal/handler/openai_409_ws_oracle_test.go +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -52,6 +52,13 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt u.validationFailures++ return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_native_namespace_changed"}}}`) } + if u.scenario == "issue854_guard_live" && n == 2 { + if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-B" || !strings.Contains(string(body), "issue854-warm-B") { + u.validationFailures++ + return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_bad_B_warmup"}}}`) + } + return []byte(`{"type":"response.completed","response":{"id":"resp_issue854_warm","status":"completed","model":"gpt-5.1","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"issue854-warm-B-complete"}]}],"usage":{"input_tokens":2,"output_tokens":1}}}`) + } if u.scenario == "bridge_model" && n == 2 { if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-A" || gjson.GetBytes(body, "model").String() != "gpt-5.4" || !strings.Contains(string(body), "model-switch-warmup") { u.validationFailures++ @@ -60,7 +67,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt return []byte(`{"type":"response.completed","response":{"id":"resp_model_warmup","status":"completed","model":"gpt-5.4","error":null,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"model-switch-complete"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`) } logicalTurn := n - if u.scenario == "bridge_model" && n > 2 { + if (u.scenario == "bridge_model" || u.scenario == "issue854_guard_live") && n > 2 { logicalTurn-- } output := []json.RawMessage{json.RawMessage(httpRebuildAgentA), json.RawMessage(httpRebuildCall("apply_patch", "call_ws_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))} diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 28bcca3df809..54827613e833 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -173,6 +173,15 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { defer provider.Close() headers := http.Header{"Session_id": {"fixture-readable-ws-session"}, "Thread-Id": {"fixture-readable-ws-thread"}} settings := map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: fmt.Sprint(scenario != "off")} + issue854 := strings.HasPrefix(scenario, "issue854_") + var authSetup func(*service.APIKey, *config.Config) *service.APIKeyService + if issue854 { + headers.Set("Authorization", "Bearer sk-handler-cyber-test") + authSetup = func(key *service.APIKey, cfg *config.Config) *service.APIKeyService { + key.Status = service.StatusActive + return service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg) + } + } identityCase, modelCase := scenario == "identity" || strings.HasPrefix(scenario, "header_"), scenario == "bridge_model" customTools := strings.HasPrefix(scenario, "tools_") nativeNamespace := scenario == "native_namespace" @@ -191,9 +200,9 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { settings[service.SettingKeyCyberSessionIdentityStrictEnabled] = "true" } var accounts *readableWSAccounts - h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, provider.URL, headers, + h := newOpenAIWSPassthroughHandlerHarnessWithAuth(t, provider.URL, headers, settings, - repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, + repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, nil, authSetup, func(a *service.Account, cfg *config.Config, upstream *service.HTTPUpstream, repo *service.AccountRepository) { a.ID, a.Priority = 1, 0 a.Credentials["api_key"] = "fixture-readable-ws-A" @@ -317,6 +326,21 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { } else { accounts.disable(1) } + if scenario == "issue854_fresh" || scenario == "issue854_guard_live" { + issue600Finish(t, h, headers) + dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + conn, _, err := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers}) + cancel() + require.NoError(t, err) + h.clientConn = conn + t.Cleanup(func() { _ = conn.CloseNow() }) + if scenario == "issue854_guard_live" { + issue715WSSend(t, conn, create([]string{httpRebuildMessage("user", "issue854-warm-B")}, "")) + warm := issue715WSRead(t, conn) + require.Contains(t, string(warm), "issue854-warm-B-complete") + extraSends = 1 + } + } if scenario == "b_disabled" { accounts.disable(2) } @@ -352,7 +376,7 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { oracle.mu.Lock() sends := len(oracle.frames) oracle.mu.Unlock() - if scenario != "completed" && !identityCase && !modelCase && !nativeNamespace && smartMode == "" { + if scenario != "completed" && !issue854 && !identityCase && !modelCase && !nativeNamespace && smartMode == "" { require.NotErrorIs(t, readErr, context.DeadlineExceeded) closeCtx, cancelClose := context.WithTimeout(context.Background(), 5*time.Second) defer cancelClose() @@ -409,6 +433,10 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { } else if smartMode != "" { require.Equal(t, 2, sends, "WS_REVIEW_SMART_SESSION_STALE: close=%v terminal=%s", readErr, secondRaw) } + if scenario == "issue854_guard_live" && sends != 3 { + require.Equal(t, 2, sends) + logReadableWSDispatchFailure(t, h, readErr) + } require.Equal(t, 2+extraSends, sends, "WS_READABLE_B_DISPATCH_MISSING: same client must automatically replace disabled A before any next generation; close=%v terminal=%s", readErr, secondRaw) if modelCase { accounts.mu.Lock() @@ -459,6 +487,9 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { oracle.mu.Lock() defer oracle.mu.Unlock() expectedIdentities := []string{"Bearer fixture-readable-ws-A", "Bearer fixture-readable-ws-B", "Bearer fixture-readable-ws-B"} + if scenario == "issue854_guard_live" { + expectedIdentities = append(expectedIdentities, "Bearer fixture-readable-ws-B") + } if modelCase { expectedIdentities = append([]string{"Bearer fixture-readable-ws-A"}, expectedIdentities...) require.Equal(t, "gpt-5.4", gjson.GetBytes(oracle.frames[1], "model").String(), "A actually accepted M2 before the later omission") diff --git a/backend/internal/handler/openai_issue854_continuation_test.go b/backend/internal/handler/openai_issue854_continuation_test.go new file mode 100644 index 000000000000..e5e276910a03 --- /dev/null +++ b/backend/internal/handler/openai_issue854_continuation_test.go @@ -0,0 +1,18 @@ +//go:build unit + +package handler + +import "testing" + +// Real authentication, scheduler and forwarders; only repositories and paid +// providers are fixtures. B must validate tools, completed results and absence +// of A's ciphertext/pointers before completing the remaining tool loop. +func TestIssue854OwnerContinuation(t *testing.T) { + for _, mode := range readableWSModes { + for _, connection := range []string{"original", "fresh", "guard_live"} { + t.Run(mode+"/"+connection, func(t *testing.T) { + runReadableWSContinuation(t, mode, "issue854_"+connection) + }) + } + } +} diff --git a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go index 39a4f33bab4d..91c7dd052a57 100644 --- a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go +++ b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go @@ -60,6 +60,10 @@ func newOpenAIWSPassthroughHandlerHarnessWithKey(t *testing.T, upstreamURL strin } func newOpenAIWSPassthroughHandlerHarnessWithAudit(t *testing.T, upstreamURL string, clientHeaders http.Header, extraSettings map[string]string, gatewayCache service.GatewayCache, configureKey func(*service.APIKey), configureHandler func(*OpenAIGatewayHandler), configure ...func(*service.Account, *config.Config, *service.HTTPUpstream, *service.AccountRepository)) *openAIWSPassthroughHandlerHarness { + return newOpenAIWSPassthroughHandlerHarnessWithAuth(t, upstreamURL, clientHeaders, extraSettings, gatewayCache, configureKey, configureHandler, nil, configure...) +} + +func newOpenAIWSPassthroughHandlerHarnessWithAuth(t *testing.T, upstreamURL string, clientHeaders http.Header, extraSettings map[string]string, gatewayCache service.GatewayCache, configureKey func(*service.APIKey), configureHandler func(*OpenAIGatewayHandler), authSetup func(*service.APIKey, *config.Config) *service.APIKeyService, configure ...func(*service.Account, *config.Config, *service.HTTPUpstream, *service.AccountRepository)) *openAIWSPassthroughHandlerHarness { t.Helper() if gatewayCache == nil { gatewayCache = testutil.NewRedisGatewayCache(t) @@ -166,10 +170,16 @@ func newOpenAIWSPassthroughHandlerHarnessWithAudit(t *testing.T, upstreamURL str return zapcore.NewTee(core, requestCore) })) c.Request = c.Request.WithContext(logger.IntoContext(c.Request.Context(), observed)) - c.Set(string(middleware.ContextKeyAPIKey), apiKey) - c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) + if authSetup == nil { + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) + } c.Next() }) + if authSetup != nil { + h.apiKeyService = authSetup(apiKey, cfg) + router.Use(gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(h.apiKeyService, nil, cfg))) + } router.GET("/openai/v1/responses", func(c *gin.Context) { h.ResponsesWebSocket(c) finalHeaders <- c.Request.Header.Clone() From 276aac908b829dbd853be90cd2d1032dae07c9ee Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:44:52 +0800 Subject: [PATCH 06/38] test: include strict issue854 evidence validator --- .github/scripts/issue854-evidence.py | 55 +++++++++++++++++++++++ .github/scripts/test_issue854_evidence.py | 42 +++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 .github/scripts/issue854-evidence.py create mode 100644 .github/scripts/test_issue854_evidence.py diff --git a/.github/scripts/issue854-evidence.py b/.github/scripts/issue854-evidence.py new file mode 100644 index 000000000000..591e76ff8024 --- /dev/null +++ b/.github/scripts/issue854-evidence.py @@ -0,0 +1,55 @@ +"""Accept named business failures only; shared validator rejects dirty logs.""" +import importlib.util +import json +import sys +from collections import Counter +from pathlib import Path + +spec = importlib.util.spec_from_file_location("common", Path(__file__).with_name("assert-readable-continuation.py")) +common = importlib.util.module_from_spec(spec) +spec.loader.exec_module(common) +ROOT = "TestIssue854OwnerContinuation" +MODES = ("http_bridge", "ctx_pool", "shared", "dedicated", "passthrough") +LEAVES = {f"{ROOT}/{mode}/{case}" for mode in MODES for case in ("original", "fresh", "guard_live")} +PARENTS = {ROOT} | {f"{ROOT}/{mode}" for mode in MODES} + + +def validate(phase, status, raw): + if phase not in ("RED", "GREEN"): + raise ValueError("invalid phase") + common.check_clean(raw) + events = [] + for line in raw.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(event, dict): + raise ValueError("invalid event") + events.append(event) + counts = Counter((e.get("Action"), e.get("Test")) for e in events if e.get("Package") == common.PACKAGE) + failures = {n for n in LEAVES if n.endswith("/guard_live")} if phase == "RED" else set() + failed_parents = PARENTS if failures else set() + expected = {n: "fail" if n in failures | failed_parents else "pass" for n in LEAVES | PARENTS} + expected[None] = "fail" if failures else "pass" + if status != (1 if failures else 0): + raise ValueError("wrong exit status") + for name, terminal in expected.items(): + if name and counts["run", name] != 1: + raise ValueError(f"missing/repeated run: {name}") + if counts[terminal, name] != 1 or counts["pass", name] + counts["fail", name] != 1: + raise ValueError(f"wrong terminal: {name}") + for e in events: + if e.get("Action") in ("run", "pass", "fail") and (e.get("Package") != common.PACKAGE or e.get("Test") not in expected): + raise ValueError("unrelated test") + for name in failures: + output = "".join(e.get("Output", "") for e in events if e.get("Test") == name) + for marker in ("WS_READABLE_B_DISPATCH_MISSING", "The proven encrypted agent owner is currently unavailable"): + if marker not in output: + raise ValueError(f"missing business assertion: {name}: {marker}") + + +if __name__ == "__main__": + phase, status, filename = sys.argv[1:] + validate(phase, int(status), Path(filename).read_text()) + print(f"{phase}: all {len(LEAVES)} named lifecycle leaves verified") diff --git a/.github/scripts/test_issue854_evidence.py b/.github/scripts/test_issue854_evidence.py new file mode 100644 index 000000000000..9ac998b95393 --- /dev/null +++ b/.github/scripts/test_issue854_evidence.py @@ -0,0 +1,42 @@ +import importlib.util +import json +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location("gate", Path(__file__).with_name("issue854-evidence.py")) +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) + + +def transcript(phase): + events = [] + for name in sorted(gate.LEAVES | gate.PARENTS): + events.append(dict(Action="run", Test=name, Package=gate.common.PACKAGE)) + failed = phase == "RED" and (name in gate.PARENTS or name.endswith("/guard_live")) + if failed: + events.append(dict(Action="output", Test=name, Package=gate.common.PACKAGE, Output="WS_READABLE_B_DISPATCH_MISSING: The proven encrypted agent owner is currently unavailable")) + events.append(dict(Action="fail" if failed else "pass", Test=name, Package=gate.common.PACKAGE)) + events.append(dict(Action="fail" if phase == "RED" else "pass", Package=gate.common.PACKAGE)) + return "\n".join(json.dumps(e) for e in events) + + +class EvidenceTest(unittest.TestCase): + def test_valid_and_polluted(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + raw = transcript(phase) + gate.validate(phase, code, raw) + for pollution in ("panic: fixture", "DATA RACE", "build failed", "setup failed", "no tests to run", "--- SKIP: x", "signal: killed", "fatal error", "test timed out", "crash"): + with self.subTest(phase=phase, pollution=pollution), self.assertRaises(ValueError): + gate.validate(phase, code, raw + "\n" + pollution) + with self.assertRaises(ValueError): + gate.validate(phase, code, raw.replace('"Action": "run"', '"Action": "skip"', 1)) + with self.assertRaises(ValueError): + gate.validate(phase, code, raw + "\n" + raw) + with self.assertRaises(ValueError): + gate.validate(phase, code, "") + with self.assertRaises(ValueError): + gate.validate("RED", 1, transcript("RED").replace("WS_READABLE_B_DISPATCH_MISSING", "unrelated error")) + + +if __name__ == "__main__": + unittest.main() From c1b5bcd2e1e025d7b9895996a71e364372b5d9f0 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:47:10 +0800 Subject: [PATCH 07/38] test: hydrate authenticated lifecycle fixture group --- backend/internal/handler/openai_409_ws_rebuild_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 54827613e833..0e379e55f18d 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -179,6 +179,8 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { headers.Set("Authorization", "Bearer sk-handler-cyber-test") authSetup = func(key *service.APIKey, cfg *config.Config) *service.APIKeyService { key.Status = service.StatusActive + key.User.Concurrency = 1 + key.Group = &service.Group{ID: *key.GroupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, Hydrated: true} return service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg) } } From 909e2dc8be413885673fe8b40421c5b54ae632a3 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 01:56:42 +0800 Subject: [PATCH 08/38] test: cover recovery persistence and safe owner limit diagnostics --- .github/scripts/issue854-evidence.py | 35 ++++-- .github/scripts/test_issue854_evidence.py | 20 +++- .github/workflows/backend-ci.yml | 50 ++++++--- .../handler/openai_409_http_rebuild_test.go | 21 +++- .../handler/openai_409_ws_oracle_test.go | 4 +- .../handler/openai_409_ws_rebuild_test.go | 49 ++++++++- .../openai_issue854_continuation_test.go | 22 +++- .../handler/openai_issue854_upstream_test.go | 102 ++++++++++++++++++ .../openai_ws_v2_passthrough_cyber_test.go | 8 +- 9 files changed, 275 insertions(+), 36 deletions(-) create mode 100644 backend/internal/handler/openai_issue854_upstream_test.go diff --git a/.github/scripts/issue854-evidence.py b/.github/scripts/issue854-evidence.py index 591e76ff8024..d16952f8224a 100644 --- a/.github/scripts/issue854-evidence.py +++ b/.github/scripts/issue854-evidence.py @@ -11,10 +11,26 @@ ROOT = "TestIssue854OwnerContinuation" MODES = ("http_bridge", "ctx_pool", "shared", "dedicated", "passthrough") LEAVES = {f"{ROOT}/{mode}/{case}" for mode in MODES for case in ("original", "fresh", "guard_live")} -PARENTS = {ROOT} | {f"{ROOT}/{mode}" for mode in MODES} +PARENTS = {ROOT} -def validate(phase, status, raw): +def inventory(suite): + if suite == "lifecycle": + return LEAVES, PARENTS, {n for n in LEAVES if n.endswith("/guard_live")}, ("WS_READABLE_B_DISPATCH_MISSING", "The proven encrypted agent owner is currently unavailable") + if suite == "persistence": + root = "TestIssue854OwnerFailurePersistence" + leaves = {f"{root}/{mode}" for mode in MODES} + return leaves, {root}, leaves, ("ISSUE854_FAILURE_NOT_PERSISTED",) + if suite == "upstream": + root = "TestIssue854UpstreamOwnerRateLimit" + parents = {root} + leaves = {f"{root}/stream={stream}/encrypted_agent_recovery_{code}" for stream in ("false", "true") for code in ("owner_rate_limited", "untrusted_fixture")} + return leaves, parents, {n for n in leaves if n.endswith("owner_rate_limited")}, ("ISSUE854_OWNER_LIMIT_CODE_LOST",) + raise ValueError("invalid suite") + + +def validate(phase, status, raw, suite="lifecycle"): + leaves, parents, red_failures, markers = inventory(suite) if phase not in ("RED", "GREEN"): raise ValueError("invalid phase") common.check_clean(raw) @@ -28,9 +44,9 @@ def validate(phase, status, raw): raise ValueError("invalid event") events.append(event) counts = Counter((e.get("Action"), e.get("Test")) for e in events if e.get("Package") == common.PACKAGE) - failures = {n for n in LEAVES if n.endswith("/guard_live")} if phase == "RED" else set() - failed_parents = PARENTS if failures else set() - expected = {n: "fail" if n in failures | failed_parents else "pass" for n in LEAVES | PARENTS} + failures = red_failures if phase == "RED" else set() + failed_parents = {p for p in parents if any(n.startswith(p + "/") for n in failures)} + expected = {n: "fail" if n in failures | failed_parents else "pass" for n in leaves | parents} expected[None] = "fail" if failures else "pass" if status != (1 if failures else 0): raise ValueError("wrong exit status") @@ -44,12 +60,13 @@ def validate(phase, status, raw): raise ValueError("unrelated test") for name in failures: output = "".join(e.get("Output", "") for e in events if e.get("Test") == name) - for marker in ("WS_READABLE_B_DISPATCH_MISSING", "The proven encrypted agent owner is currently unavailable"): + for marker in markers: if marker not in output: raise ValueError(f"missing business assertion: {name}: {marker}") if __name__ == "__main__": - phase, status, filename = sys.argv[1:] - validate(phase, int(status), Path(filename).read_text()) - print(f"{phase}: all {len(LEAVES)} named lifecycle leaves verified") + phase, status, filename, *extra = sys.argv[1:] + suite = extra[0] if extra else "lifecycle" + validate(phase, int(status), Path(filename).read_text(), suite) + print(f"{phase}: all {len(inventory(suite)[0])} named {suite} leaves verified") diff --git a/.github/scripts/test_issue854_evidence.py b/.github/scripts/test_issue854_evidence.py index 9ac998b95393..5cc774aeb444 100644 --- a/.github/scripts/test_issue854_evidence.py +++ b/.github/scripts/test_issue854_evidence.py @@ -8,19 +8,31 @@ spec.loader.exec_module(gate) -def transcript(phase): +def transcript(phase, suite="lifecycle"): + leaves, parents, failures, markers = gate.inventory(suite) events = [] - for name in sorted(gate.LEAVES | gate.PARENTS): + for name in sorted(leaves | parents): events.append(dict(Action="run", Test=name, Package=gate.common.PACKAGE)) - failed = phase == "RED" and (name in gate.PARENTS or name.endswith("/guard_live")) + failed = phase == "RED" and (name in failures or (name in parents and any(n.startswith(name + "/") for n in failures))) if failed: - events.append(dict(Action="output", Test=name, Package=gate.common.PACKAGE, Output="WS_READABLE_B_DISPATCH_MISSING: The proven encrypted agent owner is currently unavailable")) + events.append(dict(Action="output", Test=name, Package=gate.common.PACKAGE, Output=" ".join(markers))) events.append(dict(Action="fail" if failed else "pass", Test=name, Package=gate.common.PACKAGE)) events.append(dict(Action="fail" if phase == "RED" else "pass", Package=gate.common.PACKAGE)) return "\n".join(json.dumps(e) for e in events) class EvidenceTest(unittest.TestCase): + def test_other_suites(self): + for suite in ("persistence", "upstream"): + for phase, code in (("RED", 1), ("GREEN", 0)): + raw = transcript(phase, suite) + gate.validate(phase, code, raw, suite) + for pollution in ("build failed", "setup failed", "no tests to run", "panic", "DATA RACE", "--- SKIP: fixture", "crash"): + with self.assertRaises(ValueError): + gate.validate(phase, code, raw + "\n" + pollution, suite) + with self.assertRaises(ValueError): + gate.validate(phase, code, raw.replace('"Action": "run"', '"Action": "skip"', 1), suite) + def test_valid_and_polluted(self): for phase, code in (("RED", 1), ("GREEN", 0)): raw = transcript(phase) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index e45b0ae7d34f..cd22119a910d 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -38,12 +38,13 @@ jobs: set -euo pipefail baseline=aa8e596e6d6f3e4648d6beba73b39b240dd5357a git worktree add --detach "$RUNNER_TEMP/issue854-red" "$EXPECTED_HEAD_SHA" + git rev-parse "$baseline" "$baseline^{tree}" > "$RUNNER_TEMP/issue854-evidence/baseline.txt" git diff --name-only "$baseline" "$EXPECTED_HEAD_SHA" -- backend | while IFS= read -r target; do case "$target" in *_test.go) continue ;; *.go) if git cat-file -e "$baseline:$target" 2>/dev/null; then - git rev-parse "$baseline:$target" >> "$RUNNER_TEMP/issue854-evidence/baseline-blobs.txt" + printf '%s %s\n' "$(git rev-parse "$baseline:$target")" "$target" >> "$RUNNER_TEMP/issue854-evidence/baseline-blobs.txt" git show "$baseline:$target" > "$RUNNER_TEMP/issue854-red/$target" else rm -- "$RUNNER_TEMP/issue854-red/$target" @@ -52,24 +53,47 @@ jobs: done cd "$RUNNER_TEMP/issue854-red" git diff --stat > "$RUNNER_TEMP/issue854-evidence/red-diff.txt" - set +e - (cd backend && go test -tags=unit ./internal/handler -run '^TestIssue854OwnerContinuation$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/red.jsonl" 2>&1 - status=$? - set -e - cat "$RUNNER_TEMP/issue854-evidence/red.jsonl" - python3 .github/scripts/issue854-evidence.py RED "$status" "$RUNNER_TEMP/issue854-evidence/red.jsonl" + for suite in lifecycle persistence upstream; do + case "$suite" in + lifecycle) test_name=TestIssue854OwnerContinuation ;; + persistence) test_name=TestIssue854OwnerFailurePersistence ;; + upstream) test_name=TestIssue854UpstreamOwnerRateLimit ;; + esac + set +e + (cd backend && go test -tags=unit ./internal/handler -run "^${test_name}$" -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/red-$suite.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/issue854-evidence/red-$suite.jsonl" + python3 .github/scripts/issue854-evidence.py RED "$status" "$RUNNER_TEMP/issue854-evidence/red-$suite.jsonl" "$suite" + done - name: GREEN clean candidate and lifecycle race checks shell: bash run: | set -euo pipefail test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD_SHA" git diff --exit-code - set +e - (cd backend && go test -race -tags=unit ./internal/handler -run '^TestIssue854OwnerContinuation$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/green.jsonl" 2>&1 - status=$? - set -e - cat "$RUNNER_TEMP/issue854-evidence/green.jsonl" - python3 .github/scripts/issue854-evidence.py GREEN "$status" "$RUNNER_TEMP/issue854-evidence/green.jsonl" + for suite in lifecycle persistence upstream; do + case "$suite" in + lifecycle) test_name=TestIssue854OwnerContinuation ;; + persistence) test_name=TestIssue854OwnerFailurePersistence ;; + upstream) test_name=TestIssue854UpstreamOwnerRateLimit ;; + esac + set +e + (cd backend && go test -race -tags=unit ./internal/handler -run "^${test_name}$" -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/green-$suite.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/issue854-evidence/green-$suite.jsonl" + python3 .github/scripts/issue854-evidence.py GREEN "$status" "$RUNNER_TEMP/issue854-evidence/green-$suite.jsonl" "$suite" + done + - name: Contract and safety regressions + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -tags=unit ./internal/handler -run '^Test(OpenAI409(WSReadableBoundaries|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|HTTPTaskRebuild|HTTPRebuildBoundaries|HTTPToolDefinitionOracle)|Issue854HTTPContinuation|Issue805|Issue758WS)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" + python3 .github/scripts/assert-ws-readable.py GREEN 0 "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" ws-boundaries + (cd backend && go test -race -tags=unit ./internal/service -run '^Test(OpenAI409WSUnsentTurnBoundary|Issue715WS|OpenAI409WS|OpenAIWS.*(Agent|Replay))' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/service-contracts.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/issue854-evidence/service-contracts.jsonl" - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_409_http_rebuild_test.go b/backend/internal/handler/openai_409_http_rebuild_test.go index ca243d2e5ba7..b2934eb0c5a8 100644 --- a/backend/internal/handler/openai_409_http_rebuild_test.go +++ b/backend/internal/handler/openai_409_http_rebuild_test.go @@ -465,6 +465,10 @@ func httpRebuildOwnerKey(t *testing.T, h *OpenAIGatewayHandler, agent string) st func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointer, outcome, boundary, mutation string) { t.Helper() + authenticated := boundary == "issue854_auth" + if authenticated { + boundary = "" + } noOpaque := strings.HasSuffix(pointer, "_no_opaque") pointer = strings.TrimSuffix(pointer, "_no_opaque") mixed := strings.HasPrefix(boundary, "mixed/") @@ -571,11 +575,21 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe pendingBeforeWrite := false var observeErr error router := gin.New() + if authenticated { + key := template.Keys[string(middleware.ContextKeyAPIKey)].(*service.APIKey) + key.Key, key.Status, key.UserID = "fixture-issue854-http", service.StatusActive, key.User.ID + key.User.Status = service.StatusActive + key.Group.Status, key.Group.Hydrated = service.StatusActive, true + h.apiKeyService = service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg) + router.Use(gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(h.apiKeyService, nil, cfg))) + } router.POST("/v1/responses", func(c *gin.Context) { defer func() { done <- struct{}{} }() sessions = append(sessions, c.GetHeader("session_id")) - for key, value := range template.Keys { - c.Set(key, value) + if !authenticated { + for key, value := range template.Keys { + c.Set(key, value) + } } if c.GetHeader("X-Fixture-Foreign-User") == "true" { c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 101}) @@ -623,6 +637,9 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe require.NoError(t, err) req.Header.Set("Content-Type", "application/json") req.Header.Set("session_id", httpRebuildSession) + if authenticated { + req.Header.Set("Authorization", "Bearer fixture-issue854-http") + } if boundary == "foreign_user" && previous.Exists() { req.Header.Set("X-Fixture-Foreign-User", "true") } diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index 2d1a4f99f47d..b6de9cf11223 100644 --- a/backend/internal/handler/openai_409_ws_oracle_test.go +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -52,7 +52,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt u.validationFailures++ return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_native_namespace_changed"}}}`) } - if u.scenario == "issue854_guard_live" && n == 2 { + if strings.HasPrefix(u.scenario, "issue854_guard_") && n == 2 { if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-B" || !strings.Contains(string(body), "issue854-warm-B") { u.validationFailures++ return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_bad_B_warmup"}}}`) @@ -67,7 +67,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt return []byte(`{"type":"response.completed","response":{"id":"resp_model_warmup","status":"completed","model":"gpt-5.4","error":null,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"model-switch-complete"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`) } logicalTurn := n - if (u.scenario == "bridge_model" || u.scenario == "issue854_guard_live") && n > 2 { + if (u.scenario == "bridge_model" || strings.HasPrefix(u.scenario, "issue854_guard_")) && n > 2 { logicalTurn-- } output := []json.RawMessage{json.RawMessage(httpRebuildAgentA), json.RawMessage(httpRebuildCall("apply_patch", "call_ws_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))} diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 0e379e55f18d..2125e0b47e49 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -174,6 +174,17 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { headers := http.Header{"Session_id": {"fixture-readable-ws-session"}, "Thread-Id": {"fixture-readable-ws-thread"}} settings := map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: fmt.Sprint(scenario != "off")} issue854 := strings.HasPrefix(scenario, "issue854_") + issue854Failure := scenario == "issue854_guard_refusal" + var failureRepo *ingressRejectOpsRepo + var configureHandler func(*OpenAIGatewayHandler) + if issue854Failure { + setupOpsErrorLogTestQueue(t, 4) + failureRepo = &ingressRejectOpsRepo{} + settings[service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled] = "false" + configureHandler = func(h *OpenAIGatewayHandler) { + h.opsService = service.NewOpsService(failureRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + } + } var authSetup func(*service.APIKey, *config.Config) *service.APIKeyService if issue854 { headers.Set("Authorization", "Bearer sk-handler-cyber-test") @@ -204,7 +215,7 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { var accounts *readableWSAccounts h := newOpenAIWSPassthroughHandlerHarnessWithAuth(t, provider.URL, headers, settings, - repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, nil, authSetup, + repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, configureHandler, authSetup, func(a *service.Account, cfg *config.Config, upstream *service.HTTPUpstream, repo *service.AccountRepository) { a.ID, a.Priority = 1, 0 a.Credentials["api_key"] = "fixture-readable-ws-A" @@ -328,7 +339,7 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { } else { accounts.disable(1) } - if scenario == "issue854_fresh" || scenario == "issue854_guard_live" { + if scenario == "issue854_fresh" || strings.HasPrefix(scenario, "issue854_guard_") { issue600Finish(t, h, headers) dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) conn, _, err := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers}) @@ -336,7 +347,7 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { require.NoError(t, err) h.clientConn = conn t.Cleanup(func() { _ = conn.CloseNow() }) - if scenario == "issue854_guard_live" { + if strings.HasPrefix(scenario, "issue854_guard_") { issue715WSSend(t, conn, create([]string{httpRebuildMessage("user", "issue854-warm-B")}, "")) warm := issue715WSRead(t, conn) require.Contains(t, string(warm), "issue854-warm-B-complete") @@ -378,6 +389,38 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { oracle.mu.Lock() sends := len(oracle.frames) oracle.mu.Unlock() + if issue854Failure { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for readErr == nil { + _, _, readErr = h.clientConn.Read(ctx) + } + require.Equal(t, coderws.StatusPolicyViolation, coderws.CloseStatus(readErr)) + select { + case <-h.handlerDone: + case <-ctx.Done(): + t.Fatal("owner refusal did not finish") + } + finished = true + for len(opsErrorLogQueue) > 0 { + flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue}) + } + require.Len(t, failureRepo.entries, 1, "ISSUE854_FAILURE_NOT_PERSISTED: WS101 must not hide the failed turn") + entry := failureRepo.entries[0] + require.Equal(t, 409, entry.StatusCode) + require.Equal(t, "internal", entry.ErrorPhase) + require.Equal(t, "platform", entry.ErrorOwner) + require.Equal(t, int16(service.RequestTypeWSV2), *entry.RequestType) + require.Equal(t, "encrypted_agent_recovery_owner_unavailable", gjson.Get(entry.ErrorBody, "error.code").String()) + require.Equal(t, "websocket", gjson.Get(entry.ErrorBody, "error.protocol").String()) + require.EqualValues(t, 2, gjson.Get(entry.ErrorBody, "error.turn").Int()) + require.Equal(t, "before_upstream_write", gjson.Get(entry.ErrorBody, "error.phase").String()) + require.Equal(t, gjson.False, gjson.Get(entry.ErrorBody, "error.request_written").Type) + require.NotContains(t, entry.ErrorBody, "fixture-opaque-A") + require.Equal(t, "encrypted_agent_recovery_owner_unavailable", gjson.GetBytes(secondRaw, "error.code").String()) + require.Equal(t, 2, sends, "failed turn cannot reach either upstream") + return + } if scenario != "completed" && !issue854 && !identityCase && !modelCase && !nativeNamespace && smartMode == "" { require.NotErrorIs(t, readErr, context.DeadlineExceeded) closeCtx, cancelClose := context.WithTimeout(context.Background(), 5*time.Second) diff --git a/backend/internal/handler/openai_issue854_continuation_test.go b/backend/internal/handler/openai_issue854_continuation_test.go index e5e276910a03..b67b202f2c53 100644 --- a/backend/internal/handler/openai_issue854_continuation_test.go +++ b/backend/internal/handler/openai_issue854_continuation_test.go @@ -2,7 +2,11 @@ package handler -import "testing" +import ( + "fmt" + "github.com/Wei-Shaw/sub2api/internal/service" + "testing" +) // Real authentication, scheduler and forwarders; only repositories and paid // providers are fixtures. B must validate tools, completed results and absence @@ -16,3 +20,19 @@ func TestIssue854OwnerContinuation(t *testing.T) { } } } + +func TestIssue854OwnerFailurePersistence(t *testing.T) { + for _, mode := range readableWSModes { + t.Run(mode, func(t *testing.T) { + runReadableWSContinuation(t, mode, "issue854_guard_refusal") + }) + } +} + +func TestIssue854HTTPContinuation(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%v", stream), func(t *testing.T) { + runHTTPRebuildFixture(t, service.AccountTypeAPIKey, stream, "previous", "completed", "issue854_auth", "") + }) + } +} diff --git a/backend/internal/handler/openai_issue854_upstream_test.go b/backend/internal/handler/openai_issue854_upstream_test.go new file mode 100644 index 000000000000..f15f890f9cf6 --- /dev/null +++ b/backend/internal/handler/openai_issue854_upstream_test.go @@ -0,0 +1,102 @@ +//go:build unit + +package handler + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestIssue854UpstreamOwnerRateLimit(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, code := range []string{"encrypted_agent_recovery_owner_rate_limited", "encrypted_agent_recovery_untrusted_fixture"} { + t.Run(fmt.Sprintf("stream=%v/%s", stream, code), func(t *testing.T) { + setupOpsErrorLogTestQueue(t, 4) + var sends atomic.Int32 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sends.Add(1) + body, err := io.ReadAll(r.Body) + if err != nil || gjson.GetBytes(body, "model").String() != "gpt-5.1" { + t.Error("invalid fixture provider request") + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusTooManyRequests) + _, _ = fmt.Fprintf(w, `{"error":{"type":"rate_limit_error","code":%q,"message":"fixture-private-provider-diagnostic","param":"fixture-private-param"}}`, code) + })) + defer provider.Close() + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + accounts := issue715AccountsOfType(service.AccountTypeAPIKey) + for i := range accounts { + accounts[i].Credentials = map[string]any{"base_url": provider.URL, "api_key": "fixture-owner-limit"} + } + h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, testutil.NewRealHTTPUpstream(cfg), nil, nil, &readable409UsageRepo{}, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + h.maxAccountSwitches = 1 + key := &service.APIKey{ID: 99, UserID: 100, Key: "fixture-issue854-client", Status: service.StatusActive, AllowLongContext: true, + User: &service.User{ID: 100, Status: service.StatusActive, Concurrency: 1}, + Group: &service.Group{ID: 3132, Platform: service.PlatformOpenAI, Status: service.StatusActive, Hydrated: true}} + key.GroupID = &key.Group.ID + h.apiKeyService = service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg) + repo := &ingressRejectOpsRepo{} + ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + done := make(chan struct{}, 1) + router := gin.New() + router.Use(func(c *gin.Context) { c.Next(); done <- struct{}{} }) + router.Use(OpsErrorLoggerMiddleware(ops)) + router.Use(gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(h.apiKeyService, nil, cfg))) + router.POST("/v1/responses", h.Responses) + gateway := httptest.NewServer(router) + defer gateway.Close() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(fmt.Sprintf(`{"model":"gpt-5.1","stream":%v,"input":"fixture continuation"}`, stream))) + require.NoError(t, err) + req.Header.Set("Authorization", "Bearer "+key.Key) + req.Header.Set("Content-Type", "application/json") + res, err := gateway.Client().Do(req) + require.NoError(t, err) + body, err := io.ReadAll(res.Body) + _ = res.Body.Close() + require.NoError(t, err) + select { + case <-done: + case <-ctx.Done(): + t.Fatal("rate limit handler did not finish") + } + require.Equal(t, 429, res.StatusCode) + require.GreaterOrEqual(t, sends.Load(), int32(1)) + require.LessOrEqual(t, sends.Load(), int32(2), "rejection recovery is bounded") + if code == "encrypted_agent_recovery_owner_rate_limited" { + require.Equal(t, code, gjson.GetBytes(body, "error.code").String(), "ISSUE854_OWNER_LIMIT_CODE_LOST") + } else { + require.NotContains(t, string(body), code, "arbitrary recovery-prefixed codes are not trusted") + } + require.NotContains(t, string(body), "fixture-private") + for len(opsErrorLogQueue) > 0 { + flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue}) + } + require.Len(t, repo.entries, 1) + require.Equal(t, 429, repo.entries[0].StatusCode) + if code == "encrypted_agent_recovery_owner_rate_limited" { + require.Equal(t, code, gjson.Get(repo.entries[0].ErrorBody, "error.code").String()) + } + }) + } + } +} diff --git a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go index 91c7dd052a57..b6a53c00f9bb 100644 --- a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go +++ b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go @@ -180,11 +180,15 @@ func newOpenAIWSPassthroughHandlerHarnessWithAuth(t *testing.T, upstreamURL stri h.apiKeyService = authSetup(apiKey, cfg) router.Use(gin.HandlerFunc(middleware.NewAPIKeyAuthMiddleware(h.apiKeyService, nil, cfg))) } - router.GET("/openai/v1/responses", func(c *gin.Context) { - h.ResponsesWebSocket(c) + router.Use(func(c *gin.Context) { + c.Next() finalHeaders <- c.Request.Header.Clone() handlerDone <- struct{}{} }) + if h.opsService != nil { + router.Use(OpsErrorLoggerMiddleware(h.opsService)) + } + router.GET("/openai/v1/responses", h.ResponsesWebSocket) handlerServer := httptest.NewServer(router) t.Cleanup(handlerServer.Close) From 6b3f7607b323a49ec9c74aa8d4b004955fe1aff4 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:02:11 +0800 Subject: [PATCH 09/38] ci: run isolated issue854 evidence on available macos runner --- .github/workflows/backend-ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index cd22119a910d..e4c3dd33495c 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -13,7 +13,7 @@ env: jobs: issue854-behavior: if: github.event_name == 'pull_request' && github.head_ref == 'fix/issue854-ws-owner-continuation' - runs-on: ubuntu-latest + runs-on: macos-15-intel timeout-minutes: 35 steps: - uses: actions/checkout@v6 From f52a018590fa629af07cd7f495d2daba1e4e327d Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:03:06 +0800 Subject: [PATCH 10/38] test: await relay teardown before attributing owner refusal --- backend/internal/handler/openai_409_ws_rebuild_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 2125e0b47e49..eb7398a0c09c 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -147,8 +147,10 @@ func logReadableWSDispatchFailure(t *testing.T, h *openAIWSPassthroughHandlerHar var peerClose coderws.CloseError require.ErrorAs(t, clientErr, &peerClose) require.Equal(t, coderws.StatusPolicyViolation, peerClose.Code) + require.Eventually(t, func() bool { + return h.requestLogs.FilterMessage("openai.websocket_proxy_failed").Len() == 1 + }, 3*time.Second, 5*time.Millisecond, "expected one actual failed B dispatch") entries := h.requestLogs.FilterMessage("openai.websocket_proxy_failed").All() - require.Len(t, entries, 1, "expected one actual failed B dispatch") require.Equal(t, int64(2), entries[0].ContextMap()["account_id"]) var reported error for _, field := range entries[0].Context { From 8a0a51cbd940f41a814aac5b0932568f0d05bded Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:08:26 +0800 Subject: [PATCH 11/38] fix: rebuild unsent websocket owner continuations and persist refusals --- .../handler/openai_agent_message_recovery.go | 28 +++++++++++- .../handler/openai_gateway_handler.go | 22 ++++++++-- .../handler/openai_issue854_upstream_test.go | 2 +- backend/internal/handler/ops_error_logger.go | 18 +++++++- .../service/openai_gateway_upstream_errors.go | 5 +++ .../service/openai_upstream_client_error.go | 11 +++++ .../service/openai_ws_forwarder_ingress.go | 5 ++- .../internal/service/openai_ws_http_bridge.go | 32 ++++++++------ .../openai_ws_readable_continuation.go | 43 +++++++++++++++++-- .../openai_ws_v2_passthrough_adapter.go | 8 +++- .../internal/service/ops_upstream_context.go | 9 ++++ 11 files changed, 157 insertions(+), 26 deletions(-) diff --git a/backend/internal/handler/openai_agent_message_recovery.go b/backend/internal/handler/openai_agent_message_recovery.go index 49cad7c167b2..f663a90c7619 100644 --- a/backend/internal/handler/openai_agent_message_recovery.go +++ b/backend/internal/handler/openai_agent_message_recovery.go @@ -17,6 +17,11 @@ func (h *OpenAIGatewayHandler) handleOpenAIAgentRecoveryError(c *gin.Context, er if !errors.As(err, &recovery) { return false } + protocol := "http" + if streamStarted || c.GetBool(opsStreamKey) { + protocol = "sse" + } + markOpenAIRecoveryFailure(c, recovery, protocol, "before_dispatch", boolPointer(false)) committed := streamStarted || c.Writer.Written() if !committed && !recovery.RetryAt.IsZero() { seconds := max(int64(1), int64((time.Until(recovery.RetryAt)+time.Second-1)/time.Second)) @@ -28,11 +33,22 @@ func (h *OpenAIGatewayHandler) handleOpenAIAgentRecoveryError(c *gin.Context, er // The socket has already upgraded when initial scheduling runs. Send the full // recovery guidance as an error event; close reasons alone are length limited. -func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Context, conn *coderws.Conn, err error) bool { +func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Context, conn *coderws.Conn, err error, contexts ...*gin.Context) bool { var recovery *service.OpenAIAgentRecoveryError if !errors.As(err, &recovery) { return false } + if len(contexts) > 0 && contexts[0] != nil { + phase, written := "before_dispatch", boolPointer(false) + var closeErr *service.OpenAIWSClientCloseError + if errors.As(err, &closeErr) { + phase, written = "forwarding", nil + } + if service.OpenAIWSAgentRecoveryBeforeSend(err) { + phase, written = "before_upstream_write", boolPointer(false) + } + markOpenAIRecoveryFailure(contexts[0], recovery, "websocket", phase, written) + } payload, _ := json.Marshal(map[string]any{ "type": "error", "status": recovery.HTTPStatus(), "error": map[string]string{"type": recovery.ClientType(), "code": recovery.ClientCode(), "message": recovery.ClientMessage()}, @@ -48,3 +64,13 @@ func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Cont closeOpenAIClientWS(conn, status, reason) return true } + +func boolPointer(value bool) *bool { return &value } + +func markOpenAIRecoveryFailure(c *gin.Context, recovery *service.OpenAIAgentRecoveryError, protocol, phase string, written *bool) { + service.MarkOpsStreamErrorValue(c, service.OpsStreamError{ + ErrType: recovery.ClientType(), Code: recovery.ClientCode(), Message: recovery.ClientMessage(), + IntendedStatus: recovery.HTTPStatus(), CountTowardsSLA: true, NonStream: protocol == "http", + RecoveryFailure: &service.OpsRecoveryFailure{Protocol: protocol, Phase: phase, RequestWritten: written}, + }) +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 3b15d85be21f..7b5ffbf0536e 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3350,7 +3350,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { ctx = h.gatewayService.WithOpenAIWSAgentRecovery(ctx, c, firstMessage, sessionHash, wsForwardModel) ctx = service.WithOpenAIGuardianParentAffinity(ctx, c, firstMessage, reqModel) if next, clean, changed, rebuildErr := h.gatewayService.PrepareOpenAI409ReadableContinuation(ctx, c, firstMessage, sessionHash, wsForwardModel); rebuildErr != nil { - h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr) + h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr, c) return } else if changed { ctx, firstMessage, previousResponseID = next, clean, "" @@ -3478,7 +3478,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { requestPlatform, ) if err != nil { - if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err) { + if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) { return } if errors.Is(err, service.ErrPriorityLatencyUnavailable) { @@ -4105,10 +4105,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { } next, clean, changed, rebuildErr := h.gatewayService.RebuildOpenAIWSUnsentTurn(ctx, c, raw, sessionHash, currentForwardModel) if rebuildErr != nil { - h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr) + h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr, c) return } if !changed { + if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) { + return + } closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account eligibility changed; reconnect with complete context") return } @@ -4160,7 +4163,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { reqModel, wsRouteModel, wsForwardModel = currentModel, currentRouteModel, currentForwardModel channelMappingWS = mapping wsAttemptMessage, previousResponseID, previousResponseCanMove = clean, "", true - failedAccountIDs[account.ID] = struct{}{} + if !service.OpenAIWSUnsentTurnKeepsAccount(err) { + failedAccountIDs[account.ID] = struct{}{} + } switchCount++ h.gatewayService.RecordOpenAIAccountSwitch() if !ensureUserSlotHeld() { @@ -4169,6 +4174,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { reqLog.Info("openai.websocket_readable_continuation", zap.Bool("context_loss", true), zap.Int("switch_count", switchCount)) break } + if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) { + releaseTurnSlots() + return + } if isOpenAIRPMError(err) { releaseTurnSlots() reason := "OpenAI OAuth RPM protection is temporarily unavailable; retry later" @@ -4633,6 +4642,11 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE upstreamMsg := service.ExtractUpstreamErrorMessage(responseBody) service.SetOpsUpstreamError(c, statusCode, upstreamMsg, "") + if code, message, ok := service.OpenAIUpstreamRecoveryRateLimit(statusCode, responseBody); ok { + service.SetOpsUpstreamError(c, statusCode, message, "") + h.handleStreamingAwareErrorWithCode(c, statusCode, "rate_limit_error", code, message, streamStarted, false) + return + } // 使用默认的错误映射 status, errType, errMsg := h.mapUpstreamError(statusCode) h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted) diff --git a/backend/internal/handler/openai_issue854_upstream_test.go b/backend/internal/handler/openai_issue854_upstream_test.go index f15f890f9cf6..55d06ce94cf2 100644 --- a/backend/internal/handler/openai_issue854_upstream_test.go +++ b/backend/internal/handler/openai_issue854_upstream_test.go @@ -49,7 +49,7 @@ func TestIssue854UpstreamOwnerRateLimit(t *testing.T) { h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true h.maxAccountSwitches = 1 key := &service.APIKey{ID: 99, UserID: 100, Key: "fixture-issue854-client", Status: service.StatusActive, AllowLongContext: true, - User: &service.User{ID: 100, Status: service.StatusActive, Concurrency: 1}, + User: &service.User{ID: 100, Status: service.StatusActive}, Group: &service.Group{ID: 3132, Platform: service.PlatformOpenAI, Status: service.StatusActive, Hydrated: true}} key.GroupID = &key.Group.ID h.apiKeyService = service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg) diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index cd4cd929ac1c..8ef6e1346795 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 || marked.TransportFailure != nil) { + if marked, ok := service.GetOpsStreamError(c); ok && (marked.BridgeFailure != nil || marked.TransportFailure != nil || marked.RecoveryFailure != nil) { // A trusted final marker must not erase failures from earlier WS turns. logOpsStreamError(c, ops, status) return @@ -1545,6 +1545,16 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus errorBody = string(payload) } } + if failure := streamErr.RecoveryFailure; failure != nil { + fields := gin.H{"type": normalizedType, "code": streamErr.Code, "message": streamErr.Message, + "protocol": failure.Protocol, "turn": streamErr.Turn, "phase": failure.Phase, "outcome": "failed"} + if failure.RequestWritten != nil { + fields["request_written"] = *failure.RequestWritten + } + if payload, err := json.Marshal(gin.H{"error": fields}); err == nil { + errorBody = string(payload) + } + } if streamErr.BridgeFailure != nil { if payload, err := json.Marshal(gin.H{"error": streamErr.BridgeFailure.Details()}); err == nil { errorBody = string(payload) @@ -1654,6 +1664,12 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus } entry.UpstreamErrorMessage, entry.UpstreamErrorDetail = nil, nil } + if streamErr.RecoveryFailure != nil { + entry.ErrorPhase, entry.ErrorOwner, entry.ErrorSource = "internal", "platform", "gateway" + entry.IsBusinessLimited = false + entry.UpstreamStatusCode, entry.UpstreamErrorMessage, entry.UpstreamErrorDetail = nil, nil, nil + entry.UpstreamErrors = nil + } if streamErr.TransportFailure != nil { entry.ErrorPhase, entry.ErrorType = "network", "transport_error" entry.ErrorOwner, entry.ErrorSource, entry.Severity = "provider", "upstream_transport", "error" diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 16f3fa9c7172..024b851779e6 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -826,6 +826,11 @@ func (s *OpenAIGatewayService) handleErrorResponse( return nil, fmt.Errorf("upstream error: %d message=%s", resp.StatusCode, upstreamMsg) } + if code, message, ok := OpenAIUpstreamRecoveryRateLimit(resp.StatusCode, body); ok { + setOpsUpstreamError(c, resp.StatusCode, message, "") + c.JSON(resp.StatusCode, gin.H{"error": gin.H{"type": "rate_limit_error", "code": code, "message": message}}) + return nil, fmt.Errorf("upstream owner rate limited: %d", resp.StatusCode) + } // Return appropriate error response var errType, errMsg string var statusCode int diff --git a/backend/internal/service/openai_upstream_client_error.go b/backend/internal/service/openai_upstream_client_error.go index 431f5a7703fd..8a394a18215e 100644 --- a/backend/internal/service/openai_upstream_client_error.go +++ b/backend/internal/service/openai_upstream_client_error.go @@ -61,3 +61,14 @@ func writeOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte, func WriteOpenAIUpstreamClientError(c *gin.Context, statusCode int, body []byte, upstreamMsg string) { writeOpenAIUpstreamClientError(c, statusCode, body, upstreamMsg) } + +// OpenAIUpstreamRecoveryRateLimit preserves one explicitly safe provider code. +// A matching prefix, arbitrary message/param, or contradictory HTTP status is +// not trusted evidence and must retain the ordinary public error mapping. +func OpenAIUpstreamRecoveryRateLimit(status int, body []byte) (code, message string, ok bool) { + const ownerRateLimit = "encrypted_agent_recovery_owner_rate_limited" + if status != http.StatusTooManyRequests || gjson.GetBytes(body, "error.code").String() != ownerRateLimit { + return "", "", false + } + return ownerRateLimit, "The upstream encrypted agent owner is temporarily rate limited. Resume this conversation after its limit resets.", true +} diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 740a43489077..454357b2645a 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -1884,11 +1884,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if err := s.priorityLatencyBeforeSend(priorityLatencyCtx, account); err != nil { return nil, err } - latencyGenerationStartedTurn = turn } if err := agentRecovery.beginSocket(latest, clientPayload, payload, wsURL, lease.conn.agentRecoveryHeaders, "ctx_pool"); err != nil { + if latencyGenerationStartedTurn != turn { + return nil, openAIWSUnsentAgentTurn(err, clientPayload, originalModel, turn) + } return nil, openAIWSAgentRecoveryClose(err) } + latencyGenerationStartedTurn = turn if err := lease.WriteJSONWithContextTimeout(ctx, json.RawMessage(payload), s.openAIWSWriteTimeout()); err != nil { return nil, wrapOpenAIWSIngressTurnError( "write_upstream", diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 85e58e09fe2f..53430a54e2df 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -366,12 +366,16 @@ func buildOpenAIWSHTTPBridgeErrorEvent(statusCode int, message string, source .. } errorBody := map[string]any{"type": "upstream_error", "message": message} if len(source) > 0 { - // Preserve only the standard error identity fields, not an arbitrary - // upstream envelope. The caller already sanitized the message. - for _, field := range []string{"code", "type", "param"} { - value := gjson.GetBytes(source[0], "error."+field) - if value.Type == gjson.String && value.String() != "" { - errorBody[field] = value.String() + if code, safeMessage, ok := OpenAIUpstreamRecoveryRateLimit(statusCode, source[0]); ok { + errorBody = map[string]any{"type": "rate_limit_error", "code": code, "message": safeMessage} + } else { + // Preserve only the standard error identity fields, not an arbitrary + // upstream envelope. The caller already sanitized the message. + for _, field := range []string{"code", "type", "param"} { + value := gjson.GetBytes(source[0], "error."+field) + if value.Type == gjson.String && value.String() != "" { + errorBody[field] = value.String() + } } } } @@ -620,17 +624,20 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( } return nil, admissionErr } - // Freeze the first-send boundary. Rejected-field network attempts remain - // in forwarding and in the compatible helper-entry legacy timer. - if forwardStart.IsZero() { - forwardStart = requesttiming.Now(ctx) - } if recovery := openAIWSAgentRecoveryFromContext(ctx); recovery != nil { source, _ := ctx.Value(openAIWSAgentSourceKey{}).([]byte) if err := recovery.begin(latest, source, body, upstreamReq, "http_bridge"); err != nil { + if forwardStart.IsZero() { + return nil, openAIWSUnsentAgentTurn(err, source, originalModel, turn) + } return nil, openAIWSAgentRecoveryClose(err) } } + // Only crossing the physical send boundary makes this turn ineligible + // for unsent recovery, including any later rejected-field attempt. + if forwardStart.IsZero() { + forwardStart = requesttiming.Now(ctx) + } resp, err = s.doOpenAIUpstream(upstreamReq, proxyURL, account) if err != nil { var phaseTimeout *openAIHTTPPhaseTimeout @@ -710,7 +717,8 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( s.handleOpenAIAccountUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody, actualModel) } clientError := buildOpenAIWSHTTPBridgeErrorEvent(resp.StatusCode, upstreamMsg) - if preserveAgentHistory { + _, _, safeOwnerLimit := OpenAIUpstreamRecoveryRateLimit(resp.StatusCode, respBody) + if preserveAgentHistory || safeOwnerLimit { clientError = buildOpenAIWSHTTPBridgeErrorEvent(resp.StatusCode, upstreamMsg, respBody) } if writeErr := writeClientMessage(clientError); writeErr == nil { diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index 97f3e95f9208..abd7e34d2112 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -16,10 +16,11 @@ import ( // Constructed only at transport boundaries before the CURRENT generation has // been written. Neither a transport failure nor lack of output proves this. type openAIWSUnsentTurnError struct { - cause error - body []byte - model string - turn int + cause error + body []byte + model string + turn int + keepAccount bool // an owner mismatch does not disqualify a healthy selected account } func (e *openAIWSUnsentTurnError) Error() string { @@ -40,6 +41,40 @@ func openAIWSUnsentTurn(err error, body []byte, model string, turn int) error { return &openAIWSUnsentTurnError{cause: err, body: append([]byte(nil), body...), model: model, turn: turn} } +// Retains send-boundary evidence even when the specific guard is terminal. +type openAIWSRecoveryBeforeSendError struct{ cause error } + +func (e *openAIWSRecoveryBeforeSendError) Error() string { return e.cause.Error() } +func (e *openAIWSRecoveryBeforeSendError) Unwrap() error { return e.cause } +func OpenAIWSAgentRecoveryBeforeSend(err error) bool { + var before *openAIWSRecoveryBeforeSendError + return errors.As(err, &before) +} + +// Called only before the current generation's first physical write. A guard +// refusal on an internal retry is not proof that earlier work was unsent. +func openAIWSUnsentAgentTurn(err error, body []byte, model string, turn int) error { + closed := openAIWSAgentRecoveryClose(&openAIWSRecoveryBeforeSendError{cause: err}) + var recovery *OpenAIAgentRecoveryError + if turn < 1 || !errors.As(err, &recovery) || !gjson.ValidBytes(body) { + return closed + } + switch recovery.Reason { + case "owner_unavailable", "route_changed": + // Rebuild still checks completed ownership, delivery fences, readable + // intent, tool results and final payload integrity. Do not turn wire + // mutation, pending/failed/conflicting ownership or store errors into retries. + default: + return closed + } + return &openAIWSUnsentTurnError{cause: closed, body: append([]byte(nil), body...), model: model, turn: turn, keepAccount: true} +} + +func OpenAIWSUnsentTurnKeepsAccount(err error) bool { + var unsent *openAIWSUnsentTurnError + return errors.As(err, &unsent) && unsent.keepAccount +} + func OpenAIWSUnsentTurnPayload(err error) ([]byte, string, int, bool) { var unsent *openAIWSUnsentTurnError if !errors.As(err, &unsent) { diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 46bc5baf4994..59b7368c6a14 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -1405,7 +1405,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } if err := agentRecovery.beginSocket(latest, pendingAgentSource, firstClientMessage, wsURL, headers, "passthrough"); err != nil { cancelFirstWrite() - return openAIWSAgentRecoveryClose(err) + return openAIWSUnsentAgentTurn(err, pendingAgentSource, gjson.GetBytes(firstClientMessage, "model").String(), 1) } firstWriteErr := relayUpstreamFrameConn.WriteFrame(firstWriteCtx, coderws.MessageText, firstClientMessage) cancelFirstWrite() @@ -1469,7 +1469,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( return err } if err := agentRecovery.beginSocket(latest, pendingAgentSource, payload, wsURL, headers, "passthrough"); err != nil { - return openAIWSAgentRecoveryClose(err) + return openAIWSUnsentAgentTurn(err, pendingAgentSource, usageMeta.requestModelForFrame(pendingAgentSource), max(2, int(completedTurns.Load())+1)) } return nil }, @@ -1829,6 +1829,10 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } func openAIWSPassthroughRelayClientClose(exit openaiwsv2.RelayExit, completedTurns int) (coderws.StatusCode, string, bool) { + var recovery *OpenAIAgentRecoveryError + if errors.As(exit.Err, &recovery) { + return 0, "", false // Handler persists the outcome and writes the safe error before closing. + } if _, _, _, unsent := OpenAIWSUnsentTurnPayload(exit.Err); unsent { return 0, "", false // Handler owns bounded fresh admission on the same client. } diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index eff976900e39..12b37294e5dc 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -185,7 +185,16 @@ func IsOpsRequestScopedError(c *gin.Context) bool { // 可用账号等),以及上游 2xx 正文或事件里携带的错误结果(NonStream 标记非流式正文)。 // 由于 HTTP 状态码停留在 2xx,ops_error_logger 中间件在 status<400 分支消费该标记并 // 补记错误日志;标记方是 handler.handleStreamingAwareError 或各 service 的带内检测。 +// OpsRecoveryFailure is trusted local compatibility evidence, never populated +// from an upstream error envelope or client metadata. +type OpsRecoveryFailure struct { + Protocol string + Phase string + RequestWritten *bool // nil means no proof of whether the generation was sent +} + type OpsStreamError struct { + RecoveryFailure *OpsRecoveryFailure TransportFailure *OpsTransportFailure // BridgeFailure is set only by the local BPS conversion boundary. It keeps // real upstream HTTP evidence while assigning failure ownership to gateway. From e946fc3ba54223f71350dd278126b6f172b1f152 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:17:53 +0800 Subject: [PATCH 12/38] fix: preserve missing owner fences and distinguish stream failures --- .github/workflows/backend-ci.yml | 7 ++-- .../handler/openai_409_ws_rebuild_test.go | 18 ++++++++++- .../handler/openai_agent_message_recovery.go | 8 ++++- .../handler/openai_gateway_handler.go | 7 +++- .../openai_issue854_continuation_test.go | 6 ++++ .../service/openai_ws_agent_recovery.go | 2 +- .../service/openai_ws_agent_recovery_test.go | 32 +++++++++++++++++++ .../openai_ws_readable_continuation.go | 11 +++++++ frontend/src/utils/errorCategory.ts | 1 + .../ops/components/OpsErrorDetailModal.vue | 5 ++- .../admin/ops/components/OpsErrorLogTable.vue | 3 ++ .../__tests__/OpsErrorDetailModal.spec.ts | 18 +++++++++++ .../__tests__/OpsErrorLogTable.spec.ts | 11 +++++++ 13 files changed, 122 insertions(+), 7 deletions(-) diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index e4c3dd33495c..f99494490ef6 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -89,10 +89,10 @@ jobs: shell: bash run: | set -euo pipefail - (cd backend && go test -race -tags=unit ./internal/handler -run '^Test(OpenAI409(WSReadableBoundaries|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|HTTPTaskRebuild|HTTPRebuildBoundaries|HTTPToolDefinitionOracle)|Issue854HTTPContinuation|Issue805|Issue758WS)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" 2>&1 + (cd backend && go test -race -tags=unit ./internal/handler -run '^Test(OpenAI409(WSReadableBoundaries|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|HTTPTaskRebuild|HTTPRebuildBoundaries|HTTPToolDefinitionOracle)|Issue854HTTPContinuation|Issue854LostOwnerEvidence|Issue805|Issue758WS)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" python3 .github/scripts/assert-ws-readable.py GREEN 0 "$RUNNER_TEMP/issue854-evidence/contracts.jsonl" ws-boundaries - (cd backend && go test -race -tags=unit ./internal/service -run '^Test(OpenAI409WSUnsentTurnBoundary|Issue715WS|OpenAI409WS|OpenAIWS.*(Agent|Replay))' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/service-contracts.jsonl" 2>&1 + (cd backend && go test -race -tags=unit ./internal/service -run '^Test(Issue854BeforeSendRecoveryGuards|OpenAI409WSUnsentTurnBoundary|Issue715WS|OpenAI409WS|OpenAIWS.*(Agent|Replay))' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/issue854-evidence/service-contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/issue854-evidence/service-contracts.jsonl" - uses: actions/upload-artifact@v7 if: always() @@ -304,6 +304,9 @@ jobs: run: pnpm install --frozen-lockfile - name: Frontend typecheck and critical vitest run: make test-frontend + - name: Issue854 transport failure presentation + if: github.head_ref == 'fix/issue854-ws-owner-continuation' || github.ref_name == 'fix/issue854-ws-owner-continuation' + run: pnpm --dir frontend exec vitest run src/views/admin/ops/components/__tests__/OpsErrorLogTable.spec.ts src/views/admin/ops/components/__tests__/OpsErrorDetailModal.spec.ts golangci-lint: runs-on: ubuntu-latest diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index eb7398a0c09c..e11d3b91facb 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -338,9 +338,14 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { accounts.mu.Lock() accounts.disableAdmission = 2 accounts.mu.Unlock() - } else { + } else if scenario != "issue854_lost_owner" { accounts.disable(1) } + if scenario == "issue854_lost_owner" { + for key := range owners { + require.NoError(t, probe.Del(context.Background(), key).Err()) + } + } if scenario == "issue854_fresh" || strings.HasPrefix(scenario, "issue854_guard_") { issue600Finish(t, h, headers) dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) @@ -391,6 +396,17 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { oracle.mu.Lock() sends := len(oracle.frames) oracle.mu.Unlock() + if scenario == "issue854_lost_owner" { + require.NoError(t, readErr) + require.Equal(t, "encrypted_agent_recovery_owner_unavailable", gjson.GetBytes(secondRaw, "error.code").String()) + require.Equal(t, 1, sends, "loss of previously observed owner evidence must refuse before any generation") + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + a, err := accounts.GetByID(context.Background(), 1) + require.NoError(t, err) + require.True(t, a.Schedulable, "this refusal must come from owner evidence, not account admission") + return + } if issue854Failure { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() diff --git a/backend/internal/handler/openai_agent_message_recovery.go b/backend/internal/handler/openai_agent_message_recovery.go index f663a90c7619..f503daff5f43 100644 --- a/backend/internal/handler/openai_agent_message_recovery.go +++ b/backend/internal/handler/openai_agent_message_recovery.go @@ -21,7 +21,13 @@ func (h *OpenAIGatewayHandler) handleOpenAIAgentRecoveryError(c *gin.Context, er if streamStarted || c.GetBool(opsStreamKey) { protocol = "sse" } - markOpenAIRecoveryFailure(c, recovery, protocol, "before_dispatch", boolPointer(false)) + // HTTP forwarders can return a compatibility error after a provider read; + // the HTTP handler alone cannot prove an unsent generation. + phase := "before_response" + if streamStarted || c.Writer.Written() { + phase = "forwarding" + } + markOpenAIRecoveryFailure(c, recovery, protocol, phase, nil) committed := streamStarted || c.Writer.Written() if !committed && !recovery.RetryAt.IsZero() { seconds := max(int64(1), int64((time.Until(recovery.RetryAt)+time.Second-1)/time.Second)) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 7b5ffbf0536e..0263b40f5398 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3359,6 +3359,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { } maxAccountSwitches := h.maxAccountSwitches switchCount := 0 + opsTurnOffset := 0 var forbiddenBudget grokForbiddenFailoverBudget profitVetoCount := 0 failedAccountIDs := make(map[int64]struct{}) @@ -3737,7 +3738,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { moderationLogicalTurn++ } c.Set(securityAuditWSTurnContextKey, moderationLogicalTurn) - service.BeginOpsStreamTurn(c, turn) + service.BeginOpsStreamTurn(c, opsTurnOffset+turn) // 连接级 cyber session gate 也在 BeforeRequest 先执行,使 native 与 // passthrough ingress 都能在 BeforeTurn 及上游写入前无副作用地拒绝。 // BeforeTurn 中保留同一检查作为防御式兜底。 @@ -4075,6 +4076,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { // transport, never the connection's warmup or a failed generation. releaseTurnSlots() if switchCount >= maxAccountSwitches || !service.OpenAIWSIngressCanFailover(ctx, c) { + if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err, c) { + return + } closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account eligibility changed; continuation budget exhausted") return } @@ -4162,6 +4166,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { } reqModel, wsRouteModel, wsForwardModel = currentModel, currentRouteModel, currentForwardModel channelMappingWS = mapping + opsTurnOffset += turn - 1 wsAttemptMessage, previousResponseID, previousResponseCanMove = clean, "", true if !service.OpenAIWSUnsentTurnKeepsAccount(err) { failedAccountIDs[account.ID] = struct{}{} diff --git a/backend/internal/handler/openai_issue854_continuation_test.go b/backend/internal/handler/openai_issue854_continuation_test.go index b67b202f2c53..f56d50b6b9fa 100644 --- a/backend/internal/handler/openai_issue854_continuation_test.go +++ b/backend/internal/handler/openai_issue854_continuation_test.go @@ -36,3 +36,9 @@ func TestIssue854HTTPContinuation(t *testing.T) { }) } } + +func TestIssue854LostOwnerEvidence(t *testing.T) { + for _, mode := range readableWSModes { + t.Run(mode, func(t *testing.T) { runReadableWSContinuation(t, mode, "issue854_lost_owner") }) + } +} diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index d26560e52b10..7acc80eeb582 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -253,7 +253,7 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, } for _, key := range r.request.keys { if r.known[key] && !r.request.known[key] { - return openAIAgentRecoveryError("owner_unavailable") + return &openAIWSLostOwnerEvidenceError{cause: openAIAgentRecoveryError("owner_unavailable")} } } // These call sites have already selected a native Responses socket or diff --git a/backend/internal/service/openai_ws_agent_recovery_test.go b/backend/internal/service/openai_ws_agent_recovery_test.go index 664e120afeb3..4d3eb35cf8a5 100644 --- a/backend/internal/service/openai_ws_agent_recovery_test.go +++ b/backend/internal/service/openai_ws_agent_recovery_test.go @@ -188,3 +188,35 @@ func TestIssue715WSBridgeValidatesBuiltPayload(t *testing.T) { err := manager.begin(account, []byte(issue715OpaqueBody), []byte(issue715OpaqueBody), newRequest(built), "http_bridge") require.Error(t, err, "bridge must validate actual built HTTP body before granting opaque task admission") } + +func TestIssue854BeforeSendRecoveryGuards(t *testing.T) { + for _, tc := range []struct { + name string + cause error + recoverable bool + }{ + {"owner_unavailable", openAIAgentRecoveryError("owner_unavailable"), true}, + {"route_changed", openAIAgentRecoveryError("route_changed"), true}, + {"wire_integrity", openAIAgentRecoveryError("wire_changed"), false}, + {"conflicting_owners", openAIAgentRecoveryError("owner_conflict"), false}, + {"delivery_pending", openAIAgentRecoveryError("delivery_pending"), false}, + {"store_unavailable", openAIAgentRecoveryError("store_unavailable"), false}, + {"lost_known_owner", &openAIWSLostOwnerEvidenceError{cause: openAIAgentRecoveryError("owner_unavailable")}, false}, + {"unknown_send", errors.New("upstream write outcome unknown"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + body := []byte(`{"type":"response.create","input":"private-current-task"}`) + result := openAIWSUnsentAgentTurn(tc.cause, body, "gpt-5.1", 2) + body[0] = '!' + payload, model, turn, ok := OpenAIWSUnsentTurnPayload(result) + require.Equal(t, tc.recoverable, ok) + require.Equal(t, tc.recoverable, OpenAIWSUnsentTurnKeepsAccount(result)) + require.NotContains(t, result.Error(), "private-current-task") + if ok { + require.True(t, gjson.ValidBytes(payload)) + require.Equal(t, "gpt-5.1", model) + require.Equal(t, 2, turn) + } + }) + } +} diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index abd7e34d2112..29ab90f48654 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -51,10 +51,21 @@ func OpenAIWSAgentRecoveryBeforeSend(err error) bool { return errors.As(err, &before) } +// Losing ownership already observed on this socket is not ordinary account +// unavailability. It must never become permission to discard that fence. +type openAIWSLostOwnerEvidenceError struct{ cause error } + +func (e *openAIWSLostOwnerEvidenceError) Error() string { return e.cause.Error() } +func (e *openAIWSLostOwnerEvidenceError) Unwrap() error { return e.cause } + // Called only before the current generation's first physical write. A guard // refusal on an internal retry is not proof that earlier work was unsent. func openAIWSUnsentAgentTurn(err error, body []byte, model string, turn int) error { closed := openAIWSAgentRecoveryClose(&openAIWSRecoveryBeforeSendError{cause: err}) + var lost *openAIWSLostOwnerEvidenceError + if errors.As(err, &lost) { + return closed + } var recovery *OpenAIAgentRecoveryError if turn < 1 || !errors.As(err, &recovery) || !gjson.ValidBytes(body) { return closed diff --git a/frontend/src/utils/errorCategory.ts b/frontend/src/utils/errorCategory.ts index 7150c18265ac..e7c589d5441f 100644 --- a/frontend/src/utils/errorCategory.ts +++ b/frontend/src/utils/errorCategory.ts @@ -4,6 +4,7 @@ * 两处修改须同步。返回稳定分类码,展示文案走 i18n `usage.errors.categories.*`。 */ export function mapErrorCategory(phase?: string | null, errType?: string | null): string { + if ((errType || '').toLowerCase() === 'transport_error') return 'transport_error' switch ((phase || '').toLowerCase()) { case 'auth': return 'auth' diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue index 80ec0a067870..b1295f600d78 100644 --- a/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue +++ b/frontend/src/views/admin/ops/components/OpsErrorDetailModal.vue @@ -89,12 +89,15 @@
-
{{ t('admin.ops.errorDetail.status') }}
+
{{ t(detail.type === 'transport_error' ? 'usage.errors.detail.clientHttpStatus' : 'admin.ops.errorDetail.status') }}
{{ detail.status_code }}
+

+ {{ t('usage.errors.detail.streamFailedAfterHeaders') }} +

diff --git a/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue b/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue index 7d1eb7c0d097..a7fc7413638c 100644 --- a/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue +++ b/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue @@ -107,6 +107,9 @@