From 7c8ac6d8d169315e6d6d066e8ba87774bb029667 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Mon, 16 Nov 2026 12:16:08 +0800 Subject: [PATCH 1/4] fix: preserve safe BPS search failure diagnostics --- .../service/basispoints/WEB_SEARCH.md | 34 +++ .../internal/service/basispoints/request.go | 1 + .../internal/service/basispoints/stream.go | 2 +- .../service/basispoints/upstream_failure.go | 28 +- .../service/basispoints/web_search.go | 9 +- .../service/basispoints/web_search_failure.go | 109 +++++++ .../basispoints/web_search_failure_test.go | 110 +++++++ .../service/basispoints/web_search_stream.go | 48 +-- backend/internal/service/openai_excel_bps.go | 7 +- .../service/openai_excel_bps_search.go | 23 +- ...penai_excel_bps_search_diagnostics_test.go | 278 ++++++++++++++++++ 11 files changed, 611 insertions(+), 38 deletions(-) create mode 100644 backend/internal/service/basispoints/web_search_failure.go create mode 100644 backend/internal/service/basispoints/web_search_failure_test.go create mode 100644 backend/internal/service/openai_excel_bps_search_diagnostics_test.go diff --git a/backend/internal/service/basispoints/WEB_SEARCH.md b/backend/internal/service/basispoints/WEB_SEARCH.md index a29f5f9ef85b..61631369c61a 100644 --- a/backend/internal/service/basispoints/WEB_SEARCH.md +++ b/backend/internal/service/basispoints/WEB_SEARCH.md @@ -55,6 +55,40 @@ is invented for it. Any provider-side search cost/entitlement needs separate operational verification before enabling accounts. No real paid call is part of CI or local validation. +## Failure diagnostics + +`basispoints_search_failed` keeps its existing semantic status 502 and +`server_error` type. It does not imply that the search endpoint returned 502, +or even that a search HTTP request was sent. Failures do not cause replay, +account cooldown, or account disabling based on the diagnostic HTTP status. + +Normalized JSON/SSE errors include `error.search_diagnostic` with allowlisted +`phase`, `reason`, and optional `upstream_status`. The same safe summary is +appended to `error.message` and retained in existing Ops error message/detail +fields. An already committed compact keepalive retains the summary in its +failure message; its existing compact error shape is unchanged. + +| Phase | Meaning / example reasons | +| --- | --- | +| `search_http` | Search request/transport/rejection: `request_failed`, `transport_failed`, `http_rejected`, `deadline_exceeded`, `canceled` | +| `search_result` | Search body processing: `read_failed`, `parse_failed` | +| `model_initial` | First model stream: `invalid_event`, `unexpected_eof`, `model_did_not_complete`, or fixed stream identity/validation reasons | +| `model_continuation` | Continuation request, HTTP rejection, stream or continuation validation failure | +| `tool_validation` | Tool batch/identity/arguments rejection, including `invalid_tool_response`, `mixed_tool_batch`, `parallel_search_unavailable`, `duplicate_item_id`, `duplicate_call_id` | +| `unknown` | No recognized local failure phase is available | + +Unrecognized or missing reasons become `unknown`; missing HTTP evidence is +omitted, never replaced with the semantic status. Search result read/parse +failures can correctly report observed HTTP 200. Model stream failures omit +HTTP status because that bridge boundary has only a response body. Raw model +claims cannot supply search HTTP evidence. Diagnostics contain no error text, +HTTP bodies, query, credential, URL, or identity values. Normal hosted-search +query/source output continues under its existing contract. Client cancellation +retains cancellation handling instead of emitting a search failure. + +These diagnostics address evidence loss only. The cause of the historical +failure in issue #871 and real upstream search recovery remain unverified. + ## Management entry points The account editor, bulk editor, OAuth BPS defaults card and quality-rule BPS diff --git a/backend/internal/service/basispoints/request.go b/backend/internal/service/basispoints/request.go index fe0becf14abc..9d48ddc9a732 100644 --- a/backend/internal/service/basispoints/request.go +++ b/backend/internal/service/basispoints/request.go @@ -39,6 +39,7 @@ type Bridge struct { clientStream bool toolChoice string selectedTool *tool + searchDiagnostics bool } func decode(raw []byte, target any) error { diff --git a/backend/internal/service/basispoints/stream.go b/backend/internal/service/basispoints/stream.go index 4ccdbd88f25a..81453db44cc8 100644 --- a/backend/internal/service/basispoints/stream.go +++ b/backend/internal/service/basispoints/stream.go @@ -279,7 +279,7 @@ func (b *Bridge) transformWithRepairs(ctx context.Context, reader io.Reader, wri } } terminal = kind == "response.completed" || kind == "response.incomplete" || kind == "response.failed" || kind == "response.cancelled" || kind == "error" - return emit(kind, normalizeFailureEvent(kind, payload)) + return emit(kind, b.normalizeFailureEvent(kind, payload)) } err := readEvents(reader, func(event string, data []byte) error { if terminal { diff --git a/backend/internal/service/basispoints/upstream_failure.go b/backend/internal/service/basispoints/upstream_failure.go index 50d6c45778fa..1ee38a49f1a1 100644 --- a/backend/internal/service/basispoints/upstream_failure.go +++ b/backend/internal/service/basispoints/upstream_failure.go @@ -12,12 +12,17 @@ type UpstreamFailure struct { Code string Type string Message string + Search *SearchFailure } func (f *UpstreamFailure) Error() string { return f.Message } func (f *UpstreamFailure) Details() map[string]any { - return object{"status": f.Status, "code": f.Code, "type": f.Type, "message": f.Message} + detail := object{"status": f.Status, "code": f.Code, "type": f.Type, "message": f.Message} + if f.Search != nil { + detail["search_diagnostic"] = f.Search.details() + } + return detail } // ParseUpstreamFailure recognizes failure terminals only. Unknown identifiers @@ -79,8 +84,15 @@ func classifyUpstreamFailure(kind string, payload object) *UpstreamFailure { errorType = "invalid_request_error" } } - return &UpstreamFailure{Status: status, Code: code, Type: errorType, + failure := &UpstreamFailure{Status: status, Code: code, Type: errorType, Message: "Excel BPS upstream failure: " + code + "; request was not replayed"} + if code == "basispoints_search_failed" { + failure.Search = parseSearchFailure(detail["search_diagnostic"]) + // The safe summary also survives compact keepalives and existing Ops + // consumers that retain only the normalized message. + failure.Message += "; " + failure.Search.Error() + } + return failure } func failureStatus(value any) int { @@ -125,7 +137,17 @@ func failureIdentifierStatus(identifier string) int { // normalizeFailureEvent preserves response identity/output/usage after the // bridge has withheld tools, but replaces error details with safe identifiers. -func normalizeFailureEvent(kind string, payload object) object { +func (b *Bridge) normalizeFailureEvent(kind string, payload object) object { + if !b.searchDiagnostics && (kind == "error" || kind == "response.failed" || kind == "response.cancelled") { + // Only the local search runner can attest to a search HTTP response. + // A raw model terminal must not manufacture search status evidence. + response, _ := payload["response"].(object) + for _, value := range []any{response["error"], payload["error"], payload} { + if detail, ok := value.(object); ok { + delete(detail, "search_diagnostic") + } + } + } failure := classifyUpstreamFailure(kind, payload) if failure == nil { return payload diff --git a/backend/internal/service/basispoints/web_search.go b/backend/internal/service/basispoints/web_search.go index a72bfd68048f..b7946eedb756 100644 --- a/backend/internal/service/basispoints/web_search.go +++ b/backend/internal/service/basispoints/web_search.go @@ -3,7 +3,6 @@ package basispoints import ( "bytes" "encoding/json" - "fmt" "net/url" "strings" ) @@ -35,10 +34,14 @@ func isWebSearch(kind string) bool { return false } -func searchRequestError(reason string) error { - return fmt.Errorf("basispoints web_search rejected; reason=%s", reason) +type searchRequestRejection string + +func (r searchRequestRejection) Error() string { + return "basispoints web_search rejected; reason=" + string(r) } +func searchRequestError(reason string) error { return searchRequestRejection(reason) } + // NormalizeWebSearchRequest removes hosted declarations before catalog caching. // Disabled accounts retain the existing native routing/omission behavior. func NormalizeWebSearchRequest(raw []byte, enabled, automatic bool) ([]byte, *SearchPlan, error) { diff --git a/backend/internal/service/basispoints/web_search_failure.go b/backend/internal/service/basispoints/web_search_failure.go new file mode 100644 index 000000000000..f9ef5c1a35b9 --- /dev/null +++ b/backend/internal/service/basispoints/web_search_failure.go @@ -0,0 +1,109 @@ +package basispoints + +import ( + "context" + "encoding/json" + "errors" + "io" + "strconv" +) + +// SearchFailure contains only bounded diagnostics, never the underlying error. +// Its HTTP status is observed evidence, independent of the semantic 502 status. +type SearchFailure struct { + phase string + reason string + upstreamStatus int +} + +// NewSearchFailure is used at adapter boundaries with an actually observed HTTP +// status, or zero when no response was received. Unknown identifiers are dropped. +func NewSearchFailure(phase, reason string, upstreamStatus int) *SearchFailure { + known := false + switch phase { + case "search_http": + switch reason { + case "request_failed", "transport_failed", "http_rejected", "deadline_exceeded", "canceled": + known = true + } + case "search_result": + known = reason == "read_failed" || reason == "parse_failed" + case "model_initial", "model_continuation": + switch reason { + case "request_failed", "transport_failed", "http_rejected", "read_failed", "unexpected_eof", + "invalid_event", "model_did_not_complete", "missing_response_id", "invalid_continuation", + "continuation_too_large", "missing_continuation", "deadline_exceeded", "canceled", + "invalid_output_index", "too_many_tool_items", "missing_item_id", "item_identity_changed", + "invalid_text_delta", "text_too_large", "missing_terminal_tool", "missing_terminal_item", + "terminal_identity_changed", "missing_terminal_text", "terminal_text_changed": + known = true + } + case "tool_validation": + switch reason { + case "invalid_tool_response", "duplicate_item_id", "duplicate_call_id", "invalid_query", + "parallel_search_unavailable", "mixed_tool_batch", "required_search_missing", + "required_tool_missing", "executor_unavailable": + known = true + } + default: + phase = "unknown" + } + if !known { + reason = "unknown" + } + if upstreamStatus < 100 || upstreamStatus > 599 { + upstreamStatus = 0 + } + return &SearchFailure{phase: phase, reason: reason, upstreamStatus: upstreamStatus} +} + +func (f *SearchFailure) Error() string { + message := "phase=" + f.phase + "; reason=" + f.reason + if f.upstreamStatus != 0 { + message += "; upstream_status=" + strconv.Itoa(f.upstreamStatus) + } + return message +} + +func (f *SearchFailure) details() object { + detail := object{"phase": f.phase, "reason": f.reason} + if f.upstreamStatus != 0 { + detail["upstream_status"] = f.upstreamStatus + } + return detail +} + +func searchFailureAt(err error, phase, fallback string) error { + // Preserve the existing closed-pipe exit without synthesizing a terminal. + if errors.Is(err, io.ErrClosedPipe) { + return err + } + var failure *SearchFailure + if errors.As(err, &failure) { + return NewSearchFailure(failure.phase, failure.reason, failure.upstreamStatus) + } + var rejection searchRequestRejection + switch { + case errors.As(err, &rejection): + fallback = string(rejection) + case errors.Is(err, context.DeadlineExceeded): + fallback = "deadline_exceeded" + case errors.Is(err, context.Canceled): + fallback = "canceled" + case errors.Is(err, io.ErrUnexpectedEOF): + fallback = "unexpected_eof" + } + return NewSearchFailure(phase, fallback, 0) +} + +// Revalidate at the SSE boundary; never trust arbitrary upstream diagnostics. +func parseSearchFailure(value any) *SearchFailure { + detail, _ := value.(object) + status := 0 + if number, ok := detail["upstream_status"].(json.Number); ok { + if n, err := number.Int64(); err == nil && n >= 100 && n <= 599 { + status = int(n) + } + } + return NewSearchFailure(text(detail["phase"]), text(detail["reason"]), status) +} diff --git a/backend/internal/service/basispoints/web_search_failure_test.go b/backend/internal/service/basispoints/web_search_failure_test.go new file mode 100644 index 000000000000..4dbbd186d640 --- /dev/null +++ b/backend/internal/service/basispoints/web_search_failure_test.go @@ -0,0 +1,110 @@ +package basispoints + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestWebSearchUnknownFailuresNeverInferHTTPOrLeakText(t *testing.T) { + for _, tc := range []struct { + name, phase, reason string + err error + status int + }{ + {"arbitrary", "search_http", "unknown", errors.New("HTTP 429 PRIVATE_QUERY Bearer PRIVATE_TOKEN https://private.invalid private@example.invalid"), 0}, + {"unknown_identifiers", "unknown", "unknown", NewSearchFailure("PRIVATE_PHASE", "PRIVATE_REASON", 999), 0}, + {"wrapped", "search_http", "http_rejected", fmt.Errorf("PRIVATE_WRAPPER: %w", NewSearchFailure("search_http", "http_rejected", 429)), 429}, + {"deadline", "search_http", "deadline_exceeded", context.DeadlineExceeded, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + wire, bridge, plan := prepareSearch(t, searchSource(), false, nil) + searches, continuations := 0, 0 + stream := bridge.StreamWithSearch(context.Background(), searchRound(0, searchCall(0)), wire, plan, + func(context.Context, string) (SearchResult, error) { searches++; return SearchResult{}, tc.err }, + func(context.Context, []byte) (io.ReadCloser, error) { continuations++; return nil, nil }) + events := repairEvents(t, stream) + last := events[len(events)-1] + require.Equal(t, "response.failed", last["type"]) + response := mustTestValue[object](t, last["response"]) + detail := mustTestValue[object](t, response["error"]) + diagnostic := mustTestValue[object](t, detail["search_diagnostic"]) + require.Equal(t, tc.phase, diagnostic["phase"]) + require.Equal(t, tc.reason, diagnostic["reason"]) + if tc.status == 0 { + require.NotContains(t, diagnostic, "upstream_status") + } else { + require.Equal(t, json.Number("429"), diagnostic["upstream_status"]) + } + raw, err := json.Marshal(detail) + require.NoError(t, err) + require.NotContains(t, string(raw), "PRIVATE") + require.NotContains(t, string(raw), "https://") + require.NotContains(t, string(raw), "@") + require.Equal(t, 1, searches) + require.Zero(t, continuations) + }) + } +} + +func TestWebSearchDiagnosticSSEBoundaryAllowlistsEveryField(t *testing.T) { + for _, tc := range []struct { + name string + diagnostic any + phase string + reason string + }{ + {"missing", nil, "unknown", "unknown"}, + {"not_object", "PRIVATE", "unknown", "unknown"}, + {"unknown", object{"phase": "PRIVATE", "reason": "PRIVATE", "upstream_status": 600, "query": "PRIVATE"}, "unknown", "unknown"}, + {"string_status", object{"phase": "search_http", "reason": "http_rejected", "upstream_status": "403 PRIVATE", "body": "PRIVATE"}, "search_http", "http_rejected"}, + {"fraction_status", object{"phase": "search_http", "reason": "http_rejected", "upstream_status": 429.5}, "search_http", "http_rejected"}, + {"wrong_phase_reason", object{"phase": "tool_validation", "reason": "http_rejected", "url": "PRIVATE"}, "tool_validation", "unknown"}, + } { + t.Run(tc.name, func(t *testing.T) { + _, bridge := mustPrepare(t, testSource(), "", nil) + // Exercise revalidation at the second, trusted local SSE boundary. + bridge.searchDiagnostics = true + raw := sse(object{"type": "response.failed", "response": object{"status": "failed", "output": []any{}, "error": object{"code": "basispoints_search_failed", "message": "PRIVATE", "search_diagnostic": tc.diagnostic}}}) + events := repairEvents(t, bridge.Stream(io.NopCloser(strings.NewReader(raw)))) + response := mustTestValue[object](t, events[len(events)-1]["response"]) + detail := mustTestValue[object](t, response["error"]) + diagnostic := mustTestValue[object](t, detail["search_diagnostic"]) + require.Equal(t, object{"phase": tc.phase, "reason": tc.reason}, diagnostic) + encoded, err := json.Marshal(detail) + require.NoError(t, err) + require.NotContains(t, string(encoded), "PRIVATE") + }) + } +} + +func TestWebSearchRawModelCannotManufactureSearchHTTPStatus(t *testing.T) { + _, bridge := mustPrepare(t, testSource(), "", nil) + raw := sse(object{"type": "response.failed", "response": object{"status": "failed", "output": []any{}, "error": object{ + "code": "basispoints_search_failed", "message": "PRIVATE", "search_diagnostic": object{"phase": "search_http", "reason": "http_rejected", "upstream_status": 403}, + }}}) + events := repairEvents(t, bridge.Stream(io.NopCloser(strings.NewReader(raw)))) + response := mustTestValue[object](t, events[len(events)-1]["response"]) + detail := mustTestValue[object](t, response["error"]) + require.Equal(t, object{"phase": "unknown", "reason": "unknown"}, detail["search_diagnostic"]) + require.NotContains(t, detail["message"], "403") +} + +func TestWebSearchClosedPipeKeepsExistingExitWithoutFailureTerminal(t *testing.T) { + wire, bridge, plan := prepareSearch(t, searchSource(), false, nil) + continuations := 0 + stream := bridge.StreamWithSearch(context.Background(), searchRound(0, searchCall(0)), wire, plan, + func(context.Context, string) (SearchResult, error) { return SearchResult{}, io.ErrClosedPipe }, + func(context.Context, []byte) (io.ReadCloser, error) { continuations++; return nil, nil }) + defer func() { _ = stream.Close() }() + raw, err := io.ReadAll(stream) + require.ErrorIs(t, err, io.ErrClosedPipe) + require.NotContains(t, string(raw), "response.failed") + require.Zero(t, continuations) +} diff --git a/backend/internal/service/basispoints/web_search_stream.go b/backend/internal/service/basispoints/web_search_stream.go index fc8c36edb832..a6a9fb273275 100644 --- a/backend/internal/service/basispoints/web_search_stream.go +++ b/backend/internal/service/basispoints/web_search_stream.go @@ -24,6 +24,7 @@ func (b *Bridge) StreamWithSearch(parent context.Context, upstream io.ReadCloser upstream = &searchRoundBody{ReadCloser: upstream} raw := &streamBody{PipeReader: reader, upstream: upstream, cancel: cancel} final := *b + final.searchDiagnostics = true final.tools = make(map[string]tool, len(b.tools)) for key, value := range b.tools { if key != serverSearchTool { @@ -68,7 +69,12 @@ func (b *Bridge) runWebSearch(ctx context.Context, upstream io.ReadCloser, write } // A search/model continuation failure cannot look like a successful HTTP 200. // Keep observed model usage; upstream bodies and search queries are not errors. - response := object{"id": state.id, "model": state.model, "status": "failed", "output": []any{}, "usage": state.usage, "error": object{"code": "basispoints_search_failed", "message": err.Error()}} + failure := NewSearchFailure("unknown", "unknown", 0) + var known *SearchFailure + if errors.As(err, &known) { + failure = NewSearchFailure(known.phase, known.reason, known.upstreamStatus) + } + response := object{"id": state.id, "model": state.model, "status": "failed", "output": []any{}, "usage": state.usage, "error": object{"code": "basispoints_search_failed", "search_diagnostic": failure.details()}} return state.emit("response.failed", object{"response": response}) } @@ -76,9 +82,10 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire var prepared object if err := decode(wire, &prepared); err != nil { _ = upstream.Close() - return searchRequestError("invalid_continuation") + return NewSearchFailure("model_initial", "invalid_continuation", 0) } current := upstream + phase := "model_initial" defer func() { if current != nil { _ = current.Close() @@ -112,13 +119,13 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire } } if err != nil { - return err + return searchFailureAt(err, phase, "read_failed") } if state.id == "" { - return searchRequestError("missing_response_id") + return NewSearchFailure(phase, "missing_response_id", 0) } if err = observed.validate(response); err != nil { - return err + return searchFailureAt(err, phase, "unknown") } output, _ := response["output"].([]any) nativeSearch := []object{} @@ -130,13 +137,13 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire check.stagedReplays = nil // Validate every tool before any search side effect. All IDs are request-wide. if err = check.validateToolResponse(response); err != nil { - return err + return searchFailureAt(err, "tool_validation", "invalid_tool_response") } for i, rawItem := range output { item, _ := rawItem.(object) if id := text(item["id"]); id != "" { if state.identities[id] { - return searchRequestError("duplicate_item_id") + return NewSearchFailure("tool_validation", "duplicate_item_id", 0) } state.identities[id] = true } @@ -145,12 +152,12 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire } callID := text(item["call_id"]) if callID == "" || state.callIDs[callID] { - return searchRequestError("duplicate_call_id") + return NewSearchFailure("tool_validation", "duplicate_call_id", 0) } state.callIDs[callID] = true translated, translateErr := check.translateCall(item) if translateErr != nil { - return translateErr + return searchFailureAt(translateErr, "tool_validation", "invalid_tool_response") } if text(translated["name"]) != serverSearchTool { clientCalls++ @@ -158,28 +165,28 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire } var args object if decode([]byte(text(translated["arguments"])), &args) != nil { - return searchRequestError("invalid_query") + return NewSearchFailure("tool_validation", "invalid_query", 0) } query := strings.TrimSpace(text(args["query"])) if query == "" || len(query) > 4096 { - return searchRequestError("invalid_query") + return NewSearchFailure("tool_validation", "invalid_query", 0) } nativeSearch = append(nativeSearch, item) searchIndexes = append(searchIndexes, i) queries = append(queries, query) } if len(nativeSearch) > 1 { - return searchRequestError("parallel_search_unavailable") + return NewSearchFailure("tool_validation", "parallel_search_unavailable", 0) } if len(nativeSearch) > 0 && clientCalls > 0 { - return searchRequestError("mixed_tool_batch") + return NewSearchFailure("tool_validation", "mixed_tool_batch", 0) } if len(nativeSearch) == 0 { if plan.Required && !state.completedSearch { - return searchRequestError("required_search_missing") + return NewSearchFailure("tool_validation", "required_search_missing", 0) } if plan.RequiredAny && !state.completedSearch && clientCalls == 0 { - return searchRequestError("required_tool_missing") + return NewSearchFailure("tool_validation", "required_tool_missing", 0) } state.output = append(state.output, output...) response["output"], response["usage"], response["id"] = state.output, state.usage, state.id @@ -192,7 +199,7 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire return state.emit("response.completed", object{"response": response}) } if search == nil || next == nil { - return searchRequestError("executor_unavailable") + return NewSearchFailure("tool_validation", "executor_unavailable", 0) } index := searchIndexes[0] nativeOutput := append([]any(nil), output...) @@ -231,7 +238,7 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire result, searchErr := waitForWebSearch(searchCtx, search, queries[0]) cancel() if searchErr != nil { - return searchErr + return searchFailureAt(searchErr, "search_http", "unknown") } state.completedSearch = true public["status"] = "completed" @@ -269,15 +276,16 @@ func (b *Bridge) searchRounds(ctx context.Context, upstream io.ReadCloser, wire } snapshot, _ := json.Marshal(state.output) if len(encoded) > 32<<20 || len(snapshot) > 32<<20 { - return searchRequestError("continuation_too_large") + return NewSearchFailure("model_continuation", "continuation_too_large", 0) } current, err = next(ctx, encoded) if err != nil { - return err + return searchFailureAt(err, "model_continuation", "unknown") } if current == nil { - return searchRequestError("missing_continuation") + return NewSearchFailure("model_continuation", "missing_continuation", 0) } + phase = "model_continuation" current = &searchRoundBody{ReadCloser: current} } } diff --git a/backend/internal/service/openai_excel_bps.go b/backend/internal/service/openai_excel_bps.go index 405a019c31ef..7872bf2c480f 100644 --- a/backend/internal/service/openai_excel_bps.go +++ b/backend/internal/service/openai_excel_bps.go @@ -935,7 +935,12 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte if upstreamFailure != nil { // Preserve the actual HTTP status separately from the event's // semantic status. An accepted generation is never replayed. - setOpsUpstreamError(c, resp.StatusCode, upstreamFailure.Message, "") + safeDetail := "" + if upstreamFailure.Search != nil { + raw, _ := json.Marshal(upstreamFailure.Details()) + safeDetail = string(raw) + } + setOpsUpstreamError(c, resp.StatusCode, upstreamFailure.Message, safeDetail) MarkOpsStreamErrorValue(c, OpsStreamError{ ErrType: upstreamFailure.Type, Code: upstreamFailure.Code, Message: upstreamFailure.Message, IntendedStatus: upstreamFailure.Status, CountTowardsSLA: true, NonStream: !stream, diff --git a/backend/internal/service/openai_excel_bps_search.go b/backend/internal/service/openai_excel_bps_search.go index 6b5d7d1e7c16..c702872bfa88 100644 --- a/backend/internal/service/openai_excel_bps_search.go +++ b/backend/internal/service/openai_excel_bps_search.go @@ -3,7 +3,6 @@ package service import ( "bytes" "context" - "fmt" "io" "net/http" @@ -32,45 +31,49 @@ func (s *OpenAIGatewayService) executeExcelBPSSearch(ctx context.Context, accoun } body, err := plan.SearchRequestBody(model, uuid.NewString(), query) if err != nil { - return empty, err + return empty, basispoints.NewSearchFailure("search_http", "request_failed", 0) } req, err := newExcelBPSSearchRequest(ctx, body, token, accountID) if err != nil { - return empty, fmt.Errorf("BPS search request could not be prepared") + return empty, basispoints.NewSearchFailure("search_http", "request_failed", 0) } resp, err := s.httpUpstream.Do(req, proxy, account.ID, account.Concurrency) if err != nil { if ctx.Err() != nil { return empty, ctx.Err() } - return empty, fmt.Errorf("BPS search connection failed; request was not replayed") + return empty, basispoints.NewSearchFailure("search_http", "transport_failed", 0) } defer func() { _ = resp.Body.Close() }() if resp.StatusCode < 200 || resp.StatusCode >= 300 { - return empty, fmt.Errorf("BPS search rejected with HTTP %d; request was not replayed", resp.StatusCode) + return empty, basispoints.NewSearchFailure("search_http", "http_rejected", resp.StatusCode) } raw, err := io.ReadAll(io.LimitReader(resp.Body, (2<<20)+1)) if err != nil { - return empty, fmt.Errorf("BPS search result could not be read") + return empty, basispoints.NewSearchFailure("search_result", "read_failed", resp.StatusCode) } - return basispoints.ParseSearchResult(raw) + result, err := basispoints.ParseSearchResult(raw) + if err != nil { + return empty, basispoints.NewSearchFailure("search_result", "parse_failed", resp.StatusCode) + } + return result, nil } func (s *OpenAIGatewayService) continueExcelBPSSearch(ctx context.Context, account *Account, body []byte, token, accountID, proxy string) (io.ReadCloser, error) { req, err := newExcelBPSRequest(ctx, body, token, accountID) if err != nil { - return nil, fmt.Errorf("BPS search continuation could not be prepared") + return nil, basispoints.NewSearchFailure("model_continuation", "request_failed", 0) } resp, err := s.doPriorityObservedHTTP(req, proxy, account) if err != nil { if ctx.Err() != nil { return nil, ctx.Err() } - return nil, fmt.Errorf("BPS search continuation connection failed; request was not replayed") + return nil, basispoints.NewSearchFailure("model_continuation", "transport_failed", 0) } if resp.StatusCode < 200 || resp.StatusCode >= 300 { _ = resp.Body.Close() - return nil, fmt.Errorf("BPS search continuation rejected with HTTP %d; request was not replayed", resp.StatusCode) + return nil, basispoints.NewSearchFailure("model_continuation", "http_rejected", resp.StatusCode) } s.UpdateCodexUsageSnapshotFromHeaders(ctx, account.ID, resp.Header) s.guardExcelBPSProgress(ctx, resp) diff --git a/backend/internal/service/openai_excel_bps_search_diagnostics_test.go b/backend/internal/service/openai_excel_bps_search_diagnostics_test.go new file mode 100644 index 000000000000..815473fb9f00 --- /dev/null +++ b/backend/internal/service/openai_excel_bps_search_diagnostics_test.go @@ -0,0 +1,278 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// All values are synthetic. These markers must never reach error/Ops details; +// hosted search progress can still carry the query under the existing contract. +const issue871Private = "PRIVATE_BODY Bearer PRIVATE_TOKEN https://private.invalid/?key=PRIVATE_KEY private@example.invalid" + +func issue871Call(id, callID, name string) map[string]any { + arguments := map[string]any{} + if name == "__sub2api_web_search" { + arguments["query"] = "PRIVATE_QUERY" + } + code, _ := json.Marshal(map[string]any{"name": name, "arguments": arguments}) + args, _ := json.Marshal(map[string]any{"code": string(code), "summary": "Search", "extended_summary": "{}", "destructive": false, "references": []any{}}) + return map[string]any{"type": "function_call", "id": id, "call_id": callID, "name": "run_officejs", "arguments": string(args)} +} + +func issue871Round(id string, items ...any) *http.Response { + return excelSearchResponse(map[string]any{"id": id, "status": "completed", "model": "gpt-6-astra", "output": items, "usage": map[string]any{"input_tokens": 10, "output_tokens": 2}}) +} + +func issue871HTTP(status int, body string) *http.Response { + return &http.Response{StatusCode: status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))} +} + +func issue871Error(t *testing.T, raw string, sse bool) gjson.Result { + t.Helper() + if !sse { + return gjson.Get(raw, "error") + } + for _, line := range strings.Split(raw, "\n") { + if strings.HasPrefix(line, "data: ") { + payload := strings.TrimPrefix(line, "data: ") + if gjson.Get(payload, "type").String() == "response.failed" { + return gjson.Get(payload, "response.error") + } + } + } + t.Fatal("missing response.failed terminal") + return gjson.Result{} +} + +func TestExcelBPSSearchDiagnosticsThroughForward(t *testing.T) { + for _, tc := range []struct { + name, phase, reason string + sends, observedHTTP int + }{ + {"search_403", "search_http", "http_rejected", 2, 403}, + {"search_429", "search_http", "http_rejected", 2, 429}, + {"search_transport", "search_http", "transport_failed", 2, 0}, + {"result_read", "search_result", "read_failed", 2, 200}, + {"result_json", "search_result", "parse_failed", 2, 200}, + {"result_shape", "search_result", "parse_failed", 2, 200}, + {"result_error", "search_result", "parse_failed", 2, 200}, + {"continuation_403", "model_continuation", "http_rejected", 3, 403}, + {"continuation_429", "model_continuation", "http_rejected", 3, 429}, + {"continuation_transport", "model_continuation", "transport_failed", 3, 0}, + {"continuation_terminal", "model_continuation", "model_did_not_complete", 3, 0}, + {"continuation_eof", "model_continuation", "unexpected_eof", 3, 0}, + {"continuation_event", "model_continuation", "invalid_event", 3, 0}, + {"continuation_read", "model_continuation", "read_failed", 3, 0}, + {"initial_terminal", "model_initial", "model_did_not_complete", 1, 0}, + {"initial_event", "model_initial", "invalid_event", 1, 0}, + {"initial_eof", "model_initial", "unexpected_eof", 1, 0}, + {"mixed_batch", "tool_validation", "mixed_tool_batch", 1, 0}, + {"parallel_search", "tool_validation", "parallel_search_unavailable", 1, 0}, + {"missing_call_id", "tool_validation", "invalid_tool_response", 1, 0}, + {"duplicate_call_id", "tool_validation", "invalid_tool_response", 1, 0}, + {"duplicate_item_id", "tool_validation", "invalid_tool_response", 1, 0}, + {"repeated_item_id", "tool_validation", "duplicate_item_id", 3, 0}, + {"repeated_call_id", "tool_validation", "duplicate_call_id", 3, 0}, + } { + for _, mode := range []string{"json", "sse", "compact_keepalive"} { + t.Run(tc.name+"/"+mode, func(t *testing.T) { + call := issue871Call("fc_search", "call_search", "__sub2api_web_search") + items := []any{call} + switch tc.name { + case "mixed_batch": + items = append(items, issue871Call("fc_shell", "call_shell", "shell")) + case "parallel_search": + items = append(items, issue871Call("fc_other", "call_other", "__sub2api_web_search")) + case "missing_call_id": + delete(call, "call_id") + case "duplicate_call_id": + items = append(items, issue871Call("fc_other", "call_search", "__sub2api_web_search")) + case "duplicate_item_id": + items = append(items, issue871Call("fc_search", "call_other", "__sub2api_web_search")) + } + var sends atomic.Int64 + upstream := &bpsTestUpstream{send: func(req *http.Request, _ string) (*http.Response, error) { + _ = req.Body.Close() + n := sends.Add(1) + if n == 1 { + switch tc.name { + case "initial_terminal": + return issue871HTTP(200, "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"message\":\"PRIVATE_BODY\"}}}\n\n"), nil + case "initial_event": + return issue871HTTP(200, "data: PRIVATE_BODY\n\n"), nil + case "initial_eof": + return issue871HTTP(200, ""), nil + } + return issue871Round("resp_initial", items...), nil + } + if n == 2 { + switch tc.name { + case "search_403", "search_429": + return issue871HTTP(tc.observedHTTP, issue871Private), nil + case "search_transport": + return nil, errors.New(issue871Private) + case "result_read": + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: passthroughErrReadCloser{err: errors.New(issue871Private)}}, nil + case "result_json": + return issue871HTTP(200, issue871Private), nil + case "result_shape": + return issue871HTTP(200, `{"output":"PRIVATE_BODY","results":{}}`), nil + case "result_error": + return issue871HTTP(200, `{"results":[],"error":{"message":"PRIVATE_BODY"}}`), nil + } + return issue871HTTP(200, `{"results":[]}`), nil + } + if n == 3 { + switch tc.name { + case "continuation_403", "continuation_429": + return issue871HTTP(tc.observedHTTP, issue871Private), nil + case "continuation_transport": + return nil, errors.New(issue871Private) + case "continuation_terminal": + return issue871HTTP(200, "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"message\":\"PRIVATE_BODY\"}}}\n\n"), nil + case "continuation_eof": + return issue871HTTP(200, ""), nil + case "continuation_event": + return issue871HTTP(200, "data: PRIVATE_BODY\n\n"), nil + case "continuation_read": + return &http.Response{StatusCode: 200, Header: http.Header{}, Body: passthroughErrReadCloser{err: errors.New(issue871Private)}}, nil + case "repeated_item_id": + return issue871Round("resp_next", issue871Call("fc_search", "call_other", "__sub2api_web_search")), nil + case "repeated_call_id": + return issue871Round("resp_next", issue871Call("fc_other", "call_search", "__sub2api_web_search")), nil + } + } + return nil, errors.New("unexpected extra upstream send") + }} + svc := openAIClientToolsTestService(nil) + svc.httpUpstream = upstream + account := excelAccount() + account.Extra[ExcelBPSWebSearchKey] = true + account.Extra["openai_excel_bps_auto_disable_on_403"] = true + body := []byte(fmt.Sprintf(`{"model":"gpt-6-astra","stream":%t,"input":"search","tools":[{"type":"web_search"},{"type":"function","name":"shell","parameters":{"type":"object","properties":{}}}]}`, mode == "sse")) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(string(body))) + if mode == "compact_keepalive" { + MarkOpenAICompactClientStream(c) + stop := StartOpenAICompactSSEKeepalive(c, time.Hour) + defer stop() + value, ok := c.Get(openAICompactSSEKeepaliveKey) + require.True(t, ok) + keepalive, ok := value.(*openAICompactSSEKeepalive) + require.True(t, ok) + require.True(t, keepalive.beat()) + } + result, err := svc.Forward(c.Request.Context(), c, account, body) + require.Error(t, err) + require.NotNil(t, result) + require.Equal(t, int64(tc.sends), sends.Load(), "failure must not trigger repair, replay, or another search") + require.True(t, account.IsExcelBPSEnabled()) + require.True(t, account.Schedulable) + require.False(t, svc.isExcelBPSCoolingDown(account, "gpt-6-astra")) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.NotContains(t, rec.Body.String(), "response.completed") + detail := issue871Error(t, rec.Body.String(), mode != "json") + require.Equal(t, "basispoints_search_failed", detail.Get("code").String()) + if mode != "compact_keepalive" { + require.Equal(t, "server_error", detail.Get("type").String()) + } + message := detail.Get("message").String() + require.Contains(t, message, "request was not replayed") + require.Contains(t, message, "phase="+tc.phase+"; reason="+tc.reason) + ops, ok := GetOpsStreamError(c) + require.True(t, ok) + require.Equal(t, 502, ops.IntendedStatus) + require.Equal(t, "server_error", ops.ErrType) + require.Equal(t, 200, ops.UpstreamStatus, "initial generation HTTP is distinct from search evidence") + require.Equal(t, message, ops.Message) + opsDiagnostic := gjson.Get(ops.UpstreamDetail, "search_diagnostic") + require.Equal(t, tc.phase, opsDiagnostic.Get("phase").String()) + require.Equal(t, tc.reason, opsDiagnostic.Get("reason").String()) + if mode != "compact_keepalive" { + require.Equal(t, opsDiagnostic.Raw, detail.Get("search_diagnostic").Raw) + } + if tc.observedHTTP == 0 { + require.False(t, opsDiagnostic.Get("upstream_status").Exists()) + require.NotContains(t, message, "upstream_status=") + } else { + require.Equal(t, int64(tc.observedHTTP), opsDiagnostic.Get("upstream_status").Int()) + require.Contains(t, message, fmt.Sprintf("upstream_status=%d", tc.observedHTTP)) + } + for _, sensitive := range []string{"PRIVATE_BODY", "PRIVATE_QUERY", "PRIVATE_TOKEN", "PRIVATE_KEY", "Bearer ", "https://private.invalid", "private@example.invalid", "test-token", "test-account"} { + require.NotContains(t, detail.Raw+ops.Message+ops.UpstreamMessage+ops.UpstreamDetail, sensitive) + } + if tc.sends >= 2 { + wantInput, wantOutput := 10, 2 + if strings.HasPrefix(tc.name, "repeated_") { + wantInput, wantOutput = 20, 4 + } + require.Equal(t, wantInput, result.Usage.InputTokens) + require.Equal(t, wantOutput, result.Usage.OutputTokens) + } + }) + } + } +} + +func TestExcelBPSSearchCancellationDoesNotSendContinuation(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, stage := range []string{"search", "continuation"} { + t.Run(fmt.Sprintf("%s/stream_%t", stage, stream), func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + var sends atomic.Int64 + upstream := &bpsTestUpstream{send: func(req *http.Request, _ string) (*http.Response, error) { + _ = req.Body.Close() + n := sends.Add(1) + if n == 1 { + return issue871Round("resp_initial", issue871Call("fc_search", "call_search", "__sub2api_web_search")), nil + } + if n == 2 && stage == "continuation" { + return issue871HTTP(200, `{"results":[]}`), nil + } + cancel() + return nil, context.Canceled + }} + svc := openAIClientToolsTestService(nil) + svc.httpUpstream = upstream + account := excelAccount() + account.Extra[ExcelBPSWebSearchKey] = true + body := []byte(fmt.Sprintf(`{"model":"gpt-6-astra","stream":%t,"input":"search","tools":[{"type":"web_search"}]}`, stream)) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(ctx) + result, err := svc.Forward(ctx, c, account, body) + require.ErrorIs(t, err, context.Canceled) + require.NotNil(t, result) + require.True(t, result.ClientDisconnect) + wantSends := int64(2) + if stage == "continuation" { + wantSends = 3 + } + require.Equal(t, wantSends, sends.Load()) + require.NotContains(t, rec.Body.String(), "response.failed") + require.NotContains(t, rec.Body.String(), "basispoints_search_failed") + ops, ok := GetOpsStreamError(c) + require.True(t, ok) + require.Equal(t, OpsClientCanceledCode, ops.Code) + _, providerFailure := c.Get(OpsUpstreamErrorMessageKey) + require.False(t, providerFailure) + require.Equal(t, 10, result.Usage.InputTokens) + }) + } + } +} From b0633ade90856d4b6a4984664206d8e3863ed99b Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Mon, 16 Nov 2026 12:28:49 +0800 Subject: [PATCH 2/4] fix: attest local BPS search diagnostics before preservation --- .github/scripts/issue871-evidence.py | 60 +++++++++++++++ .github/scripts/test_issue871_evidence.py | 54 +++++++++++++ .github/workflows/bps-search.yml | 76 ++++++++++++++++++- .../service/basispoints/WEB_SEARCH.md | 5 ++ .../service/basispoints/upstream_failure.go | 37 +++++---- .../basispoints/web_search_failure_test.go | 31 ++++++++ backend/internal/service/openai_excel_bps.go | 2 +- ...penai_excel_bps_search_diagnostics_test.go | 66 +++++++++++++++- 8 files changed, 315 insertions(+), 16 deletions(-) create mode 100644 .github/scripts/issue871-evidence.py create mode 100644 .github/scripts/test_issue871_evidence.py diff --git a/.github/scripts/issue871-evidence.py b/.github/scripts/issue871-evidence.py new file mode 100644 index 000000000000..c4f121e7c43f --- /dev/null +++ b/.github/scripts/issue871-evidence.py @@ -0,0 +1,60 @@ +"""Accept only the named diagnosis assertion as the remote behavioral RED.""" + +import json +import sys +from pathlib import Path + +PACKAGE = "github.com/Wei-Shaw/sub2api/internal/service" +ROOT = "TestExcelBPSSearchDiagnosticsThroughForward" +LEAF = ROOT + "/search_403/json" +NODES = {ROOT, LEAF} +MARKER = "issue871_expected_search_diagnosis" +ASSERTION = 'does not contain "phase=search_http; reason=http_rejected"' + + +def validate(phase, status, raw, stderr=""): + if phase not in {"RED", "GREEN"} or status != (1 if phase == "RED" else 0): + raise ValueError("unexpected phase or test exit status") + combined = (raw + stderr).lower() + for forbidden in ( + "panic:", "fatal error", "data race", "build failed", "build-fail", + "setup failed", "no tests to run", "no test files", "--- skip:", + "signal:", "test timed out", + ): + if forbidden in combined: + raise ValueError("invalid behavioral evidence: " + forbidden) + events = [json.loads(line) for line in raw.splitlines() if line.strip()] + runs = {name: 0 for name in NODES} + terminals = {name: [] for name in NODES} + packages = [] + output = "" + for event in events: + if not isinstance(event, dict) or event.get("Package") != PACKAGE: + raise ValueError("unexpected event/package") + action, test = event.get("Action"), event.get("Test") + if action not in {"start", "run", "pause", "cont", "output", "pass", "fail"}: + raise ValueError("skip/build/unknown event") + if test: + if test not in NODES: + raise ValueError("unexpected test: " + test) + if action == "run": + runs[test] += 1 + if action in {"pass", "fail"}: + terminals[test].append(action) + if action == "output" and test == LEAF: + output += event.get("Output", "") + elif action in {"pass", "fail"}: + packages.append(action) + expected = "fail" if phase == "RED" else "pass" + if runs != {name: 1 for name in NODES}: + raise ValueError("missing or repeated named test execution") + if terminals != {name: [expected] for name in NODES} or packages != [expected]: + raise ValueError("unexpected test/package terminal") + if phase == "RED" and (output.count(MARKER) != 1 or ASSERTION not in output): + raise ValueError("RED did not fail at the intended diagnosis assertion") + + +if __name__ == "__main__": + phase, status, log, stderr = sys.argv[1:] + validate(phase, int(status), Path(log).read_text(), Path(stderr).read_text()) + print(phase + " named search diagnosis evidence accepted") diff --git a/.github/scripts/test_issue871_evidence.py b/.github/scripts/test_issue871_evidence.py new file mode 100644 index 000000000000..c4cb21780e79 --- /dev/null +++ b/.github/scripts/test_issue871_evidence.py @@ -0,0 +1,54 @@ +import importlib.util +import json +import unittest +from pathlib import Path + +spec = importlib.util.spec_from_file_location("gate", Path(__file__).with_name("issue871-evidence.py")) +gate = importlib.util.module_from_spec(spec) +spec.loader.exec_module(gate) + + +def transcript(phase): + terminal = "fail" if phase == "RED" else "pass" + events = [dict(Action="start", Package=gate.PACKAGE)] + for name in (gate.ROOT, gate.LEAF): + events.append(dict(Action="run", Package=gate.PACKAGE, Test=name)) + if phase == "RED": + events.append(dict(Action="output", Package=gate.PACKAGE, Test=gate.LEAF, + Output=gate.MARKER + "\n" + gate.ASSERTION + "\n")) + for name in (gate.LEAF, gate.ROOT): + events.append(dict(Action=terminal, Package=gate.PACKAGE, Test=name)) + events.append(dict(Action=terminal, Package=gate.PACKAGE)) + return "\n".join(json.dumps(event) for event in events) + + +class Issue871EvidenceTest(unittest.TestCase): + def test_named_red_and_green(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + gate.validate(phase, code, transcript(phase)) + + def test_rejects_nonbehavioral_failure_and_missing_test(self): + red = transcript("RED") + for invalid in ( + "", red.replace(gate.MARKER, "unrelated_assertion"), + red.replace("phase=search_http; reason=http_rejected", "different assertion"), + red.replace('"Action": "run"', '"Action": "skip"', 1), + red.replace(gate.LEAF, gate.ROOT + "/wrong_case"), red + "\n" + red, + red + "\nnot JSON", red.replace(gate.PACKAGE, "other/package"), + ): + with self.subTest(invalid=invalid), self.assertRaises(ValueError): + gate.validate("RED", 1, invalid) + + def test_rejects_exit_mismatch_and_runtime_pollution(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + raw = transcript(phase) + with self.assertRaises(ValueError): + gate.validate(phase, 2, raw) + for noise in ("panic: fixture", "build failed", "setup failed", "no tests to run", + "DATA RACE", "--- SKIP: fixture", "test timed out", "fatal error"): + with self.subTest(phase=phase, noise=noise), self.assertRaises(ValueError): + gate.validate(phase, code, raw, noise) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/bps-search.yml b/.github/workflows/bps-search.yml index c12447915b43..b7a06b888691 100644 --- a/.github/workflows/bps-search.yml +++ b/.github/workflows/bps-search.yml @@ -3,33 +3,107 @@ on: pull_request: paths: - backend/internal/service/basispoints/web_search* + - backend/internal/service/basispoints/upstream_failure.go + - backend/internal/service/openai_excel_bps.go - backend/internal/service/openai_excel_bps_search* - backend/internal/service/bps_search_settings_test.go - frontend/src/components/account/ExcelBPSSearchOptions.vue - frontend/src/components/account/__tests__/ExcelBPSSearchOptions.spec.ts - frontend/src/utils/excelBPSDefaults.ts - .github/scripts/bps-search-preview.mjs + - .github/scripts/issue871-evidence.py + - .github/scripts/test_issue871_evidence.py - .github/workflows/bps-search.yml permissions: contents: read jobs: search-protocol: runs-on: ubuntu-latest - timeout-minutes: 25 + timeout-minutes: 40 + env: + PYTHONDONTWRITEBYTECODE: '1' 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: Record exact candidate and baseline source identities + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + git diff --exit-code HEAD + test -z "$(git status --porcelain)" + evidence_dir="$RUNNER_TEMP/issue871-evidence" + baseline_sha=ff1082fd51038f10dcb3a8ecb1d5a738258b0f66 + mkdir -p "$evidence_dir" + git rev-parse HEAD HEAD^{tree} HEAD^ > "$evidence_dir/candidate.txt" + git rev-parse "$baseline_sha" "$baseline_sha^{tree}" > "$evidence_dir/baseline.txt" + git ls-tree -r HEAD -- backend .github/workflows/bps-search.yml .github/scripts/issue871-evidence.py .github/scripts/test_issue871_evidence.py > "$evidence_dir/candidate-blobs.txt" + git ls-tree -r "$baseline_sha" -- backend > "$evidence_dir/baseline-blobs.txt" + cp .github/scripts/issue871-evidence.py .github/scripts/test_issue871_evidence.py "$evidence_dir/" + - name: Validate behavioral evidence gate mutations + run: python3 -m unittest discover -s .github/scripts -p 'test_issue871_evidence.py' + - name: RED isolated production baseline with candidate standalone diagnostics fixture + shell: bash + run: | + set -euo pipefail + evidence_dir="$RUNNER_TEMP/issue871-evidence" + baseline_sha=ff1082fd51038f10dcb3a8ecb1d5a738258b0f66 + fixture_path=backend/internal/service/openai_excel_bps_search_diagnostics_test.go + git worktree add --detach "$RUNNER_TEMP/issue871-red" "$baseline_sha" + test "$(git -C "$RUNNER_TEMP/issue871-red" rev-parse HEAD)" = "$baseline_sha" + git show "HEAD:$fixture_path" > "$RUNNER_TEMP/issue871-red/$fixture_path" + git rev-parse "HEAD:$fixture_path" > "$evidence_dir/fixture-blob.txt" + test "$(git hash-object "$RUNNER_TEMP/issue871-red/$fixture_path")" = "$(git rev-parse "HEAD:$fixture_path")" + cp "$RUNNER_TEMP/issue871-red/$fixture_path" "$evidence_dir/standalone-diagnostics_test.go" + git -C "$RUNNER_TEMP/issue871-red" status --short > "$evidence_dir/red-status.txt" + git -C "$RUNNER_TEMP/issue871-red" diff --exit-code HEAD + set +e + (cd "$RUNNER_TEMP/issue871-red/backend" && go test -tags=unit ./internal/service -run '^TestExcelBPSSearchDiagnosticsThroughForward$/^search_403$/^json$' -count=1 -json -timeout=5m) > "$evidence_dir/red.jsonl" 2> "$evidence_dir/red.stderr" + test_status=$? + set -e + printf '%s\n' "$test_status" > "$evidence_dir/red-exit.txt" + python3 .github/scripts/issue871-evidence.py RED "$test_status" "$evidence_dir/red.jsonl" "$evidence_dir/red.stderr" + test "$(git -C "$RUNNER_TEMP/issue871-red" rev-parse HEAD)" = "$baseline_sha" + git -C "$RUNNER_TEMP/issue871-red" diff --exit-code HEAD + - name: GREEN clean exact candidate diagnosis boundary + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} + shell: bash + run: | + set -euo pipefail + evidence_dir="$RUNNER_TEMP/issue871-evidence" + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + git diff --exit-code HEAD + test -z "$(git status --porcelain)" + set +e + (cd backend && go test -race -tags=unit ./internal/service -run '^TestExcelBPSSearchDiagnosticsThroughForward$/^search_403$/^json$' -count=1 -json -timeout=5m) > "$evidence_dir/green.jsonl" 2> "$evidence_dir/green.stderr" + test_status=$? + set -e + printf '%s\n' "$test_status" > "$evidence_dir/green-exit.txt" + python3 .github/scripts/issue871-evidence.py GREEN "$test_status" "$evidence_dir/green.jsonl" "$evidence_dir/green.stderr" + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + git diff --exit-code HEAD + test -z "$(git status --porcelain)" - working-directory: backend run: go test -race ./internal/service/basispoints -run 'Test(WebSearch|AlphaSearch|ToolChoice|CurrentEncrypted|CompactionPolicy)' -count=1 -v - working-directory: backend run: go test -race -tags=unit ./internal/service -run 'Test(ExcelBPSAccountSearch|ExcelBPSSearch|BPSSearchDefaults)' -count=1 -v -timeout=10m - working-directory: backend run: go test -tags=integration ./internal/repository -run '^TestQuality(BPSSnapshotEqualDefaultsAndManualChanges|EnableBPSRestoreAfterAccountEditorSave|BPSSearchRestorePreservesManualChanges)$' -count=1 -v -timeout=10m + - uses: actions/upload-artifact@v7 + if: always() + with: + name: issue871-behavior-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/issue871-evidence/ + retention-days: 30 search-ui: runs-on: ubuntu-latest timeout-minutes: 20 diff --git a/backend/internal/service/basispoints/WEB_SEARCH.md b/backend/internal/service/basispoints/WEB_SEARCH.md index 61631369c61a..8b1c47eb7bf7 100644 --- a/backend/internal/service/basispoints/WEB_SEARCH.md +++ b/backend/internal/service/basispoints/WEB_SEARCH.md @@ -86,6 +86,11 @@ HTTP bodies, query, credential, URL, or identity values. Normal hosted-search query/source output continues under its existing contract. Client cancellation retains cancellation handling instead of emitting a search failure. +Raw failure classification, including both tool-correction readers, always +discards claimed search diagnostics. Only the local search bridge and the +gateway parser of its normalized output retain this evidence; correction +errors that bypass ordinary stream normalization still report `unknown`. + These diagnostics address evidence loss only. The cause of the historical failure in issue #871 and real upstream search recovery remain unverified. diff --git a/backend/internal/service/basispoints/upstream_failure.go b/backend/internal/service/basispoints/upstream_failure.go index 1ee38a49f1a1..44c1edde0990 100644 --- a/backend/internal/service/basispoints/upstream_failure.go +++ b/backend/internal/service/basispoints/upstream_failure.go @@ -28,6 +28,17 @@ func (f *UpstreamFailure) Details() map[string]any { // ParseUpstreamFailure recognizes failure terminals only. Unknown identifiers // and free-form upstream messages never enter client responses or diagnostics. func ParseUpstreamFailure(raw []byte) *UpstreamFailure { + return parseUpstreamFailure(raw, false) +} + +// ParseNormalizedUpstreamFailure is for gateway consumption of bridge output, +// never raw model/correction events. Only that boundary may retain locally +// attested search diagnostics that have already passed bridge normalization. +func ParseNormalizedUpstreamFailure(raw []byte) *UpstreamFailure { + return parseUpstreamFailure(raw, true) +} + +func parseUpstreamFailure(raw []byte, searchDiagnostics bool) *UpstreamFailure { if ParseBridgeFailure(raw) != nil { return nil } @@ -35,10 +46,17 @@ func ParseUpstreamFailure(raw []byte) *UpstreamFailure { if decode(raw, &payload) != nil { return nil } - return classifyUpstreamFailure(text(payload["type"]), payload) + return classifyUpstreamFailureWithSearch(text(payload["type"]), payload, searchDiagnostics) } +// Raw upstream readers, including both correction readers, cannot attest to +// search HTTP evidence. Keep this default safe even when Details bypasses the +// ordinary bridge normalizer on an error return. func classifyUpstreamFailure(kind string, payload object) *UpstreamFailure { + return classifyUpstreamFailureWithSearch(kind, payload, false) +} + +func classifyUpstreamFailureWithSearch(kind string, payload object, searchDiagnostics bool) *UpstreamFailure { switch kind { case "error", "response.failed", "response.cancelled": default: @@ -87,7 +105,10 @@ func classifyUpstreamFailure(kind string, payload object) *UpstreamFailure { failure := &UpstreamFailure{Status: status, Code: code, Type: errorType, Message: "Excel BPS upstream failure: " + code + "; request was not replayed"} if code == "basispoints_search_failed" { - failure.Search = parseSearchFailure(detail["search_diagnostic"]) + failure.Search = NewSearchFailure("unknown", "unknown", 0) + if searchDiagnostics { + failure.Search = parseSearchFailure(detail["search_diagnostic"]) + } // The safe summary also survives compact keepalives and existing Ops // consumers that retain only the normalized message. failure.Message += "; " + failure.Search.Error() @@ -138,17 +159,7 @@ func failureIdentifierStatus(identifier string) int { // normalizeFailureEvent preserves response identity/output/usage after the // bridge has withheld tools, but replaces error details with safe identifiers. func (b *Bridge) normalizeFailureEvent(kind string, payload object) object { - if !b.searchDiagnostics && (kind == "error" || kind == "response.failed" || kind == "response.cancelled") { - // Only the local search runner can attest to a search HTTP response. - // A raw model terminal must not manufacture search status evidence. - response, _ := payload["response"].(object) - for _, value := range []any{response["error"], payload["error"], payload} { - if detail, ok := value.(object); ok { - delete(detail, "search_diagnostic") - } - } - } - failure := classifyUpstreamFailure(kind, payload) + failure := classifyUpstreamFailureWithSearch(kind, payload, b.searchDiagnostics) if failure == nil { return payload } diff --git a/backend/internal/service/basispoints/web_search_failure_test.go b/backend/internal/service/basispoints/web_search_failure_test.go index 4dbbd186d640..bf02abc84a6f 100644 --- a/backend/internal/service/basispoints/web_search_failure_test.go +++ b/backend/internal/service/basispoints/web_search_failure_test.go @@ -108,3 +108,34 @@ func TestWebSearchClosedPipeKeepsExistingExitWithoutFailureTerminal(t *testing.T require.NotContains(t, string(raw), "response.failed") require.Zero(t, continuations) } + +func TestWebSearchRepairReadersRejectForgedSearchEvidence(t *testing.T) { + for _, reader := range []struct { + name string + read func(io.Reader) (map[string]any, error) + }{ + {"ReadToolRepairResponse", ReadToolRepairResponse}, + {"readRepairResponse", readRepairResponse}, + } { + for _, kind := range []string{"response.failed", "response.cancelled", "error"} { + t.Run(reader.name+"/"+kind, func(t *testing.T) { + detail := object{"code": "basispoints_search_failed", "message": "PRIVATE_BODY", "search_diagnostic": object{ + "phase": "search_http", "reason": "http_rejected", "upstream_status": 403, + }} + payload := object{"type": kind, "response": object{"status": "failed", "output": []any{}, "error": detail}, "error": detail} + _, err := reader.read(strings.NewReader(sse(payload))) + var failure *UpstreamFailure + require.ErrorAs(t, err, &failure) + require.Equal(t, 502, failure.Status) + require.Equal(t, "basispoints_search_failed", failure.Code) + require.Equal(t, "server_error", failure.Type) + require.Equal(t, object{"phase": "unknown", "reason": "unknown"}, failure.Details()["search_diagnostic"]) + encoded, marshalErr := json.Marshal(failure.Details()) + require.NoError(t, marshalErr) + require.NotContains(t, string(encoded), "403", "raw correction cannot attest to search HTTP") + require.NotContains(t, string(encoded), "PRIVATE_BODY") + require.NotContains(t, failure.Message, "upstream_status=") + }) + } + } +} diff --git a/backend/internal/service/openai_excel_bps.go b/backend/internal/service/openai_excel_bps.go index 7872bf2c480f..5b0f37354912 100644 --- a/backend/internal/service/openai_excel_bps.go +++ b/backend/internal/service/openai_excel_bps.go @@ -915,7 +915,7 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte result.ResponseID = gjson.GetBytes(payload, "response.id").String() result.UpstreamResponseModel = gjson.GetBytes(payload, "response.model").String() result.UpstreamResponseServiceTier = normalizeObservedOpenAIServiceTier(gjson.GetBytes(payload, "response.service_tier").String()) - upstreamFailure = basispoints.ParseUpstreamFailure(payload) + upstreamFailure = basispoints.ParseNormalizedUpstreamFailure(payload) if bridgeFailure != nil { markPriorityAttemptFailure(ctx) setOpsUpstreamError(c, resp.StatusCode, "", "") diff --git a/backend/internal/service/openai_excel_bps_search_diagnostics_test.go b/backend/internal/service/openai_excel_bps_search_diagnostics_test.go index 815473fb9f00..3d3b6a0c113f 100644 --- a/backend/internal/service/openai_excel_bps_search_diagnostics_test.go +++ b/backend/internal/service/openai_excel_bps_search_diagnostics_test.go @@ -192,7 +192,7 @@ func TestExcelBPSSearchDiagnosticsThroughForward(t *testing.T) { } message := detail.Get("message").String() require.Contains(t, message, "request was not replayed") - require.Contains(t, message, "phase="+tc.phase+"; reason="+tc.reason) + require.Contains(t, message, "phase="+tc.phase+"; reason="+tc.reason, "issue871_expected_search_diagnosis") ops, ok := GetOpsStreamError(c) require.True(t, ok) require.Equal(t, 502, ops.IntendedStatus) @@ -276,3 +276,67 @@ func TestExcelBPSSearchCancellationDoesNotSendContinuation(t *testing.T) { } } } + +func TestExcelBPSSearchRepairProvenanceThroughForward(t *testing.T) { + for _, repair := range []string{"transport", "unknown_target"} { + for _, mode := range []string{"json", "sse", "compact_keepalive"} { + t.Run(repair+"/"+mode, func(t *testing.T) { + code, summary := "text(42);", "Run client tool" + if repair == "unknown_target" { + code, summary = `{"name":"missing","arguments":{}}`, "Run" + } + first := issue871HTTP(200, excelBPSRepairWire(t, "original", summary, code)) + forged := issue871HTTP(200, "data: {\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"output\":[],\"error\":{\"code\":\"basispoints_search_failed\",\"message\":\"PRIVATE_BODY\",\"search_diagnostic\":{\"phase\":\"search_http\",\"reason\":\"http_rejected\",\"upstream_status\":403}}}}\n\n") + upstream := &httpUpstreamRecorder{responses: []*http.Response{first, forged}} + svc := openAIClientToolsTestService(upstream) + account := excelAccount() + account.Extra["openai_excel_bps_auto_disable_on_403"] = true + body := []byte(fmt.Sprintf(`{"model":"gpt-5.6-sol","stream":%t,"input":"test correction","tools":[{"type":"namespace","name":"functions","tools":[{"type":"custom","name":"exec"}]}]}`, mode == "sse")) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + if mode == "compact_keepalive" { + MarkOpenAICompactClientStream(c) + stop := StartOpenAICompactSSEKeepalive(c, time.Hour) + defer stop() + value, ok := c.Get(openAICompactSSEKeepaliveKey) + require.True(t, ok) + keepalive, ok := value.(*openAICompactSSEKeepalive) + require.True(t, ok) + require.True(t, keepalive.beat()) + } + _, err := svc.Forward(c.Request.Context(), c, account, body) + require.Error(t, err) + require.Len(t, upstream.requests, 2, "one existing correction, no extra submission") + for _, request := range upstream.requests { + require.Equal(t, "/basispoints/api/responses", request.URL.Path, "no search HTTP request occurred") + } + if repair == "transport" { + require.Contains(t, string(upstream.bodies[1]), "invalid_client_tool_transport", "must exercise ReadToolRepairResponse") + } else { + require.Contains(t, string(upstream.bodies[1]), "previous response selected a tool absent", "must exercise readRepairResponse") + } + detail := issue871Error(t, rec.Body.String(), mode != "json") + require.Equal(t, "basispoints_search_failed", detail.Get("code").String()) + require.Contains(t, detail.Get("message").String(), "phase=unknown; reason=unknown") + ops, ok := GetOpsStreamError(c) + require.True(t, ok) + require.Equal(t, 502, ops.IntendedStatus) + require.Equal(t, 200, ops.UpstreamStatus) + require.Equal(t, "server_error", ops.ErrType) + require.Equal(t, "unknown", gjson.Get(ops.UpstreamDetail, "search_diagnostic.phase").String()) + require.Equal(t, "unknown", gjson.Get(ops.UpstreamDetail, "search_diagnostic.reason").String()) + require.False(t, gjson.Get(ops.UpstreamDetail, "search_diagnostic.upstream_status").Exists()) + if mode != "compact_keepalive" { + require.False(t, detail.Get("search_diagnostic.upstream_status").Exists()) + } + for _, unsafe := range []string{"403", "upstream_status", "PRIVATE_BODY", "http_rejected"} { + require.NotContains(t, detail.Raw+ops.Message+ops.UpstreamMessage+ops.UpstreamDetail, unsafe) + } + require.NotContains(t, rec.Body.String(), "response.completed") + require.True(t, account.IsExcelBPSEnabled()) + require.False(t, svc.isExcelBPSCoolingDown(account, "gpt-5.6-sol")) + }) + } + } +} From 551d0f75eee392c043dd36b574c97a2ba08d9535 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Mon, 16 Nov 2026 12:46:33 +0800 Subject: [PATCH 3/4] fix: isolate BPS repair request body ownership --- .github/workflows/bps-search.yml | 14 ++ backend/internal/service/openai_excel_bps.go | 10 +- .../openai_excel_bps_search_race_test.go | 165 ++++++++++++++++++ 3 files changed, 186 insertions(+), 3 deletions(-) create mode 100644 backend/internal/service/openai_excel_bps_search_race_test.go diff --git a/.github/workflows/bps-search.yml b/.github/workflows/bps-search.yml index b7a06b888691..d154be177e5e 100644 --- a/.github/workflows/bps-search.yml +++ b/.github/workflows/bps-search.yml @@ -92,6 +92,20 @@ jobs: test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" git diff --exit-code HEAD test -z "$(git status --porcelain)" + - name: Repeat real Forward repair ownership and provenance with race detection + working-directory: backend + shell: bash + run: | + set -euo pipefail + race_log="$RUNNER_TEMP/issue871-evidence/repair-race-repeat.log" + go test -race -tags=unit ./internal/service -run '^TestExcelBPSSearchRepair(OwnershipRaceThroughForward|ProvenanceThroughForward)$' -count=20 -v -timeout=10m 2>&1 | tee "$race_log" + for repair in transport unknown_target; do + for outcome in success failed; do + for mode in json sse compact_keepalive; do + test "$(grep -Fc -- "--- PASS: TestExcelBPSSearchRepairOwnershipRaceThroughForward/$repair/$outcome/$mode " "$race_log")" -eq 20 + done + done + done - working-directory: backend run: go test -race ./internal/service/basispoints -run 'Test(WebSearch|AlphaSearch|ToolChoice|CurrentEncrypted|CompactionPolicy)' -count=1 -v - working-directory: backend diff --git a/backend/internal/service/openai_excel_bps.go b/backend/internal/service/openai_excel_bps.go index 5b0f37354912..b26a943ead07 100644 --- a/backend/internal/service/openai_excel_bps.go +++ b/backend/internal/service/openai_excel_bps.go @@ -755,12 +755,16 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte return s.continueExcelBPSSearch(nextCtx, account, nextBody, token, accountID, proxyURL) }) } else { + // Both repair callbacks run serially on the bridge goroutine. Their + // evolving request body must not replace the caller's immutable body, + // which is still read below when constructing result metadata. + repairUpstreamBody := upstreamBody converted = bridge.StreamWithRepairs(requestCtx, resp.Body, func(repairCtx context.Context, failed map[string]any, validation error) (map[string]any, error) { if isControlledExperiment(ctx) { return nil, errors.New("controlled experiment disables BPS tool repair submissions") } markPriorityAttemptFailure(repairCtx) - correctedBody, err := basispoints.BuildToolRepairRequest(upstreamBody, failed, validation) + correctedBody, err := basispoints.BuildToolRepairRequest(repairUpstreamBody, failed, validation) if err != nil { return nil, err } @@ -803,11 +807,11 @@ func (s *OpenAIGatewayService) forwardExcelBPS(ctx context.Context, c *gin.Conte return nil, fmt.Errorf("excel BPS correction returned HTTP %d", repairResp.StatusCode) } s.UpdateCodexUsageSnapshotFromHeaders(repairCtx, account.ID, repairResp.Header) - upstreamBody = correctedBody + repairUpstreamBody = correctedBody return basispoints.ReadToolRepairResponse(repairResp.Body) }, func(repairCtx context.Context) (io.ReadCloser, error) { markPriorityAttemptFailure(repairCtx) - repairBody, err := basispoints.RepairRequest(upstreamBody) + repairBody, err := basispoints.RepairRequest(repairUpstreamBody) if err != nil { return nil, err } diff --git a/backend/internal/service/openai_excel_bps_search_race_test.go b/backend/internal/service/openai_excel_bps_search_race_test.go new file mode 100644 index 000000000000..731649199e42 --- /dev/null +++ b/backend/internal/service/openai_excel_bps_search_race_test.go @@ -0,0 +1,165 @@ +package service + +import ( + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Pause the real Forward caller immediately before result metadata is read. +// The repair HTTP call must enter before either side can proceed. Closing +// release precedes BOTH the caller read and the callback's body replacement; +// it deliberately does not order those two accesses or hide their old race. +type issue871RepairRaceContext struct { + context.Context + armed atomic.Bool + metadataGate atomic.Bool + repairEntered chan struct{} + release chan struct{} +} + +func (c *issue871RepairRaceContext) Value(key any) any { + if _, ok := key.(requestedReasoningEffortContextKey); ok && c.armed.Load() && c.metadataGate.CompareAndSwap(false, true) { + select { + case <-c.repairEntered: + case <-c.Context.Done(): + } + close(c.release) + } + return c.Context.Value(key) +} + +func TestExcelBPSSearchRepairOwnershipRaceThroughForward(t *testing.T) { + for _, repair := range []string{"transport", "unknown_target"} { + for _, outcome := range []string{"success", "failed"} { + for _, mode := range []string{"json", "sse", "compact_keepalive"} { + t.Run(repair+"/"+outcome+"/"+mode, func(t *testing.T) { + parent, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + gate := &issue871RepairRaceContext{Context: parent, repairEntered: make(chan struct{}), release: make(chan struct{})} + var calls atomic.Int64 + var requestsMu sync.Mutex + var bodies [][]byte + var paths, grants []string + firstCode := "text(42);" + if repair == "unknown_target" { + firstCode = `{"name":"missing","arguments":{}}` + } + initial := excelBPSRepairWire(t, "original", "Run client tool", firstCode) + invalid := excelBPSRepairWire(t, "invalid", "Run client tool", "text(42);") + valid := excelBPSRepairWire(t, "fixed", "codex2api.custom/functions.exec", "text(42);") + failed := "data: {\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":1},\"error\":{\"code\":\"basispoints_search_failed\",\"search_diagnostic\":{\"phase\":\"search_http\",\"reason\":\"http_rejected\",\"upstream_status\":403}}}}\n\n" + upstream := &bpsTestUpstream{send: func(req *http.Request, _ string) (*http.Response, error) { + raw, err := io.ReadAll(req.Body) + _ = req.Body.Close() + if err != nil { + return nil, err + } + requestsMu.Lock() + bodies = append(bodies, raw) + paths = append(paths, req.URL.Path) + grants = append(grants, req.Header.Get("Authorization")) + requestsMu.Unlock() + n := calls.Add(1) + if n == 1 { + gate.armed.Store(true) + return issue871HTTP(200, initial), nil + } + if n == 2 { + close(gate.repairEntered) + select { + case <-gate.release: + case <-req.Context().Done(): + return nil, req.Context().Err() + } + if outcome == "failed" { + return issue871HTTP(200, failed), nil + } + if repair == "transport" { + return issue871HTTP(200, invalid), nil + } + return issue871HTTP(200, valid), nil + } + if n == 3 && repair == "transport" && outcome == "success" { + return issue871HTTP(200, valid), nil + } + return nil, fmt.Errorf("unexpected repair/replay send %d", n) + }} + svc := openAIClientToolsTestService(nil) + svc.httpUpstream = upstream + account := excelAccount() + account.Extra["openai_excel_bps_auto_disable_on_403"] = true + body := []byte(fmt.Sprintf(`{"model":"gpt-5.6-sol","stream":%t,"input":"test correction ownership","tools":[{"type":"namespace","name":"functions","tools":[{"type":"custom","name":"exec"}]}]}`, mode == "sse")) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil).WithContext(gate) + if mode == "compact_keepalive" { + MarkOpenAICompactClientStream(c) + stop := StartOpenAICompactSSEKeepalive(c, time.Hour) + defer stop() + value, ok := c.Get(openAICompactSSEKeepaliveKey) + require.True(t, ok) + keepalive, ok := value.(*openAICompactSSEKeepalive) + require.True(t, ok) + require.True(t, keepalive.beat()) + } + result, err := svc.Forward(gate, c, account, body) + require.True(t, gate.metadataGate.Load(), "caller must reach the metadata rendezvous") + require.NoError(t, parent.Err(), "repair must enter while caller metadata is paused") + require.NotNil(t, result) + wantCalls, wantInput, wantOutput := 2, 20, 4 + if outcome == "failed" { + require.Error(t, err) + wantInput, wantOutput = 17, 3 + detail := issue871Error(t, rec.Body.String(), mode != "json") + require.Equal(t, "basispoints_search_failed", detail.Get("code").String()) + require.NotContains(t, detail.Raw, "403") + require.NotContains(t, detail.Raw, "upstream_status") + ops, ok := GetOpsStreamError(c) + require.True(t, ok) + require.Equal(t, 502, ops.IntendedStatus) + } else { + require.NoError(t, err) + require.Contains(t, rec.Body.String(), "text(42);") + if repair == "transport" { + wantCalls, wantInput, wantOutput = 3, 30, 6 + } + } + require.Equal(t, int64(wantCalls), calls.Load()) + require.Equal(t, wantInput, result.Usage.InputTokens) + require.Equal(t, wantOutput, result.Usage.OutputTokens) + requestsMu.Lock() + sentBodies := append([][]byte(nil), bodies...) + sentPaths := append([]string(nil), paths...) + sentGrants := append([]string(nil), grants...) + requestsMu.Unlock() + for i, sent := range sentBodies { + require.Equal(t, "/basispoints/api/responses", sentPaths[i], "no search or replay endpoint") + require.Equal(t, "Bearer test-token", sentGrants[i]) + require.Equal(t, "gpt-5.6-sol", gjson.GetBytes(sent, "model").String()) + if repair == "transport" { + require.Equal(t, fmt.Sprint(i+1), gjson.GetBytes(sent, "metadata.agent_iteration").String()) + } + } + if wantCalls == 3 { + require.Contains(t, string(sentBodies[2]), "call_original", "second correction must retain the first correction's request history") + require.Contains(t, string(sentBodies[2]), "call_invalid") + } + require.True(t, account.IsExcelBPSEnabled()) + require.True(t, account.Schedulable) + require.False(t, svc.isExcelBPSCoolingDown(account, "gpt-5.6-sol")) + }) + } + } + } +} From 78e339c03192d15d357c2030908c899d90887453 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Mon, 16 Nov 2026 12:56:31 +0800 Subject: [PATCH 4/4] test: use promoted context cancellation method --- backend/internal/service/openai_excel_bps_search_race_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/openai_excel_bps_search_race_test.go b/backend/internal/service/openai_excel_bps_search_race_test.go index 731649199e42..82ee88a80416 100644 --- a/backend/internal/service/openai_excel_bps_search_race_test.go +++ b/backend/internal/service/openai_excel_bps_search_race_test.go @@ -32,7 +32,7 @@ func (c *issue871RepairRaceContext) Value(key any) any { if _, ok := key.(requestedReasoningEffortContextKey); ok && c.armed.Load() && c.metadataGate.CompareAndSwap(false, true) { select { case <-c.repairEntered: - case <-c.Context.Done(): + case <-c.Done(): } close(c.release) }