From 063019dcb605c03502bacf51f600b189d5c40310 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:43:56 +0800 Subject: [PATCH 1/7] =?UTF-8?q?fix:=20=E8=A1=A5=E9=BD=90=E9=87=8D=E5=BB=BA?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E7=9A=84=E5=8F=91=E9=80=81=E6=8A=95=E5=BD=B1?= =?UTF-8?q?=E4=B8=8E=20WS=20=E5=88=9D=E5=A7=8B=E9=80=89=E5=8F=B7=E6=81=A2?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../workflows/rebuilt-request-dispatch.yml | 88 +++++++++++++++++++ .../handler/openai_409_http_rebuild_test.go | 44 ++++++++++ .../handler/openai_409_ws_rebuild_test.go | 36 +++++++- .../handler/openai_gateway_handler.go | 19 ++++ .../service/openai_409_omit_history.go | 75 +++++++++++++++- .../service/openai_account_scheduler.go | 3 + .../service/openai_agent_message_recovery.go | 6 +- .../service/openai_gateway_forward.go | 11 ++- .../service/openai_request_timezone_egress.go | 6 ++ .../openai_request_timezone_egress_test.go | 79 +++++++++++++++++ backend/internal/service/openai_ws_client.go | 3 +- docs/encrypted-history-409-beta.md | 8 ++ 12 files changed, 368 insertions(+), 10 deletions(-) create mode 100644 .github/workflows/rebuilt-request-dispatch.yml diff --git a/.github/workflows/rebuilt-request-dispatch.yml b/.github/workflows/rebuilt-request-dispatch.yml new file mode 100644 index 000000000000..bb8169484182 --- /dev/null +++ b/.github/workflows/rebuilt-request-dispatch.yml @@ -0,0 +1,88 @@ +name: Rebuilt request dispatch +on: + pull_request: + paths: + - 'backend/internal/service/openai_409_omit_history*' + - 'backend/internal/service/openai_agent_message_recovery.go' + - 'backend/internal/service/openai_gateway_forward.go' + - 'backend/internal/service/openai_account_scheduler.go' + - 'backend/internal/service/openai_request_timezone_egress*' + - 'backend/internal/service/openai_ws_client.go' + - 'backend/internal/handler/openai_409_*' + - 'backend/internal/handler/openai_gateway_handler.go' + - '.github/workflows/rebuilt-request-dispatch.yml' +permissions: + contents: read +jobs: + behavior: + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + phase: [RED, GREEN] + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated Redis fixture + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + - name: Restore release implementation for RED + if: matrix.phase == 'RED' + run: | + set -euo pipefail + baseline=aa8e596e6d6f3e4648d6beba73b39b240dd5357a + for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; do + git show "$baseline:$target" > "$target" + done + - name: Same network and tool-loop regressions + env: + PHASE: ${{ matrix.phase }} + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit ./internal/service ./internal/handler -run '^TestOpenAI409(HTTPProjectionAndPassthrough|WSInitialWithoutPointer|PhysicalTimezonePreservesReadableTask)$' -count=1 -timeout=10m) > "$RUNNER_TEMP/dispatch.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/dispatch.jsonl" + python3 - "$PHASE" "$result" "$RUNNER_TEMP/dispatch.jsonl" <<'PY' + import json,sys + phase,result,path=sys.argv[1:] + raw=open(path).read() + for invalid in ('[build failed]', 'undefined:', 'panic:', 'WARNING: DATA RACE', 'no tests to run'): + assert invalid not in raw, invalid + events=[] + for line in raw.splitlines(): + try: events.append(json.loads(line)) + except ValueError: pass + terminals={e['Test']:e['Action'] for e in events if 'Test' in e and e.get('Action') in ('pass','fail','skip')} + assert terminals and 'skip' not in terminals.values(), terminals + expected=[ + 'TestOpenAI409HTTPProjectionAndPassthrough/oauth/stream=false/internal_metadata', + 'TestOpenAI409HTTPProjectionAndPassthrough/oauth/stream=true/message_namespace', + 'TestOpenAI409HTTPProjectionAndPassthrough/apikey/stream=true/passthrough', + 'TestOpenAI409PhysicalTimezonePreservesReadableTask/http/preserved=true', + 'TestOpenAI409PhysicalTimezonePreservesReadableTask/ws/preserved=true', + ] + if phase=='GREEN': + assert int(result)==0 and set(terminals.values())=={'pass'}, terminals + assert all(terminals.get(t)=='pass' for t in expected) + assert len([t for t,v in terminals.items() if t.startswith('TestOpenAI409WSInitialWithoutPointer/') and t.count('/')==2 and v=='pass'])==15 + else: + assert int(result)!=0 + assert all(terminals.get(t)=='fail' for t in expected), terminals + assert any(t.startswith('TestOpenAI409WSInitialWithoutPointer/') and t.count('/')==2 and v=='fail' for t,v in terminals.items()), terminals + PY + - uses: actions/upload-artifact@v7 + if: always() + with: + name: rebuilt-dispatch-${{ matrix.phase }}-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/dispatch.jsonl diff --git a/backend/internal/handler/openai_409_http_rebuild_test.go b/backend/internal/handler/openai_409_http_rebuild_test.go index ca243d2e5ba7..5690d6ed6046 100644 --- a/backend/internal/handler/openai_409_http_rebuild_test.go +++ b/backend/internal/handler/openai_409_http_rebuild_test.go @@ -271,6 +271,21 @@ func TestOpenAI409HTTPRebuildOwnerCooldown(t *testing.T) { } } +func TestOpenAI409HTTPProjectionAndPassthrough(t *testing.T) { + for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, shape := range []string{"message_namespace", "internal_metadata", "tool_schema_null", "passthrough"} { + if shape == "passthrough" && accountType != service.AccountTypeAPIKey { + continue + } + t.Run(fmt.Sprintf("%s/stream=%t/%s", accountType, stream, shape), func(t *testing.T) { + runHTTPRebuildFixture(t, accountType, stream, shape, "completed", "", "") + }) + } + } + } +} + func TestOpenAI409HTTPControlNormalization(t *testing.T) { for _, stream := range []bool{false, true} { for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { @@ -522,6 +537,12 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe gjson.GetBytes(body, "stream").Bool() && gjson.GetBytes(body, "store").Type == gjson.False && gjson.GetBytes(body, `input.#(role==system)`).Type == gjson.Null } + if pointer == "message_namespace" { + valid = valid && !gjson.GetBytes(body, "input.0.namespace").Exists() + } + if pointer == "internal_metadata" && accountType == service.AccountTypeOAuth { + valid = valid && !gjson.GetBytes(body, "input.0.internal_chat_message_metadata_passthrough").Exists() + } if n == 3 { valid = valid && httpRebuildToolPair(body, "run_tests", httpRebuildCheck) } @@ -561,6 +582,9 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe for i, label := range []string{"A", "B"} { accounts[i].Credentials = map[string]any{"base_url": provider.URL, "api_key": "fixture-rebuild-" + label, "access_token": "fixture-rebuild-" + label, "chatgpt_account_id": "fixture-chatgpt-" + label} } + if pointer == "passthrough" { + accounts[1].Extra = map[string]any{"openai_passthrough": true, "openai_responses_mode": "force_responses"} + } settings := service.NewSettingService(&omit409SettingsRepo{enabled: boundary != "strict"}, cfg) usage := &readable409UsageRepo{} h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, transport, repository.NewGatewayCache(clients()), settings, usage, accounts...) @@ -612,6 +636,26 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe delete(body, "tools") body["parallel_tool_calls"] = true } + if previous.Exists() { + history = append([]string(nil), history...) + var field string + switch pointer { + case "message_namespace": + field = "namespace" + case "internal_metadata": + field = "internal_chat_message_metadata_passthrough" + } + if field != "" { + updated, err := sjson.Set(history[0], field, "fixture-output-metadata") + require.NoError(t, err) + history[0] = updated + } + if pointer == "tool_schema_null" { + declarations := httpRebuildToolDefinitions() + declarations[0].(map[string]any)["parameters"].(map[string]any)["type"] = nil + body["tools"] = declarations + } + } body["input"] = json.RawMessage("[" + strings.Join(history, ",") + "]") if previous.Exists() && (pointer == "previous" || boundary == "pointer_only") { body["previous_response_id"] = previous.Get("id").String() diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 28bcca3df809..9b455f0b4ba3 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -164,6 +164,16 @@ func logReadableWSDispatchFailure(t *testing.T, h *openAIWSPassthroughHandlerHar t.Logf("actual B dispatch error: %v; client close: %v", reported, clientErr) } +func TestOpenAI409WSInitialWithoutPointer(t *testing.T) { + for _, mode := range readableWSModes { + for _, state := range []string{"paused", "rate_limited", "overloaded"} { + t.Run(mode+"/"+state, func(t *testing.T) { + runReadableWSContinuation(t, mode, "initial_no_pointer_"+state) + }) + } + } +} + func runReadableWSContinuation(t *testing.T, mode, scenario string) { t.Helper() clients := issue805Redis(t) @@ -173,6 +183,7 @@ 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")} + initialNoPointer := strings.HasPrefix(scenario, "initial_no_pointer_") identityCase, modelCase := scenario == "identity" || strings.HasPrefix(scenario, "header_"), scenario == "bridge_model" customTools := strings.HasPrefix(scenario, "tools_") nativeNamespace := scenario == "native_namespace" @@ -317,6 +328,27 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { } else { accounts.disable(1) } + if initialNoPointer { + if scenario != "initial_no_pointer_paused" { + accounts.mu.Lock() + reset := time.Now().Add(7 * 24 * time.Hour) + accounts.accounts[0].Schedulable = true + if scenario == "initial_no_pointer_rate_limited" { + accounts.accounts[0].RateLimitResetAt = &reset + } else { + accounts.accounts[0].OverloadUntil = &reset + } + accounts.mu.Unlock() + } + 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() }) + previous = "" + } if scenario == "b_disabled" { accounts.disable(2) } @@ -352,7 +384,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" && !initialNoPointer && !identityCase && !modelCase && !nativeNamespace && smartMode == "" { require.NotErrorIs(t, readErr, context.DeadlineExceeded) closeCtx, cancelClose := context.WithTimeout(context.Background(), 5*time.Second) defer cancelClose() @@ -455,7 +487,7 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string) { require.Equal(t, 1, tools.verifications) a, err := accounts.GetByID(context.Background(), 1) require.NoError(t, err) - require.False(t, a.Schedulable) + require.False(t, a.IsSchedulable()) oracle.mu.Lock() defer oracle.mu.Unlock() expectedIdentities := []string{"Bearer fixture-readable-ws-A", "Bearer fixture-readable-ws-B", "Bearer fixture-readable-ws-B"} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 3b15d85be21f..1f35b11f318e 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3367,6 +3367,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { var rpmAdmission openAIRPMAdmission var oauth429FailoverState service.OpenAIOAuth429FailoverState wsAttemptMessage := append([]byte(nil), firstMessage...) + initialSelectionCanRebuild := true waitForWSSameAccountRetry := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { if !service.OpenAIWSAgentRecoveryCanRetry(ctx) { return false @@ -3478,6 +3479,23 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { requestPlatform, ) if err != nil { + // No transport has been invoked on this path. A known owner's + // unavailability may only be discovered by initial selection, after + // the eager rebuild skipped a single-owner frame without pointers. + if initialSelectionCanRebuild && switchCount < maxAccountSwitches && requestPlatform == service.PlatformOpenAI { + initialSelectionCanRebuild = false + if next, clean, changed, rebuildErr := h.gatewayService.TryRebuildOpenAI409History(ctx, c, wsAttemptMessage, sessionHash, wsForwardModel, err); rebuildErr != nil { + err = rebuildErr + } else if changed { + ctx, firstMessage, wsAttemptMessage, previousResponseID = next, clean, clean, "" + previousResponseCanMove = true + ctx = service.ResetOpenAIWSReadableProviderSession(ctx, c) + c.Request = c.Request.WithContext(ctx) + switchCount++ + reqLog.Info("openai.websocket_initial_readable_continuation", zap.Bool("context_loss", true)) + continue + } + } if h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, err) { return } @@ -4037,6 +4055,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { }, } + initialSelectionCanRebuild = false wsFirstMessage := wsAttemptMessage // 切组/会话失配防护:previous_response_id 未在当前分组命中粘连账号(StickyPreviousHit=false), // 说明该会话链不属于本次调度到的账号,原样转发会触发上游会话链鉴权失败(“鉴权失败,请检查 API Key”)。 diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 94f9df00cf46..93178fb65c76 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -10,9 +10,11 @@ import ( "time" "unicode/utf8" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" "github.com/tidwall/sjson" + "go.uber.org/zap" ) const openAIHistoricalCiphertextOmitted = "[Historical encrypted content omitted by the gateway. Its contents are unavailable; do not infer missing instructions or results.]" @@ -508,7 +510,7 @@ func prepareOpenAI409APIKeyReplay(ctx context.Context, body []byte, responsesLit return body, nil } if openAIAgentRecoveryInputDigest(body) != r.inputDigest || openAI409ControlsDigest(body) != r.replayControlsDigest { - return nil, openAIAgentRecoveryError("wire_changed") + return nil, openAIRecoveryWireRefusal(ctx, "apikey_projection_source") } prepared, _, err := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite) if err != nil { @@ -535,8 +537,11 @@ func prepareOpenAI409OAuthReplay(ctx context.Context, c *gin.Context, body map[s return err } if openAIAgentRecoveryInputDigest(before) != r.inputDigest || openAI409ControlsDigest(before) != r.replayControlsDigest { - return openAIAgentRecoveryError("wire_changed") + return openAIRecoveryWireRefusal(ctx, "oauth_projection_source") } + // ChatGPT rejects this output-only metadata. Normalize before freezing the + // OAuth representation; the later ordinary transform must be idempotent. + normalizeOpenAIOAuthResponsesCompatibilityFields(body) if isInstructionsEmpty(body) { body["instructions"] = defaultCodexSynthInstructions(firstNonEmptyString(body["model"])) } @@ -559,3 +564,69 @@ func prepareOpenAI409OAuthReplay(ctx context.Context, c *gin.Context, body map[s r.oauthReplayPrepared = true return nil } + +// A rebuilt request is a new native Responses conversation. An API-key +// account's ordinary passthrough preference must not route this prepared +// request around the native input and delivery checks. +func openAI409UsesNativeAPIKey(ctx context.Context, account *Account) bool { + r := openAIAgentRecoveryFromContext(ctx) + return r != nil && r.omittedHistory && account != nil && account.IsOpenAIApiKey() +} + +func openAIRecoveryWireRefusal(ctx context.Context, stage string) error { + logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", zap.String("stage", stage)) + return openAIAgentRecoveryError("wire_changed") +} + +// Derive the HTTP representation only from the verified readable snapshot, +// before Forward's compatibility pipeline touches it. Keep the original +// context immutable so a later account admission starts from the same input. +// This is not a digest update at the final send boundary. +func (s *OpenAIGatewayService) prepareOpenAI409HTTPProjection(ctx context.Context, c *gin.Context, account *Account, body []byte) (context.Context, []byte, error) { + r := openAIAgentRecoveryFromContext(ctx) + if r == nil || !r.omittedHistory { + return ctx, body, nil + } + if openAIAgentRecoveryInputDigest(body) != r.inputDigest || openAI409ControlsDigest(body) != r.replayControlsDigest { + return ctx, body, openAIRecoveryWireRefusal(ctx, "http_projection_source") + } + clean := s.normalizeRequestTimezone(ctx, account, body, "http") + var err error + clean, _, err = normalizeOpenAIResponsesLegacyIngressWithConfig(s.cfg, clean) + if err != nil { + return ctx, body, err + } + clean, _, err = sanitizeOpenAIResponsesToolSchemasForPlatform(clean, account.Platform) + if err != nil { + return ctx, body, err + } + if isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)) { + clean, _, err = normalizeOpenAIResponsesLitePayloadForAccount(clean, account) + if err != nil { + return ctx, body, err + } + } + clean, err = normalizeOpenAIResponsesNamespaces(c, account, clean, OpenAIUpstreamTransportHTTPSSE, false, false) + if err != nil { + return ctx, body, err + } + snapshot := *r + snapshot.inputDigest = openAIAgentRecoveryInputDigest(clean) + snapshot.replayControlsDigest = openAI409ControlsDigest(clean) + snapshot.apiReplayPrepared, snapshot.oauthReplayPrepared = false, false + return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &snapshot), clean, nil +} + +// Account-scoped routing exclusions are applied before acquiring a candidate. +// The same boundary remains enforced by the dispatch guard after revalidation. +func (s *OpenAIGatewayService) openAI409AccountRouteSupported(ctx context.Context, account *Account, model string) bool { + r := openAIAgentRecoveryFromContext(ctx) + if r == nil || !r.omittedHistory { + return true + } + return account != nil && account.IsOpenAI() && !account.HasManagedOpenAIConnections() && account.AuthConnectionID == "" && + !account.IsCopilotSDKEnabled() && !account.IsSIWCEnabled() && + !account.IsExcelBPSEnabledForModel(model) && !account.IsPrismBrowserEnabledForModel(model) && + s.resolveUpstreamProtocolFor(ctx, account, APIProtocolResponses, account.GetMappedModel(model)) == APIProtocolResponses && + (!account.IsOpenAIPassthroughEnabled() || account.IsOpenAIApiKey()) +} diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 452a6d0a615d..389ca2e92d41 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -2348,6 +2348,9 @@ func (s *defaultOpenAIAccountScheduler) isAccountRequestCompatibleReason(ctx con if account == nil { return false, "account_nil" } + if s != nil && s.service != nil && !s.service.openAI409AccountRouteSupported(ctx, account, req.RequestedModel) { + return false, "readable_rebuild_route_unsupported" + } if account.IsExcelOAuth() && s != nil && s.service != nil && !s.service.excelBPSGloballyEnabled(ctx) { return false, "excel_bps_disabled" } diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index aa794ad13cc7..db80033374eb 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -327,7 +327,7 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryDispatch(ctx context.Cont // /responses/compact bridge rewrites the body and endpoint, so it remains // outside this contract. if !account.IsOpenAI() || account.HasManagedOpenAIConnections() || account.AuthConnectionID != "" || - account.IsOpenAIPassthroughEnabled() || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() || + (account.IsOpenAIPassthroughEnabled() && !openAI409UsesNativeAPIKey(ctx, account)) || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() || account.IsExcelBPSEnabledForModel(model) || account.IsPrismBrowserEnabledForModel(model) || isOpenAIResponsesCompactPath(c) || (isOpenAINativeCompactionV2(c) && shouldForwardDeepSeekResponsesCompactViaChatCompletions(account, body)) || @@ -382,7 +382,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con } // Managed credentials and adapters need their own route ownership contract. if !account.IsOpenAI() || account.HasManagedOpenAIConnections() || account.AuthConnectionID != "" || - account.IsOpenAIPassthroughEnabled() || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() { + (account.IsOpenAIPassthroughEnabled() && !openAI409UsesNativeAPIKey(ctx, account)) || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() { if request.owner != nil || request.preservesHistory() { return noop, openAIAgentRecoveryError("wire_changed") } @@ -433,7 +433,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con } if request.omittedHistory && (gjson.GetBytes(body, "previous_response_id").Exists() || gjson.GetBytes(body, "conversation").Exists() || openAI409ControlsDigest(body) != expectedControls) { - return noop, openAIAgentRecoveryError("wire_changed") + return noop, openAIRecoveryWireRefusal(ctx, "controls_integrity") } if request.previousResponseID != "" && gjson.GetBytes(body, "previous_response_id").String() != request.previousResponseID { return noop, openAIAgentRecoveryError("owner_unavailable") diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 9e2e7098f714..85cc8e8c1494 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -122,7 +122,9 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } defer func() { resultErr = regionalMeterFinishForward(ctx, result, resultErr, finishMeter) }() ctx = s.withRequestTimezoneEgress(ctx, account) - body = s.normalizeRequestTimezone(ctx, account, body, "http") + if r := openAIAgentRecoveryFromContext(ctx); r == nil || !r.omittedHistory { + body = s.normalizeRequestTimezone(ctx, account, body, "http") + } if astraSchedulingAppliesToRequest(s.cfg.AstraRouting(ctx), account, gjson.GetBytes(body, "model").String(), getOpenAIGroupIDFromContext(c)) { if err := s.checkAstraSchedulingRoute(ctx, account); err != nil { return nil, err @@ -172,6 +174,11 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco clearOpenAIResponsesClientToolMapping(c) clearOpenAIResponsesNamespaceNames(c) setCodexToolNameReverse(c, nil) + var projectionErr error + ctx, body, projectionErr = s.prepareOpenAI409HTTPProjection(ctx, c, account, body) + if projectionErr != nil { + return nil, projectionErr + } if _, err := s.prepareCodexAccountIdentitySource(ctx, c, account); err != nil { return nil, err } @@ -327,7 +334,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } } - passthroughEnabled := account.IsOpenAIPassthroughEnabled() + passthroughEnabled := account.IsOpenAIPassthroughEnabled() && !openAI409UsesNativeAPIKey(ctx, account) compactPath := isOpenAIResponsesCompactPath(c) body, err = normalizeOpenAIResponsesNamespaces(c, account, body, wsDecision.Transport, passthroughEnabled, compactPath) if err != nil { diff --git a/backend/internal/service/openai_request_timezone_egress.go b/backend/internal/service/openai_request_timezone_egress.go index baae0914f8aa..e267aca2fd74 100644 --- a/backend/internal/service/openai_request_timezone_egress.go +++ b/backend/internal/service/openai_request_timezone_egress.go @@ -136,6 +136,12 @@ func BindOpenAIRequestTimezone(req *http.Request, proxy string) (*http.Request, } clone := req.Clone(req.Context()) rewriteRequestTimezoneHeaders(clone.Header, name) + // A rebuilt/explicitly preserved task already has a verified input and + // tools snapshot. Keep that body at the physical transport boundary; + // automatic egress timezone still applies to the header metadata. + if openAIAgentRecoveryPreservesHistory(req.Context()) { + return clone, nil + } if req.GetBody == nil || (req.Header.Get("Content-Type") != "" && !strings.HasPrefix(strings.ToLower(req.Header.Get("Content-Type")), "application/json")) { return clone, nil } diff --git a/backend/internal/service/openai_request_timezone_egress_test.go b/backend/internal/service/openai_request_timezone_egress_test.go index 9f97781ceef6..615577839756 100644 --- a/backend/internal/service/openai_request_timezone_egress_test.go +++ b/backend/internal/service/openai_request_timezone_egress_test.go @@ -1,10 +1,12 @@ package service import ( + "bytes" "context" "crypto/sha256" "encoding/json" "errors" + "fmt" "io" "net/http" "net/http/httptest" @@ -273,3 +275,80 @@ func TestRequestTimezoneEgressWebSocketFrames(t *testing.T) { } require.Len(t, probe.calls, 1) } + +// Observe actual HTTP/WS bytes, rather than only the service's pre-send digest. +func TestOpenAI409PhysicalTimezonePreservesReadableTask(t *testing.T) { + original := localeTestBody([]string{"Asia/Shanghai", "keep the already completed tool result"}, nil) + probe := &egressTimezoneProber{probe: func(context.Context, string) (*ProxyExitInfo, int64, error) { + return &ProxyExitInfo{IP: "203.0.113.10", Timezone: "Asia/Tokyo"}, 0, nil + }} + svc := timezoneAutoService(true, true, probe) + account := &Account{ID: 1, Platform: PlatformOpenAI} + for _, transport := range []string{"http", "ws"} { + for _, preserved := range []bool{false, true} { + t.Run(transport+"/preserved="+fmt.Sprint(preserved), func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + ctx = svc.withRequestTimezoneEgress(ctx, account) + if preserved { + ctx = context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &openAIAgentRecoveryRequest{omittedHistory: true}) + } + received := make(chan []byte, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if transport == "http" { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + received <- body + w.WriteHeader(http.StatusNoContent) + return + } + conn, err := coderws.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer conn.CloseNow() + _, body, err := conn.Read(ctx) + if err != nil { + t.Error(err) + return + } + received <- body + <-ctx.Done() + })) + defer server.Close() + if transport == "http" { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, server.URL, bytes.NewReader(original)) + require.NoError(t, err) + req.Header.Set("X-Timezone", "Asia/Shanghai") + bound, err := BindOpenAIRequestTimezone(req, "") + require.NoError(t, err) + require.Equal(t, "Asia/Tokyo", bound.Header.Get("X-Timezone")) + response, err := server.Client().Do(bound) + require.NoError(t, err) + require.NoError(t, response.Body.Close()) + } else { + conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) + require.NoError(t, err) + defer conn.CloseNow() + wrapped := &coderOpenAIWSClientConn{conn: conn, timezoneBinding: &requestTimezoneBinding{svc, account}, requestTimezone: "Asia/Tokyo"} + require.NoError(t, wrapped.WriteFrame(ctx, coderws.MessageText, original)) + } + select { + case body := <-received: + if preserved { + require.JSONEq(t, string(original), string(body), "physical send must preserve the rebuilt task") + } else { + require.Contains(t, string(body), "Asia/Tokyo", "ordinary egress normalization remains active") + } + case <-ctx.Done(): + t.Fatal("provider did not receive a frame") + } + cancel() + }) + } + } +} diff --git a/backend/internal/service/openai_ws_client.go b/backend/internal/service/openai_ws_client.go index 866f07b44e31..22bb4c0528bc 100644 --- a/backend/internal/service/openai_ws_client.go +++ b/backend/internal/service/openai_ws_client.go @@ -448,7 +448,8 @@ func (c *coderOpenAIWSClientConn) WriteFrame(ctx context.Context, msgType coderw if ctx == nil { ctx = context.Background() } - if msgType == coderws.MessageText && c.timezoneBinding.enabled(ctx) { + preserveBody := openAIAgentRecoveryPreservesHistory(ctx) + if msgType == coderws.MessageText && !preserveBody && c.timezoneBinding.enabled(ctx) { c.timezoneMu.Lock() if c.requestTimezone == "" { c.requestTimezone = c.timezoneBinding.service.egressRequestTimezone(ctx, c.timezoneProxy) diff --git a/docs/encrypted-history-409-beta.md b/docs/encrypted-history-409-beta.md index f2a2ec64b41a..679e1ce774e5 100644 --- a/docs/encrypted-history-409-beta.md +++ b/docs/encrypted-history-409-beta.md @@ -35,3 +35,11 @@ HTTP 当前轮尚未发送时,原账号的本地 `owner_rate_limited`(429) 如果后续一般兼容逻辑会删除整个 reasoning 或可读 reasoning.content,仍会拒绝该输入,而不是静默丢弃。此时服务器记录 `openai.encrypted_history_409_refused`、`stage=input_integrity`,不含正文、凭据或密文摘要,客户端错误码保持 `encrypted_agent_recovery_wire_changed`。并非所有历史形态都保证可恢复,未知供应商接受度需另行验证。 CI 使用真实 handler、隔离 Redis 和 localhost HTTP/WebSocket 假上游。五适配器回归保留同一客户端,执行 A 工具请求、管理员停用 A、B 复用已完成结果、后续工具验证和正常 terminal;另有关闭开关、无意图、B 不可用、交付未确认及 B 发送后断线的边界。远程 RED/GREEN 必须逐叶核验且不能含编译、panic、race、skip 污染;当前源码本身不代表这些检查已通过。真实供应商验收需要另行授权的隔离环境、两个受控账号和预算,不能用合成 CI 冒充。 + +## 重建后的发送表示 + +HTTP 重建请求会在原始可读快照验证通过后,按目标账号执行有限的 namespace、工具 schema、Lite 和手动时区转换,并在独立请求上下文中固定结果。OAuth 输出专用消息元数据在 OAuth 快照生成前移除;后续兼容处理不得再改变冻结的任务、工具参数或结果。完整性检查失败时,日志记录固定的 `http_projection_source`、`apikey_projection_source`、`oauth_projection_source`、`input_integrity` 或 `controls_integrity` 阶段,不记录内容或摘要。 + +API Key 账号开启普通透传时,重建请求使用原生 Responses 构造与交付流程;普通请求仍使用透传。其他尚不支持重建的账号路线在选号时排除,避免先选中再本地拒绝。WS 新连接首帧没有会话指针、但已有可读任务和原 owner 时,初次选号发现 owner 不可用也会进入一次有界重建。 + +重建或显式完整历史保护请求的正文在物理发送前不再按自动出口时区改写,以免验证后更改用户任务;HTTP 时区请求头仍可按出口更新,普通请求的自动时区行为不变。手动时区在 HTTP 重建投影中处理。缺少可读任务、未完成工具或交付不确定时继续停止,不以重新计算最终摘要掩盖变化。 From 190578eca4ebd5b9521351c43986ee062d814606 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:44:46 +0800 Subject: [PATCH 2/7] =?UTF-8?q?fix:=20=E5=B0=86=E9=87=8D=E5=BB=BA=E6=8A=95?= =?UTF-8?q?=E5=BD=B1=E7=9A=84=E4=BA=A4=E4=BB=98=E7=8A=B6=E6=80=81=E7=BB=91?= =?UTF-8?q?=E5=AE=9A=E5=88=B0=E5=93=8D=E5=BA=94=E8=A7=82=E5=AF=9F=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_gateway_forward.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 85cc8e8c1494..3edf8bdedc4a 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -179,6 +179,16 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if projectionErr != nil { return nil, projectionErr } + if projected := openAIAgentRecoveryFromContext(ctx); projected != openAIAgentRecoveryFromContext(c.Request.Context()) { + // Response observers use gin's context, while final send checks use ctx. + // Both must see the same delivery fence for this attempt. Restore only + // the recovery value afterwards, keeping unrelated context additions. + originalRecovery := openAIAgentRecoveryFromContext(c.Request.Context()) + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), openAIAgentRecoveryContextKey{}, projected)) + defer func() { + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), openAIAgentRecoveryContextKey{}, originalRecovery)) + }() + } if _, err := s.prepareCodexAccountIdentitySource(ctx, c, account); err != nil { return nil, err } From 91fca6791233ff57b4fc44b69f39cec5db3ce663 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:46:00 +0800 Subject: [PATCH 3/7] =?UTF-8?q?fix:=20=E4=BF=9D=E6=8C=81=E9=80=8F=E4=BC=A0?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E9=87=8D=E5=BB=BA=E5=90=8E=E5=B7=B2=E4=BA=A4?= =?UTF-8?q?=E4=BB=98=E4=BC=9A=E8=AF=9D=E7=9A=84=E5=8E=9F=E7=94=9F=E8=B7=AF?= =?UTF-8?q?=E7=BA=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/openai_409_http_rebuild_test.go | 9 +++++++++ backend/internal/service/openai_409_omit_history.go | 7 +++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/openai_409_http_rebuild_test.go b/backend/internal/handler/openai_409_http_rebuild_test.go index 5690d6ed6046..c9b60eb97896 100644 --- a/backend/internal/handler/openai_409_http_rebuild_test.go +++ b/backend/internal/handler/openai_409_http_rebuild_test.go @@ -638,6 +638,15 @@ func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointe } if previous.Exists() { history = append([]string(nil), history...) + if pointer == "passthrough" && previous.Get("id").String() == "resp_rebuild_B" { + filtered := history[:0] + for _, item := range history { + if item != httpRebuildAgentA { + filtered = append(filtered, item) + } + } + history = filtered // only B's established opaque owner remains + } var field string switch pointer { case "message_namespace": diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 93178fb65c76..a947ff64affb 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -567,10 +567,13 @@ func prepareOpenAI409OAuthReplay(ctx context.Context, c *gin.Context, body map[s // A rebuilt request is a new native Responses conversation. An API-key // account's ordinary passthrough preference must not route this prepared -// request around the native input and delivery checks. +// request around the native input and delivery checks. Subsequent single-owner +// turns must keep the learned native route too; exact route/credentials/wire +// validation still runs before sending. func openAI409UsesNativeAPIKey(ctx context.Context, account *Account) bool { r := openAIAgentRecoveryFromContext(ctx) - return r != nil && r.omittedHistory && account != nil && account.IsOpenAIApiKey() + return r != nil && account != nil && account.IsOpenAIApiKey() && + (r.omittedHistory || (r.ownerBindingRequired() && r.owner.accountID == account.ID)) } func openAIRecoveryWireRefusal(ctx context.Context, stage string) error { From 052d7c2ad48e69212e58876a55d171ce4de541d1 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 02:49:12 +0800 Subject: [PATCH 4/7] =?UTF-8?q?fix:=20=E8=A7=84=E8=8C=83=E5=8C=96=20namesp?= =?UTF-8?q?ace=20=E6=97=B6=E4=BF=9D=E7=95=99=E5=B7=A5=E5=85=B7=20schema=20?= =?UTF-8?q?=E4=B8=8E=E5=8E=86=E5=8F=B2=E7=9A=84=E5=A4=A7=E6=95=B4=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/rebuilt-request-dispatch.yml | 5 +++-- backend/internal/service/openai_409_omit_history_test.go | 8 ++++++++ backend/internal/service/openai_responses_namespace.go | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/rebuilt-request-dispatch.yml b/.github/workflows/rebuilt-request-dispatch.yml index bb8169484182..ababa5388856 100644 --- a/.github/workflows/rebuilt-request-dispatch.yml +++ b/.github/workflows/rebuilt-request-dispatch.yml @@ -8,6 +8,7 @@ on: - 'backend/internal/service/openai_account_scheduler.go' - 'backend/internal/service/openai_request_timezone_egress*' - 'backend/internal/service/openai_ws_client.go' + - 'backend/internal/service/openai_responses_namespace.go' - 'backend/internal/handler/openai_409_*' - 'backend/internal/handler/openai_gateway_handler.go' - '.github/workflows/rebuilt-request-dispatch.yml' @@ -40,7 +41,7 @@ jobs: run: | set -euo pipefail baseline=aa8e596e6d6f3e4648d6beba73b39b240dd5357a - for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; do + for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go backend/internal/service/openai_responses_namespace.go; do git show "$baseline:$target" > "$target" done - name: Same network and tool-loop regressions @@ -49,7 +50,7 @@ jobs: run: | set -euo pipefail set +e - (cd backend && go test -race -json -tags=unit ./internal/service ./internal/handler -run '^TestOpenAI409(HTTPProjectionAndPassthrough|WSInitialWithoutPointer|PhysicalTimezonePreservesReadableTask)$' -count=1 -timeout=10m) > "$RUNNER_TEMP/dispatch.jsonl" 2>&1 + (cd backend && go test -race -json -tags=unit ./internal/service ./internal/handler -run '^TestOpenAI409(HTTPProjectionAndPassthrough|WSInitialWithoutPointer|PhysicalTimezonePreservesReadableTask|NamespaceProjectionPreservesNumbers)$' -count=1 -timeout=10m) > "$RUNNER_TEMP/dispatch.jsonl" 2>&1 result=$? set -e cat "$RUNNER_TEMP/dispatch.jsonl" diff --git a/backend/internal/service/openai_409_omit_history_test.go b/backend/internal/service/openai_409_omit_history_test.go index b568f962e8c9..8aa1adecf1f0 100644 --- a/backend/internal/service/openai_409_omit_history_test.go +++ b/backend/internal/service/openai_409_omit_history_test.go @@ -320,3 +320,11 @@ func TestOpenAI409OAuthReplayKeepsOriginalSnapshotAndFinalControls(t *testing.T) }) } } + +func TestOpenAI409NamespaceProjectionPreservesNumbers(t *testing.T) { + body := []byte(`{"tools":[{"type":"namespace","name":"math","tools":[{"type":"function","name":"sum","parameters":{"type":"object","properties":{"count":{"type":"integer","enum":[9007199254740993]}}}}]}],"input":[{"role":"user","content":"continue with the recorded value","sequence":9007199254740993}]}`) + projected, err := flattenOpenAIResponsesNamespaces(nil, body) + require.NoError(t, err) + require.Equal(t, "9007199254740993", gjson.GetBytes(projected, "input.0.sequence").Raw) + require.Equal(t, "9007199254740993", gjson.GetBytes(projected, "tools.0.parameters.properties.count.enum.0").Raw) +} diff --git a/backend/internal/service/openai_responses_namespace.go b/backend/internal/service/openai_responses_namespace.go index 17ee43606470..c740e028985f 100644 --- a/backend/internal/service/openai_responses_namespace.go +++ b/backend/internal/service/openai_responses_namespace.go @@ -166,7 +166,7 @@ func flattenOpenAIResponsesNamespaces(c *gin.Context, body []byte) ([]byte, erro return body, nil } var requestBody map[string]any - if err := json.Unmarshal(body, &requestBody); err != nil { + if err := decodeOpenAIJSONUseNumber(body, &requestBody); err != nil { return body, fmt.Errorf("decode OpenAI namespace body: %w", err) } names, changed, err := apicompat.FlattenResponsesNamespacesExcept(requestBody, map[string]bool{"image_gen": true}) From fae7b48331cd265b5b354cfe473ee7aa8e101415 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 03:11:21 +0800 Subject: [PATCH 5/7] =?UTF-8?q?fix:=20=E6=B8=85=E7=90=86=20WS=20=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E6=81=A2=E5=A4=8D=E7=9A=84=E6=97=A0=E6=95=88=E8=B5=8B?= =?UTF-8?q?=E5=80=BC=E5=92=8C=E6=B5=8B=E8=AF=95=E5=85=B3=E9=97=AD=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/handler/openai_gateway_handler.go | 2 +- .../internal/service/openai_request_timezone_egress_test.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 1f35b11f318e..b361d2689eb8 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -3487,7 +3487,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { if next, clean, changed, rebuildErr := h.gatewayService.TryRebuildOpenAI409History(ctx, c, wsAttemptMessage, sessionHash, wsForwardModel, err); rebuildErr != nil { err = rebuildErr } else if changed { - ctx, firstMessage, wsAttemptMessage, previousResponseID = next, clean, clean, "" + ctx, wsAttemptMessage, previousResponseID = next, clean, "" previousResponseCanMove = true ctx = service.ResetOpenAIWSReadableProviderSession(ctx, c) c.Request = c.Request.WithContext(ctx) diff --git a/backend/internal/service/openai_request_timezone_egress_test.go b/backend/internal/service/openai_request_timezone_egress_test.go index 615577839756..e9521fa46bfa 100644 --- a/backend/internal/service/openai_request_timezone_egress_test.go +++ b/backend/internal/service/openai_request_timezone_egress_test.go @@ -310,7 +310,7 @@ func TestOpenAI409PhysicalTimezonePreservesReadableTask(t *testing.T) { t.Error(err) return } - defer conn.CloseNow() + defer func() { _ = conn.CloseNow() }() _, body, err := conn.Read(ctx) if err != nil { t.Error(err) @@ -333,7 +333,7 @@ func TestOpenAI409PhysicalTimezonePreservesReadableTask(t *testing.T) { } else { conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http"), nil) require.NoError(t, err) - defer conn.CloseNow() + defer func() { _ = conn.CloseNow() }() wrapped := &coderOpenAIWSClientConn{conn: conn, timezoneBinding: &requestTimezoneBinding{svc, account}, requestTimezone: "Asia/Tokyo"} require.NoError(t, wrapped.WriteFrame(ctx, coderws.MessageText, original)) } From ee85d5e50ef9d89ce387982b4cd9fe1fd910af91 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 03:48:38 +0800 Subject: [PATCH 6/7] =?UTF-8?q?ci:=20=E5=9B=BA=E5=AE=9A=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E6=81=A2=E5=A4=8D=20RED=20=E7=9A=84=E6=97=B6=E5=8C=BA=E8=B0=83?= =?UTF-8?q?=E7=94=A8=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/issue715-agent-recovery.yml | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml index c1cfe5ab849a..e587a3d3a3f4 100644 --- a/.github/workflows/issue715-agent-recovery.yml +++ b/.github/workflows/issue715-agent-recovery.yml @@ -56,9 +56,10 @@ jobs: set -euo pipefail git rev-parse HEAD original=6df0cd5bb0ce4d774d34004008f9dd661d236468 + bash .github/scripts/historical-recovery-timezone-callers.sh targets=(backend/internal/service/openai_codex_model_metadata.go backend/internal/service/openai_codex_models_service.go backend/internal/service/openai_excel_bps_models_manifest.go) git fetch --no-tags --depth=1 origin "$original" - trap 'git restore --source=HEAD -- "${targets[@]}"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "${targets[@]}" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" for target in "${targets[@]}"; do expected=$(git rev-parse "$original:$target") @@ -97,6 +98,7 @@ jobs: set -euo pipefail git rev-parse HEAD original=6df0cd5bb0ce4d774d34004008f9dd661d236468 + bash .github/scripts/historical-recovery-timezone-callers.sh 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. @@ -117,7 +119,7 @@ jobs: git fetch --no-tags --depth=1 origin "$original" git fetch --no-tags --depth=1 origin "$analysis_compat" git fetch --no-tags --depth=1 origin "$billing_compat" - trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" git restore --source="$analysis_compat" -- "$analysis_leaf" git restore --source="$billing_compat" -- "$billing_leaf" @@ -173,9 +175,10 @@ jobs: set -euo pipefail git rev-parse HEAD original=18b7c0a4f5f4306a9c92f9715f08164f520df457 + bash .github/scripts/historical-recovery-timezone-callers.sh target=backend/internal/service/openai_gateway_response_handling.go git fetch --no-tags --depth=1 origin "$original" - trap 'git restore --source=HEAD -- "$target"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "$target" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "$target" expected=$(git rev-parse "$original:$target") actual=$(git hash-object "$target") @@ -209,9 +212,10 @@ jobs: set -euo pipefail git rev-parse HEAD original=b6d780f1a4fee66c2930219dfe9e400b8f0279de + bash .github/scripts/historical-recovery-timezone-callers.sh target=backend/internal/service/openai_gateway_response_handling.go git fetch --no-tags --depth=1 origin "$original" - trap 'git restore --source=HEAD -- "$target"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "$target" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "$target" expected=$(git rev-parse "$original:$target") actual=$(git hash-object "$target") @@ -245,6 +249,7 @@ jobs: set -euo pipefail git rev-parse HEAD original=242f5b0892a59d95005099e6294262b066bd2f8b + bash .github/scripts/historical-recovery-timezone-callers.sh targets=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_gateway_response_handling.go) added=backend/internal/service/openai_agent_message_delivery.go ws_original=a575df898ccd0876c4c0eb1559da38cedfdfe99d @@ -263,7 +268,7 @@ jobs: 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 + trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "${omission_added[@]}" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" git restore --source="$ws_original" -- "${ws_targets[@]}" git restore --source="$scheduler_compat" -- "$scheduler_leaf" @@ -312,9 +317,10 @@ jobs: set -euo pipefail git rev-parse HEAD original=d91d890049a9bd8bd0e414f30b0cb3b5bcc0f06e + bash .github/scripts/historical-recovery-timezone-callers.sh target=backend/internal/service/openai_ws_forwarder_ingress.go git fetch --no-tags --depth=1 origin "$original" - trap 'git restore --source=HEAD -- "$target"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "$target" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "$target" expected=$(git rev-parse "$original:$target") actual=$(git hash-object "$target") @@ -347,6 +353,7 @@ jobs: set -euo pipefail git rev-parse HEAD original=e7f54240d83765c90a98e961ad5e33b0fa35ab56 + bash .github/scripts/historical-recovery-timezone-callers.sh target=backend/internal/service/openai_ws_agent_recovery.go caller=backend/internal/service/openai_ws_forwarder_ingress.go passthrough=backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -354,7 +361,7 @@ jobs: # Manager fields and readable-payload methods live together. Restore # both transport callers with that manager; retain candidate tests and # standalone admission/principal helpers required by current HTTP. - trap 'git restore --source=HEAD -- "$target" "$caller" "$passthrough"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "$target" "$caller" "$passthrough" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "$target" "$caller" "$passthrough" expected=$(git rev-parse "$original:$target") actual=$(git hash-object "$target") @@ -426,13 +433,14 @@ jobs: set -euo pipefail git rev-parse HEAD original=a575df898ccd0876c4c0eb1559da38cedfdfe99d + bash .github/scripts/historical-recovery-timezone-callers.sh targets=(backend/internal/handler/openai_gateway_handler.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) # Search activation references fields absent in this pool. Retain the # standalone recovery helpers needed by current HTTP code; the pinned # pre-WS handler/transports never call them or publish WS ownership. added=(backend/internal/service/openai_ws_search_activation.go) git fetch --no-tags --depth=1 origin "$original" - trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}"; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" rm -- "${added[@]}" for target in "${targets[@]}"; do From 8ffd0116504e0940fd7024642d7e1737359ef26a Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 03:48:57 +0800 Subject: [PATCH 7/7] =?UTF-8?q?ci:=20=E6=8F=90=E4=BA=A4=E5=9B=BA=E5=AE=9A?= =?UTF-8?q?=E5=8E=86=E5=8F=B2=E6=97=B6=E5=8C=BA=E8=B0=83=E7=94=A8=E6=96=B9?= =?UTF-8?q?=E7=9A=84=E9=AA=8C=E8=AF=81=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../historical-recovery-timezone-callers.sh | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .github/scripts/historical-recovery-timezone-callers.sh diff --git a/.github/scripts/historical-recovery-timezone-callers.sh b/.github/scripts/historical-recovery-timezone-callers.sh new file mode 100644 index 000000000000..41a50fc6c442 --- /dev/null +++ b/.github/scripts/historical-recovery-timezone-callers.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +# Disposable historical RED overlays only. New physical-send timezone guards +# call recovery helpers absent in those baselines. Pin the pre-guard callers; +# never replace the causal recovery implementation or selected test fixtures. +set -euo pipefail +timezone_callers=aa8e596e6d6f3e4648d6beba73b39b240dd5357a +git fetch --no-tags --depth=1 origin "$timezone_callers" +for target in backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; do + git restore --source="$timezone_callers" -- "$target" + expected=$(git rev-parse "$timezone_callers:$target") + actual=$(git hash-object "$target") + test "$expected" = "$actual" + printf 'timezone compatibility caller baseline=%s path=%s expected=%s actual=%s\n' "$timezone_callers" "$target" "$expected" "$actual" +done