From 19ad762716ca8ad3f3f5997efd306d98539a61db Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 21:20:15 +0800 Subject: [PATCH 01/26] test: reproduce live WS mixed completed-owner refusal --- .github/workflows/ws-owner-conflict.yml | 98 ++++++++ .../handler/openai_ws_owner_conflict_test.go | 221 ++++++++++++++++++ 2 files changed, 319 insertions(+) create mode 100644 .github/workflows/ws-owner-conflict.yml create mode 100644 backend/internal/handler/openai_ws_owner_conflict_test.go diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml new file mode 100644 index 000000000000..fba07f3d3b64 --- /dev/null +++ b/.github/workflows/ws-owner-conflict.yml @@ -0,0 +1,98 @@ +name: WS owner conflict behavior + +on: + pull_request: + branches: [production] + paths: + - backend/internal/handler/openai_ws_owner_conflict_test.go + - backend/internal/service/openai_ws_readable_continuation.go + - backend/internal/service/openai_ws_agent_recovery.go + - .github/workflows/ws-owner-conflict.yml + +permissions: + contents: read + +jobs: + behavior: + runs-on: macos-15-intel + timeout-minutes: 45 + env: + CANDIDATE: ${{ github.event.pull_request.head.sha }} + BASELINE: 0e8e97aa23afd8e88a61ea64a84a8fb84f1bfdc6 + 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 + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' + run: | + if ! command -v redis-server >/dev/null; then brew install redis; fi + - name: Real handler RED against exact production blobs + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + mkdir -p "$RUNNER_TEMP/ws-owner-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/ws-owner-evidence/candidate.txt" + git worktree add --detach "$RUNNER_TEMP/ws-owner-red" "$CANDIDATE" + git diff --name-only "$BASELINE" "$CANDIDATE" -- backend | while IFS= read -r target; do + case "$target" in + *_test.go) continue ;; + *.go) + if git cat-file -e "$BASELINE:$target" 2>/dev/null; then + git show "$BASELINE:$target" > "$RUNNER_TEMP/ws-owner-red/$target" + test "$(git hash-object "$RUNNER_TEMP/ws-owner-red/$target")" = "$(git rev-parse "$BASELINE:$target")" + printf '%s %s\n' "$(git rev-parse "$BASELINE:$target")" "$target" >> "$RUNNER_TEMP/ws-owner-evidence/baseline-blobs.txt" + else + rm -- "$RUNNER_TEMP/ws-owner-red/$target" + fi ;; + esac + done + set +e + (cd "$RUNNER_TEMP/ws-owner-red/backend" && go test -p=2 -tags=unit ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$/turn_2$' -count=1 -json -timeout=2m) > "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" + test "$status" -eq 1 + python3 - "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" <<'PY' + import json, sys + rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] + leaf = 'TestOpenAIWSMixedOwnerContinuation/turn_2' + assert any(r.get('Action') == 'fail' and r.get('Test') == leaf for r in rows), 'missing actual handler failure' + outputs = ''.join(r.get('Output', '') for r in rows) + assert 'MIXED_COMPLETED_OWNER_NOT_RESUMED' in outputs, 'not the intended behavior RED' + assert 'encrypted_agent_recovery_owner_conflict' in outputs, 'missing actual refusal code' + assert not any(r.get('Action') == 'skip' for r in rows), 'skipped coverage' + assert 'panic:' not in outputs and '[build failed]' not in outputs, 'setup failure is not RED' + PY + - name: Candidate GREEN after production repair + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git diff --exit-code + if git diff --quiet "$BASELINE" "$CANDIDATE" -- backend/internal/service; then + echo 'Production repair not yet present; GREEN NOT EXECUTED (initial RED draft).' + exit 0 + fi + (cd backend && go test -race -p=2 -tags=unit ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" 2>&1 + cat "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" + python3 - "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" <<'PY' + import json, sys + rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] + for turn in (2, 53): + assert any(r.get('Action') == 'pass' and r.get('Test') == f'TestOpenAIWSMixedOwnerContinuation/turn_{turn}' for r in rows) + assert not any(r.get('Action') in ('skip', 'fail') for r in rows) + PY + - uses: actions/upload-artifact@v7 + if: always() + with: + name: ws-owner-conflict-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/ws-owner-evidence diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go new file mode 100644 index 000000000000..b933f3c119b2 --- /dev/null +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -0,0 +1,221 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Actual authenticated ingress and native forwarders, with only the provider +// and account repository replaced. Both owners are earned by delivered output. +func TestOpenAIWSMixedOwnerContinuation(t *testing.T) { + for _, turn := range []int{2, 53} { + t.Run(fmt.Sprintf("turn_%d", turn), func(t *testing.T) { + runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, turn) + }) + } +} + +func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { + t.Helper() + clients := issue805Redis(t) + probe := clients() + var mu sync.Mutex + var frames [][]byte + var identities []string + response := func(r *http.Request, body []byte) []byte { + mu.Lock() + defer mu.Unlock() + frames = append(frames, append([]byte(nil), body...)) + identities = append(identities, r.Header.Get("Authorization")) + n := len(frames) + output := []json.RawMessage{json.RawMessage(httpRebuildMessage("assistant", "fixture warm complete"))} + switch { + case n == 1: + output = []json.RawMessage{json.RawMessage(httpRebuildAgentA), json.RawMessage(httpRebuildCall("apply_patch", "call_mixed_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))} + case n == 2: + output = []json.RawMessage{json.RawMessage(httpRebuildAgentB)} + case n == turn+1: + output = []json.RawMessage{json.RawMessage(httpRebuildCall("run_tests", "call_mixed_verify", map[string]any{"path": "sum.go"}))} + case n == turn+2: + output = []json.RawMessage{json.RawMessage(httpRebuildMessage("assistant", "fixture mixed task complete"))} + } + return []byte(httpRebuildJSON(map[string]any{"type": "response.completed", "response": map[string]any{ + "id": fmt.Sprintf("resp_mixed_%d", n), "status": "completed", "model": "gpt-5.1", "output": output, + "usage": map[string]int{"input_tokens": 5, "output_tokens": 3}, + }})) + } + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", response(r, body)) + return + } + conn, err := coderws.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer conn.CloseNow() //nolint:errcheck // Isolated fixture cleanup. + for { + _, body, err := conn.Read(r.Context()) + if err != nil || conn.Write(r.Context(), coderws.MessageText, response(r, body)) != nil { + return + } + } + })) + defer provider.Close() + headers := http.Header{"Authorization": {"Bearer sk-handler-cyber-test"}, "Session_id": {"fixture-mixed-session"}, "Thread-Id": {"fixture-mixed-thread"}} + var accounts *readableWSAccounts + h := newOpenAIWSPassthroughHandlerHarnessWithAuth(t, provider.URL, headers, + map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}, + repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, nil, + func(key *service.APIKey, cfg *config.Config) *service.APIKeyService { + key.Status = service.StatusActive + key.User.Concurrency = 1 + key.Group = &service.Group{ID: *key.GroupID, Platform: service.PlatformOpenAI, Status: service.StatusActive, Hydrated: true} + return service.NewAPIKeyService(&wsRevalidationKeyRepoStub{current: key}, nil, nil, nil, nil, nil, cfg) + }, func(a *service.Account, cfg *config.Config, _ *service.HTTPUpstream, repo *service.AccountRepository) { + a.ID, a.Priority = 1, 0 + a.Credentials["api_key"] = "fixture-mixed-A" + a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode + a.Extra["codex_fingerprint_mode"] = "off" + cfg.Gateway.MaxAccountSwitches = 2 + cfg.Gateway.Scheduling.OpenAITurnAdmissionCacheTTLSeconds = 0 + cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 15 + other := *a + other.ID, other.Priority = 2, 1 + other.Credentials = map[string]any{"api_key": "fixture-mixed-B", "base_url": provider.URL} + accounts = &readableWSAccounts{issue600SwitchRepo: &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, other}}}} + *repo = accounts + }) + defer func() { _ = h.clientConn.CloseNow() }() + create := func(input []string, previous string) string { + body := map[string]any{"type": "response.create", "model": "gpt-5.1", "store": true, + "tools": httpRebuildToolDefinitions(), "input": json.RawMessage("[" + strings.Join(input, ",") + "]"), + "client_metadata": map[string]string{"thread_id": "fixture-mixed-thread"}} + if previous != "" { + body["previous_response_id"] = previous + } + return httpRebuildJSON(body) + } + read := func() ([]byte, error) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + var refusal []byte + for { + _, raw, err := h.clientConn.Read(ctx) + if err != nil { + if refusal != nil { + return refusal, err // Drain the close handshake after an error event. + } + return raw, err + } + switch gjson.GetBytes(raw, "type").String() { + case "error": + refusal = raw + case "response.completed", "response.failed": + return raw, nil + } + } + } + history := []string{httpRebuildMessage("user", httpRebuildTask)} + issue715WSSend(t, h.clientConn, create(history, "")) + first := gjson.GetBytes(issue715WSRead(t, h.clientConn), "response") + require.Equal(t, "completed", first.Get("status").String()) + tools := &httpRebuildTools{} + for _, item := range first.Get("output").Array() { + history = append(history, item.Raw) + } + history = append(history, tools.execute(t, first)...) + issue600Finish(t, h, headers) + accounts.disable(1) + 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 + var previous string + for warm := 1; warm < turn; warm++ { + issue715WSSend(t, h.clientConn, create([]string{httpRebuildMessage("user", "fixture warm")}, "")) + raw, readErr := read() + require.NoError(t, readErr) + completed := gjson.GetBytes(raw, "response") + require.Equal(t, "completed", completed.Get("status").String()) + previous = completed.Get("id").String() + if warm == 1 { + history = append(history, completed.Get("output.0").Raw) + } + } + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 2 { + return false + } + for _, raw := range owners { + if !gjson.Parse(raw).IsArray() { + return false + } + } + return true + }, 3*time.Second, 5*time.Millisecond) + owners := issue805Owners(t, probe) + issue715WSSend(t, h.clientConn, create(history, previous)) + resumed, resumeErr := read() + mu.Lock() + sends := len(frames) + mu.Unlock() + require.Equal(t, turn+1, sends, "MIXED_COMPLETED_OWNER_NOT_RESUMED: completed mixed owners must reach B exactly once; code=%s close=%v", gjson.GetBytes(resumed, "error.code").String(), resumeErr) + require.NoError(t, resumeErr) + require.Equal(t, "completed", gjson.GetBytes(resumed, "response.status").String()) + second := gjson.GetBytes(resumed, "response") + for _, item := range second.Get("output").Array() { + history = append(history, item.Raw) + } + history = append(history, tools.execute(t, second)...) + issue715WSSend(t, h.clientConn, create(history, second.Get("id").String())) + final, err := read() + require.NoError(t, err) + require.Contains(t, string(final), "fixture mixed task complete") + require.Equal(t, 1, tools.patches) + require.Equal(t, 1, tools.verifications) + issue600Finish(t, h, headers) + mu.Lock() + defer mu.Unlock() + require.Len(t, frames, turn+2, "no extra generation or retry") + for i, wire := range frames[turn:] { + require.Equal(t, "Bearer fixture-mixed-B", identities[turn+i]) + require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") + require.Contains(t, string(wire), httpRebuildTask) + require.Equal(t, 1, strings.Count(string(wire), httpRebuildPatch)) + require.NotContains(t, string(wire), "fixture-opaque-A") + require.NotContains(t, string(wire), "fixture-readable-B") + require.False(t, gjson.GetBytes(wire, "previous_response_id").Exists()) + for _, item := range gjson.GetBytes(wire, "input").Array() { + require.NotContains(t, item.Get("type").String(), "call", "completed tools must be inert readable history") + } + } + require.Equal(t, 1, strings.Count(string(frames[turn+1]), httpRebuildCheck)) + require.Equal(t, owners, issue805Owners(t, probe), "historical owner records remain unchanged") +} From 5c23196d34073cadbd7883dbeb49ac99a7e880d3 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 21:31:58 +0800 Subject: [PATCH 02/26] fix: rebuild proven unsent WS mixed-owner turns without old tool calls --- .../test_ws_owner_conflict_evidence.py | 50 ++++++ .github/scripts/ws-owner-conflict-evidence.py | 54 +++++++ .github/workflows/ws-owner-conflict.yml | 41 ++--- .../handler/openai_409_ws_oracle_test.go | 37 ++++- .../handler/openai_ws_owner_conflict_test.go | 145 ++++++++++++++++-- .../service/openai_409_omit_history.go | 13 ++ .../service/openai_agent_message_recovery.go | 36 +++++ .../service/openai_ws_agent_recovery.go | 2 +- .../openai_ws_readable_continuation.go | 56 ++++++- 9 files changed, 390 insertions(+), 44 deletions(-) create mode 100644 .github/scripts/test_ws_owner_conflict_evidence.py create mode 100644 .github/scripts/ws-owner-conflict-evidence.py diff --git a/.github/scripts/test_ws_owner_conflict_evidence.py b/.github/scripts/test_ws_owner_conflict_evidence.py new file mode 100644 index 000000000000..7cd325dc386d --- /dev/null +++ b/.github/scripts/test_ws_owner_conflict_evidence.py @@ -0,0 +1,50 @@ +import importlib.util +import json +import unittest +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location("evidence", Path(__file__).with_name("ws-owner-conflict-evidence.py")) +EVIDENCE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(EVIDENCE) + + +def fixture(suite): + leaves = EVIDENCE.SUITES[suite] + tests = leaves | {"/".join(leaf.split("/")[:i]) for leaf in leaves for i in range(1, len(leaf.split("/")))} + outcome = "fail" if suite == "red" else "pass" + rows = [{"Package": EVIDENCE.PACKAGE, "Test": name, "Action": action} for name in sorted(tests) for action in ("run", outcome)] + rows.append({"Package": EVIDENCE.PACKAGE, "Action": outcome}) + if suite == "red": + rows.append({"Package": EVIDENCE.PACKAGE, "Test": next(iter(leaves)), "Action": "output", + "Output": "MIXED_COMPLETED_OWNER_NOT_RESUMED code=encrypted_agent_recovery_owner_conflict"}) + return rows + + +class EvidenceTests(unittest.TestCase): + def test_complete_inventories(self): + for suite in EVIDENCE.SUITES: + EVIDENCE.validate(suite, 1 if suite == "red" else 0, "\n".join(map(json.dumps, fixture(suite)))) + + def test_false_red_rejected(self): + for mutation in ("compile", "skip", "panic", "race", "unrelated", "wrong_marker", "duplicate", "missing"): + with self.subTest(mutation=mutation): + rows = fixture("red") + if mutation == "compile": rows = [] + if mutation == "skip": rows[1]["Action"] = "skip" + if mutation in ("panic", "race"): rows[-1]["Output"] += " panic: fixture" if mutation == "panic" else " WARNING: DATA RACE" + if mutation == "unrelated": rows[-1]["Test"] = "OtherTest" + if mutation == "wrong_marker": rows[-1]["Output"] = "unexpected EOF" + if mutation == "duplicate": rows.append(rows[0]) + if mutation == "missing": rows.pop(0) + with self.assertRaises(ValueError): + EVIDENCE.validate("red", 1, "\n".join(map(json.dumps, rows))) + + def test_partial_green_rejected(self): + rows = fixture("transports") + rows = [r for r in rows if r.get("Test") != "TestOpenAIWSMixedOwnerTransports/ctx_pool/fresh"] + with self.assertRaises(ValueError): + EVIDENCE.validate("transports", 0, "\n".join(map(json.dumps, rows))) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/ws-owner-conflict-evidence.py b/.github/scripts/ws-owner-conflict-evidence.py new file mode 100644 index 000000000000..ba83ce663d03 --- /dev/null +++ b/.github/scripts/ws-owner-conflict-evidence.py @@ -0,0 +1,54 @@ +"""Require named network behavior; compiler/setup failures are never RED.""" + +import importlib.util +import json +import sys +from collections import Counter +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location("readable_common", Path(__file__).with_name("assert-readable-continuation.py")) +COMMON = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(COMMON) +PACKAGE = "github.com/Wei-Shaw/sub2api/internal/handler" +ROOT = "TestOpenAIWSMixedOwnerContinuation" +MODES = ("http_bridge", "ctx_pool", "shared", "dedicated", "passthrough") +BOUNDARIES = {f"{state}_{order}" for state in ("pending", "failed", "conflicted") for order in ("first", "last")} | { + "unknown", "unpaired_call", "unpaired_output", "duplicate_call", "duplicate_output", "incomplete", "off", "no_intent", +} +SUITES = { + "red": {f"{ROOT}/turn_2"}, + "continuation": {f"{ROOT}/turn_{turn}" for turn in (2, 53)}, + "boundaries": {f"TestOpenAIWSMixedOwnerBoundaries/{name}" for name in BOUNDARIES}, + "transports": {f"TestOpenAIWSMixedOwnerTransports/{mode}/{case}" for mode in MODES for case in ("live", "fresh", "binding_changed")}, +} + + +def validate(suite, status, raw): + COMMON.check_clean(raw) + leaves = SUITES[suite] + expected = "fail" if suite == "red" else "pass" + if status != (1 if suite == "red" else 0): + raise ValueError("unexpected process exit") + rows = [json.loads(line) for line in raw.splitlines() if line.startswith("{")] + ancestors = {"/".join(leaf.split("/")[:i]) for leaf in leaves for i in range(1, len(leaf.split("/")))} + tests = leaves | ancestors + counts = Counter((r.get("Action"), r.get("Test")) for r in rows if r.get("Package") == PACKAGE) + for name in tests: + if counts["run", name] != 1 or counts[expected, name] != 1 or counts["pass", name] + counts["fail", name] != 1: + raise ValueError(f"missing/duplicate/wrong named result: {name}") + if counts[expected, None] != 1 or counts["pass", None] + counts["fail", None] != 1: + raise ValueError("missing package completion") + for row in rows: + if row.get("Action") in ("run", "pass", "fail") and (row.get("Package") != PACKAGE or row.get("Test") not in tests | {None}): + raise ValueError("unrelated execution cannot satisfy evidence") + if suite == "red": + own = "".join(r.get("Output", "") for r in rows if r.get("Package") == PACKAGE and r.get("Test") in leaves) + for marker in ("MIXED_COMPLETED_OWNER_NOT_RESUMED", "encrypted_agent_recovery_owner_conflict"): + if marker not in own: + raise ValueError("missing own actual handler refusal") + + +if __name__ == "__main__": + suite, status, filename = sys.argv[1:] + validate(suite, int(status), Path(filename).read_text()) + print(f"Verified {suite}: {len(SUITES[suite])} named handler scenarios") diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index fba07f3d3b64..dbd138c16500 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -8,6 +8,8 @@ on: - backend/internal/service/openai_ws_readable_continuation.go - backend/internal/service/openai_ws_agent_recovery.go - .github/workflows/ws-owner-conflict.yml + - .github/scripts/ws-owner-conflict-evidence.py + - .github/scripts/test_ws_owner_conflict_evidence.py permissions: contents: read @@ -61,36 +63,27 @@ jobs: set -e cat "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" test "$status" -eq 1 - python3 - "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" <<'PY' - import json, sys - rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] - leaf = 'TestOpenAIWSMixedOwnerContinuation/turn_2' - assert any(r.get('Action') == 'fail' and r.get('Test') == leaf for r in rows), 'missing actual handler failure' - outputs = ''.join(r.get('Output', '') for r in rows) - assert 'MIXED_COMPLETED_OWNER_NOT_RESUMED' in outputs, 'not the intended behavior RED' - assert 'encrypted_agent_recovery_owner_conflict' in outputs, 'missing actual refusal code' - assert not any(r.get('Action') == 'skip' for r in rows), 'skipped coverage' - assert 'panic:' not in outputs and '[build failed]' not in outputs, 'setup failure is not RED' - PY + python3 .github/scripts/ws-owner-conflict-evidence.py red "$status" "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" - name: Candidate GREEN after production repair shell: bash run: | set -euo pipefail test "$(git rev-parse HEAD)" = "$CANDIDATE" git diff --exit-code - if git diff --quiet "$BASELINE" "$CANDIDATE" -- backend/internal/service; then - echo 'Production repair not yet present; GREEN NOT EXECUTED (initial RED draft).' - exit 0 - fi - (cd backend && go test -race -p=2 -tags=unit ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" 2>&1 - cat "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" - python3 - "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" <<'PY' - import json, sys - rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] - for turn in (2, 53): - assert any(r.get('Action') == 'pass' and r.get('Test') == f'TestOpenAIWSMixedOwnerContinuation/turn_{turn}' for r in rows) - assert not any(r.get('Action') in ('skip', 'fail') for r in rows) - PY + python3 -m unittest discover -s .github/scripts -p 'test_ws_owner_conflict_evidence.py' + for suite in continuation boundaries transports; do + case "$suite" in + continuation) test_name=TestOpenAIWSMixedOwnerContinuation ;; + boundaries) test_name=TestOpenAIWSMixedOwnerBoundaries ;; + transports) test_name=TestOpenAIWSMixedOwnerTransports ;; + esac + set +e + (cd backend && go test -race -p=2 -tags=unit ./internal/handler -run "^${test_name}$" -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/green-$suite.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/ws-owner-evidence/green-$suite.jsonl" + python3 .github/scripts/ws-owner-conflict-evidence.py "$suite" "$status" "$RUNNER_TEMP/ws-owner-evidence/green-$suite.jsonl" + done - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index b6de9cf11223..845f14c0fc31 100644 --- a/backend/internal/handler/openai_409_ws_oracle_test.go +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -81,14 +81,14 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt } validTools := httpRebuildToolsAvailable(body) if customTools { - validTools = readableWSCustomToolsAvailable(body) + validTools = readableWSCustomToolsAvailable(body, logicalTurn == 3) } if u.scenario == "native_namespace" { validTools = true // exact native declarations/schema checked above, including A } valid := r.Header.Get("Authorization") == "Bearer fixture-readable-ws-B" && strings.Contains(string(body), httpRebuildTask) && validTools && - httpRebuildToolPair(body, "apply_patch", httpRebuildPatch) && + readableWSCompletedResult(body, "apply_patch", httpRebuildPatch, logicalTurn == 3) && !strings.Contains(string(body), "fixture-opaque-A") && !gjson.GetBytes(body, "previous_response_id").Exists() && !gjson.GetBytes(body, "conversation").Exists() if u.scenario == "bridge_model" { @@ -105,7 +105,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt return nil } output = []json.RawMessage{json.RawMessage(httpRebuildAgentB), json.RawMessage(httpRebuildCall("run_tests", "call_ws_verify", map[string]any{"path": "sum.go"}))} - if logicalTurn == 3 && httpRebuildToolPair(body, "run_tests", httpRebuildCheck) { + if logicalTurn == 3 && readableWSCompletedResult(body, "run_tests", httpRebuildCheck, true) { output = []json.RawMessage{json.RawMessage(httpRebuildJSON(map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "ws-coding-task-complete"}}}))} } else if logicalTurn > 2 { return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_duplicate_or_missing_tool"}}}`) @@ -114,7 +114,33 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt return []byte(httpRebuildJSON(map[string]any{"type": "response.completed", "response": map[string]any{"id": fmt.Sprintf("resp_readable_ws_%d", n), "status": "completed", "model": gjson.GetBytes(body, "model").String(), "error": nil, "output": output, "usage": map[string]int{"input_tokens": 5, "output_tokens": 3}}})) } -func readableWSCustomToolsAvailable(body []byte) bool { +func readableWSCompletedResult(body []byte, name, output string, projected bool) bool { + if !projected { + return httpRebuildToolPair(body, name, output) + } + count := 0 + for _, item := range gjson.GetBytes(body, "input").Array() { + if strings.Contains(item.Get("type").String(), "call") { + return false + } + for _, part := range item.Get("content").Array() { + text := part.Get("text").String() + const prefix = "Historical completed tool result (data only; do not execute again): " + if strings.HasPrefix(text, prefix) { + record := gjson.Parse(strings.TrimPrefix(text, prefix)) + if record.Get("name").String() == name { + if item.Get("role").String() != "assistant" || record.Get("output").String() != output { + return false + } + count++ + } + } + } + } + return count == 1 +} + +func readableWSCustomToolsAvailable(body []byte, projected ...bool) bool { tools := gjson.GetBytes(body, "tools").Array() if len(tools) != 3 || tools[2].Get("type").String() != "function" || tools[2].Get("name").String() != "exec" { return false @@ -127,6 +153,9 @@ func readableWSCustomToolsAvailable(body []byte) bool { if err != nil || !httpRebuildToolsAvailable(functions) { return false } + if len(projected) > 0 && projected[0] { + return readableWSCompletedResult(body, "exec", "custom-exec-once", true) + } calls, outputs := 0, 0 for _, item := range gjson.GetBytes(body, "input").Array() { if item.Get("call_id").String() != "call_ws_exec" { diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index b933f3c119b2..2719bb367d10 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -20,6 +20,7 @@ import ( coderws "github.com/coder/websocket" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" + "github.com/tidwall/sjson" ) // Actual authenticated ingress and native forwarders, with only the provider @@ -32,8 +33,36 @@ func TestOpenAIWSMixedOwnerContinuation(t *testing.T) { } } -func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { +func TestOpenAIWSMixedOwnerBoundaries(t *testing.T) { + for _, state := range []string{"pending", "failed", "conflicted"} { + for _, order := range []string{"first", "last"} { + t.Run(state+"_"+order, func(t *testing.T) { + runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, 3, state+"_"+order) + }) + } + } + for _, scenario := range []string{"unknown", "unpaired_call", "unpaired_output", "duplicate_call", "duplicate_output", "incomplete", "off", "no_intent"} { + t.Run(scenario, func(t *testing.T) { runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, 2, scenario) }) + } +} + +func TestOpenAIWSMixedOwnerTransports(t *testing.T) { + for _, mode := range readableWSModes { + for _, scenario := range []string{"live", "fresh", "binding_changed"} { + t.Run(mode+"/"+scenario, func(t *testing.T) { runWSMixedOwnerContinuation(t, mode, 2, scenario) }) + } + } +} + +func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios ...string) { t.Helper() + scenario := "live" + if len(scenarios) > 0 { + scenario = scenarios[0] + } + negative := scenario != "live" && scenario != "fresh" && scenario != "binding_changed" + oldFence := strings.HasSuffix(scenario, "_first") || strings.HasSuffix(scenario, "_last") + thirdItem := strings.ReplaceAll(httpRebuildAgentB, "fixture-readable-B", "fixture-old-completed-C") clients := issue805Redis(t) probe := clients() var mu sync.Mutex @@ -51,6 +80,8 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { output = []json.RawMessage{json.RawMessage(httpRebuildAgentA), json.RawMessage(httpRebuildCall("apply_patch", "call_mixed_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))} case n == 2: output = []json.RawMessage{json.RawMessage(httpRebuildAgentB)} + case n == 3 && oldFence: + output = []json.RawMessage{json.RawMessage(thirdItem)} case n == turn+1: output = []json.RawMessage{json.RawMessage(httpRebuildCall("run_tests", "call_mixed_verify", map[string]any{"path": "sum.go"}))} case n == turn+2: @@ -89,7 +120,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { headers := http.Header{"Authorization": {"Bearer sk-handler-cyber-test"}, "Session_id": {"fixture-mixed-session"}, "Thread-Id": {"fixture-mixed-thread"}} var accounts *readableWSAccounts h := newOpenAIWSPassthroughHandlerHarnessWithAuth(t, provider.URL, headers, - map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}, + map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: fmt.Sprint(scenario != "off")}, repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, nil, func(key *service.APIKey, cfg *config.Config) *service.APIKeyService { key.Status = service.StatusActive @@ -111,6 +142,19 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { *repo = accounts }) defer func() { _ = h.clientConn.CloseNow() }() + // Long-lived sessions also exercise usage recording without filling the + // shared harness's deliberately small observer buffer. + stopUsage := make(chan struct{}) + defer close(stopUsage) + go func() { + for { + select { + case <-stopUsage: + return + case <-h.usageLogs: + } + } + }() create := func(input []string, previous string) string { body := map[string]any{"type": "response.create", "model": "gpt-5.1", "store": true, "tools": httpRebuildToolDefinitions(), "input": json.RawMessage("[" + strings.Join(input, ",") + "]"), @@ -156,7 +200,23 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { cancel() require.NoError(t, err) h.clientConn = conn + waitOwners := func(count int) map[string]string { + deadline := time.Now().Add(5 * time.Second) + for { + owners := issue805Owners(t, probe) + completed := len(owners) == count + for _, raw := range owners { + completed = completed && json.Valid([]byte(raw)) && gjson.Parse(raw).IsArray() + } + if completed { + return owners + } + require.True(t, time.Now().Before(deadline), "actual downstream deliveries must commit before fixture mutation") + time.Sleep(5 * time.Millisecond) + } + } var previous string + var firstTwoOwners map[string]string for warm := 1; warm < turn; warm++ { issue715WSSend(t, h.clientConn, create([]string{httpRebuildMessage("user", "fixture warm")}, "")) raw, readErr := read() @@ -166,26 +226,79 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { previous = completed.Get("id").String() if warm == 1 { history = append(history, completed.Get("output.0").Raw) + firstTwoOwners = waitOwners(2) } } - require.Eventually(t, func() bool { - owners := issue805Owners(t, probe) - if len(owners) != 2 { - return false - } - for _, raw := range owners { - if !gjson.Parse(raw).IsArray() { - return false + expectedOwners := 2 + if oldFence { + expectedOwners++ + } + owners := waitOwners(expectedOwners) + if oldFence { + // Fence only C, identified by the extra actual downstream delivery. + // Both completed A/B owners remain, before/after this older fence. + for key, raw := range owners { + if _, exists := firstTwoOwners[key]; exists { + continue } + value := "conflict" + if strings.HasPrefix(scenario, "pending") { + value = "pending:fixture-old:" + raw + } + if strings.HasPrefix(scenario, "failed") { + value = "failed" + } + require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err()) } - return true - }, 3*time.Second, 5*time.Millisecond) - owners := issue805Owners(t, probe) + history = append(history, thirdItem) + if strings.HasSuffix(scenario, "_first") { + history = append([]string{thirdItem}, history[:len(history)-1]...) + } + } + switch scenario { + case "unknown": + history = append(history, thirdItem) + case "unpaired_call": + history = append(history[:3], history[4:]...) + case "unpaired_output": + history = append(history[:2], history[3:]...) + case "duplicate_call": + history = append(history, history[2]) + case "duplicate_output": + history = append(history, history[3]) + case "incomplete": + history[2], err = sjson.Set(history[2], "status", "in_progress") + require.NoError(t, err) + case "no_intent": + history = history[1:] + case "binding_changed": + accounts.mu.Lock() + accounts.accounts[1].Credentials["api_key"] = "fixture-mixed-B-rotated" + accounts.mu.Unlock() + case "fresh": + issue600Finish(t, h, headers) + dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + conn, _, dialErr := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers}) + cancel() + require.NoError(t, dialErr) + h.clientConn = conn + } + owners = issue805Owners(t, probe) issue715WSSend(t, h.clientConn, create(history, previous)) resumed, resumeErr := read() mu.Lock() sends := len(frames) mu.Unlock() + if negative { + require.Equal(t, turn, sends, "unsafe history must produce zero extra generations") + require.Equal(t, "error", gjson.GetBytes(resumed, "type").String(), "a setup EOF is not a refusal") + require.Contains(t, []string{"encrypted_agent_recovery_owner_conflict", "encrypted_agent_recovery_owner_unavailable", "encrypted_agent_recovery_delivery_pending", "encrypted_agent_recovery_readable_intent_missing"}, gjson.GetBytes(resumed, "error.code").String()) + require.Equal(t, coderws.StatusPolicyViolation, coderws.CloseStatus(resumeErr)) + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + require.Equal(t, owners, issue805Owners(t, probe), "refusals cannot modify owners") + return + } require.Equal(t, turn+1, sends, "MIXED_COMPLETED_OWNER_NOT_RESUMED: completed mixed owners must reach B exactly once; code=%s close=%v", gjson.GetBytes(resumed, "error.code").String(), resumeErr) require.NoError(t, resumeErr) require.Equal(t, "completed", gjson.GetBytes(resumed, "response.status").String()) @@ -205,7 +318,11 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { defer mu.Unlock() require.Len(t, frames, turn+2, "no extra generation or retry") for i, wire := range frames[turn:] { - require.Equal(t, "Bearer fixture-mixed-B", identities[turn+i]) + expectedIdentity := "Bearer fixture-mixed-B" + if scenario == "binding_changed" { + expectedIdentity += "-rotated" + } + require.Equal(t, expectedIdentity, identities[turn+i]) require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") require.Contains(t, string(wire), httpRebuildTask) require.Equal(t, 1, strings.Count(string(wire), httpRebuildPatch)) diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index d259eced63b3..2647a6440533 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "strings" + "sync/atomic" "time" "unicode/utf8" @@ -60,6 +61,11 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c if r.conflict || (r.owner != nil && (r.owner.pending != "" || r.owner.failed || r.owner.conflicted)) { return ctx, body, false, openAIAgentRecoveryError("owner_conflict") } + _, websocket := ctx.Value(openAIWSAgentRecoveryRetryKey{}).(*atomic.Bool) + mixedWS := websocket && r.mixedOwners + if mixedWS && !r.hasCompletedMixedOwners() { + return ctx, body, false, openAIAgentRecoveryError("owner_conflict") + } if len(r.items) == 0 && !openAI409HasProviderState(body) { return ctx, body, false, nil } @@ -81,6 +87,13 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c if err != nil { return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") } + if mixedWS { + clean, err = projectOpenAIWSCompletedTools(clean) + if err != nil { + return ctx, body, false, err + } + r.requireCompletedOwners = true + } fresh := context.WithValue(ctx, openAIGuardianParentAffinityContextKey{}, openAIGuardianParentAffinity{}) next := s.WithOpenAIAgentMessageRecovery(WithOpenAIEncryptedReasoningAffinity(fresh, clean), c, clean, session, model) request := openAIAgentRecoveryFromContext(next) diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 36947164e9ce..f86d060658bc 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -87,6 +87,9 @@ type openAIAgentRecoveryRequest struct { groupID int64 model string session string + + completedOwners map[[32]byte]openAIAgentRecoveryBinding + requireCompletedOwners bool // mixed WS omission retains each original completed route } // WithOpenAIAgentMessageRecovery observes only opaque item identities. A route @@ -161,12 +164,39 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex request.known = make(map[[32]byte]bool) } request.known[key] = true + if request.completedOwners == nil { + request.completedOwners = make(map[[32]byte]openAIAgentRecoveryBinding) + } + request.completedOwners[key] = binding copy := binding request.owner = © } return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, request) } +// This proof is private to the before-write route check. A public conflict code, +// a subset of completed items or a last-item owner cannot authorize omission. +func (r *openAIAgentRecoveryRequest) hasCompletedMixedOwners() bool { + if r == nil || !r.mixedOwners || r.conflict || r.lookupErr != nil || len(r.keys) < 2 { + return false + } + for _, key := range r.keys { + binding, found := r.completedOwners[key] + if !found || !r.known[key] || binding.pending != "" || binding.failed || binding.conflicted { + return false + } + } + return true +} + +func (r *openAIAgentRecoveryRequest) completedOwnerUnchanged(key [32]byte, actual openAIAgentRecoveryBinding, found bool) bool { + if !r.requireCompletedOwners { + return true + } + expected, known := r.completedOwners[key] + return known && found && actual.pending == "" && !actual.failed && !actual.conflicted && sameOpenAIAgentRecoveryRoute(expected, actual) +} + func openAIAgentRecoveryFromContext(ctx context.Context) *openAIAgentRecoveryRequest { request, _ := ctx.Value(openAIAgentRecoveryContextKey{}).(*openAIAgentRecoveryRequest) return request @@ -504,6 +534,9 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Conte if err != nil { return openAIAgentRecoveryError("store_unavailable") } + if !request.completedOwnerUnchanged(key, old, found) { + return openAIAgentRecoveryError("owner_conflict") + } if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { return openAIAgentRecoveryError("owner_conflict") } @@ -518,6 +551,9 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Conte for _, key := range request.keys { old, exists := state.bindings[key] found := exists && time.Now().Before(old.expiresAt) + if !request.completedOwnerUnchanged(key, old, found) { + return openAIAgentRecoveryError("owner_conflict") + } if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { return openAIAgentRecoveryError("owner_conflict") } diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index e1a43bb8bfdc..eedcb83074fe 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -316,7 +316,7 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, return openAIAgentRecoveryError("wire_changed") } if err := r.service.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { - return &openAIWSOwnerRouteError{cause: err} + return &openAIWSOwnerRouteError{cause: err, completedMixedOwners: r.request.hasCompletedMixedOwners()} } if !r.request.omittedHistory && (r.request.owner != nil || r.request.disableOwnerBinding) && previous != "" { owner, err := r.service.getOpenAIWSStateStore().GetResponseAccount(ctx, r.request.groupID, previous) diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index 9e57ed6050e9..df71abbcdc7a 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -60,7 +60,10 @@ func (e *openAIWSLostOwnerEvidenceError) Unwrap() error { return e.cause } // Only the account/route compatibility check may grant this evidence. The same // public code from a later integrity or delivery fence stays terminal. -type openAIWSOwnerRouteError struct{ cause error } +type openAIWSOwnerRouteError struct { + cause error + completedMixedOwners bool +} func (e *openAIWSOwnerRouteError) Error() string { return e.cause.Error() } func (e *openAIWSOwnerRouteError) Unwrap() error { return e.cause } @@ -79,6 +82,10 @@ func openAIWSUnsentAgentTurn(err error, body []byte, model string, turn int) err return closed } switch recovery.Reason { + case "owner_conflict": + if !route.completedMixedOwners { + return closed + } case "owner_unavailable", "route_changed": // Rebuild still checks completed ownership, delivery fences, readable // intent, tool results and final payload integrity. Do not turn wire @@ -89,6 +96,53 @@ func openAIWSUnsentAgentTurn(err error, body []byte, model string, turn int) err return &openAIWSUnsentTurnError{cause: closed, body: append([]byte(nil), body...), model: model, turn: turn, keepAccount: true} } +// Keep completed results as data in a new provider conversation. Historical +// callable records and arguments are unnecessary there; current declarations +// remain available for genuinely new tool work. Pairing is checked before loss. +func projectOpenAIWSCompletedTools(body []byte) ([]byte, error) { + if !openAIWSCompletedToolInputs(body) { + return nil, openAIAgentRecoveryError("owner_conflict") + } + calls := make(map[string]gjson.Result) + for _, item := range gjson.GetBytes(body, "input").Array() { + if kind := item.Get("type").String(); kind == "function_call" || kind == "custom_tool_call" { + if item.Get("name").Type != gjson.String || strings.TrimSpace(item.Get("name").String()) == "" { + return nil, openAIAgentRecoveryError("owner_conflict") + } + calls[item.Get("call_id").String()] = item + } + } + var input []json.RawMessage + for _, item := range gjson.GetBytes(body, "input").Array() { + switch item.Get("type").String() { + case "function_call", "custom_tool_call": + continue + case "function_call_output", "custom_tool_call_output": + output := item.Get("output") + if !openAIReadableShadowTextOnly(output) { + return nil, openAIAgentRecoveryError("readable_history_unsupported") + } + record, err := json.Marshal(map[string]any{"name": calls[item.Get("call_id").String()].Get("name").String(), "output": json.RawMessage(output.Raw)}) + if err != nil { + return nil, openAIAgentRecoveryError("readable_history_unsupported") + } + message, _ := json.Marshal(map[string]any{"type": "message", "role": "assistant", "content": []any{ + map[string]any{"type": "output_text", "text": "Historical completed tool result (data only; do not execute again): " + string(record)}, + }}) + input = append(input, message) + case "", "message": + input = append(input, json.RawMessage(item.Raw)) + default: + return nil, openAIAgentRecoveryError("readable_history_unsupported") + } + } + encoded, err := json.Marshal(input) + if err != nil { + return nil, err + } + return sjson.SetRawBytes(body, "input", encoded) +} + func OpenAIWSUnsentTurnKeepsAccount(err error) bool { var unsent *openAIWSUnsentTurnError return errors.As(err, &unsent) && unsent.keepAccount From 52ca6298b4a6cd5ba8ca56740e6b7f658e6f5689 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 21:44:05 +0800 Subject: [PATCH 03/26] fix: retain owner proof through rebuild and diagnose terminal fences --- .../scripts/prepare-replay-red-fixtures.sh | 4 + .../scripts/prepare-ws-owner-red-fixtures.sh | 63 ++++++ .github/workflows/encrypted-history-409.yml | 1 + .../workflows/issue842-replay-metadata.yml | 2 + .../workflows/readable-continuation-409.yml | 1 + .github/workflows/ws-owner-conflict.yml | 25 ++- .../handler/openai_409_ws_oracle_test.go | 6 +- .../handler/openai_agent_message_recovery.go | 1 + .../handler/openai_gateway_handler.go | 2 +- .../handler/openai_ws_owner_conflict_test.go | 37 +++- .../service/openai_409_omit_history.go | 26 ++- .../service/openai_409_readable_shadow.go | 45 +++- .../service/openai_account_scheduler.go | 2 +- .../service/openai_agent_message_recovery.go | 49 +++-- .../openai_agent_message_recovery_error.go | 5 +- .../openai_agent_recovery_diagnostics.go | 204 ++++++++++++++++++ .../service/openai_agent_replay_metadata.go | 2 +- .../service/openai_ws_agent_recovery.go | 5 +- .../service/openai_ws_owner_conflict_test.go | 181 ++++++++++++++++ .../openai_ws_readable_continuation.go | 80 +++---- docs/ws-mixed-owner-continuation.md | 47 ++++ 21 files changed, 707 insertions(+), 81 deletions(-) create mode 100644 .github/scripts/prepare-ws-owner-red-fixtures.sh create mode 100644 backend/internal/service/openai_agent_recovery_diagnostics.go create mode 100644 backend/internal/service/openai_ws_owner_conflict_test.go create mode 100644 docs/ws-mixed-owner-continuation.md diff --git a/.github/scripts/prepare-replay-red-fixtures.sh b/.github/scripts/prepare-replay-red-fixtures.sh index b3373ac01d3d..f5ce3a18a2fb 100644 --- a/.github/scripts/prepare-replay-red-fixtures.sh +++ b/.github/scripts/prepare-replay-red-fixtures.sh @@ -55,3 +55,7 @@ if ! git -C "$tree" grep -q 'func (a \*Account) IsExcelBPSSearchEnabled' "$basel fi exclude_absent_fixture backend/internal/service/openai_excel_bps_search_test.go "$contract" fi + +# Later mixed-owner proofs/diagnostics share the restored recovery struct. +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +bash "$script_dir/prepare-ws-owner-red-fixtures.sh" "$baseline" "$tree" "$candidate" diff --git a/.github/scripts/prepare-ws-owner-red-fixtures.sh b/.github/scripts/prepare-ws-owner-red-fixtures.sh new file mode 100644 index 000000000000..5cec43f9aef6 --- /dev/null +++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh @@ -0,0 +1,63 @@ +#!/usr/bin/env bash +# Restore the coherent pre-mixed-owner API only in an existing historical RED +# overlay. Selected historical defect blobs and assertions remain untouched. +set -euo pipefail +baseline="$1" +tree="${2:-.}" +candidate="${3:-HEAD}" +contract=backend/internal/service/openai_agent_message_recovery.go +if grep -q 'requireCompletedOwners' "$tree/$contract"; then + exit 0 # Candidate GREEN or a baseline that already supports this contract. +fi + +for target in \ + backend/internal/service/openai_409_omit_history.go \ + backend/internal/service/openai_ws_readable_continuation.go \ + backend/internal/service/openai_409_readable_shadow.go \ + backend/internal/service/openai_agent_message_recovery_error.go \ + backend/internal/service/openai_agent_recovery_diagnostics.go \ + backend/internal/service/openai_agent_replay_metadata.go \ + backend/internal/service/openai_account_scheduler.go \ + backend/internal/service/openai_ws_agent_recovery.go \ + backend/internal/handler/openai_agent_message_recovery.go \ + backend/internal/handler/openai_gateway_handler.go; do + test -f "$tree/$target" || continue + # Do not replace a selected defect blob or an already verified compatibility + # blob. Only untouched candidate callers can contain this later dependency. + expected=$(git -C "$tree" rev-parse "$candidate:$target") + actual=$(git -C "$tree" hash-object "$target") + test "$actual" = "$expected" || continue + if git -C "$tree" cat-file -e "$baseline:$target" 2>/dev/null; then + git -C "$tree" show "$baseline:$target" > "$tree/$target" + restored=$(git -C "$tree" hash-object "$target") + test "$restored" = "$(git -C "$tree" rev-parse "$baseline:$target")" + printf 'ws-owner caller baseline=%s path=%s candidate=%s restored=%s\n' "$baseline" "$target" "$expected" "$restored" + else + rm -- "$tree/$target" + printf 'ws-owner caller baseline=%s path=%s candidate=%s restored=absent\n' "$baseline" "$target" "$expected" + fi +done + +exclude_new_fixture() { + local target="$1" + test -f "$tree/$target" || return 0 + if git -C "$tree" cat-file -e "$baseline:$target" 2>/dev/null; then + printf 'refusing to remove baseline fixture %s\n' "$target" >&2 + exit 1 + fi + local expected actual + expected=$(git -C "$tree" rev-parse "$candidate:$target") + actual=$(git -C "$tree" hash-object "$target") + test "$actual" = "$expected" + rm -- "$tree/$target" + printf 'unrelated ws-owner fixture baseline=%s path=%s candidate=%s actual=absent\n' "$baseline" "$target" "$expected" +} + +# New service tests require new private proof/diagnostic types. Their own RED +# uses handler tests; every candidate GREEN retains them and all negative cases. +exclude_new_fixture backend/internal/service/openai_ws_owner_conflict_test.go +# Very old Issue805 baselines intentionally exclude the later readable harness. +# Only that dependency absence permits removing its new consumer as well. +if ! test -f "$tree/backend/internal/handler/openai_409_ws_rebuild_test.go"; then + exclude_new_fixture backend/internal/handler/openai_ws_owner_conflict_test.go +fi diff --git a/.github/workflows/encrypted-history-409.yml b/.github/workflows/encrypted-history-409.yml index 62b47b9f38cf..41d1c73c609b 100644 --- a/.github/workflows/encrypted-history-409.yml +++ b/.github/workflows/encrypted-history-409.yml @@ -79,6 +79,7 @@ jobs: actual=$(git hash-object "$target") test "$actual" = "$expected" echo "$target defect_source=$callers defect_blob=absent compatibility=$compatibility candidate=$candidate_blob expected=$expected actual=$actual" >> "$RUNNER_TEMP/omit-history-red-compat.txt" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-ws-owner-red-fixtures.sh" "$callers" . HEAD | tee "$RUNNER_TEMP/omit-history-ws-owner-red-blobs.txt" target=backend/internal/service/openai_409_omit_history.go git show "$baseline:$target" > "$target" test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" diff --git a/.github/workflows/issue842-replay-metadata.yml b/.github/workflows/issue842-replay-metadata.yml index 1fe5347ec12f..362f8176dd92 100644 --- a/.github/workflows/issue842-replay-metadata.yml +++ b/.github/workflows/issue842-replay-metadata.yml @@ -84,6 +84,7 @@ jobs: echo "$target baseline=absent actual=absent" >> "$RUNNER_TEMP/issue842/red-blobs.txt" target=backend/internal/handler/openai_issue842_replay_test.go test "$(git hash-object "$target")" = "$(git rev-parse "$EXPECTED_HEAD_SHA:$target")" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-ws-owner-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue842/ws-owner-red-blobs.txt" git diff --stat > "$RUNNER_TEMP/issue842/red-diff.txt" set +e (cd backend && go test -json -tags=unit ./internal/handler -run '^TestIssue842(HTTP|WS)ReplayMetadata$' -count=1 -timeout=5m) > "$RUNNER_TEMP/issue842/red.jsonl" 2>&1 @@ -127,6 +128,7 @@ jobs: echo "$target expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue842/oauth-red-blobs.txt" test "$expected" = "$actual" done + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-ws-owner-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue842/ws-owner-oauth-red-blobs.txt" for target in backend/internal/handler/openai_issue842_oauth_repair_test.go backend/internal/service/issue842_gateway_test_support.go; do test "$(git hash-object "$target")" = "$(git rev-parse "$EXPECTED_HEAD_SHA:$target")" done diff --git a/.github/workflows/readable-continuation-409.yml b/.github/workflows/readable-continuation-409.yml index faa9d9c2f6e7..c685a8a9a508 100644 --- a/.github/workflows/readable-continuation-409.yml +++ b/.github/workflows/readable-continuation-409.yml @@ -117,6 +117,7 @@ jobs: actual=$(git hash-object "$target") test "$actual" = "$expected" echo "$target defect_source=$baseline defect_blob=absent compatibility=$compatibility candidate=$candidate_blob expected=$expected actual=$actual" >> "$RUNNER_TEMP/readable-RED-provenance.txt" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-ws-owner-red-fixtures.sh" "$baseline" . HEAD | tee "$RUNNER_TEMP/readable-ws-owner-red-blobs.txt" - name: Same HTTP JSON and SSE behavior in both checkouts env: PHASE: ${{ matrix.phase }} diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index dbd138c16500..a017d0751e27 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -4,9 +4,8 @@ on: pull_request: branches: [production] paths: - - backend/internal/handler/openai_ws_owner_conflict_test.go - - backend/internal/service/openai_ws_readable_continuation.go - - backend/internal/service/openai_ws_agent_recovery.go + - backend/internal/handler/openai*go + - backend/internal/service/openai*go - .github/workflows/ws-owner-conflict.yml - .github/scripts/ws-owner-conflict-evidence.py - .github/scripts/test_ws_owner_conflict_evidence.py @@ -71,6 +70,12 @@ jobs: test "$(git rev-parse HEAD)" = "$CANDIDATE" git diff --exit-code python3 -m unittest discover -s .github/scripts -p 'test_ws_owner_conflict_evidence.py' + set +e + (cd backend && go test -p=2 -tags=unit ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$' -count=1 -json -timeout=2m) > "$RUNNER_TEMP/ws-owner-evidence/first-green.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/ws-owner-evidence/first-green.jsonl" + python3 .github/scripts/ws-owner-conflict-evidence.py continuation "$status" "$RUNNER_TEMP/ws-owner-evidence/first-green.jsonl" for suite in continuation boundaries transports; do case "$suite" in continuation) test_name=TestOpenAIWSMixedOwnerContinuation ;; @@ -84,6 +89,20 @@ jobs: cat "$RUNNER_TEMP/ws-owner-evidence/green-$suite.jsonl" python3 .github/scripts/ws-owner-conflict-evidence.py "$suite" "$status" "$RUNNER_TEMP/ws-owner-evidence/green-$suite.jsonl" done + - name: Existing policy, shadow and actual-wire contracts + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -p=2 -tags=unit ./internal/handler -run '^Test(OpenAI409(WSReadableContinuation|WSReadableBoundaries|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|FutureShadowPublicationFences|FutureShadowBoundaries|FutureShadowTaskAssociation|FutureShadowAuditProvenance)|OpenAIWSRevalidation|OpenAIResponsesWebSocketRevalidatesKeyWithoutCache|OpenAIWSKeyQueueAdmissionUsesCurrentTurnPermissions|OpenAIWSTurnPricing|Issue600ClientIdentityNetwork)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" + (cd backend && go test -race -p=2 -tags=unit ./internal/service -run '^Test(OpenAIWSMixedOwner|OpenAIRecovery(Diagnostics|ShadowRefusalDiagnostics)|OpenAI409(RebuildRechecksOriginalDeliveryBeforeSend|WSUnsentTurnBoundary|WSTicket|ReplayInputTamperingStillFails|OAuthReplayKeepsOriginalSnapshotAndFinalControls)|Issue854BeforeSendRecoveryGuards|Issue715WS)' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" + python3 - "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" <<'PY' + import json, sys + rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] + for test in ('TestOpenAIWSMixedOwnerFinalSendFences', 'TestOpenAIWSMixedOwnerProofCannotComeFromDiagnostics', 'TestOpenAIRecoveryDiagnosticsAreAllowlisted', 'TestOpenAIRecoveryShadowRefusalDiagnostics'): + assert sum(r.get('Action') == 'pass' and r.get('Test') == test for r in rows) == 1, test + PY - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index 845f14c0fc31..3242a68a2a0d 100644 --- a/backend/internal/handler/openai_409_ws_oracle_test.go +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -81,14 +81,14 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt } validTools := httpRebuildToolsAvailable(body) if customTools { - validTools = readableWSCustomToolsAvailable(body, logicalTurn == 3) + validTools = readableWSCustomToolsAvailable(body, logicalTurn == 3 && u.scenario != "bridge_model") } if u.scenario == "native_namespace" { validTools = true // exact native declarations/schema checked above, including A } valid := r.Header.Get("Authorization") == "Bearer fixture-readable-ws-B" && strings.Contains(string(body), httpRebuildTask) && validTools && - readableWSCompletedResult(body, "apply_patch", httpRebuildPatch, logicalTurn == 3) && + readableWSCompletedResult(body, "apply_patch", httpRebuildPatch, logicalTurn == 3 && u.scenario != "bridge_model") && !strings.Contains(string(body), "fixture-opaque-A") && !gjson.GetBytes(body, "previous_response_id").Exists() && !gjson.GetBytes(body, "conversation").Exists() if u.scenario == "bridge_model" { @@ -105,7 +105,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt return nil } output = []json.RawMessage{json.RawMessage(httpRebuildAgentB), json.RawMessage(httpRebuildCall("run_tests", "call_ws_verify", map[string]any{"path": "sum.go"}))} - if logicalTurn == 3 && readableWSCompletedResult(body, "run_tests", httpRebuildCheck, true) { + if logicalTurn == 3 && readableWSCompletedResult(body, "run_tests", httpRebuildCheck, u.scenario != "bridge_model") { output = []json.RawMessage{json.RawMessage(httpRebuildJSON(map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "ws-coding-task-complete"}}}))} } else if logicalTurn > 2 { return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_duplicate_or_missing_tool"}}}`) diff --git a/backend/internal/handler/openai_agent_message_recovery.go b/backend/internal/handler/openai_agent_message_recovery.go index f503daff5f43..22a4f70c77f9 100644 --- a/backend/internal/handler/openai_agent_message_recovery.go +++ b/backend/internal/handler/openai_agent_message_recovery.go @@ -74,6 +74,7 @@ func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Cont func boolPointer(value bool) *bool { return &value } func markOpenAIRecoveryFailure(c *gin.Context, recovery *service.OpenAIAgentRecoveryError, protocol, phase string, written *bool) { + service.LogOpenAIAgentRecoveryRefusal(c.Request.Context(), recovery) service.MarkOpsStreamErrorValue(c, service.OpsStreamError{ ErrType: recovery.ClientType(), Code: recovery.ClientCode(), Message: recovery.ClientMessage(), IntendedStatus: recovery.HTTPStatus(), CountTowardsSLA: true, NonStream: protocol == "http", diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 18134373390f..a0ea1ad215de 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -4163,7 +4163,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { return } } - next, clean, changed, rebuildErr := h.gatewayService.RebuildOpenAIWSUnsentTurn(ctx, c, raw, sessionHash, currentForwardModel) + next, clean, changed, rebuildErr := h.gatewayService.RebuildOpenAIWSUnsentTurn(service.WithOpenAIWSUnsentOwnerProof(ctx, err), c, raw, sessionHash, currentForwardModel) if rebuildErr != nil { h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr, c) return diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index 2719bb367d10..a383d51e22dc 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -138,7 +138,14 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios other := *a other.ID, other.Priority = 2, 1 other.Credentials = map[string]any{"api_key": "fixture-mixed-B", "base_url": provider.URL} - accounts = &readableWSAccounts{issue600SwitchRepo: &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, other}}}} + pool := []service.Account{*a, other} + if scenario == "binding_changed" { + third := other + third.ID, third.Priority = 3, 2 + third.Credentials = map[string]any{"api_key": "fixture-mixed-C", "base_url": provider.URL} + pool = append(pool, third) + } + accounts = &readableWSAccounts{issue600SwitchRepo: &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: pool}}} *repo = accounts }) defer func() { _ = h.clientConn.CloseNow() }() @@ -297,6 +304,32 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.Equal(t, 1, tools.patches) require.Zero(t, tools.verifications) require.Equal(t, owners, issue805Owners(t, probe), "refusals cannot modify owners") + entries := h.requestLogs.FilterMessage("openai.agent_recovery_refused").All() + require.Len(t, entries, 1, "the real handler logs one safe diagnostic for its terminal refusal") + fields := entries[0].ContextMap() + expectedDetail := map[string]string{ + "unknown": "owner_delivery_unknown", "unpaired_call": "tool_unpaired", "unpaired_output": "tool_unpaired", + "duplicate_call": "tool_duplicate", "duplicate_output": "tool_duplicate", "incomplete": "tool_incomplete", + "off": "mixed_completed_owners", "no_intent": "readable_intent_missing", + }[scenario] + if oldFence { + state := strings.Split(scenario, "_")[0] + expectedDetail = "owner_record_" + state + require.Equal(t, int64(1), fields["owner_"+state]) + if strings.HasSuffix(scenario, "_first") { + require.Equal(t, "partial", fields["owner_observation"]) + require.Equal(t, int64(2), fields["owner_unexamined"]) + } else { + require.Equal(t, int64(2), fields["owner_completed"]) + } + } + require.Equal(t, expectedDetail, fields["subreason"]) + require.False(t, gjson.GetBytes(resumed, "error.subreason").Exists(), "public error contract is unchanged") + logged, marshalErr := json.Marshal(fields) + require.NoError(t, marshalErr) + for _, secret := range []string{httpRebuildTask, httpRebuildPatch, "fixture-opaque-A", "fixture-mixed-B", "call_mixed_patch"} { + require.NotContains(t, string(logged), secret) + } return } require.Equal(t, turn+1, sends, "MIXED_COMPLETED_OWNER_NOT_RESUMED: completed mixed owners must reach B exactly once; code=%s close=%v", gjson.GetBytes(resumed, "error.code").String(), resumeErr) @@ -320,7 +353,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios for i, wire := range frames[turn:] { expectedIdentity := "Bearer fixture-mixed-B" if scenario == "binding_changed" { - expectedIdentity += "-rotated" + expectedIdentity = "Bearer fixture-mixed-C" } require.Equal(t, expectedIdentity, identities[turn+i]) require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 2647a6440533..8294ea9c93f3 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -58,19 +58,30 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c if r.lookupErr != nil { return ctx, body, false, r.lookupErr } - if r.conflict || (r.owner != nil && (r.owner.pending != "" || r.owner.failed || r.owner.conflicted)) { - return ctx, body, false, openAIAgentRecoveryError("owner_conflict") + if r.conflict { + return ctx, body, false, openAIRecoveryDiagnosticError("owner_conflict", r.diagnostics.subreason, r) + } + if r.owner != nil && (r.owner.pending != "" || r.owner.failed || r.owner.conflicted) { + return ctx, body, false, openAIRecoveryDiagnosticError("owner_conflict", openAIRecoveryOwnerDetail(*r.owner, true), r) } _, websocket := ctx.Value(openAIWSAgentRecoveryRetryKey{}).(*atomic.Bool) mixedWS := websocket && r.mixedOwners if mixedWS && !r.hasCompletedMixedOwners() { - return ctx, body, false, openAIAgentRecoveryError("owner_conflict") + return ctx, body, false, openAIRecoveryDiagnosticError("owner_conflict", "owner_delivery_unknown", r) + } + if mixedWS { + for _, item := range gjson.GetBytes(body, "input").Array() { + kind := item.Get("type").String() + if (kind == "function_call_output" || kind == "custom_tool_call_output") && !openAIReadableShadowTextOnly(item.Get("output")) { + return ctx, body, false, openAIRecoveryDiagnosticError("readable_history_unsupported", "tool_history_unsupported", r) + } + } } if len(r.items) == 0 && !openAI409HasProviderState(body) { return ctx, body, false, nil } if !openAI409HasReadableIntent(body) { - return ctx, body, false, openAIAgentRecoveryError("readable_intent_missing") + return ctx, body, false, openAIRecoveryDiagnosticError("readable_intent_missing", "readable_intent_missing", r) } clean, changed := omitOpenAIHistoricalCiphertext(body) if ctx.Err() != nil { @@ -88,9 +99,12 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") } if mixedWS { + if _, detail := inspectOpenAIWSCompletedTools(body); detail != "" { + return ctx, body, false, openAIRecoveryDiagnosticError("owner_conflict", detail, r) + } clean, err = projectOpenAIWSCompletedTools(clean) if err != nil { - return ctx, body, false, err + return ctx, body, false, withOpenAIRecoveryDiagnostics(err, r, "tool_history_unsupported") } r.requireCompletedOwners = true } @@ -591,7 +605,7 @@ func openAI409UsesNativeAPIKey(ctx context.Context, account *Account) bool { 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") + return openAIRecoveryDiagnosticError("wire_changed", stage, openAIAgentRecoveryFromContext(ctx)) } // Derive the HTTP representation only from the verified readable snapshot, diff --git a/backend/internal/service/openai_409_readable_shadow.go b/backend/internal/service/openai_409_readable_shadow.go index b8807f2ecbfe..8df17a55932e 100644 --- a/backend/internal/service/openai_409_readable_shadow.go +++ b/backend/internal/service/openai_409_readable_shadow.go @@ -69,7 +69,9 @@ func (r *openAIAgentRecoveryRequest) shadowEpochKey(item [32]byte) string { // The first supported future case is one exact opaque agent task with no new // client intent or unpaired tool work. Existing readable requests never consult // shadow. A miss/error leaves ordinary routing/refusal intact, never invents text. -func (s *OpenAIGatewayService) RestoreOpenAIReadableShadow(ctx context.Context, c *gin.Context, body []byte, session string) (context.Context, []byte) { +func (s *OpenAIGatewayService) RestoreOpenAIReadableShadow(ctx context.Context, c *gin.Context, body []byte, session string) (restoredCtx context.Context, restoredBody []byte) { + state := openAIRecoveryShadowState{lookup: "not_consulted", epoch: "not_checked"} + defer func() { restoredCtx = context.WithValue(restoredCtx, openAIRecoveryShadowStateKey{}, state) }() if s == nil || s.settingService == nil || openAI409HasReadableIntent(body) || isOpenAIResponsesCompactPath(c) || isOpenAINativeCompactionV2(c) || !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { @@ -102,15 +104,18 @@ func (s *OpenAIGatewayService) RestoreOpenAIReadableShadow(ctx context.Context, return ctx, body } var epoch string + state.lookup, state.epoch = "miss", "unknown" for { var err error epoch, err = epochs.GetOpenAIAgentRecoveryEpoch(storeCtx, r.shadowPrincipal()+":"+task) if err != nil { + state.lookup = "unavailable" return ctx, body } if !strings.HasPrefix(epoch, "pending:") { break } + state.epoch = "pending" timer := time.NewTimer(5 * time.Millisecond) select { case <-storeCtx.Done(): @@ -120,12 +125,27 @@ func (s *OpenAIGatewayService) RestoreOpenAIReadableShadow(ctx context.Context, } } if !strings.HasPrefix(epoch, "ready:pending:") { + state.epoch = "not_ready" + if epoch == "" { + state.epoch = "missing" + } + if strings.HasPrefix(epoch, "pending:") { + state.epoch = "pending" + } return ctx, body } + state.epoch = "ready" raw, err := store.GetOpenAIReadableShadow(storeCtx, r.shadowPrincipal(), task) if err != nil || raw == "" || len(raw) > OpenAIReadableShadowMaxBytes { + if err != nil { + state.lookup = "unavailable" + } + if len(raw) > OpenAIReadableShadowMaxBytes { + state.lookup = "invalid" + } return ctx, body } + state.lookup = "invalid" var record openAIReadableShadow if json.Unmarshal([]byte(raw), &record) != nil || record.Version != 2 || record.Scope != task || epoch != "ready:"+record.Epoch || len(record.Fences) == 0 || len(record.Fences) > 64 || !gjson.ParseBytes(record.Input).IsArray() || @@ -154,8 +174,10 @@ func (s *OpenAIGatewayService) RestoreOpenAIReadableShadow(ctx context.Context, } observation := &openAIReadableShadowObservation{principal: r.shadowPrincipal(), task: task, raw: raw, epoch: epoch, fences: record.Fences} if s.checkOpenAIReadableShadowObservation(storeCtx, observation) != nil { + state.lookup, state.epoch = "changed", "unknown" return ctx, body } + state.lookup = "hit" return context.WithValue(WithRecoveredContextPrivacy(ctx), openAIReadableShadowContextKey{}, observation), clean } @@ -166,20 +188,23 @@ func (s *OpenAIGatewayService) checkOpenAIReadableShadowObservation(ctx context. store, ok := s.cache.(OpenAIReadableShadowCache) epochs, hasEpoch := s.cache.(OpenAIAgentRecoveryEpochCache) if !ok || !hasEpoch { - return openAIAgentRecoveryError("store_unavailable") + return openAIRecoveryDiagnosticError("store_unavailable", "shadow_store_unavailable", nil) } ctx, cancel := context.WithTimeout(ctx, time.Second) defer cancel() raw, err := store.GetOpenAIReadableShadow(ctx, observation.principal, observation.task) if err != nil { - return openAIAgentRecoveryError("store_unavailable") + return openAIRecoveryDiagnosticError("store_unavailable", "shadow_store_unavailable", nil) } epoch, err := epochs.GetOpenAIAgentRecoveryEpoch(ctx, observation.principal+":"+observation.task) if err != nil { - return openAIAgentRecoveryError("store_unavailable") + return openAIRecoveryDiagnosticError("store_unavailable", "shadow_store_unavailable", nil) + } + if epoch != observation.epoch { + return openAIRecoveryDiagnosticError("owner_conflict", "shadow_epoch_changed", &openAIAgentRecoveryRequest{diagnostics: openAIRecoveryDiagnostics{shadow: openAIRecoveryShadowState{lookup: "hit", epoch: "changed"}}}) } - if raw != observation.raw || epoch != observation.epoch { - return openAIAgentRecoveryError("owner_conflict") + if raw != observation.raw { + return openAIRecoveryDiagnosticError("owner_conflict", "shadow_record_changed", &openAIAgentRecoveryRequest{diagnostics: openAIRecoveryDiagnostics{shadow: openAIRecoveryShadowState{lookup: "changed", epoch: "ready"}}}) } return s.checkOpenAIReadableShadowFences(ctx, observation.fences) } @@ -190,21 +215,21 @@ func (s *OpenAIGatewayService) checkOpenAIReadableShadowFences(ctx context.Conte } store, ok := s.cache.(OpenAIAgentRecoveryCache) if !ok { - return openAIAgentRecoveryError("store_unavailable") + return openAIRecoveryDiagnosticError("store_unavailable", "shadow_store_unavailable", nil) } ctx, cancel := context.WithTimeout(ctx, time.Second) defer cancel() for key, expected := range fences { binding, found, err := decodeOpenAIAgentRecoveryBinding(expected) if err != nil || !found || binding.pending != "" || binding.failed || binding.conflicted { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryDiagnosticError("owner_conflict", "shadow_fence_invalid", nil) } actual, err := store.GetOpenAIAgentRecovery(ctx, key) if err != nil { - return openAIAgentRecoveryError("store_unavailable") + return openAIRecoveryDiagnosticError("store_unavailable", "shadow_store_unavailable", nil) } if actual != expected { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryDiagnosticError("owner_conflict", "shadow_fence_changed", nil) } } return nil diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 389ca2e92d41..4a47af886380 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -427,7 +427,7 @@ func (s *defaultOpenAIAccountScheduler) Select( return nil, decision, recovery.lookupErr } if recovery != nil && recovery.conflict { - return nil, decision, openAIAgentRecoveryError("owner_conflict") + return nil, decision, openAIRecoveryDiagnosticError("owner_conflict", recovery.diagnostics.subreason, recovery) } if recovery != nil && recovery.owner != nil { if req.Platform != PlatformOpenAI || req.SessionHash != recovery.session || diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index f86d060658bc..504bdc300d5c 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -6,6 +6,7 @@ import ( "crypto/sha256" "encoding/hex" "encoding/json" + "errors" "io" "net/http" "sort" @@ -88,6 +89,7 @@ type openAIAgentRecoveryRequest struct { model string session string + diagnostics openAIRecoveryDiagnostics completedOwners map[[32]byte]openAIAgentRecoveryBinding requireCompletedOwners bool // mixed WS omission retains each original completed route } @@ -124,9 +126,13 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex if (bytes.Contains(body, []byte("agent_message")) || bytes.Contains(body, []byte(`\u`))) && (!utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body)) { request.conflict = true + request.diagnostics.subreason = "input_invalid" return context.WithValue(ctx, openAIAgentRecoveryContextKey{}, request) } request.items = openAIAgentRecoveryItemDigests(body) + request.diagnostics.tools, _ = inspectOpenAIWSCompletedTools(body) + request.diagnostics.shadow, _ = ctx.Value(openAIRecoveryShadowStateKey{}).(openAIRecoveryShadowState) + request.diagnostics.owners = openAIRecoveryOwnerCounts{observed: true, total: len(request.items), unexamined: len(request.items)} if request.preservesHistory() { request.inputDigest = openAIAgentRecoveryInputDigest(body) request.replaySource = append([]byte(nil), body...) @@ -144,8 +150,14 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex defer cancel() for _, key := range request.keys { binding, found, err := s.awaitOpenAIAgentRecovery(storeCtx, shared, state, key) + request.diagnostics.owners.observe(binding, found, err) if err != nil { - request.lookupErr = err + detail := openAIRecoveryOwnerDetail(binding, found) + var recovery *OpenAIAgentRecoveryError + if errors.As(err, &recovery) && recovery.Reason == "store_unavailable" { + detail = "owner_lookup_unavailable" + } + request.lookupErr = withOpenAIRecoveryDiagnostics(err, request, detail) break } if !found { @@ -153,6 +165,7 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex } if binding.conflicted { request.conflict = true + request.diagnostics.subreason = "owner_record_conflicted" break } if request.ownerBindingRequired() && !sameOpenAIAgentRecoveryRoute(*request.owner, binding) { @@ -322,8 +335,15 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryAccount(ctx context.Conte if request.lookupErr != nil { return request.lookupErr } - if request.conflict || request.mixedOwners { - return openAIAgentRecoveryError("owner_conflict") + if request.conflict { + return openAIRecoveryDiagnosticError("owner_conflict", request.diagnostics.subreason, request) + } + if request.mixedOwners { + detail := "owner_delivery_unknown" + if request.hasCompletedMixedOwners() { + detail = "mixed_completed_owners" + } + return openAIRecoveryDiagnosticError("owner_conflict", detail, request) } // Provider-side response state is never made portable by the agent policy, // even on a pointer-only request with no known opaque item owner. @@ -406,7 +426,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, err } if err := s.checkOpenAIReadableShadowObservation(ctx, request.shadowObservation); err != nil { - return noop, err + return noop, withOpenAIRecoveryDiagnostics(err, request, "") } if request.omittedSource != nil { // Re-read every original item at the actual send, even though opaque @@ -521,6 +541,9 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con } func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Context, request *openAIAgentRecoveryRequest, binding openAIAgentRecoveryBinding) error { + observed := *request + observed.diagnostics.owners = openAIRecoveryOwnerCounts{observed: true, total: len(request.keys), unexamined: len(request.keys)} + request = &observed // Actual-send counts must not mutate the original proof. shared, _ := s.cache.(OpenAIAgentRecoveryCache) if shared != nil { storeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) @@ -528,20 +551,21 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Conte for _, key := range request.keys { raw, err := shared.GetOpenAIAgentRecovery(storeCtx, hex.EncodeToString(key[:])) if err != nil { - return openAIAgentRecoveryError("store_unavailable") + return openAIRecoveryDiagnosticError("store_unavailable", "owner_lookup_unavailable", request) } old, found, err := decodeOpenAIAgentRecoveryBinding(raw) if err != nil { - return openAIAgentRecoveryError("store_unavailable") + return openAIRecoveryDiagnosticError("store_unavailable", "owner_lookup_unavailable", request) } + request.diagnostics.owners.observe(old, found, nil) if !request.completedOwnerUnchanged(key, old, found) { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryDiagnosticError("owner_conflict", openAIRecoveryOwnerDetail(old, found), request) } if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryDiagnosticError("owner_conflict", openAIRecoveryOwnerDetail(old, found), request) } if !found && request.known[key] { - return openAIAgentRecoveryError("owner_unavailable") + return openAIRecoveryDiagnosticError("owner_unavailable", "owner_delivery_unknown", request) } } } else { @@ -551,14 +575,15 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Conte for _, key := range request.keys { old, exists := state.bindings[key] found := exists && time.Now().Before(old.expiresAt) + request.diagnostics.owners.observe(old, found, nil) if !request.completedOwnerUnchanged(key, old, found) { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryDiagnosticError("owner_conflict", openAIRecoveryOwnerDetail(old, found), request) } if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryDiagnosticError("owner_conflict", openAIRecoveryOwnerDetail(old, found), request) } if request.disableOwnerBinding && !found && request.known[key] { - return openAIAgentRecoveryError("owner_unavailable") + return openAIRecoveryDiagnosticError("owner_unavailable", "owner_delivery_unknown", request) } } } diff --git a/backend/internal/service/openai_agent_message_recovery_error.go b/backend/internal/service/openai_agent_message_recovery_error.go index 31192894f23a..72d96dd07f7c 100644 --- a/backend/internal/service/openai_agent_message_recovery_error.go +++ b/backend/internal/service/openai_agent_message_recovery_error.go @@ -11,8 +11,9 @@ var errOpenAIAgentRecoveryUnavailable = errors.New("encrypted agent continuation // OpenAIAgentRecoveryError is a local compatibility refusal, not a failure of // the entire account pool. Reasons contain no route IDs, credentials or input. type OpenAIAgentRecoveryError struct { - Reason string - RetryAt time.Time + diagnostic *openAIRecoveryDiagnostics + Reason string + RetryAt time.Time } func (e *OpenAIAgentRecoveryError) Error() string { return e.ClientMessage() } diff --git a/backend/internal/service/openai_agent_recovery_diagnostics.go b/backend/internal/service/openai_agent_recovery_diagnostics.go new file mode 100644 index 000000000000..2af0298b07fd --- /dev/null +++ b/backend/internal/service/openai_agent_recovery_diagnostics.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "errors" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/tidwall/gjson" + "go.uber.org/zap" +) + +// Diagnostic values are deliberately separate from authorization evidence. +// No body, item/call identity, route, hash, credential or store error belongs here. +type openAIRecoveryOwnerCounts struct { + observed bool + total, completed, pending, failed, conflicted, unknown, unexamined int +} + +func (d *openAIRecoveryOwnerCounts) observe(b openAIAgentRecoveryBinding, found bool, err error) { + d.unexamined-- + switch { + case b.conflicted: + d.conflicted++ + case b.pending != "": + d.pending++ + case b.failed: + d.failed++ + case err != nil || !found: + d.unknown++ + default: + d.completed++ + } +} + +type openAIRecoveryToolCounts struct { + observed bool + calls, results, pairs, unpaired, duplicate, incomplete, invalid int +} + +func inspectOpenAIWSCompletedTools(body []byte) (openAIRecoveryToolCounts, string) { + d := openAIRecoveryToolCounts{observed: true} + calls, results := map[string]string{}, map[string]string{} + for _, item := range gjson.GetBytes(body, "input").Array() { + kind, id := item.Get("type").String(), item.Get("call_id").String() + switch kind { + case "function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output": + if id == "" || item.Get("call_id").Type != gjson.String { + d.invalid++ + } + if item.Get("status").Exists() && item.Get("status").String() != "completed" { + d.incomplete++ + } + if strings.HasSuffix(kind, "_output") { + d.results++ + if results[id] != "" { + d.duplicate++ + } + if !item.Get("output").Exists() || item.Get("output").Type == gjson.Null { + d.invalid++ + } + results[id] = kind + } else { + d.calls++ + if calls[id] != "" { + d.duplicate++ + } + calls[id] = kind + "_output" + } + } + } + for id, kind := range calls { + if results[id] == kind && id != "" { + d.pairs++ + } else { + d.unpaired++ + } + } + for id, kind := range results { + if calls[id] != kind || id == "" { + d.unpaired++ + } + } + switch { + case d.invalid > 0: + return d, "tool_invalid" + case d.incomplete > 0: + return d, "tool_incomplete" + case d.duplicate > 0: + return d, "tool_duplicate" + case d.unpaired > 0: + return d, "tool_unpaired" + default: + return d, "" + } +} + +type openAIRecoveryShadowStateKey struct{} +type openAIRecoveryShadowState struct{ lookup, epoch string } +type openAIRecoveryDiagnostics struct { + subreason string + owners openAIRecoveryOwnerCounts + tools openAIRecoveryToolCounts + shadow openAIRecoveryShadowState +} + +func openAIRecoveryDiagnosticError(reason, detail string, r *openAIAgentRecoveryRequest) error { + e := &OpenAIAgentRecoveryError{Reason: reason} + d := openAIRecoveryDiagnostics{} + if r != nil { + d = r.diagnostics + } + d.subreason = detail + e.diagnostic = &d + return e +} + +func withOpenAIRecoveryDiagnostics(err error, r *openAIAgentRecoveryRequest, detail string) error { + var recovery *OpenAIAgentRecoveryError + if !errors.As(err, &recovery) { + return err + } + copy := *recovery + d := openAIRecoveryDiagnostics{} + if r != nil { + d = r.diagnostics + } + if recovery.diagnostic != nil && detail == "" { + d.subreason = recovery.diagnostic.subreason + } else { + d.subreason = detail + } + if recovery.diagnostic != nil && recovery.diagnostic.shadow.lookup != "" { + d.shadow = recovery.diagnostic.shadow + } + copy.diagnostic = &d + return © +} + +func openAIRecoveryOwnerDetail(b openAIAgentRecoveryBinding, found bool) string { + switch { + case b.conflicted: + return "owner_record_conflicted" + case b.pending != "": + return "owner_record_pending" + case b.failed: + return "owner_record_failed" + case !found: + return "owner_delivery_unknown" + default: + return "owner_route_changed" + } +} + +func safeOpenAIRecoverySubreason(value string) string { + switch value { + case "mixed_completed_owners", "owner_record_conflicted", "owner_record_pending", "owner_record_failed", + "owner_delivery_unknown", "owner_route_changed", "owner_record_changed", "owner_lookup_unavailable", + "tool_invalid", "tool_incomplete", "tool_duplicate", "tool_unpaired", "tool_history_unsupported", + "shadow_record_changed", "shadow_epoch_changed", "shadow_fence_changed", "shadow_fence_invalid", + "shadow_store_unavailable", "input_invalid", "input_integrity", "controls_integrity", "readable_intent_missing": + return value + default: + return "unknown" + } +} + +func safeOpenAIRecoveryShadowState(value string) string { + switch value { + case "not_consulted", "not_checked", "miss", "unavailable", "invalid", "hit", "changed", "missing", "pending", "ready", "not_ready": + return value + default: + return "unknown" + } +} + +// Only fixed categories/counts cross the request logger boundary. Public error +// codes/messages and persisted logical status remain the existing contract. +func LogOpenAIAgentRecoveryRefusal(ctx context.Context, recovery *OpenAIAgentRecoveryError) { + d := openAIRecoveryDiagnostics{} + if recovery != nil && recovery.diagnostic != nil { + d = *recovery.diagnostic + } + ownerObservation, toolObservation := "unknown", "unknown" + if d.owners.observed { + ownerObservation = "complete" + if d.owners.unexamined > 0 { + ownerObservation = "partial" + } + } + if d.tools.observed { + toolObservation = "complete" + } + logger.FromContext(ctx).Warn("openai.agent_recovery_refused", + zap.String("subreason", safeOpenAIRecoverySubreason(d.subreason)), + zap.String("owner_observation", ownerObservation), zap.String("tool_observation", toolObservation), + zap.Int("owner_total", d.owners.total), zap.Int("owner_completed", d.owners.completed), + zap.Int("owner_pending", d.owners.pending), zap.Int("owner_failed", d.owners.failed), + zap.Int("owner_conflicted", d.owners.conflicted), zap.Int("owner_unknown", d.owners.unknown), zap.Int("owner_unexamined", d.owners.unexamined), + zap.Int("tool_calls", d.tools.calls), zap.Int("tool_results", d.tools.results), zap.Int("tool_pairs", d.tools.pairs), + zap.Int("tool_unpaired", d.tools.unpaired), zap.Int("tool_duplicate", d.tools.duplicate), zap.Int("tool_incomplete", d.tools.incomplete), zap.Int("tool_invalid", d.tools.invalid), + zap.String("shadow_lookup", safeOpenAIRecoveryShadowState(d.shadow.lookup)), zap.String("shadow_epoch", safeOpenAIRecoveryShadowState(d.shadow.epoch)), + ) +} diff --git a/backend/internal/service/openai_agent_replay_metadata.go b/backend/internal/service/openai_agent_replay_metadata.go index c30a6c97cef9..a6bdbb6db718 100644 --- a/backend/internal/service/openai_agent_replay_metadata.go +++ b/backend/internal/service/openai_agent_replay_metadata.go @@ -103,7 +103,7 @@ func openAIAgentRecoveryRefusal(ctx context.Context, stage string) error { if r := openAIAgentRecoveryFromContext(ctx); r != nil && r.disableOwnerBinding { logger.FromContext(ctx).Warn("openai.encrypted_agent_recovery_refused", zap.String("stage", stage)) } - return openAIAgentRecoveryError("wire_changed") + return openAIRecoveryDiagnosticError("wire_changed", stage, openAIAgentRecoveryFromContext(ctx)) } // Shared with readable Beta preparation. This deliberately excludes OAuth diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index eedcb83074fe..450651529144 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -316,7 +316,10 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, return openAIAgentRecoveryError("wire_changed") } if err := r.service.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { - return &openAIWSOwnerRouteError{cause: err, completedMixedOwners: r.request.hasCompletedMixedOwners()} + if r.request.hasCompletedMixedOwners() { + return &openAIWSOwnerRouteError{cause: err, completedMixedOwners: true, completedSource: r.request} + } + return &openAIWSOwnerRouteError{cause: err} } if !r.request.omittedHistory && (r.request.owner != nil || r.request.disableOwnerBinding) && previous != "" { owner, err := r.service.getOpenAIWSStateStore().GetResponseAccount(ctx, r.request.groupID, previous) diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go new file mode 100644 index 000000000000..466b3eaa3477 --- /dev/null +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -0,0 +1,181 @@ +package service + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" +) + +func TestOpenAIWSMixedOwnerFinalSendFences(t *testing.T) { + for _, mutation := range []string{"none", "pending", "failed", "conflicted", "missing", "changed", "input", "tools"} { + t.Run(mutation, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + a, b := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + other := strings.ReplaceAll(issue715OpaqueBody, "fixture-opaque-reference", "fixture-other-owner") + issue715LearnRoute(t, svc, a, issue715OpaqueBody) + issue715LearnRoute(t, svc, b, other) + body := []byte(`{"model":"gpt-6-astra","tools":[{"type":"function","name":"inspect","parameters":{"type":"object","properties":{}}}],"input":[{"role":"user","content":"continue the supplied task"},` + gjson.Get(issue715OpaqueBody, "input.0").Raw + `,` + gjson.Get(other, "input.0").Raw + `, + {"type":"function_call","name":"apply_patch","call_id":"fixture-first","arguments":"{}"}, + {"type":"function_call_output","call_id":"fixture-first","output":"fixture patch completed once"}, + {"type":"custom_tool_call","name":"exec","call_id":"fixture-second","input":"fixture command"}, + {"type":"custom_tool_call_output","call_id":"fixture-second","output":"fixture command completed once"}]}`) + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIWSAgentRecovery(context.Background(), c, body, "fixture-session", "gpt-6-astra") + next, clean, changed, err := svc.RebuildOpenAIWSUnsentTurn(ctx, c, body, "fixture-session", "gpt-6-astra") + require.NoError(t, err) + require.True(t, changed) + r := openAIAgentRecoveryFromContext(next) + require.NotNil(t, r.omittedSource) + require.True(t, r.omittedSource.requireCompletedOwners) + for _, item := range gjson.GetBytes(clean, "input").Array() { + require.NotContains(t, item.Get("type").String(), "call") + } + for _, result := range []string{"fixture patch completed once", "fixture command completed once"} { + require.Equal(t, 1, strings.Count(string(clean), result)) + } + key := r.omittedSource.keys[0] + binding := svc.agentMessageRecovery.bindings[key] + switch mutation { + case "pending": + binding.pending = "fixture-pending" + case "failed": + binding.failed = true + case "conflicted": + binding.conflicted = true + case "changed": + binding.accountID++ + case "input": + clean, err = sjson.SetBytes(clean, "input.0.content", "fixture mutated input") + case "tools": + clean, err = sjson.SetBytes(clean, "tools.0.name", "fixture changed schema") + } + require.NoError(t, err) + svc.agentMessageRecovery.bindings[key] = binding + if mutation == "missing" { + delete(svc.agentMessageRecovery.bindings, key) + } + before := make(map[[32]byte]openAIAgentRecoveryBinding) + for k, v := range svc.agentMessageRecovery.bindings { + before[k] = v + } + req, err := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(clean)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(next, b, req) + finish(false) + if mutation == "none" { + require.NoError(t, err) + } else { + require.Error(t, err, "a changed original record or final payload must refuse before generation") + var recovery *OpenAIAgentRecoveryError + require.ErrorAs(t, err, &recovery) + require.Equal(t, http.StatusConflict, recovery.HTTPStatus()) + } + require.Equal(t, before, svc.agentMessageRecovery.bindings) + }) + } +} + +func TestOpenAIWSMixedOwnerProofCannotComeFromDiagnostics(t *testing.T) { + for _, detail := range []string{"unknown", "mixed_completed_owners"} { + cause := openAIRecoveryDiagnosticError("owner_conflict", detail, nil) + err := openAIWSUnsentAgentTurn(&openAIWSOwnerRouteError{cause: cause}, []byte(`{"input":"fixture"}`), "gpt-6-astra", 53) + _, _, _, retry := OpenAIWSUnsentTurnPayload(err) + require.False(t, retry) + } + for _, reason := range []string{"wire_changed", "delivery_pending", "store_unavailable"} { + err := openAIWSUnsentAgentTurn(&openAIWSOwnerRouteError{cause: openAIAgentRecoveryError(reason), completedMixedOwners: true}, []byte(`{"input":"fixture"}`), "gpt-6-astra", 53) + _, _, _, retry := OpenAIWSUnsentTurnPayload(err) + require.False(t, retry) + } +} + +func TestOpenAIRecoveryDiagnosticsAreAllowlisted(t *testing.T) { + core, logs := observer.New(zap.WarnLevel) + ctx := logger.IntoContext(context.Background(), zap.New(core)) + canary := "fixture-private-cipher-body-key-label-itemhash" + r := &openAIAgentRecoveryRequest{diagnostics: openAIRecoveryDiagnostics{ + owners: openAIRecoveryOwnerCounts{observed: true, total: 3, completed: 2, pending: 1}, + shadow: openAIRecoveryShadowState{lookup: canary, epoch: canary}, + }} + r.diagnostics.tools, _ = inspectOpenAIWSCompletedTools([]byte(`{"input":[{"type":"function_call","call_id":"` + canary + `"},{"type":"function_call_output","call_id":"` + canary + `","output":"` + canary + `"}]}`)) + err := openAIRecoveryDiagnosticError("owner_conflict", canary, r) + var recovery *OpenAIAgentRecoveryError + require.True(t, errors.As(err, &recovery)) + LogOpenAIAgentRecoveryRefusal(ctx, recovery) + entry := logs.All()[0] + require.Equal(t, "openai.agent_recovery_refused", entry.Message) + fields := entry.ContextMap() + require.Equal(t, "unknown", fields["subreason"]) + require.Equal(t, "unknown", fields["shadow_lookup"]) + require.Equal(t, "unknown", fields["shadow_epoch"]) + require.Equal(t, int64(2), fields["owner_completed"]) + require.Equal(t, int64(1), fields["owner_pending"]) + require.Equal(t, int64(1), fields["tool_pairs"]) + encoded, err := json.Marshal(fields) + require.NoError(t, err) + require.NotContains(t, string(encoded), canary) + require.Equal(t, "encrypted_agent_recovery_owner_conflict", recovery.ClientCode()) + require.Equal(t, openAIAgentRecoveryError("owner_conflict").Error(), recovery.ClientMessage()) + LogOpenAIAgentRecoveryRefusal(ctx, &OpenAIAgentRecoveryError{Reason: "owner_conflict"}) + unknown := logs.All()[1].ContextMap() + require.Equal(t, "unknown", unknown["owner_observation"]) + require.Equal(t, "unknown", unknown["tool_observation"]) +} + +type mixedOwnerShadowStore struct { + GatewayCache + OpenAIReadableShadowCache + OpenAIAgentRecoveryEpochCache + raw, epoch string +} + +func (s *mixedOwnerShadowStore) GetOpenAIReadableShadow(context.Context, string, string) (string, error) { + return s.raw, nil +} +func (s *mixedOwnerShadowStore) GetOpenAIAgentRecoveryEpoch(context.Context, string) (string, error) { + return s.epoch, nil +} + +func TestOpenAIRecoveryShadowRefusalDiagnostics(t *testing.T) { + for _, mutation := range []string{"none", "record", "epoch"} { + t.Run(mutation, func(t *testing.T) { + observation := &openAIReadableShadowObservation{raw: "fixture-private-record", epoch: "ready:pending:fixture-private-epoch"} + store := &mixedOwnerShadowStore{raw: observation.raw, epoch: observation.epoch} + if mutation == "record" { + store.raw += "-changed" + } + if mutation == "epoch" { + store.epoch += "-changed" + } + svc := &OpenAIGatewayService{cache: store} + err := svc.checkOpenAIReadableShadowObservation(context.Background(), observation) + if mutation == "none" { + require.NoError(t, err) + return + } + var recovery *OpenAIAgentRecoveryError + require.ErrorAs(t, err, &recovery) + require.Equal(t, "encrypted_agent_recovery_owner_conflict", recovery.ClientCode()) + core, logs := observer.New(zap.WarnLevel) + LogOpenAIAgentRecoveryRefusal(logger.IntoContext(context.Background(), zap.New(core)), recovery) + fields := logs.All()[0].ContextMap() + require.Equal(t, "shadow_"+mutation+"_changed", fields["subreason"]) + encoded, marshalErr := json.Marshal(fields) + require.NoError(t, marshalErr) + require.NotContains(t, string(encoded), "fixture-private") + }) + } +} diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index df71abbcdc7a..858880f0c3da 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -16,11 +16,12 @@ import ( // Constructed only at transport boundaries before the CURRENT generation has // been written. Neither a transport failure nor lack of output proves this. type openAIWSUnsentTurnError struct { - cause error - body []byte - model string - turn int - keepAccount bool // an owner mismatch does not disqualify a healthy selected account + cause error + body []byte + model string + turn int + keepAccount bool // an owner mismatch does not disqualify a healthy selected account + completedSource *openAIAgentRecoveryRequest } func (e *openAIWSUnsentTurnError) Error() string { @@ -63,6 +64,7 @@ func (e *openAIWSLostOwnerEvidenceError) Unwrap() error { return e.cause } type openAIWSOwnerRouteError struct { cause error completedMixedOwners bool + completedSource *openAIAgentRecoveryRequest } func (e *openAIWSOwnerRouteError) Error() string { return e.cause.Error() } @@ -93,7 +95,19 @@ func openAIWSUnsentAgentTurn(err error, body []byte, model string, turn int) err default: return closed } - return &openAIWSUnsentTurnError{cause: closed, body: append([]byte(nil), body...), model: model, turn: turn, keepAccount: true} + return &openAIWSUnsentTurnError{cause: closed, body: append([]byte(nil), body...), model: model, turn: turn, keepAccount: true, completedSource: route.completedSource} +} + +type openAIWSUnsentOwnerProofKey struct{} + +// Carry the route check's observations through the handler's auth boundary. +// Rebuild consumes this current-turn evidence once; it cannot leak to later turns. +func WithOpenAIWSUnsentOwnerProof(ctx context.Context, err error) context.Context { + var unsent *openAIWSUnsentTurnError + if errors.As(err, &unsent) && unsent.completedSource != nil { + return context.WithValue(ctx, openAIWSUnsentOwnerProofKey{}, unsent.completedSource) + } + return ctx } // Keep completed results as data in a new provider conversation. Historical @@ -190,41 +204,15 @@ func openAIReadableRecoveryUser(c *gin.Context, keyID int64) int64 { // A new provider conversation may reuse completed results, never unfinished // tool work. Reject duplicate, orphan or unknown-status tool records. func openAIWSCompletedToolInputs(body []byte) bool { - calls, results := map[string]string{}, map[string]string{} - for _, item := range gjson.GetBytes(body, "input").Array() { - kind, id := item.Get("type").String(), item.Get("call_id").String() - switch kind { - case "function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output": - if id == "" || (item.Get("status").Exists() && item.Get("status").String() != "completed") { - return false - } - if strings.HasSuffix(kind, "_output") { - if results[id] != "" || !item.Get("output").Exists() || item.Get("output").Type == gjson.Null { - return false - } - results[id] = kind - } else { - if calls[id] != "" { - return false - } - calls[id] = kind + "_output" - } - } - } - if len(calls) != len(results) { - return false - } - for id, kind := range calls { - if results[id] != kind { - return false - } - } - return true + _, reason := inspectOpenAIWSCompletedTools(body) + return reason == "" } // Called before fresh admission/moderation of an unsent frame. Lookup is scoped // to this exact task; missing historical intent is never fabricated. func (s *OpenAIGatewayService) RebuildOpenAIWSUnsentTurn(ctx context.Context, c *gin.Context, body []byte, session, model string) (context.Context, []byte, bool, error) { + proof, _ := ctx.Value(openAIWSUnsentOwnerProofKey{}).(*openAIAgentRecoveryRequest) + ctx = context.WithValue(ctx, openAIWSUnsentOwnerProofKey{}, (*openAIAgentRecoveryRequest)(nil)) if s == nil || s.settingService == nil || !s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { return ctx, body, false, nil } @@ -246,10 +234,24 @@ func (s *OpenAIGatewayService) RebuildOpenAIWSUnsentTurn(ctx context.Context, c } } next := s.WithOpenAIWSAgentRecovery(ctx, c, body, session, model) - if !openAIWSCompletedToolInputs(body) { - return ctx, body, false, openAIAgentRecoveryError("owner_conflict") - } r := openAIAgentRecoveryFromContext(next) + if proof != nil { + if r.lookupErr != nil { + return ctx, body, false, r.lookupErr + } + if !r.hasCompletedMixedOwners() || len(r.keys) != len(proof.keys) { + return ctx, body, false, openAIRecoveryDiagnosticError("owner_conflict", "owner_record_changed", r) + } + for _, key := range proof.keys { + actual, found := r.completedOwners[key] + if !found || !sameOpenAIAgentRecoveryRoute(proof.completedOwners[key], actual) { + return ctx, body, false, openAIRecoveryDiagnosticError("owner_conflict", "owner_record_changed", r) + } + } + } + if _, reason := inspectOpenAIWSCompletedTools(body); reason != "" { + return ctx, body, false, openAIRecoveryDiagnosticError("owner_conflict", reason, r) + } if len(r.items) == 0 && !openAI409HasProviderState(body) && !r.disallowLearning { if !openAI409HasReadableIntent(body) { return ctx, body, false, openAIAgentRecoveryError("readable_intent_missing") diff --git a/docs/ws-mixed-owner-continuation.md b/docs/ws-mixed-owner-continuation.md new file mode 100644 index 000000000000..5d1ab4bbf8ff --- /dev/null +++ b/docs/ws-mixed-owner-continuation.md @@ -0,0 +1,47 @@ +# Completed mixed-owner WebSocket continuation + +With `openai_409_omit_encrypted_history_enabled` enabled, an existing client +WebSocket can rebuild a current, provably unsent turn containing opaque history +from multiple completed producers. This closes the live-socket gap between the +send-boundary owner check and the existing readable continuation handler. + +The gateway requires a completed ownership observation for **every** supplied +opaque item, readable current intent, and complete, unique tool call/result +pairs. It discards provider pointers and historical ciphertext. In this mixed +WS case, it carries completed tool names/results as inert assistant text and +removes historical callable records/arguments. Current tool definitions and +schemas remain available for new tool work. The client keeps its existing +session identity and socket; no client confirmation or new conversation is +required for this supported branch. + +The permit comes from a private before-write route check. The public +`encrypted_agent_recovery_owner_conflict` code alone never permits retry. +Unknown ownership, pending/failed/conflicted delivery, missing/duplicate or +incomplete tool pairs, unsupported result representations, and changed shadow +associations remain refusals. All original completed routes are checked again +at the physical send, including after history omission. Historical owner +records are retained. Identity, authorization, moderation and recovered-body +privacy, billing, model policy, admission, payload integrity and no-replay +checks remain in the normal handler/forwarder path. + +The request log event `openai.agent_recovery_refused` adds allowlisted internal +subreasons and owner/tool structural counts, plus shadow lookup/epoch states. +It never adds bodies, ciphertext, item/call hashes or identifiers, credentials, +route addresses, or account labels. `unknown` and partial/unexamined states are +explicit; these diagnostics do not confer permission. The public error code, +message, logical HTTP status and WebSocket error/close contract remain intact. + +Regression evidence uses authenticated ingress, production forwarding, isolated +Redis and loopback fake providers. It includes turn 53, fresh/live sockets, +account binding changes, exactly-once client tool effects, final wire schemas, +and terminal negative controls. The CI restores exact production blobs in a +disposable checkout for behavioral RED, then runs the candidate with the race +detector. Compile errors, skips and panics are not accepted as RED. + +This source branch is not an attribution of the historical incident: its exact +internal refusal subreason was not recorded. The deployed baseline already +contains #855 and #860. A before-dispatch refusal proves only that the current +generation was unsent; it says nothing about earlier turns' tools or charges. +Real-provider acceptance is **NOT EXECUTED**. A passing local fake-provider +oracle is not a production deployment or a guarantee that a provider will +accept every reconstructed conversation. From b7e09ca6d73d8340100c1e9122591aed26daa417 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 21:44:35 +0800 Subject: [PATCH 04/26] =?UTF-8?q?fix:=20=E4=B8=BA=E7=BB=AD=E6=8E=A5?= =?UTF-8?q?=E6=8B=92=E7=BB=9D=E4=BF=9D=E5=AD=98=E5=9B=BA=E5=AE=9A=E5=AD=90?= =?UTF-8?q?=E5=8E=9F=E5=9B=A0=E5=B9=B6=E9=AA=8C=E8=AF=81=E6=9C=AA=E5=8F=91?= =?UTF-8?q?=E9=80=81=E6=81=A2=E5=A4=8D=E8=BE=B9=E7=95=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ws-owner-conflict.yml | 19 ++-- .../handler/openai_agent_message_recovery.go | 18 +++- .../handler/openai_ws_owner_conflict_test.go | 79 ++++++++++++++-- backend/internal/handler/ops_error_logger.go | 1 + .../service/openai_409_omit_history.go | 7 +- .../service/openai_409_readable_shadow.go | 11 ++- .../service/openai_account_scheduler.go | 2 +- .../service/openai_agent_message_delivery.go | 6 +- .../service/openai_agent_message_recovery.go | 11 ++- .../openai_agent_message_recovery_error.go | 45 +++++++++- .../service/openai_agent_replay_metadata.go | 2 +- .../service/openai_owner_conflict_test.go | 89 +++++++++++++++++++ .../service/openai_ws_agent_recovery.go | 3 + .../openai_ws_readable_continuation.go | 37 +++++--- .../internal/service/ops_upstream_context.go | 1 + 15 files changed, 286 insertions(+), 45 deletions(-) create mode 100644 backend/internal/service/openai_owner_conflict_test.go diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index fba07f3d3b64..7a6e203bf027 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -7,6 +7,8 @@ on: - backend/internal/handler/openai_ws_owner_conflict_test.go - backend/internal/service/openai_ws_readable_continuation.go - backend/internal/service/openai_ws_agent_recovery.go + - backend/internal/service/openai_agent_message_recovery_error.go + - backend/internal/service/openai_owner_conflict_test.go - .github/workflows/ws-owner-conflict.yml permissions: @@ -56,7 +58,7 @@ jobs: esac done set +e - (cd "$RUNNER_TEMP/ws-owner-red/backend" && go test -p=2 -tags=unit ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$/turn_2$' -count=1 -json -timeout=2m) > "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" 2>&1 + (cd "$RUNNER_TEMP/ws-owner-red/backend" && go test -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$/turn_2$/ctx_pool$/pointer$' -count=1 -json -timeout=2m) > "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" 2>&1 status=$? set -e cat "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" @@ -64,7 +66,7 @@ jobs: python3 - "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" <<'PY' import json, sys rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] - leaf = 'TestOpenAIWSMixedOwnerContinuation/turn_2' + leaf = 'TestOpenAIWSMixedOwnerContinuation/turn_2/ctx_pool/pointer' assert any(r.get('Action') == 'fail' and r.get('Test') == leaf for r in rows), 'missing actual handler failure' outputs = ''.join(r.get('Output', '') for r in rows) assert 'MIXED_COMPLETED_OWNER_NOT_RESUMED' in outputs, 'not the intended behavior RED' @@ -78,19 +80,20 @@ jobs: set -euo pipefail test "$(git rev-parse HEAD)" = "$CANDIDATE" git diff --exit-code - if git diff --quiet "$BASELINE" "$CANDIDATE" -- backend/internal/service; then - echo 'Production repair not yet present; GREEN NOT EXECUTED (initial RED draft).' - exit 0 - fi - (cd backend && go test -race -p=2 -tags=unit ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" 2>&1 + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^Test(OpenAIWSMixedOwnerContinuation|OwnerConflict)' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" 2>&1 cat "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" python3 - "$RUNNER_TEMP/ws-owner-evidence/green.jsonl" <<'PY' import json, sys rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] for turn in (2, 53): - assert any(r.get('Action') == 'pass' and r.get('Test') == f'TestOpenAIWSMixedOwnerContinuation/turn_{turn}' for r in rows) + for mode in ('http_bridge','ctx_pool','shared','dedicated','passthrough'): + for scenario in ('pointer','no_pointer'): + assert any(r.get('Action') == 'pass' and r.get('Test') == f'TestOpenAIWSMixedOwnerContinuation/turn_{turn}/{mode}/{scenario}' for r in rows) assert not any(r.get('Action') in ('skip', 'fail') for r in rows) PY + - name: Service diagnostics and refusal boundaries + working-directory: backend + run: go test -race -tags=unit,ownerconflict ./internal/service -run '^Test(OwnerConflict|Issue854BeforeSendRecoveryGuards|OpenAI409RebuildRechecksOriginalDeliveryBeforeSend)' -count=1 -v -timeout=5m - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_agent_message_recovery.go b/backend/internal/handler/openai_agent_message_recovery.go index f503daff5f43..a903bdd5fe3f 100644 --- a/backend/internal/handler/openai_agent_message_recovery.go +++ b/backend/internal/handler/openai_agent_message_recovery.go @@ -7,9 +7,12 @@ import ( "strconv" "time" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/service" coderws "github.com/coder/websocket" "github.com/gin-gonic/gin" + "go.uber.org/zap" ) func (h *OpenAIGatewayHandler) handleOpenAIAgentRecoveryError(c *gin.Context, err error, streamStarted bool) bool { @@ -74,9 +77,22 @@ func (h *OpenAIGatewayHandler) handleOpenAIWSAgentRecoveryError(ctx context.Cont func boolPointer(value bool) *bool { return &value } func markOpenAIRecoveryFailure(c *gin.Context, recovery *service.OpenAIAgentRecoveryError, protocol, phase string, written *bool) { + turn := 0 + if value, ok := c.Get(service.OpsStreamTurnKey); ok { + turn, _ = value.(int) + } + requestID, _ := c.Request.Context().Value(ctxkey.RequestID).(string) + writeState := "unknown" + if written != nil { + writeState = strconv.FormatBool(*written) + } + logger.FromContext(c.Request.Context()).Warn("openai.agent_recovery_refused", + zap.String("request_id", requestID), zap.Int("turn", turn), + zap.String("protocol", protocol), zap.String("phase", phase), + zap.String("subreason", recovery.InternalSubreason()), zap.String("request_written", writeState)) service.MarkOpsStreamErrorValue(c, service.OpsStreamError{ ErrType: recovery.ClientType(), Code: recovery.ClientCode(), Message: recovery.ClientMessage(), IntendedStatus: recovery.HTTPStatus(), CountTowardsSLA: true, NonStream: protocol == "http", - RecoveryFailure: &service.OpsRecoveryFailure{Protocol: protocol, Phase: phase, RequestWritten: written}, + RecoveryFailure: &service.OpsRecoveryFailure{Protocol: protocol, Phase: phase, RequestWritten: written, Subreason: recovery.InternalSubreason()}, }) } diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index b933f3c119b2..4f0084f4900e 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -1,4 +1,4 @@ -//go:build unit +//go:build unit && ownerconflict package handler @@ -26,13 +26,20 @@ import ( // and account repository replaced. Both owners are earned by delivered output. func TestOpenAIWSMixedOwnerContinuation(t *testing.T) { for _, turn := range []int{2, 53} { - t.Run(fmt.Sprintf("turn_%d", turn), func(t *testing.T) { - runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, turn) - }) + for _, mode := range readableWSModes { + for _, scenario := range []string{"pointer", "no_pointer"} { + t.Run(fmt.Sprintf("turn_%d/%s/%s", turn, mode, scenario), func(t *testing.T) { runWSMixedOwnerContinuation(t, mode, turn, scenario) }) + } + } + } +} +func TestOwnerConflictNegativeControls(t *testing.T) { + for _, scenario := range []string{"off", "pending_first", "pending_last", "failed_first", "failed_last", "conflict_first", "conflict_last", "orphan", "duplicate", "unfinished"} { + t.Run(scenario, func(t *testing.T) { runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, 53, scenario) }) } } -func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { +func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenario string) { t.Helper() clients := issue805Redis(t) probe := clients() @@ -87,9 +94,13 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { })) defer provider.Close() headers := http.Header{"Authorization": {"Bearer sk-handler-cyber-test"}, "Session_id": {"fixture-mixed-session"}, "Thread-Id": {"fixture-mixed-thread"}} + enabled := "true" + if scenario == "off" { + enabled = "false" + } var accounts *readableWSAccounts h := newOpenAIWSPassthroughHandlerHarnessWithAuth(t, provider.URL, headers, - map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}, + map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: enabled}, repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, nil, func(key *service.APIKey, cfg *config.Config) *service.APIKeyService { key.Status = service.StatusActive @@ -181,11 +192,67 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int) { return true }, 3*time.Second, 5*time.Millisecond) owners := issue805Owners(t, probe) + if scenario == "no_pointer" { + previous = "" + } + negative := scenario != "pointer" && scenario != "no_pointer" + for _, state := range []string{"pending", "failed", "conflict"} { + if strings.HasPrefix(scenario, state+"_") { + accountID := int64(1) + if strings.HasSuffix(scenario, "last") { + accountID = 2 + } + for key, raw := range owners { + if gjson.Get(raw, "1").Int() == accountID { + value := state + if state == "pending" { + value = "pending:fixture-held:" + raw + } + require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err()) + } + } + } + } + if scenario == "orphan" { + filtered := []string{} + for _, raw := range history { + if gjson.Get(raw, "type").String() != "function_call" { + filtered = append(filtered, raw) + } + } + history = filtered + } + if scenario == "duplicate" { + for _, raw := range history { + if gjson.Get(raw, "type").String() == "function_call_output" { + history = append(history, raw) + break + } + } + } + if scenario == "unfinished" { + for i, raw := range history { + if gjson.Get(raw, "type").String() == "function_call" { + history[i] = strings.TrimSuffix(raw, "}") + `,"status":"in_progress"}` + break + } + } + } + owners = issue805Owners(t, probe) issue715WSSend(t, h.clientConn, create(history, previous)) resumed, resumeErr := read() mu.Lock() sends := len(frames) mu.Unlock() + if negative { + require.Equal(t, turn, sends, "unsafe continuation cannot generate") + require.Equal(t, "error", gjson.GetBytes(resumed, "type").String()) + require.NotEmpty(t, gjson.GetBytes(resumed, "error.code").String()) + require.Equal(t, owners, issue805Owners(t, probe), "refusal preserves all owner fences") + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + return + } require.Equal(t, turn+1, sends, "MIXED_COMPLETED_OWNER_NOT_RESUMED: completed mixed owners must reach B exactly once; code=%s close=%v", gjson.GetBytes(resumed, "error.code").String(), resumeErr) require.NoError(t, resumeErr) require.Equal(t, "completed", gjson.GetBytes(resumed, "response.status").String()) diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 76d784caaa90..24d3e16f630d 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -1548,6 +1548,7 @@ func logOpsStreamErrorValue(c *gin.Context, ops *service.OpsService, wireStatus if failure := streamErr.RecoveryFailure; failure != nil { fields := gin.H{"type": normalizedType, "code": streamErr.Code, "message": streamErr.Message, "protocol": failure.Protocol, "turn": streamErr.Turn, "phase": failure.Phase, "outcome": "failed", + "subreason": service.OpenAIRecoverySubreason(failure.Subreason), "wire_status": wireStatus, "status": streamErr.IntendedStatus} if failure.RequestWritten != nil { fields["request_written"] = *failure.RequestWritten diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index d259eced63b3..c34d57de9dc7 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -57,8 +57,11 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c if r.lookupErr != nil { return ctx, body, false, r.lookupErr } - if r.conflict || (r.owner != nil && (r.owner.pending != "" || r.owner.failed || r.owner.conflicted)) { - return ctx, body, false, openAIAgentRecoveryError("owner_conflict") + if r.conflict { + return ctx, body, false, openAIAgentRecoveryDetailedError("owner_conflict", "owner_record_conflicted") + } + if r.owner != nil && (r.owner.pending != "" || r.owner.failed || r.owner.conflicted) { + return ctx, body, false, openAIRecoveryRecordConflict(*r.owner) } if len(r.items) == 0 && !openAI409HasProviderState(body) { return ctx, body, false, nil diff --git a/backend/internal/service/openai_409_readable_shadow.go b/backend/internal/service/openai_409_readable_shadow.go index b8807f2ecbfe..e6c43c14db3b 100644 --- a/backend/internal/service/openai_409_readable_shadow.go +++ b/backend/internal/service/openai_409_readable_shadow.go @@ -178,8 +178,11 @@ func (s *OpenAIGatewayService) checkOpenAIReadableShadowObservation(ctx context. if err != nil { return openAIAgentRecoveryError("store_unavailable") } - if raw != observation.raw || epoch != observation.epoch { - return openAIAgentRecoveryError("owner_conflict") + if raw != observation.raw { + return openAIAgentRecoveryDetailedError("owner_conflict", "shadow_changed") + } + if epoch != observation.epoch { + return openAIAgentRecoveryDetailedError("owner_conflict", "shadow_epoch_changed") } return s.checkOpenAIReadableShadowFences(ctx, observation.fences) } @@ -197,14 +200,14 @@ func (s *OpenAIGatewayService) checkOpenAIReadableShadowFences(ctx context.Conte for key, expected := range fences { binding, found, err := decodeOpenAIAgentRecoveryBinding(expected) if err != nil || !found || binding.pending != "" || binding.failed || binding.conflicted { - return openAIAgentRecoveryError("owner_conflict") + return openAIAgentRecoveryDetailedError("owner_conflict", "shadow_fence_invalid") } actual, err := store.GetOpenAIAgentRecovery(ctx, key) if err != nil { return openAIAgentRecoveryError("store_unavailable") } if actual != expected { - return openAIAgentRecoveryError("owner_conflict") + return openAIAgentRecoveryDetailedError("owner_conflict", "shadow_fence_changed") } } return nil diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go index 389ca2e92d41..948785fdee7f 100644 --- a/backend/internal/service/openai_account_scheduler.go +++ b/backend/internal/service/openai_account_scheduler.go @@ -427,7 +427,7 @@ func (s *defaultOpenAIAccountScheduler) Select( return nil, decision, recovery.lookupErr } if recovery != nil && recovery.conflict { - return nil, decision, openAIAgentRecoveryError("owner_conflict") + return nil, decision, openAIAgentRecoveryDetailedError("owner_conflict", "owner_record_conflicted") } if recovery != nil && recovery.owner != nil { if req.Platform != PlatformOpenAI || req.SessionHash != recovery.session || diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index cd8123084bed..a5c9c3aa8195 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -65,7 +65,7 @@ func (s *OpenAIGatewayService) awaitOpenAIAgentRecovery(ctx context.Context, sha } if err != nil { if observedPending && ctx.Err() != nil { - return b, false, openAIAgentRecoveryError("delivery_pending") + return b, false, openAIAgentRecoveryDetailedError("delivery_pending", "delivery_pending") } return b, false, openAIAgentRecoveryError("store_unavailable") } @@ -76,7 +76,7 @@ func (s *OpenAIGatewayService) awaitOpenAIAgentRecovery(ctx context.Context, sha return b, found, nil } if b.failed || (!found && observedPending) { - return b, false, openAIAgentRecoveryError("owner_unavailable") + return b, false, openAIAgentRecoveryDetailedError("owner_unavailable", "owner_record_failed") } if b.pending == "" { return b, found, nil @@ -86,7 +86,7 @@ func (s *OpenAIGatewayService) awaitOpenAIAgentRecovery(ctx context.Context, sha select { case <-ctx.Done(): timer.Stop() - return b, false, openAIAgentRecoveryError("delivery_pending") + return b, false, openAIAgentRecoveryDetailedError("delivery_pending", "delivery_pending") case <-timer.C: } } diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 36947164e9ce..1fea3f75991b 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -292,8 +292,11 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryAccount(ctx context.Conte if request.lookupErr != nil { return request.lookupErr } - if request.conflict || request.mixedOwners { - return openAIAgentRecoveryError("owner_conflict") + if request.conflict { + return openAIAgentRecoveryDetailedError("owner_conflict", "owner_record_conflicted") + } + if request.mixedOwners { + return openAIAgentRecoveryDetailedError("owner_conflict", "mixed_completed_owners") } // Provider-side response state is never made portable by the agent policy, // even on a pointer-only request with no known opaque item owner. @@ -505,7 +508,7 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Conte return openAIAgentRecoveryError("store_unavailable") } if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryRecordConflict(old) } if !found && request.known[key] { return openAIAgentRecoveryError("owner_unavailable") @@ -519,7 +522,7 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryRecords(ctx context.Conte old, exists := state.bindings[key] found := exists && time.Now().Before(old.expiresAt) if found && (old.conflicted || old.failed || old.pending != "" || (!request.disableOwnerBinding && !sameOpenAIAgentRecoveryRoute(old, binding))) { - return openAIAgentRecoveryError("owner_conflict") + return openAIRecoveryRecordConflict(old) } if request.disableOwnerBinding && !found && request.known[key] { return openAIAgentRecoveryError("owner_unavailable") diff --git a/backend/internal/service/openai_agent_message_recovery_error.go b/backend/internal/service/openai_agent_message_recovery_error.go index 31192894f23a..010c27f9bfb7 100644 --- a/backend/internal/service/openai_agent_message_recovery_error.go +++ b/backend/internal/service/openai_agent_message_recovery_error.go @@ -11,8 +11,9 @@ var errOpenAIAgentRecoveryUnavailable = errors.New("encrypted agent continuation // OpenAIAgentRecoveryError is a local compatibility refusal, not a failure of // the entire account pool. Reasons contain no route IDs, credentials or input. type OpenAIAgentRecoveryError struct { - Reason string - RetryAt time.Time + Reason string + subreason string // fixed internal discriminator, never client data + RetryAt time.Time } func (e *OpenAIAgentRecoveryError) Error() string { return e.ClientMessage() } @@ -59,8 +60,8 @@ func (e *OpenAIAgentRecoveryError) ClientMessage() string { } action = "Wait until " + e.RetryAt.UTC().Format(time.RFC3339) + " (estimated), then resume this same conversation with its complete history. Compatibility records are retained through that window; current permissions and route compatibility will be checked again. Do not resubmit tool results while an earlier delivery is uncertain." case "owner_conflict": - reason = "The encrypted agent items have conflicting compatible owners." - action = "Ask the administrator to verify the original compatible owner; do not switch accounts or replay tool results." + reason = "The supplied continuation cannot satisfy its ownership, delivery or history integrity checks." + action = "Ask the administrator to inspect the refusal details; do not replay completed tools or bypass continuation checks." case "route_changed": reason = "The proven encrypted agent route or credentials changed." action = "Ask the administrator to verify the original compatible route and current authorized credentials before continuing." @@ -90,3 +91,39 @@ type openAINonStreamingDeliveryError struct{ err error } func (e *openAINonStreamingDeliveryError) Error() string { return e.err.Error() } func (e *openAINonStreamingDeliveryError) Unwrap() error { return e.err } + +// InternalSubreason is intentionally absent from client envelopes. Revalidate +// this closed list at persistence boundaries so upstream/client text cannot leak. +func (e *OpenAIAgentRecoveryError) InternalSubreason() string { + return OpenAIRecoverySubreason(e.subreason) +} +func OpenAIRecoverySubreason(reason string) string { + switch reason { + case "mixed_completed_owners", "owner_record_conflicted", "owner_record_pending", "owner_record_failed", "owner_route_changed", "owner_record_lost", "delivery_pending", "tool_missing_id", "tool_incomplete", "tool_duplicate_call", "tool_duplicate_result", "tool_result_missing", "tool_unpaired", "shadow_changed", "shadow_epoch_changed", "shadow_fence_invalid", "shadow_fence_changed", "input_integrity", "body_unreadable", "unsupported_adapter", "route_identity": + return reason + default: + return "unknown" + } +} +func openAIAgentRecoveryDetailedError(reason, detail string) error { + return &OpenAIAgentRecoveryError{Reason: reason, subreason: OpenAIRecoverySubreason(detail)} +} + +// Only the observed completed-owner route mismatch creates this marker. Public +// owner_conflict alone and post-admission state changes never grant a retry. +type openAIWSMixedCompletedOwnersError struct{ cause error } + +func (e *openAIWSMixedCompletedOwnersError) Error() string { return e.cause.Error() } +func (e *openAIWSMixedCompletedOwnersError) Unwrap() error { return e.cause } +func openAIRecoveryRecordConflict(b openAIAgentRecoveryBinding) error { + detail := "owner_route_changed" + switch { + case b.conflicted: + detail = "owner_record_conflicted" + case b.failed: + detail = "owner_record_failed" + case b.pending != "": + detail = "owner_record_pending" + } + return openAIAgentRecoveryDetailedError("owner_conflict", detail) +} diff --git a/backend/internal/service/openai_agent_replay_metadata.go b/backend/internal/service/openai_agent_replay_metadata.go index c30a6c97cef9..bb6748febd4d 100644 --- a/backend/internal/service/openai_agent_replay_metadata.go +++ b/backend/internal/service/openai_agent_replay_metadata.go @@ -103,7 +103,7 @@ func openAIAgentRecoveryRefusal(ctx context.Context, stage string) error { if r := openAIAgentRecoveryFromContext(ctx); r != nil && r.disableOwnerBinding { logger.FromContext(ctx).Warn("openai.encrypted_agent_recovery_refused", zap.String("stage", stage)) } - return openAIAgentRecoveryError("wire_changed") + return openAIAgentRecoveryDetailedError("wire_changed", stage) } // Shared with readable Beta preparation. This deliberately excludes OAuth diff --git a/backend/internal/service/openai_owner_conflict_test.go b/backend/internal/service/openai_owner_conflict_test.go new file mode 100644 index 000000000000..cf952e7addfc --- /dev/null +++ b/backend/internal/service/openai_owner_conflict_test.go @@ -0,0 +1,89 @@ +//go:build unit && ownerconflict + +package service + +import ( + "bytes" + "context" + "errors" + "net/http" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" +) + +func TestOwnerConflictTypedBeforeSendBoundary(t *testing.T) { + body := []byte(`{"input":"synthetic task"}`) + for _, tc := range []struct { + name string + err error + want bool + }{ + {"completed", &openAIWSMixedCompletedOwnersError{cause: openAIAgentRecoveryDetailedError("owner_conflict", "mixed_completed_owners")}, true}, + {"plain conflict", openAIAgentRecoveryError("owner_conflict"), false}, + {"route conflict", &openAIWSOwnerRouteError{cause: openAIAgentRecoveryError("owner_conflict")}, false}, + {"lost owner", &openAIWSLostOwnerEvidenceError{cause: &openAIWSMixedCompletedOwnersError{cause: openAIAgentRecoveryError("owner_conflict")}}, false}, + {"partial write", errors.New("synthetic partial write"), false}, + } { + t.Run(tc.name, func(t *testing.T) { + _, _, _, ok := OpenAIWSUnsentTurnPayload(openAIWSUnsentAgentTurn(tc.err, body, "gpt-5.1", 53)) + require.Equal(t, tc.want, ok) + }) + } +} + +func TestOwnerConflictToolPairingDiagnostics(t *testing.T) { + call := `{"type":"function_call","call_id":"c","name":"fixture","arguments":"{}"}` + result := `{"type":"function_call_output","call_id":"c","output":"completed"}` + for _, tc := range []struct{ input, want string }{ + {call + "," + result, ""}, {result, "tool_unpaired"}, {call, "tool_unpaired"}, + {call + "," + call + "," + result, "tool_duplicate_call"}, {call + "," + result + "," + result, "tool_duplicate_result"}, + {`{"type":"function_call","name":"secret"}`, "tool_missing_id"}, + {`{"type":"function_call","call_id":"c","status":"in_progress"}`, "tool_incomplete"}, + {`{"type":"function_call_output","call_id":"c","output":null}`, "tool_result_missing"}, + {call + `,{"type":"custom_tool_call_output","call_id":"c","output":"done"}`, "tool_unpaired"}, + } { + require.Equal(t, tc.want, openAIWSToolPairingRefusal([]byte(`{"input":[`+tc.input+`]}`))) + } +} + +func TestOwnerConflictDiagnosticsDoNotAuthorizeStateChanges(t *testing.T) { + for _, state := range []string{"pending", "failed", "conflict"} { + t.Run(state, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + issue715LearnRoute(t, svc, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, issue715OpaqueBody) + body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"role":"user","content":"complete existing task"}]}` + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra") + next, clean, changed, err := svc.TryRebuildOpenAI409History(ctx, c, []byte(body), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError("owner_unavailable")) + require.NoError(t, err) + require.True(t, changed) + key := openAIAgentRecoveryFromContext(ctx).keys[0] + binding := svc.agentMessageRecovery.bindings[key] + want := "owner_record_conflicted" + switch state { + case "pending": + binding.pending = "fixture" + want = "owner_record_pending" + case "failed": + binding.failed = true + want = "owner_record_failed" + case "conflict": + binding.conflicted = true + } + svc.agentMessageRecovery.bindings[key] = binding + req, err := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(clean)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(next, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req) + defer finish(false) + var refusal *OpenAIAgentRecoveryError + require.ErrorAs(t, err, &refusal) + require.Equal(t, want, refusal.InternalSubreason()) + require.Equal(t, binding, svc.agentMessageRecovery.bindings[key]) + }) + } + require.Equal(t, "unknown", OpenAIRecoverySubreason("user input or credentials")) +} diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index e1a43bb8bfdc..d0ca3fa73972 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -316,6 +316,9 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, return openAIAgentRecoveryError("wire_changed") } if err := r.service.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { + if r.request.mixedOwners && !r.request.conflict && r.request.lookupErr == nil && !r.request.omittedHistory && r.request.delivery == nil { + return &openAIWSMixedCompletedOwnersError{cause: err} + } return &openAIWSOwnerRouteError{cause: err} } if !r.request.omittedHistory && (r.request.owner != nil || r.request.disableOwnerBinding) && previous != "" { diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index 9e57ed6050e9..a693c681c52f 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -74,11 +74,16 @@ func openAIWSUnsentAgentTurn(err error, body []byte, model string, turn int) err return closed } var route *openAIWSOwnerRouteError + var mixed *openAIWSMixedCompletedOwnersError var recovery *OpenAIAgentRecoveryError - if turn < 1 || !errors.As(err, &route) || !errors.As(err, &recovery) || !gjson.ValidBytes(body) { + if turn < 1 || (!errors.As(err, &route) && !errors.As(err, &mixed)) || !errors.As(err, &recovery) || !gjson.ValidBytes(body) { return closed } switch recovery.Reason { + case "owner_conflict": + if mixed == nil { + return closed + } case "owner_unavailable", "route_changed": // Rebuild still checks completed ownership, delivery fences, readable // intent, tool results and final payload integrity. Do not turn wire @@ -136,36 +141,46 @@ func openAIReadableRecoveryUser(c *gin.Context, keyID int64) int64 { // A new provider conversation may reuse completed results, never unfinished // tool work. Reject duplicate, orphan or unknown-status tool records. func openAIWSCompletedToolInputs(body []byte) bool { + return openAIWSToolPairingRefusal(body) == "" +} + +func openAIWSToolPairingRefusal(body []byte) string { calls, results := map[string]string{}, map[string]string{} for _, item := range gjson.GetBytes(body, "input").Array() { kind, id := item.Get("type").String(), item.Get("call_id").String() switch kind { case "function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output": - if id == "" || (item.Get("status").Exists() && item.Get("status").String() != "completed") { - return false + if id == "" { + return "tool_missing_id" + } + if item.Get("status").Exists() && item.Get("status").String() != "completed" { + return "tool_incomplete" } if strings.HasSuffix(kind, "_output") { - if results[id] != "" || !item.Get("output").Exists() || item.Get("output").Type == gjson.Null { - return false + if results[id] != "" { + return "tool_duplicate_result" + } + if !item.Get("output").Exists() || item.Get("output").Type == gjson.Null { + return "tool_result_missing" } results[id] = kind } else { if calls[id] != "" { - return false + return "tool_duplicate_call" } calls[id] = kind + "_output" } } } if len(calls) != len(results) { - return false + return "tool_unpaired" } for id, kind := range calls { if results[id] != kind { - return false + return "tool_unpaired" } } - return true + return "" } // Called before fresh admission/moderation of an unsent frame. Lookup is scoped @@ -192,8 +207,8 @@ func (s *OpenAIGatewayService) RebuildOpenAIWSUnsentTurn(ctx context.Context, c } } next := s.WithOpenAIWSAgentRecovery(ctx, c, body, session, model) - if !openAIWSCompletedToolInputs(body) { - return ctx, body, false, openAIAgentRecoveryError("owner_conflict") + if detail := openAIWSToolPairingRefusal(body); detail != "" { + return ctx, body, false, openAIAgentRecoveryDetailedError("owner_conflict", detail) } r := openAIAgentRecoveryFromContext(next) if len(r.items) == 0 && !openAI409HasProviderState(body) && !r.disallowLearning { diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index c14f7d4fef65..a4387e9a1af8 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -183,6 +183,7 @@ func IsOpsRequestScopedError(c *gin.Context) bool { // OpsRecoveryFailure is trusted local compatibility evidence, never populated // from an upstream error envelope or client metadata. type OpsRecoveryFailure struct { + Subreason string // fixed internal allowlist; not supplied by the client Protocol string Phase string RequestWritten *bool // nil means no proof of whether the generation was sent From 1b61a5df3be2ad409bbb6370b1549bbdaa6942cd Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 21:51:37 +0800 Subject: [PATCH 05/26] test: verify binding changes and preserve historical RED contracts --- .../test_ws_owner_conflict_evidence.py | 2 +- .github/scripts/ws-owner-conflict-evidence.py | 2 +- .github/workflows/issue715-agent-recovery.yml | 18 ++++++--- .../workflows/rebuilt-request-dispatch.yml | 3 +- .../handler/openai_ws_owner_conflict_test.go | 2 +- .../service/openai_ws_owner_conflict_test.go | 40 +++++++++++++++++++ 6 files changed, 57 insertions(+), 10 deletions(-) diff --git a/.github/scripts/test_ws_owner_conflict_evidence.py b/.github/scripts/test_ws_owner_conflict_evidence.py index 7cd325dc386d..fcef7f718bb5 100644 --- a/.github/scripts/test_ws_owner_conflict_evidence.py +++ b/.github/scripts/test_ws_owner_conflict_evidence.py @@ -10,7 +10,7 @@ def fixture(suite): leaves = EVIDENCE.SUITES[suite] - tests = leaves | {"/".join(leaf.split("/")[:i]) for leaf in leaves for i in range(1, len(leaf.split("/")))} + tests = leaves | {leaf.split("/")[0] for leaf in leaves} outcome = "fail" if suite == "red" else "pass" rows = [{"Package": EVIDENCE.PACKAGE, "Test": name, "Action": action} for name in sorted(tests) for action in ("run", outcome)] rows.append({"Package": EVIDENCE.PACKAGE, "Action": outcome}) diff --git a/.github/scripts/ws-owner-conflict-evidence.py b/.github/scripts/ws-owner-conflict-evidence.py index ba83ce663d03..38ae35e73327 100644 --- a/.github/scripts/ws-owner-conflict-evidence.py +++ b/.github/scripts/ws-owner-conflict-evidence.py @@ -30,7 +30,7 @@ def validate(suite, status, raw): if status != (1 if suite == "red" else 0): raise ValueError("unexpected process exit") rows = [json.loads(line) for line in raw.splitlines() if line.startswith("{")] - ancestors = {"/".join(leaf.split("/")[:i]) for leaf in leaves for i in range(1, len(leaf.split("/")))} + ancestors = {leaf.split("/")[0] for leaf in leaves} # t.Run uses flattened mode/case names. tests = leaves | ancestors counts = Counter((r.get("Action"), r.get("Test")) for r in rows if r.get("Package") == PACKAGE) for name in tests: diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml index 7b79fcee5d22..2d1d085c497b 100644 --- a/.github/workflows/issue715-agent-recovery.yml +++ b/.github/workflows/issue715-agent-recovery.yml @@ -102,9 +102,10 @@ jobs: targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_gateway_response_handling.go backend/internal/service/openai_gateway_service.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go) added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_agent_message_recovery_wait.go backend/internal/service/openai_ws_search_activation.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go) # The exact original gateway struct predates analysis admission state. - added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_replay_metadata.go) + added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_agent_recovery_diagnostics.go) handler_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a handler_leaf=backend/internal/handler/openai_agent_message_recovery.go + error_leaf=backend/internal/service/openai_agent_message_recovery_error.go # Pin this unrelated leaf to its pre-admission version, preserving all # Issue715 business-chain blobs and the retained handler regressions. # Issue842 compatibility-body callers depend on the later recovery @@ -126,7 +127,7 @@ jobs: git fetch --no-tags --depth=1 origin "$metadata_compat" git fetch --no-tags --depth=1 origin "$analysis_compat" git fetch --no-tags --depth=1 origin "$billing_compat" - trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}" "$handler_leaf" "$metadata_leaf" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}" "$analysis_leaf" "$billing_leaf" "${weekly_leaves[@]}" "$handler_leaf" "$error_leaf" "$metadata_leaf" 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="$metadata_compat" -- "$metadata_leaf" test "$(git hash-object "$metadata_leaf")" = "$(git rev-parse "$metadata_compat:$metadata_leaf")" @@ -150,7 +151,9 @@ jobs: echo "compatibility_leaf_baseline=$analysis_compat path=$analysis_leaf expected_blob=$expected tested_blob=$actual" test "$expected" = "$actual" git fetch --no-tags --depth=1 origin "$handler_compat" - git restore --source="$handler_compat" -- "$handler_leaf" + git restore --source="$handler_compat" -- "$handler_leaf" "$error_leaf" + test "$(git hash-object "$error_leaf")" = "$(git rev-parse "$handler_compat:$error_leaf")" + echo "error_compatibility_baseline=$handler_compat path=$error_leaf blob=$(git hash-object "$error_leaf")" test "$(git hash-object "$handler_leaf")" = "$(git rev-parse "$handler_compat:$handler_leaf")" echo "handler_compatibility_baseline=$handler_compat path=$handler_leaf" rm -- "${added[@]}" @@ -270,9 +273,10 @@ jobs: ws_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) # Neither helper exists on the restored historical socket structure. ws_added=(backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_search_activation.go) - ws_added+=(backend/internal/service/openai_ws_readable_continuation.go) + ws_added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_recovery_diagnostics.go) handler_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a handler_leaf=backend/internal/handler/openai_agent_message_recovery.go + error_leaf=backend/internal/service/openai_agent_message_recovery_error.go # The historical recovery request predates Issue758 cooldown state. # Keep the exact delivery-defect blobs above, and pin only this # scheduling compatibility leaf to the pre-Issue758 production base. @@ -288,7 +292,7 @@ jobs: git fetch --no-tags --depth=1 origin "$ws_original" git fetch --no-tags --depth=1 origin "$scheduler_compat" git fetch --no-tags --depth=1 origin "$metadata_compat" - trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "${omission_added[@]}" "$handler_leaf" "$metadata_leaf" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT + trap 'git restore --source=HEAD -- "${targets[@]}" "$added" "${ws_targets[@]}" "${ws_added[@]}" "$scheduler_leaf" "$wait_added" "${omission_added[@]}" "$handler_leaf" "$error_leaf" "$metadata_leaf" 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="$metadata_compat" -- "$metadata_leaf" @@ -300,7 +304,9 @@ jobs: echo "compatibility_leaf_baseline=$scheduler_compat path=$scheduler_leaf expected_blob=$expected tested_blob=$actual" test "$expected" = "$actual" git fetch --no-tags --depth=1 origin "$handler_compat" - git restore --source="$handler_compat" -- "$handler_leaf" + git restore --source="$handler_compat" -- "$handler_leaf" "$error_leaf" + test "$(git hash-object "$error_leaf")" = "$(git rev-parse "$handler_compat:$error_leaf")" + echo "error_compatibility_baseline=$handler_compat path=$error_leaf blob=$(git hash-object "$error_leaf")" test "$(git hash-object "$handler_leaf")" = "$(git rev-parse "$handler_compat:$handler_leaf")" echo "handler_compatibility_baseline=$handler_compat path=$handler_leaf" rm -- "$added" "${ws_added[@]}" "$wait_added" "${omission_added[@]}" diff --git a/.github/workflows/rebuilt-request-dispatch.yml b/.github/workflows/rebuilt-request-dispatch.yml index fea90ca68342..1df82ba413c9 100644 --- a/.github/workflows/rebuilt-request-dispatch.yml +++ b/.github/workflows/rebuilt-request-dispatch.yml @@ -55,7 +55,7 @@ jobs: callers=d1bd861bcfa34443a629db98de9121a4e15d1d0b fi for source in "$compatibility" "$callers"; do git fetch --no-tags --depth=1 origin "$source"; done - for target in backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_gateway_request_body.go backend/internal/service/openai_ws_agent_recovery.go; do + for target in backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_gateway_request_body.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_readable_continuation.go; do source="$callers" if [ "$target" = backend/internal/service/openai_agent_replay_metadata.go ]; then source="$compatibility"; fi expected=$(git rev-parse "$source:$target") @@ -63,6 +63,7 @@ jobs: test "$(git hash-object "$target")" = "$expected" echo "$target compatibility=$source blob=$expected" >> "$RUNNER_TEMP/dispatch-compatibility.txt" done + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-ws-owner-red-fixtures.sh" "$baseline" . HEAD | tee "$RUNNER_TEMP/dispatch-ws-owner-red-blobs.txt" - name: Same network and tool-loop regressions env: PHASE: ${{ matrix.phase }} diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index a383d51e22dc..6ca6524e6dd0 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -280,7 +280,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios history = history[1:] case "binding_changed": accounts.mu.Lock() - accounts.accounts[1].Credentials["api_key"] = "fixture-mixed-B-rotated" + accounts.accounts[1].Credentials = map[string]any{"api_key": "fixture-mixed-B-rotated", "base_url": provider.URL} accounts.mu.Unlock() case "fresh": issue600Finish(t, h, headers) diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go index 466b3eaa3477..01cc37314da0 100644 --- a/backend/internal/service/openai_ws_owner_conflict_test.go +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -102,6 +102,46 @@ func TestOpenAIWSMixedOwnerProofCannotComeFromDiagnostics(t *testing.T) { } } +func TestOpenAIWSMixedOwnerProofRecheckedAtRebuild(t *testing.T) { + for _, mutation := range []string{"none", "missing", "changed"} { + t.Run(mutation, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + a, b := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + other := strings.ReplaceAll(issue715OpaqueBody, "fixture-opaque-reference", "fixture-other-owner") + issue715LearnRoute(t, svc, a, issue715OpaqueBody) + issue715LearnRoute(t, svc, b, other) + body := []byte(`{"model":"gpt-6-astra","input":[{"role":"user","content":"continue this task"},` + gjson.Get(issue715OpaqueBody, "input.0").Raw + `,` + gjson.Get(other, "input.0").Raw + `]}`) + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIWSAgentRecovery(context.Background(), c, body, "fixture-session", "gpt-6-astra") + proof := openAIAgentRecoveryFromContext(ctx) + require.True(t, proof.hasCompletedMixedOwners()) + before := svc.checkOpenAIAgentRecoveryAccount(ctx, b) + err := openAIWSUnsentAgentTurn(&openAIWSOwnerRouteError{cause: before, completedMixedOwners: true, completedSource: proof}, body, "gpt-6-astra", 53) + _, _, _, unsent := OpenAIWSUnsentTurnPayload(err) + require.True(t, unsent) + key := proof.keys[0] + if mutation == "missing" { + delete(svc.agentMessageRecovery.bindings, key) + } else if mutation == "changed" { + binding := svc.agentMessageRecovery.bindings[key] + binding.accountID = 3 // Still mixed and completed, but different evidence. + svc.agentMessageRecovery.bindings[key] = binding + } + next, _, changed, rebuildErr := svc.RebuildOpenAIWSUnsentTurn(WithOpenAIWSUnsentOwnerProof(ctx, err), c, body, "fixture-session", "gpt-6-astra") + if mutation == "none" { + require.NoError(t, rebuildErr) + require.True(t, changed) + } else { + require.Error(t, rebuildErr) + require.False(t, changed) + } + remaining, _ := next.Value(openAIWSUnsentOwnerProofKey{}).(*openAIAgentRecoveryRequest) + require.Nil(t, remaining, "proof belongs only to the current turn") + }) + } +} + func TestOpenAIRecoveryDiagnosticsAreAllowlisted(t *testing.T) { core, logs := observer.New(zap.WarnLevel) ctx := logger.IntoContext(context.Background(), zap.New(core)) From 278cc53fe9aa71bb3485674f2d51778cbb220239 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 21:52:19 +0800 Subject: [PATCH 06/26] =?UTF-8?q?ci:=20=E9=9A=94=E7=A6=BB=E8=AF=8A?= =?UTF-8?q?=E6=96=AD=E6=96=B0=E5=A2=9E=E5=AD=97=E6=AE=B5=E7=9A=84=E6=97=A7?= =?UTF-8?q?=E6=BA=90=E7=A0=81=E5=8F=8D=E4=BE=8B=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/scripts/prepare-ws-owner-red-fixtures.sh | 2 ++ .github/workflows/ws-owner-conflict.yml | 2 +- .../internal/handler/openai_owner_conflict_diagnostics_test.go | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/scripts/prepare-ws-owner-red-fixtures.sh b/.github/scripts/prepare-ws-owner-red-fixtures.sh index 5cec43f9aef6..76b594d52990 100644 --- a/.github/scripts/prepare-ws-owner-red-fixtures.sh +++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh @@ -20,6 +20,8 @@ for target in \ backend/internal/service/openai_account_scheduler.go \ backend/internal/service/openai_ws_agent_recovery.go \ backend/internal/handler/openai_agent_message_recovery.go \ + backend/internal/handler/ops_error_logger.go \ + backend/internal/service/ops_upstream_context.go \ backend/internal/handler/openai_gateway_handler.go; do test -f "$tree/$target" || continue # Do not replace a selected defect blob or an already verified compatibility diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index d5070d0418b6..5972abbac740 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -105,7 +105,7 @@ jobs: PY - name: Persist safe refusal subtype with logical turn working-directory: backend - run: go test -race -tags=unit,ownerconflict ./internal/handler -run '^TestOwnerConflictPersistence' -count=1 -v -timeout=5m + run: go test -race -tags=unit,ownerdiagnostics ./internal/handler -run '^TestOwnerConflictPersistence' -count=1 -v -timeout=5m - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_owner_conflict_diagnostics_test.go b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go index f40df66c2ce6..777288a9e419 100644 --- a/backend/internal/handler/openai_owner_conflict_diagnostics_test.go +++ b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go @@ -1,4 +1,4 @@ -//go:build unit && ownerconflict +//go:build unit && ownerdiagnostics package handler From 65e94be9ee3994d2754d2154820491d7e1730e81 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 21:53:07 +0800 Subject: [PATCH 07/26] test: keep persisted diagnostics compatible with pinned handler RED --- .../openai_owner_conflict_diagnostics_test.go | 9 ++++++++- .../openai_agent_message_recovery_error.go | 1 - .../openai_agent_recovery_diagnostics.go | 13 ------------- .../service/openai_recovery_subreason.go | 18 ++++++++++++++++++ .../service/openai_ws_owner_conflict_test.go | 2 ++ 5 files changed, 28 insertions(+), 15 deletions(-) create mode 100644 backend/internal/service/openai_recovery_subreason.go diff --git a/backend/internal/handler/openai_owner_conflict_diagnostics_test.go b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go index f40df66c2ce6..2e19d32473ed 100644 --- a/backend/internal/handler/openai_owner_conflict_diagnostics_test.go +++ b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go @@ -3,6 +3,7 @@ package handler import ( + "encoding/json" "net/http" "net/http/httptest" "testing" @@ -22,7 +23,13 @@ func TestOwnerConflictPersistenceKeepsTurnAndSafeSubreason(t *testing.T) { service.SetOpenAIClientTransport(c, service.OpenAIClientTransportWS) service.BeginOpsStreamTurn(c, 53) written := false - service.MarkOpsStreamErrorValue(c, service.OpsStreamError{ErrType: "invalid_request_error", Code: "encrypted_agent_recovery_owner_conflict", Message: "synthetic refusal", IntendedStatus: 409, CountTowardsSLA: true, RecoveryFailure: &service.OpsRecoveryFailure{Protocol: "websocket", Phase: "before_dispatch", RequestWritten: &written, Subreason: tc.detail}}) + failure := &service.OpsRecoveryFailure{Protocol: "websocket", Phase: "before_dispatch", RequestWritten: &written} + // Baseline RED compiles this independent fixture but does not run it; + // old production ignores the new diagnostic field during decoding. + encoded, err := json.Marshal(map[string]string{"Subreason": tc.detail}) + require.NoError(t, err) + require.NoError(t, json.Unmarshal(encoded, failure)) + service.MarkOpsStreamErrorValue(c, service.OpsStreamError{ErrType: "invalid_request_error", Code: "encrypted_agent_recovery_owner_conflict", Message: "synthetic refusal", IntendedStatus: 409, CountTowardsSLA: true, RecoveryFailure: failure}) repo := &ingressRejectOpsRepo{} ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) logOpsStreamError(c, ops, http.StatusSwitchingProtocols) diff --git a/backend/internal/service/openai_agent_message_recovery_error.go b/backend/internal/service/openai_agent_message_recovery_error.go index e84bdfd61084..2c57346dfe51 100644 --- a/backend/internal/service/openai_agent_message_recovery_error.go +++ b/backend/internal/service/openai_agent_message_recovery_error.go @@ -99,4 +99,3 @@ func (e *OpenAIAgentRecoveryError) InternalSubreason() string { } return safeOpenAIRecoverySubreason(e.diagnostic.subreason) } -func OpenAIRecoverySubreason(value string) string { return safeOpenAIRecoverySubreason(value) } diff --git a/backend/internal/service/openai_agent_recovery_diagnostics.go b/backend/internal/service/openai_agent_recovery_diagnostics.go index 2af0298b07fd..ccfcd6a7065a 100644 --- a/backend/internal/service/openai_agent_recovery_diagnostics.go +++ b/backend/internal/service/openai_agent_recovery_diagnostics.go @@ -152,19 +152,6 @@ func openAIRecoveryOwnerDetail(b openAIAgentRecoveryBinding, found bool) string } } -func safeOpenAIRecoverySubreason(value string) string { - switch value { - case "mixed_completed_owners", "owner_record_conflicted", "owner_record_pending", "owner_record_failed", - "owner_delivery_unknown", "owner_route_changed", "owner_record_changed", "owner_lookup_unavailable", - "tool_invalid", "tool_incomplete", "tool_duplicate", "tool_unpaired", "tool_history_unsupported", - "shadow_record_changed", "shadow_epoch_changed", "shadow_fence_changed", "shadow_fence_invalid", - "shadow_store_unavailable", "input_invalid", "input_integrity", "controls_integrity", "readable_intent_missing": - return value - default: - return "unknown" - } -} - func safeOpenAIRecoveryShadowState(value string) string { switch value { case "not_consulted", "not_checked", "miss", "unavailable", "invalid", "hit", "changed", "missing", "pending", "ready", "not_ready": diff --git a/backend/internal/service/openai_recovery_subreason.go b/backend/internal/service/openai_recovery_subreason.go new file mode 100644 index 000000000000..d981c35723bc --- /dev/null +++ b/backend/internal/service/openai_recovery_subreason.go @@ -0,0 +1,18 @@ +package service + +// OpenAIRecoverySubreason limits persisted diagnostics to fixed categories. +// Kept independent of request/proof types so historical error callers remain coherent. +func OpenAIRecoverySubreason(value string) string { return safeOpenAIRecoverySubreason(value) } + +func safeOpenAIRecoverySubreason(value string) string { + switch value { + case "mixed_completed_owners", "owner_record_conflicted", "owner_record_pending", "owner_record_failed", + "owner_delivery_unknown", "owner_route_changed", "owner_record_changed", "owner_lookup_unavailable", + "tool_invalid", "tool_incomplete", "tool_duplicate", "tool_unpaired", "tool_history_unsupported", + "shadow_record_changed", "shadow_epoch_changed", "shadow_fence_changed", "shadow_fence_invalid", + "shadow_store_unavailable", "input_invalid", "input_integrity", "controls_integrity", "readable_intent_missing": + return value + default: + return "unknown" + } +} diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go index 01cc37314da0..fbf2e401dad8 100644 --- a/backend/internal/service/openai_ws_owner_conflict_test.go +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -1,3 +1,5 @@ +//go:build unit && ownerconflict + package service import ( From fee20e120072725dbed1c64cdaebf42b436a1cfa Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:14:59 +0800 Subject: [PATCH 08/26] test: expose unissued matched tool pairs in real WS continuation --- .../scripts/prepare-ws-owner-red-fixtures.sh | 5 +- .../scripts/ws-tool-provenance-evidence.py | 33 +++++ .github/workflows/ws-tool-provenance.yml | 84 ++++++++++++ .../handler/openai_ws_owner_conflict_test.go | 128 +++++++++++++++++- 4 files changed, 245 insertions(+), 5 deletions(-) create mode 100644 .github/scripts/ws-tool-provenance-evidence.py create mode 100644 .github/workflows/ws-tool-provenance.yml diff --git a/.github/scripts/prepare-ws-owner-red-fixtures.sh b/.github/scripts/prepare-ws-owner-red-fixtures.sh index 76b594d52990..c1e57d2230eb 100644 --- a/.github/scripts/prepare-ws-owner-red-fixtures.sh +++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh @@ -19,9 +19,10 @@ for target in \ backend/internal/service/openai_agent_replay_metadata.go \ backend/internal/service/openai_account_scheduler.go \ backend/internal/service/openai_ws_agent_recovery.go \ + backend/internal/service/openai_ws_forwarder_ingress.go \ + backend/internal/service/openai_ws_http_bridge.go \ + backend/internal/service/openai_ws_v2_passthrough_adapter.go \ backend/internal/handler/openai_agent_message_recovery.go \ - backend/internal/handler/ops_error_logger.go \ - backend/internal/service/ops_upstream_context.go \ backend/internal/handler/openai_gateway_handler.go; do test -f "$tree/$target" || continue # Do not replace a selected defect blob or an already verified compatibility diff --git a/.github/scripts/ws-tool-provenance-evidence.py b/.github/scripts/ws-tool-provenance-evidence.py new file mode 100644 index 000000000000..9a4dcee2ca05 --- /dev/null +++ b/.github/scripts/ws-tool-provenance-evidence.py @@ -0,0 +1,33 @@ +"""F1 must fail because an unissued matching pair actually reaches upstream.""" +import importlib.util +import json +import sys +from collections import Counter +from pathlib import Path + +spec = importlib.util.spec_from_file_location("clean", Path(__file__).with_name("assert-readable-continuation.py")) +clean = importlib.util.module_from_spec(spec) +spec.loader.exec_module(clean) +phase, status, path = sys.argv[1:] +raw = Path(path).read_text() +clean.check_clean(raw) +root = "TestOpenAIWSMixedOwnerToolProvenance" +leaves = {root + "/phantom_" + kind for kind in ("function", "custom")} +rows = [json.loads(line) for line in raw.splitlines() if line.startswith("{")] +expected = "fail" if phase == "RED" else "pass" +assert phase in ("RED", "GREEN") and int(status) == (1 if phase == "RED" else 0) +counts = Counter((r.get("Action"), r.get("Test")) for r in rows) +for name in leaves | {root}: + assert counts["run", name] == 1 and counts[expected, name] == 1, name + assert counts["pass", name] + counts["fail", name] == 1, name +assert counts[expected, None] == 1 +for row in rows: + if row.get("Action") in ("run", "pass", "fail"): + assert row.get("Package") == "github.com/Wei-Shaw/sub2api/internal/handler" + assert row.get("Test") in leaves | {root, None} +if phase == "RED": + for name in leaves: + output = "".join(r.get("Output", "") for r in rows if r.get("Test") == name) + assert "F1_PHANTOM_PAIR_REACHED_UPSTREAM" in output, name + assert "F1_UNTRUSTED_MATCHED_PAIR_DISPATCHED" in output, name +print(f"F1 {phase}: both actual authenticated handler phantom-pair scenarios verified") diff --git a/.github/workflows/ws-tool-provenance.yml b/.github/workflows/ws-tool-provenance.yml new file mode 100644 index 000000000000..e1d6bdb91b25 --- /dev/null +++ b/.github/workflows/ws-tool-provenance.yml @@ -0,0 +1,84 @@ +name: WS tool provenance F1 + +on: + pull_request: + branches: [production] + paths: + - backend/internal/handler/openai*go + - backend/internal/service/openai*go + - .github/workflows/ws-tool-provenance.yml + - .github/scripts/ws-owner-conflict-evidence.py + - .github/scripts/ws-tool-provenance-evidence.py + - backend/internal/repository/gateway_cache_tool_provenance.go + +permissions: + contents: read + +jobs: + behavior: + runs-on: macos-15-intel + timeout-minutes: 45 + env: + CANDIDATE: ${{ github.event.pull_request.head.sha }} + BASELINE: 18aef10f71a6a68372a124f2684ecb18024318bb + 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 + env: + HOMEBREW_NO_AUTO_UPDATE: '1' + HOMEBREW_NO_INSTALL_CLEANUP: '1' + run: | + if ! command -v redis-server >/dev/null; then brew install redis; fi + - name: Real handler RED against exact production blobs + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + mkdir -p "$RUNNER_TEMP/ws-provenance-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/ws-provenance-evidence/candidate.txt" + git worktree add --detach "$RUNNER_TEMP/ws-provenance-red" "$CANDIDATE" + git diff --name-only "$BASELINE" "$CANDIDATE" -- backend | while IFS= read -r target; do + case "$target" in + *_test.go) continue ;; + *.go) + if git cat-file -e "$BASELINE:$target" 2>/dev/null; then + git show "$BASELINE:$target" > "$RUNNER_TEMP/ws-provenance-red/$target" + test "$(git hash-object "$RUNNER_TEMP/ws-provenance-red/$target")" = "$(git rev-parse "$BASELINE:$target")" + printf '%s %s\n' "$(git rev-parse "$BASELINE:$target")" "$target" >> "$RUNNER_TEMP/ws-provenance-evidence/baseline-blobs.txt" + else + rm -- "$RUNNER_TEMP/ws-provenance-red/$target" + fi ;; + esac + done + set +e + (cd "$RUNNER_TEMP/ws-provenance-red/backend" && go test -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerToolProvenance$' -count=1 -json -timeout=2m) > "$RUNNER_TEMP/ws-provenance-evidence/red.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/ws-provenance-evidence/red.jsonl" + test "$status" -eq 1 + python3 .github/scripts/ws-tool-provenance-evidence.py RED "$status" "$RUNNER_TEMP/ws-provenance-evidence/red.jsonl" + - name: Candidate provenance GREEN + if: hashFiles('backend/internal/service/openai_tool_provenance.go') != '' + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git diff --exit-code + set +e + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerToolProvenance$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-provenance-evidence/green.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/ws-provenance-evidence/green.jsonl" + python3 .github/scripts/ws-tool-provenance-evidence.py GREEN "$status" "$RUNNER_TEMP/ws-provenance-evidence/green.jsonl" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: ws-tool-provenance-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/ws-provenance-evidence diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index c545aeb77a25..c4bd822b4220 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -54,13 +54,39 @@ func TestOpenAIWSMixedOwnerTransports(t *testing.T) { } } +// A matching client pair is not evidence that any upstream issued the call. +func TestOpenAIWSMixedOwnerToolProvenance(t *testing.T) { + for _, kind := range []string{"function", "custom"} { + t.Run("phantom_"+kind, func(t *testing.T) { + runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, 2, "phantom_"+kind) + }) + } +} + +func TestOpenAIWSMixedOwnerToolProvenanceCases(t *testing.T) { + for _, kind := range []string{"function", "custom"} { + for _, change := range []string{"valid", "id", "type", "name", "args", "epoch"} { + t.Run(kind+"/"+change, func(t *testing.T) { + turn := 2 + if change == "valid" { + turn = 53 + } + runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, turn, "f1_"+kind+"_"+change) + }) + } + } +} + func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios ...string) { t.Helper() scenario := "live" if len(scenarios) > 0 { scenario = scenarios[0] } - negative := scenario != "live" && scenario != "fresh" && scenario != "binding_changed" + provenance := strings.HasPrefix(scenario, "f1_") + customProvenance := strings.HasPrefix(scenario, "f1_custom_") + provenancePositive := provenance && strings.HasSuffix(scenario, "_valid") + negative := scenario != "live" && scenario != "fresh" && scenario != "binding_changed" && !provenancePositive oldFence := strings.HasSuffix(scenario, "_first") || strings.HasSuffix(scenario, "_last") thirdItem := strings.ReplaceAll(httpRebuildAgentB, "fixture-readable-B", "fixture-old-completed-C") clients := issue805Redis(t) @@ -78,6 +104,9 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios switch { case n == 1: output = []json.RawMessage{json.RawMessage(httpRebuildAgentA), json.RawMessage(httpRebuildCall("apply_patch", "call_mixed_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))} + if customProvenance { + output = append(output, json.RawMessage(`{"type":"custom_tool_call","call_id":"fixture-custom-delivered","name":"inspect","input":"fixture read result"}`)) + } case n == 2: output = []json.RawMessage{json.RawMessage(httpRebuildAgentB)} case n == 3 && oldFence: @@ -162,9 +191,13 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } } }() + declarations := httpRebuildToolDefinitions() + if customProvenance { + declarations = append(declarations, map[string]any{"type": "custom", "name": "inspect", "description": "fixture inspection"}) + } create := func(input []string, previous string) string { body := map[string]any{"type": "response.create", "model": "gpt-5.1", "store": true, - "tools": httpRebuildToolDefinitions(), "input": json.RawMessage("[" + strings.Join(input, ",") + "]"), + "tools": declarations, "input": json.RawMessage("[" + strings.Join(input, ",") + "]"), "client_metadata": map[string]string{"thread_id": "fixture-mixed-thread"}} if previous != "" { body["previous_response_id"] = previous @@ -200,6 +233,17 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios history = append(history, item.Raw) } history = append(history, tools.execute(t, first)...) + customExecutions := 0 + if customProvenance { + for _, item := range first.Get("output").Array() { + if item.Get("type").String() == "custom_tool_call" { + require.Equal(t, "fixture read result", item.Get("input").String()) + customExecutions++ + history = append(history, `{"type":"custom_tool_call_output","call_id":"fixture-custom-delivered","output":"fixture custom completed once"}`) + } + } + require.Equal(t, 1, customExecutions) + } issue600Finish(t, h, headers) accounts.disable(1) dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) @@ -263,6 +307,10 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } } switch scenario { + case "phantom_function": + history = append(history, `{"type":"function_call","call_id":"fixture-never-delivered","name":"charge","arguments":"{\"invoice\":\"fixture\"}"}`, `{"type":"function_call_output","call_id":"fixture-never-delivered","output":"fixture phantom charged"}`) + case "phantom_custom": + history = append(history, `{"type":"custom_tool_call","call_id":"fixture-never-delivered","name":"charge","input":"fixture invoice"}`, `{"type":"custom_tool_call_output","call_id":"fixture-never-delivered","output":"fixture phantom charged"}`) case "unknown": history = append(history, thirdItem) case "unpaired_call": @@ -290,12 +338,81 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.NoError(t, dialErr) h.clientConn = conn } + if provenance && !provenancePositive { + change := strings.TrimPrefix(scenario, "f1_function_") + if customProvenance { + change = strings.TrimPrefix(scenario, "f1_custom_") + } + kind := "function_call" + if customProvenance { + kind = "custom_tool_call" + } + for i, raw := range history { + item := gjson.Parse(raw) + if item.Get("type").String() != kind && item.Get("type").String() != kind+"_output" { + continue + } + switch change { + case "id": + history[i], err = sjson.Set(raw, "call_id", "fixture-replaced-id") + case "type": + replacement := "custom_tool_call" + if customProvenance { + replacement = "function_call" + } + if strings.HasSuffix(item.Get("type").String(), "_output") { + replacement += "_output" + } + history[i], err = sjson.Set(raw, "type", replacement) + case "name": + if item.Get("type").String() == kind { + history[i], err = sjson.Set(raw, "name", "fixture-replaced-tool") + } + case "args": + if item.Get("type").String() == kind { + field := "arguments" + value := `{"path":"fixture-other"}` + if customProvenance { + field, value = "input", "fixture other input" + } + history[i], err = sjson.Set(raw, field, value) + } + } + require.NoError(t, err) + } + if change == "epoch" { + keys, keyErr := probe.Keys(context.Background(), "openai_agent_shadow_epoch:*").Result() + require.NoError(t, keyErr) + require.NotEmpty(t, keys) + for _, key := range keys { + require.NoError(t, probe.Set(context.Background(), key, "ready:pending:fixture-reassociated", time.Minute).Err()) + } + } + } owners = issue805Owners(t, probe) issue715WSSend(t, h.clientConn, create(history, previous)) resumed, resumeErr := read() mu.Lock() sends := len(frames) mu.Unlock() + if strings.HasPrefix(scenario, "phantom_") || (provenance && !provenancePositive) { + // Capture the actual upstream acceptance before asserting zero sends. + if sends > turn && strings.HasPrefix(scenario, "phantom_") { + mu.Lock() + wire := append([]byte(nil), frames[turn]...) + mu.Unlock() + require.Contains(t, string(wire), "fixture phantom charged") + require.Equal(t, "response.completed", gjson.GetBytes(resumed, "type").String()) + t.Log("F1_PHANTOM_PAIR_REACHED_UPSTREAM: authenticated handler projected an unissued matching tool pair") + } + require.Equal(t, turn, sends, "F1_UNTRUSTED_MATCHED_PAIR_DISPATCHED: opaque completed owners must not authorize a separately fabricated tool call") + require.Equal(t, "encrypted_agent_recovery_owner_conflict", gjson.GetBytes(resumed, "error.code").String()) + require.Equal(t, coderws.StatusPolicyViolation, coderws.CloseStatus(resumeErr)) + require.Equal(t, owners, issue805Owners(t, probe)) + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + return + } if negative { require.Equal(t, turn, sends, "unsafe history must produce zero extra generations") require.Equal(t, "error", gjson.GetBytes(resumed, "type").String(), "a setup EOF is not a refusal") @@ -356,7 +473,12 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios expectedIdentity = "Bearer fixture-mixed-C" } require.Equal(t, expectedIdentity, identities[turn+i]) - require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") + if customProvenance { + require.JSONEq(t, httpRebuildJSON(declarations), gjson.GetBytes(wire, "tools").Raw) + require.Equal(t, 1, strings.Count(string(wire), "fixture custom completed once")) + } else { + require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") + } require.Contains(t, string(wire), httpRebuildTask) require.Equal(t, 1, strings.Count(string(wire), httpRebuildPatch)) require.NotContains(t, string(wire), "fixture-opaque-A") From cc1a9e80223695684ad54ab0e9cf4f27c7991bf2 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:25:22 +0800 Subject: [PATCH 09/26] fix: require delivered tool provenance before WS history recovery --- .../scripts/prepare-ws-owner-red-fixtures.sh | 3 + .github/workflows/issue715-agent-recovery.yml | 4 +- .github/workflows/ws-tool-provenance.yml | 22 + .../handler/openai_ws_owner_conflict_test.go | 37 +- .../gateway_cache_tool_provenance.go | 91 ++++ .../service/openai_409_omit_history.go | 6 + .../service/openai_agent_message_delivery.go | 43 +- .../service/openai_agent_message_recovery.go | 14 +- .../service/openai_recovery_subreason.go | 2 +- .../service/openai_tool_provenance.go | 484 ++++++++++++++++++ .../service/openai_ws_agent_recovery.go | 6 + .../service/openai_ws_owner_conflict_test.go | 29 +- .../openai_ws_readable_continuation.go | 3 + 13 files changed, 719 insertions(+), 25 deletions(-) create mode 100644 backend/internal/repository/gateway_cache_tool_provenance.go create mode 100644 backend/internal/service/openai_tool_provenance.go diff --git a/.github/scripts/prepare-ws-owner-red-fixtures.sh b/.github/scripts/prepare-ws-owner-red-fixtures.sh index c1e57d2230eb..88b98e98326c 100644 --- a/.github/scripts/prepare-ws-owner-red-fixtures.sh +++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh @@ -12,6 +12,9 @@ fi for target in \ backend/internal/service/openai_409_omit_history.go \ + backend/internal/service/openai_tool_provenance.go \ + backend/internal/repository/gateway_cache_tool_provenance.go \ + backend/internal/service/openai_agent_message_delivery.go \ backend/internal/service/openai_ws_readable_continuation.go \ backend/internal/service/openai_409_readable_shadow.go \ backend/internal/service/openai_agent_message_recovery_error.go \ diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml index 2d1d085c497b..792337f7de0e 100644 --- a/.github/workflows/issue715-agent-recovery.yml +++ b/.github/workflows/issue715-agent-recovery.yml @@ -102,7 +102,7 @@ jobs: targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_gateway_response_handling.go backend/internal/service/openai_gateway_service.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go) added=(backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_recovery_cache.go backend/internal/service/openai_agent_message_delivery.go backend/internal/repository/gateway_cache_agent_recovery.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_agent_message_recovery_wait.go backend/internal/service/openai_ws_search_activation.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go) # The exact original gateway struct predates analysis admission state. - added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_agent_recovery_diagnostics.go) + added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_replay_metadata.go backend/internal/service/openai_agent_recovery_diagnostics.go backend/internal/service/openai_tool_provenance.go backend/internal/repository/gateway_cache_tool_provenance.go) handler_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a handler_leaf=backend/internal/handler/openai_agent_message_recovery.go error_leaf=backend/internal/service/openai_agent_message_recovery_error.go @@ -273,7 +273,7 @@ jobs: ws_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) # Neither helper exists on the restored historical socket structure. ws_added=(backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_search_activation.go) - ws_added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_recovery_diagnostics.go) + ws_added+=(backend/internal/service/openai_ws_readable_continuation.go backend/internal/service/openai_agent_recovery_diagnostics.go backend/internal/service/openai_tool_provenance.go backend/internal/repository/gateway_cache_tool_provenance.go) handler_compat=aa8e596e6d6f3e4648d6beba73b39b240dd5357a handler_leaf=backend/internal/handler/openai_agent_message_recovery.go error_leaf=backend/internal/service/openai_agent_message_recovery_error.go diff --git a/.github/workflows/ws-tool-provenance.yml b/.github/workflows/ws-tool-provenance.yml index e1d6bdb91b25..f9cbe611c8aa 100644 --- a/.github/workflows/ws-tool-provenance.yml +++ b/.github/workflows/ws-tool-provenance.yml @@ -72,11 +72,33 @@ jobs: test "$(git rev-parse HEAD)" = "$CANDIDATE" git diff --exit-code set +e + (cd backend && go test -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerToolProvenance$' -count=1 -json -timeout=3m) > "$RUNNER_TEMP/ws-provenance-evidence/first-green.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/ws-provenance-evidence/first-green.jsonl" + python3 .github/scripts/ws-tool-provenance-evidence.py GREEN "$status" "$RUNNER_TEMP/ws-provenance-evidence/first-green.jsonl" + set +e (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerToolProvenance$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-provenance-evidence/green.jsonl" 2>&1 status=$? set -e cat "$RUNNER_TEMP/ws-provenance-evidence/green.jsonl" python3 .github/scripts/ws-tool-provenance-evidence.py GREEN "$status" "$RUNNER_TEMP/ws-provenance-evidence/green.jsonl" + - name: Genuine delivery, mutations and task association + if: hashFiles('backend/internal/service/openai_tool_provenance.go') != '' + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerToolProvenanceCases$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-provenance-evidence/cases.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-provenance-evidence/cases.jsonl" + python3 - "$RUNNER_TEMP/ws-provenance-evidence/cases.jsonl" <<'PY' + import json,sys + rows=[json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] + for kind in ('function','custom'): + for case in ('valid','id','type','name','args','epoch','unrelated','undelivered'): + name=f'TestOpenAIWSMixedOwnerToolProvenanceCases/{kind}/{case}' + assert sum(r.get('Action')=='pass' and r.get('Test')==name for r in rows)==1,name + assert not any(r.get('Action') in ('fail','skip') for r in rows) + PY - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index c4bd822b4220..f28aeb4c032d 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -65,12 +65,15 @@ func TestOpenAIWSMixedOwnerToolProvenance(t *testing.T) { func TestOpenAIWSMixedOwnerToolProvenanceCases(t *testing.T) { for _, kind := range []string{"function", "custom"} { - for _, change := range []string{"valid", "id", "type", "name", "args", "epoch"} { + for _, change := range []string{"valid", "id", "type", "name", "args", "epoch", "unrelated", "undelivered"} { t.Run(kind+"/"+change, func(t *testing.T) { turn := 2 if change == "valid" { turn = 53 } + if change == "unrelated" || change == "undelivered" { + turn = 3 + } runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, turn, "f1_"+kind+"_"+change) }) } @@ -86,6 +89,14 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios provenance := strings.HasPrefix(scenario, "f1_") customProvenance := strings.HasPrefix(scenario, "f1_custom_") provenancePositive := provenance && strings.HasSuffix(scenario, "_valid") + unrelatedCall := provenance && strings.HasSuffix(scenario, "_unrelated") + undeliveredCall := provenance && strings.HasSuffix(scenario, "_undelivered") + foreignCall := `{"type":"function_call","call_id":"fixture-other-task-call","name":"inspect","arguments":"{}"}` + foreignOutput := `{"type":"function_call_output","call_id":"fixture-other-task-call","output":"fixture other result"}` + if customProvenance { + foreignCall = `{"type":"custom_tool_call","call_id":"fixture-other-task-call","name":"inspect","input":"fixture other task"}` + foreignOutput = `{"type":"custom_tool_call_output","call_id":"fixture-other-task-call","output":"fixture other result"}` + } negative := scenario != "live" && scenario != "fresh" && scenario != "binding_changed" && !provenancePositive oldFence := strings.HasSuffix(scenario, "_first") || strings.HasSuffix(scenario, "_last") thirdItem := strings.ReplaceAll(httpRebuildAgentB, "fixture-readable-B", "fixture-old-completed-C") @@ -109,6 +120,11 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } case n == 2: output = []json.RawMessage{json.RawMessage(httpRebuildAgentB)} + case n == 3 && (unrelatedCall || undeliveredCall): + output = []json.RawMessage{json.RawMessage(foreignCall)} + if unrelatedCall { + output = append(output, json.RawMessage(thirdItem)) + } case n == 3 && oldFence: output = []json.RawMessage{json.RawMessage(thirdItem)} case n == turn+1: @@ -116,8 +132,12 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios case n == turn+2: output = []json.RawMessage{json.RawMessage(httpRebuildMessage("assistant", "fixture mixed task complete"))} } - return []byte(httpRebuildJSON(map[string]any{"type": "response.completed", "response": map[string]any{ - "id": fmt.Sprintf("resp_mixed_%d", n), "status": "completed", "model": "gpt-5.1", "output": output, + event, status := "response.completed", "completed" + if n == 3 && undeliveredCall { + event, status = "response.failed", "failed" + } + return []byte(httpRebuildJSON(map[string]any{"type": event, "response": map[string]any{ + "id": fmt.Sprintf("resp_mixed_%d", n), "status": status, "model": "gpt-5.1", "output": output, "usage": map[string]int{"input_tokens": 5, "output_tokens": 3}, }})) } @@ -273,7 +293,11 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios raw, readErr := read() require.NoError(t, readErr) completed := gjson.GetBytes(raw, "response") - require.Equal(t, "completed", completed.Get("status").String()) + if warm == 2 && undeliveredCall { + require.Equal(t, "failed", completed.Get("status").String()) + } else { + require.Equal(t, "completed", completed.Get("status").String()) + } previous = completed.Get("id").String() if warm == 1 { history = append(history, completed.Get("output.0").Raw) @@ -281,7 +305,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } } expectedOwners := 2 - if oldFence { + if oldFence || unrelatedCall { expectedOwners++ } owners := waitOwners(expectedOwners) @@ -338,6 +362,9 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.NoError(t, dialErr) h.clientConn = conn } + if unrelatedCall || undeliveredCall { + history = append(history, foreignCall, foreignOutput) + } if provenance && !provenancePositive { change := strings.TrimPrefix(scenario, "f1_function_") if customProvenance { diff --git a/backend/internal/repository/gateway_cache_tool_provenance.go b/backend/internal/repository/gateway_cache_tool_provenance.go new file mode 100644 index 000000000000..5b47a8122514 --- /dev/null +++ b/backend/internal/repository/gateway_cache_tool_provenance.go @@ -0,0 +1,91 @@ +package repository + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/redis/go-redis/v9" +) + +func openAIToolProvenanceKeys(scope string) (string, string, error) { + key, index, err := openAIAgentShadowEpochKeys(scope) + return strings.Replace(key, "openai_agent_shadow_epoch:", "openai_tool_provenance:", 1), strings.Replace(index, "openai_agent_shadow_index:", "openai_tool_provenance_index:", 1), err +} + +// A call ID cannot be reissued by another delivery and inherit its old grant. +// Budget/TTL eviction loses recoverability, never creates proof. +var reserveOpenAIToolProvenance = redis.NewScript(` +local now = redis.call('TIME') +local millis = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) +local expired = redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', millis) +for _, key in ipairs(expired) do redis.call('DEL', key); redis.call('ZREM', KEYS[2], key) end +local old = redis.call('GET', KEYS[1]) +local ttl = math.max(tonumber(ARGV[2]), redis.call('PTTL', KEYS[1])) +if old == ARGV[1] then return 1 end +if not old then + while redis.call('ZCARD', KEYS[2]) >= 128 do + local oldest = redis.call('ZRANGE', KEYS[2], 0, 0) + redis.call('DEL', oldest[1]); redis.call('ZREM', KEYS[2], oldest[1]) + end +end +local value = ARGV[1] +if old then value = 'conflict' end +redis.call('SET', KEYS[1], value, 'PX', ttl) +redis.call('ZADD', KEYS[2], millis + ttl, KEYS[1]) +redis.call('PEXPIRE', KEYS[2], math.max(ttl, redis.call('PTTL', KEYS[2]))) +return 1 +`) + +var finishOpenAIToolProvenance = redis.NewScript(` +if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end +local value = 'failed' +if ARGV[3] == '1' then value = ARGV[2] end +local ttl = math.max(tonumber(ARGV[4]), redis.call('PTTL', KEYS[1])) +redis.call('SET', KEYS[1], value, 'PX', ttl) +local now = redis.call('TIME') +local millis = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) +redis.call('ZADD', KEYS[2], millis + ttl, KEYS[1]) +redis.call('PEXPIRE', KEYS[2], math.max(ttl, redis.call('PTTL', KEYS[2]))) +return 1 +`) + +func (c *gatewayCache) GetOpenAIToolProvenance(ctx context.Context, scope string) (string, error) { + key, _, err := openAIToolProvenanceKeys(scope) + if err != nil { + return "", err + } + value, err := c.rdb.Get(ctx, key).Result() + if errors.Is(err, redis.Nil) { + return "", nil + } + return value, err +} +func (c *gatewayCache) ReserveOpenAIToolProvenance(ctx context.Context, scope, token string, ttl time.Duration) error { + key, index, err := openAIToolProvenanceKeys(scope) + if err != nil { + return err + } + if !strings.HasPrefix(token, "pending:") || len(token) > 1024 || ttl <= 0 { + return errors.New("invalid tool provenance reservation") + } + return reserveOpenAIToolProvenance.Run(ctx, c.rdb, []string{key, index}, token, min(ttl, service.OpenAIReadableShadowTTL).Milliseconds()).Err() +} +func (c *gatewayCache) FinishOpenAIToolProvenance(ctx context.Context, scope, token, record string, completed bool, ttl time.Duration) error { + key, index, err := openAIToolProvenanceKeys(scope) + if err != nil { + return err + } + if !strings.HasPrefix(token, "pending:") || len(token) > 1024 || len(record) > service.OpenAIToolProvenanceMaxBytes || ttl <= 0 { + return errors.New("invalid tool provenance completion") + } + flag := 0 + if completed { + flag = 1 + } + return finishOpenAIToolProvenance.Run(ctx, c.rdb, []string{key, index}, token, record, flag, min(ttl, service.OpenAIReadableShadowTTL).Milliseconds()).Err() +} + +var _ service.OpenAIToolProvenanceCache = (*gatewayCache)(nil) diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 8294ea9c93f3..72028694f9d8 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -83,6 +83,11 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c if !openAI409HasReadableIntent(body) { return ctx, body, false, openAIRecoveryDiagnosticError("readable_intent_missing", "readable_intent_missing", r) } + if websocket { + if err := s.verifyOpenAIToolInputs(ctx, r, body); err != nil { + return ctx, body, false, err + } + } clean, changed := omitOpenAIHistoricalCiphertext(body) if ctx.Err() != nil { return ctx, body, false, openAIAgentRecoveryError("store_unavailable") @@ -117,6 +122,7 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c request.inputDigest = openAIAgentRecoveryInputDigest(clean) request.replayControlsDigest = openAI409ControlsDigest(clean) request.omittedSource = r + request.toolProofs = r.toolProofs return next, clean, true, nil } diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index cd8123084bed..f2c50854e5ad 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -31,18 +31,27 @@ type OpenAIAgentRecoveryEpochCache interface { } type openAIAgentRecoveryDelivery struct { - service *OpenAIGatewayService - ctx context.Context - request *openAIAgentRecoveryRequest - binding openAIAgentRecoveryBinding - pending string - keys map[[32]byte]bool - epochs map[string]bool - once sync.Once + service *OpenAIGatewayService + ctx context.Context + request *openAIAgentRecoveryRequest + binding openAIAgentRecoveryBinding + pending string + keys map[[32]byte]bool + epochs map[string]bool + once sync.Once + tools map[string]openAIToolObservation + toolTerminal, toolInvalid, toolAnchorsValid, toolEnabled bool + toolAnchors map[string]openAIToolAnchor } func newOpenAIAgentRecoveryDelivery(s *OpenAIGatewayService, ctx context.Context, r *openAIAgentRecoveryRequest, b openAIAgentRecoveryBinding) *openAIAgentRecoveryDelivery { - return &openAIAgentRecoveryDelivery{service: s, ctx: ctx, request: r, binding: b, pending: "pending:" + uuid.NewString() + ":" + encodeOpenAIAgentRecoveryBinding(b), keys: make(map[[32]byte]bool), epochs: make(map[string]bool)} + enabled := r.userID > 0 && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) + var anchors map[string]openAIToolAnchor + valid := false + if enabled { + anchors, valid = s.toolInputAnchors(ctx, r) + } + return &openAIAgentRecoveryDelivery{toolEnabled: enabled, toolAnchors: anchors, toolAnchorsValid: valid, service: s, ctx: ctx, request: r, binding: b, pending: "pending:" + uuid.NewString() + ":" + encodeOpenAIAgentRecoveryBinding(b), keys: make(map[[32]byte]bool), epochs: make(map[string]bool)} } func (s *OpenAIGatewayService) awaitOpenAIAgentRecovery(ctx context.Context, shared OpenAIAgentRecoveryCache, state *openAIAgentRecoveryState, key [32]byte) (openAIAgentRecoveryBinding, bool, error) { @@ -107,6 +116,10 @@ func (d *openAIAgentRecoveryDelivery) reserve(items [][32]byte) error { return openAIAgentRecoveryError("store_unavailable") } } + if d.service.cache == nil && d.toolEnabled && !d.epochs[epochKey] { + d.epochs[epochKey] = true + d.service.localToolEpoch(epochKey, d.pending, false, false) + } if (d.request.disableOwnerBinding || d.request.omitted400History) && d.request.known[key] { // An echoed completed input is still its original producer's item. // Never reserve/publish it as the account consuming this history. @@ -211,6 +224,18 @@ func (d *openAIAgentRecoveryDelivery) finish(completed bool) { _ = shared.FinishOpenAIAgentRecoveryEpoch(ctx, key, d.pending, eligible[key], d.service.openAIWSSessionStickyTTL()) } } + if d.service.cache == nil && d.toolEnabled { + eligible := make(map[string]bool) + if completed { + for _, item := range d.request.outputs { + eligible[d.request.shadowEpochKey(item)] = true + } + } + for key := range d.epochs { + d.service.localToolEpoch(key, d.pending, true, eligible[key]) + } + } + d.finishTools(ctx, completed) }) } diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 504bdc300d5c..d93d5223fdf4 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -41,8 +41,10 @@ type openAIAgentRecoveryBinding struct { } type openAIAgentRecoveryState struct { - mu sync.Mutex - bindings map[[32]byte]openAIAgentRecoveryBinding + mu sync.Mutex + bindings map[[32]byte]openAIAgentRecoveryBinding + toolProofs map[string]openAIToolLocalRecord + toolEpochs map[string]openAIToolLocalRecord } type openAIAgentRecoveryRequest struct { @@ -89,6 +91,7 @@ type openAIAgentRecoveryRequest struct { model string session string + toolProofs map[string]openAIToolProofSnapshot diagnostics openAIRecoveryDiagnostics completedOwners map[[32]byte]openAIAgentRecoveryBinding requireCompletedOwners bool // mixed WS omission retains each original completed route @@ -428,6 +431,9 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con if err := s.checkOpenAIReadableShadowObservation(ctx, request.shadowObservation); err != nil { return noop, withOpenAIRecoveryDiagnostics(err, request, "") } + if err := s.recheckOpenAIToolProofs(ctx, request); err != nil { + return noop, err + } if request.omittedSource != nil { // Re-read every original item at the actual send, even though opaque // bytes were removed. Losing history must not lose a delivery fence. @@ -665,9 +671,7 @@ func observeOpenAIAgentRecoveryOutput(c *gin.Context, body []byte, nested bool) request.shadowUnsafeOutput = request.shadowUnsafeOutput || (kind != "agent_message" && kind != "message" && kind != "reasoning") } } - if !bytes.Contains(body, []byte("agent_message")) && !bytes.Contains(body, []byte(`\u`)) { - return nil - } + request.delivery.observeTools(body, nested) items := openAIAgentRecoveryDigests(body, path) // Even an early item/response event can already contain the entire opaque // item. Fence it before any bytes are released, without granting success. diff --git a/backend/internal/service/openai_recovery_subreason.go b/backend/internal/service/openai_recovery_subreason.go index d981c35723bc..7dc0f4f548fb 100644 --- a/backend/internal/service/openai_recovery_subreason.go +++ b/backend/internal/service/openai_recovery_subreason.go @@ -6,7 +6,7 @@ func OpenAIRecoverySubreason(value string) string { return safeOpenAIRecoverySub func safeOpenAIRecoverySubreason(value string) string { switch value { - case "mixed_completed_owners", "owner_record_conflicted", "owner_record_pending", "owner_record_failed", + case "tool_provenance_unknown", "tool_provenance_unavailable", "tool_provenance_changed", "tool_provenance_task_changed", "mixed_completed_owners", "owner_record_conflicted", "owner_record_pending", "owner_record_failed", "owner_delivery_unknown", "owner_route_changed", "owner_record_changed", "owner_lookup_unavailable", "tool_invalid", "tool_incomplete", "tool_duplicate", "tool_unpaired", "tool_history_unsupported", "shadow_record_changed", "shadow_epoch_changed", "shadow_fence_changed", "shadow_fence_invalid", diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go new file mode 100644 index 000000000000..953b65644f6c --- /dev/null +++ b/backend/internal/service/openai_tool_provenance.go @@ -0,0 +1,484 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "strings" + "time" + + "github.com/tidwall/gjson" +) + +// Only hashes and delivery/route metadata; never tool arguments/results. A +// separate bounded namespace prevents client history from minting call grants. +const OpenAIToolProvenanceMaxBytes = 32 * 1024 + +type OpenAIToolProvenanceCache interface { + GetOpenAIToolProvenance(context.Context, string) (string, error) + ReserveOpenAIToolProvenance(context.Context, string, string, time.Duration) error + FinishOpenAIToolProvenance(context.Context, string, string, string, bool, time.Duration) error +} + +type openAIToolAnchor struct { + Owner string `json:"owner"` + EpochKey string `json:"epoch_key,omitempty"` + Epoch string `json:"epoch,omitempty"` +} + +type openAIToolProof struct { + Version int `json:"version"` + Call string `json:"call"` + Producer string `json:"producer"` + Delivery string `json:"delivery"` + Anchors map[string]openAIToolAnchor `json:"anchors"` + ShadowPrincipal string `json:"shadow_principal,omitempty"` + ShadowTask string `json:"shadow_task,omitempty"` + ShadowDigest string `json:"shadow_digest,omitempty"` + ShadowEpoch string `json:"shadow_epoch,omitempty"` +} + +type openAIToolObservation struct { + fingerprint string + complete bool +} + +type openAIToolProofSnapshot struct { + raw string + proof openAIToolProof +} + +type openAIToolLocalRecord struct { + raw string + until time.Time +} + +func openAIToolHash(value any) string { + raw, _ := json.Marshal(value) + digest := sha256.Sum256(raw) + return hex.EncodeToString(digest[:]) +} + +func (r *openAIAgentRecoveryRequest) toolKey(id string) string { + return r.shadowPrincipal() + ":" + openAIToolHash([]any{"tool-v1", r.userID, r.keyID, r.groupID, r.session, r.model, r.shadowModel, id}) +} + +func openAIToolFingerprint(item gjson.Result) (string, bool) { + kind := item.Get("type").String() + if kind != "function_call" && kind != "custom_tool_call" { + return "", false + } + for _, field := range []string{"call_id", "name"} { + if item.Get(field).Type != gjson.String || strings.TrimSpace(item.Get(field).String()) == "" { + return "", false + } + } + if item.Get("status").Exists() && item.Get("status").String() != "completed" { + return "", false + } + field := "arguments" + if kind == "custom_tool_call" { + field = "input" + } + if item.Get(field).Type != gjson.String { + return "", false + } + // Preserve exact argument/input bytes and every semantic extension. Only + // provider item IDs/status are replay metadata; call_id is always bound. + var fields map[string]json.RawMessage + if json.Unmarshal([]byte(item.Raw), &fields) != nil { + return "", false + } + delete(fields, "id") + delete(fields, "status") + return openAIToolHash(fields), true +} + +func (s *OpenAIGatewayService) toolProofGet(ctx context.Context, key string) (string, error) { + if cache, ok := s.cache.(OpenAIToolProvenanceCache); ok { + return cache.GetOpenAIToolProvenance(ctx, key) + } + if s.cache != nil { + return "", openAIAgentRecoveryError("store_unavailable") + } + s.agentMessageRecovery.mu.Lock() + defer s.agentMessageRecovery.mu.Unlock() + r := s.agentMessageRecovery.toolProofs[key] + if time.Now().After(r.until) { + return "", nil + } + return r.raw, nil +} + +func (s *OpenAIGatewayService) toolProofReserve(ctx context.Context, key, token string) error { + if cache, ok := s.cache.(OpenAIToolProvenanceCache); ok { + return cache.ReserveOpenAIToolProvenance(ctx, key, token, OpenAIReadableShadowTTL) + } + if s.cache != nil { + return openAIAgentRecoveryError("store_unavailable") + } + s.agentMessageRecovery.mu.Lock() + defer s.agentMessageRecovery.mu.Unlock() + state := &s.agentMessageRecovery + if state.toolProofs == nil { + state.toolProofs = make(map[string]openAIToolLocalRecord) + } + for k, v := range state.toolProofs { + if time.Now().After(v.until) { + delete(state.toolProofs, k) + } + } + if len(state.toolProofs) >= 128 { + return openAIAgentRecoveryError("store_unavailable") + } + old := state.toolProofs[key] + if old.raw != "" && old.raw != token { + token = "conflict" + } + state.toolProofs[key] = openAIToolLocalRecord{raw: token, until: time.Now().Add(OpenAIReadableShadowTTL)} + return nil +} + +func (s *OpenAIGatewayService) toolProofFinish(ctx context.Context, key, token, record string, completed bool) { + if cache, ok := s.cache.(OpenAIToolProvenanceCache); ok { + _ = cache.FinishOpenAIToolProvenance(ctx, key, token, record, completed, OpenAIReadableShadowTTL) + return + } + if s.cache != nil { + return + } + s.agentMessageRecovery.mu.Lock() + defer s.agentMessageRecovery.mu.Unlock() + old := s.agentMessageRecovery.toolProofs[key] + if old.raw != token || time.Now().After(old.until) { + return + } + old.raw = "failed" + if completed { + old.raw = record + } + s.agentMessageRecovery.toolProofs[key] = old +} + +// The no-shared-cache mode still needs association epochs. It never falls back +// after an error from a configured shared store. +func (s *OpenAIGatewayService) toolEpoch(ctx context.Context, key string) (string, error) { + if epochs, ok := s.cache.(OpenAIAgentRecoveryEpochCache); ok { + return epochs.GetOpenAIAgentRecoveryEpoch(ctx, key) + } + if s.cache != nil { + return "", openAIAgentRecoveryError("store_unavailable") + } + s.agentMessageRecovery.mu.Lock() + defer s.agentMessageRecovery.mu.Unlock() + record := s.agentMessageRecovery.toolEpochs[key] + if time.Now().After(record.until) { + return "", nil + } + return record.raw, nil +} + +func (s *OpenAIGatewayService) localToolEpoch(key, token string, finish, completed bool) { + s.agentMessageRecovery.mu.Lock() + defer s.agentMessageRecovery.mu.Unlock() + state := &s.agentMessageRecovery + if state.toolEpochs == nil { + state.toolEpochs = make(map[string]openAIToolLocalRecord) + } + for k, v := range state.toolEpochs { + if time.Now().After(v.until) { + delete(state.toolEpochs, k) + } + } + old := state.toolEpochs[key] + value := token + if finish { + if old.raw != token { + return + } + value = "failed" + if completed { + value = "ready:" + token + } + } else { + if len(state.toolEpochs) >= 128 && old.raw == "" { + return + } + if old.raw == "conflict" || (strings.HasPrefix(old.raw, "pending:") && old.raw != token) { + value = "conflict" + } + } + state.toolEpochs[key] = openAIToolLocalRecord{raw: value, until: time.Now().Add(OpenAIReadableShadowTTL)} +} + +// Snapshot the original task associations before a generation is sent. Missing +// provenance loses future recovery availability, not the ordinary generation. +func (s *OpenAIGatewayService) toolInputAnchors(ctx context.Context, r *openAIAgentRecoveryRequest) (map[string]openAIToolAnchor, bool) { + anchors := make(map[string]openAIToolAnchor) + for source := r; source != nil; source = source.omittedSource { + for _, key := range source.keys { + binding, ok := source.completedOwners[key] + if !ok { + return nil, false + } + anchor := openAIToolAnchor{Owner: encodeOpenAIAgentRecoveryBinding(binding)} + for i, k := range source.keys { + if k == key { + anchor.EpochKey = source.shadowEpochKey(source.items[i]) + break + } + } + var err error + anchor.Epoch, err = s.toolEpoch(ctx, anchor.EpochKey) + if err != nil || !strings.HasPrefix(anchor.Epoch, "ready:pending:") { + return nil, false + } + encoded := hex.EncodeToString(key[:]) + if old, exists := anchors[encoded]; exists && old != anchor { + return nil, false + } + anchors[encoded] = anchor + } + } + if len(anchors) > 64 { + return nil, false + } + return anchors, true +} + +func (s *OpenAIGatewayService) checkToolAnchors(ctx context.Context, anchors map[string]openAIToolAnchor) error { + if len(anchors) == 0 || len(anchors) > 64 { + return openAIAgentRecoveryError("owner_conflict") + } + for key, anchor := range anchors { + var raw string + if store, ok := s.cache.(OpenAIAgentRecoveryCache); ok { + var err error + raw, err = store.GetOpenAIAgentRecovery(ctx, key) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + } else if s.cache == nil { + decoded, err := hex.DecodeString(key) + if err != nil || len(decoded) != 32 { + return openAIAgentRecoveryError("owner_conflict") + } + var digest [32]byte + copy(digest[:], decoded) + s.agentMessageRecovery.mu.Lock() + b, found := s.agentMessageRecovery.bindings[digest] + s.agentMessageRecovery.mu.Unlock() + if !found || time.Now().After(b.expiresAt) || b.failed || b.conflicted || b.pending != "" { + return openAIAgentRecoveryError("owner_conflict") + } + raw = encodeOpenAIAgentRecoveryBinding(b) + } else { + return openAIAgentRecoveryError("store_unavailable") + } + if raw != anchor.Owner { + return openAIAgentRecoveryError("owner_conflict") + } + if anchor.EpochKey == "" { + return openAIAgentRecoveryError("owner_conflict") + } + epoch, err := s.toolEpoch(ctx, anchor.EpochKey) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + if epoch != anchor.Epoch || !strings.HasPrefix(epoch, "ready:pending:") { + return openAIAgentRecoveryError("owner_conflict") + } + } + return nil +} + +// Called on the final CLIENT representation before its physical write. A done +// item reserves identity but only a successfully delivered terminal can commit. +func (d *openAIAgentRecoveryDelivery) observeTools(body []byte, nested bool) { + r := d.request + if !d.toolEnabled || r.keyID <= 0 { + return + } + if d.tools == nil { + d.tools = make(map[string]openAIToolObservation) + } + path := "output" + if nested { + path = "response.output" + } + items := gjson.GetBytes(body, path).Array() + if nested && gjson.GetBytes(body, "item").IsObject() { + items = append(items, gjson.GetBytes(body, "item")) + } + terminal := openAIAgentCompletedResponse(body, nested) + if terminal { + d.toolTerminal = true + } + for _, item := range items { + kind := item.Get("type").String() + if kind != "function_call" && kind != "custom_tool_call" { + continue + } + id := item.Get("call_id") + if id.Type != gjson.String || id.String() == "" || len(d.tools) >= 64 { + d.toolInvalid = true + continue + } + key := r.toolKey(id.String()) + old, exists := d.tools[key] + if !exists { + if d.service.toolProofReserve(d.ctx, key, d.pending) != nil { + d.toolInvalid = true + } + } + complete := terminal || (nested && gjson.GetBytes(body, "type").String() == "response.output_item.done") + fingerprint, valid := openAIToolFingerprint(item) + if complete && !valid { + d.toolInvalid = true + } + if complete && old.complete && old.fingerprint != fingerprint { + d.toolInvalid = true + } + if complete { + old = openAIToolObservation{fingerprint: fingerprint, complete: valid} + } + d.tools[key] = old + } +} + +func (d *openAIAgentRecoveryDelivery) finishTools(ctx context.Context, completed bool) { + if len(d.tools) == 0 { + return + } + anchors := make(map[string]openAIToolAnchor) + for key, anchor := range d.toolAnchors { + anchors[key] = anchor + } + for _, item := range d.request.outputs { + key := d.request.itemKey(item) + if !d.keys[key] { + continue + } + anchor := openAIToolAnchor{Owner: encodeOpenAIAgentRecoveryBinding(d.binding)} + anchor.EpochKey = d.request.shadowEpochKey(item) + anchor.Epoch = "ready:" + d.pending + anchors[hex.EncodeToString(key[:])] = anchor + } + valid := completed && d.toolTerminal && !d.toolInvalid && d.toolAnchorsValid && d.service.checkToolAnchors(ctx, anchors) == nil + if d.request.shadowObservation != nil && d.service.checkOpenAIReadableShadowObservation(ctx, d.request.shadowObservation) != nil { + valid = false + } + for key, call := range d.tools { + proof := openAIToolProof{Version: 1, Call: call.fingerprint, Producer: encodeOpenAIAgentRecoveryBinding(d.binding), Delivery: openAIToolHash(d.pending), Anchors: anchors} + if shadow := d.request.shadowObservation; shadow != nil { + proof.ShadowPrincipal, proof.ShadowTask = shadow.principal, shadow.task + proof.ShadowDigest, proof.ShadowEpoch = openAIToolHash(shadow.raw), shadow.epoch + } + raw, _ := json.Marshal(proof) + d.service.toolProofFinish(ctx, key, d.pending, string(raw), valid && call.complete && len(raw) <= OpenAIToolProvenanceMaxBytes) + } +} + +func (s *OpenAIGatewayService) checkToolProof(ctx context.Context, proof openAIToolProof) error { + if proof.Version != 1 || proof.Call == "" || proof.Producer == "" || proof.Delivery == "" { + return openAIAgentRecoveryError("owner_conflict") + } + if err := s.checkToolAnchors(ctx, proof.Anchors); err != nil { + return err + } + if proof.ShadowTask != "" { + store, ok := s.cache.(OpenAIReadableShadowCache) + epochs, hasEpoch := s.cache.(OpenAIAgentRecoveryEpochCache) + if !ok || !hasEpoch { + return openAIAgentRecoveryError("store_unavailable") + } + raw, err := store.GetOpenAIReadableShadow(ctx, proof.ShadowPrincipal, proof.ShadowTask) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + epoch, err := epochs.GetOpenAIAgentRecoveryEpoch(ctx, proof.ShadowPrincipal+":"+proof.ShadowTask) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + if openAIToolHash(raw) != proof.ShadowDigest || epoch != proof.ShadowEpoch { + return openAIAgentRecoveryError("owner_conflict") + } + } + return nil +} + +func (s *OpenAIGatewayService) verifyOpenAIToolInputs(ctx context.Context, r *openAIAgentRecoveryRequest, body []byte) error { + if _, reason := inspectOpenAIWSCompletedTools(body); reason != "" { + return openAIRecoveryDiagnosticError("owner_conflict", reason, r) + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + available := make(map[string]bool) + for _, key := range r.keys { + available[hex.EncodeToString(key[:])] = true + } + for key := range r.shadowFences { + available[key] = true + } + for _, item := range gjson.GetBytes(body, "input").Array() { + kind := item.Get("type").String() + if kind != "function_call" && kind != "custom_tool_call" { + continue + } + fingerprint, ok := openAIToolFingerprint(item) + if !ok || r.userID <= 0 { + return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) + } + key := r.toolKey(item.Get("call_id").String()) + raw, err := s.toolProofGet(ctx, key) + for err == nil && strings.HasPrefix(raw, "pending:") { + timer := time.NewTimer(5 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) + case <-timer.C: + } + raw, err = s.toolProofGet(ctx, key) + } + if err != nil { + return openAIRecoveryDiagnosticError("store_unavailable", "tool_provenance_unavailable", r) + } + var proof openAIToolProof + if len(raw) > OpenAIToolProvenanceMaxBytes || json.Unmarshal([]byte(raw), &proof) != nil || proof.Call != fingerprint { + return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r) + } + for anchor := range proof.Anchors { + if !available[anchor] { + return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_task_changed", r) + } + } + if err := s.checkToolProof(ctx, proof); err != nil { + return withOpenAIRecoveryDiagnostics(err, r, "tool_provenance_changed") + } + if r.toolProofs == nil { + r.toolProofs = make(map[string]openAIToolProofSnapshot) + } + r.toolProofs[key] = openAIToolProofSnapshot{raw: raw, proof: proof} + } + return nil +} + +func (s *OpenAIGatewayService) recheckOpenAIToolProofs(ctx context.Context, r *openAIAgentRecoveryRequest) error { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + for key, snapshot := range r.toolProofs { + raw, err := s.toolProofGet(ctx, key) + if err != nil { + return openAIRecoveryDiagnosticError("store_unavailable", "tool_provenance_unavailable", r) + } + if raw != snapshot.raw { + return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_changed", r) + } + if err := s.checkToolProof(ctx, snapshot.proof); err != nil { + return withOpenAIRecoveryDiagnostics(err, r, "tool_provenance_changed") + } + } + return nil +} diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index 450651529144..173cb81ec8bc 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -296,6 +296,12 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, // check refuses the send. The initial warmup context cannot replace it. r.preventReplay() } + if r.request.lookupErr != nil { + return r.request.lookupErr + } + if r.request.conflict { + return openAIRecoveryDiagnosticError("owner_conflict", r.request.diagnostics.subreason, r.request) + } for _, key := range r.request.keys { if r.known[key] && !r.request.known[key] { return &openAIWSLostOwnerEvidenceError{cause: openAIAgentRecoveryError("owner_unavailable")} diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go index fbf2e401dad8..076dbd42df3a 100644 --- a/backend/internal/service/openai_ws_owner_conflict_test.go +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -20,14 +20,31 @@ import ( "go.uber.org/zap/zaptest/observer" ) +// Calls are learned only from the real response observer and successful write +// completion; the client input below cannot populate the proof store. +func learnF1DeliveredCalls(t *testing.T, svc *OpenAIGatewayService, account *Account, opaque, call string) { + t.Helper() + manager, c, _ := issue715WSManager(t, svc, context.Background()) + SetOpenAIWSRecoveryPrincipal(c, 715, 715) + defer manager.abort() + source := `{"model":"gpt-6-astra","input":[{"role":"user","content":"fixture trusted task"}]}` + require.NoError(t, issue715WSBegin(t, manager, account, source, "ctx_pool")) + terminal := `{"type":"response.completed","response":{"id":"resp_fixture_tool_` + gjson.Parse(call).Get("call_id").String() + `","status":"completed","output":[` + gjson.Get(opaque, "input.0").Raw + `,` + call + `]}}` + require.NoError(t, manager.write([]byte(terminal), func() error { return nil })) + key := manager.request.toolKey(gjson.Parse(call).Get("call_id").String()) + raw, err := svc.toolProofGet(context.Background(), key) + require.NoError(t, err) + require.True(t, json.Valid([]byte(raw)), "only completed downstream delivery commits a call proof") +} + func TestOpenAIWSMixedOwnerFinalSendFences(t *testing.T) { - for _, mutation := range []string{"none", "pending", "failed", "conflicted", "missing", "changed", "input", "tools"} { + for _, mutation := range []string{"none", "pending", "failed", "conflicted", "missing", "changed", "input", "tools", "call_proof"} { t.Run(mutation, func(t *testing.T) { svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} a, b := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} other := strings.ReplaceAll(issue715OpaqueBody, "fixture-opaque-reference", "fixture-other-owner") - issue715LearnRoute(t, svc, a, issue715OpaqueBody) - issue715LearnRoute(t, svc, b, other) + learnF1DeliveredCalls(t, svc, a, issue715OpaqueBody, `{"type":"function_call","name":"apply_patch","call_id":"fixture-first","arguments":"{}"}`) + learnF1DeliveredCalls(t, svc, b, other, `{"type":"custom_tool_call","name":"exec","call_id":"fixture-second","input":"fixture command"}`) body := []byte(`{"model":"gpt-6-astra","tools":[{"type":"function","name":"inspect","parameters":{"type":"object","properties":{}}}],"input":[{"role":"user","content":"continue the supplied task"},` + gjson.Get(issue715OpaqueBody, "input.0").Raw + `,` + gjson.Get(other, "input.0").Raw + `, {"type":"function_call","name":"apply_patch","call_id":"fixture-first","arguments":"{}"}, {"type":"function_call_output","call_id":"fixture-first","output":"fixture patch completed once"}, @@ -35,6 +52,7 @@ func TestOpenAIWSMixedOwnerFinalSendFences(t *testing.T) { {"type":"custom_tool_call_output","call_id":"fixture-second","output":"fixture command completed once"}]}`) c, _ := newTurnStateTestContext(t, 715, "fixture-session") c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + SetOpenAIWSRecoveryPrincipal(c, 715, 715) ctx := svc.WithOpenAIWSAgentRecovery(context.Background(), c, body, "fixture-session", "gpt-6-astra") next, clean, changed, err := svc.RebuildOpenAIWSUnsentTurn(ctx, c, body, "fixture-session", "gpt-6-astra") require.NoError(t, err) @@ -63,6 +81,11 @@ func TestOpenAIWSMixedOwnerFinalSendFences(t *testing.T) { clean, err = sjson.SetBytes(clean, "input.0.content", "fixture mutated input") case "tools": clean, err = sjson.SetBytes(clean, "tools.0.name", "fixture changed schema") + case "call_proof": + for proofKey, record := range svc.agentMessageRecovery.toolProofs { + record.raw = "conflict" + svc.agentMessageRecovery.toolProofs[proofKey] = record + } } require.NoError(t, err) svc.agentMessageRecovery.bindings[key] = binding diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index 858880f0c3da..21d4926f8da0 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -269,6 +269,9 @@ func (s *OpenAIGatewayService) RebuildOpenAIWSUnsentTurn(ctx context.Context, c return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") } } + if err := s.verifyOpenAIToolInputs(next, r, body); err != nil { + return ctx, body, false, err + } clean, err := prepareOpenAI409ReadableReplay(body) if err != nil { return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") From 1dd7930bc8f7c915d5356f21fde26e182704751d Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:29:01 +0800 Subject: [PATCH 10/26] test: prove tool delivery lifecycle and restored shadow provenance --- .github/workflows/ws-tool-provenance.yml | 28 ++++-- .../handler/openai_409_ws_audit_test.go | 21 ++++- .../handler/openai_ws_owner_conflict_test.go | 89 ++++++++++++++++++- .../service/openai_agent_message_delivery.go | 1 + .../service/openai_tool_provenance.go | 13 ++- .../service/openai_ws_owner_conflict_test.go | 78 ++++++++++++++++ docs/ws-mixed-owner-continuation.md | 16 +++- 7 files changed, 231 insertions(+), 15 deletions(-) diff --git a/.github/workflows/ws-tool-provenance.yml b/.github/workflows/ws-tool-provenance.yml index f9cbe611c8aa..7bec864cd80f 100644 --- a/.github/workflows/ws-tool-provenance.yml +++ b/.github/workflows/ws-tool-provenance.yml @@ -16,7 +16,7 @@ permissions: jobs: behavior: - runs-on: macos-15-intel + runs-on: ubuntu-latest timeout-minutes: 45 env: CANDIDATE: ${{ github.event.pull_request.head.sha }} @@ -31,11 +31,12 @@ jobs: go-version-file: backend/go.mod cache-dependency-path: backend/go.sum - name: Install isolated Redis - env: - HOMEBREW_NO_AUTO_UPDATE: '1' - HOMEBREW_NO_INSTALL_CLEANUP: '1' run: | - if ! command -v redis-server >/dev/null; then brew install redis; fi + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi - name: Real handler RED against exact production blobs shell: bash run: | @@ -99,6 +100,23 @@ jobs: assert sum(r.get('Action')=='pass' and r.get('Test')==name for r in rows)==1,name assert not any(r.get('Action') in ('fail','skip') for r in rows) PY + - name: Shadow provenance and delivery lifecycle + if: hashFiles('backend/internal/service/openai_tool_provenance.go') != '' + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSShadowToolProvenance$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-provenance-evidence/shadow.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-provenance-evidence/shadow.jsonl" + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/service -run '^Test(OpenAIToolProvenanceDeliveryAndScope|OpenAIWSMixedOwnerFinalSendFences)$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-provenance-evidence/delivery.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-provenance-evidence/delivery.jsonl" + python3 - "$RUNNER_TEMP/ws-provenance-evidence" <<'PY' + import json,sys,pathlib + root=pathlib.Path(sys.argv[1]) + for filename,tests in [('shadow.jsonl',{f'TestOpenAIWSShadowToolProvenance/{kind}/{case}' for kind in ('function','custom') for case in ('valid','phantom','epoch')}),('delivery.jsonl',{'TestOpenAIToolProvenanceDeliveryAndScope','TestOpenAIWSMixedOwnerFinalSendFences'})]: + rows=[json.loads(line) for line in (root/filename).read_text().splitlines() if line.startswith('{')] + for name in tests: assert sum(r.get('Action')=='pass' and r.get('Test')==name for r in rows)==1,name + assert not any(r.get('Action') in ('fail','skip') for r in rows) + PY - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_409_ws_audit_test.go b/backend/internal/handler/openai_409_ws_audit_test.go index 78e596d18503..51c33db55004 100644 --- a/backend/internal/handler/openai_409_ws_audit_test.go +++ b/backend/internal/handler/openai_409_ws_audit_test.go @@ -120,7 +120,10 @@ func runRecoveredWSAudit(t *testing.T, mode, policy string, allowRecovery bool) output := recoveredWSAuditAgent id := "resp_audit_A" if r.Header.Get("Authorization") == "Bearer fixture-audit-A" { - writesA.Add(1) + if writesA.Add(1) == 1 { + output = strings.ReplaceAll(recoveredWSAuditAgent, "exact-task", "call-source") + `,{"type":"function_call","name":"inspect","call_id":"call_audit_done","arguments":"{}"}` + id = "resp_audit_call_source" + } } else { writesB.Add(1) bBodyMu.Lock() @@ -212,7 +215,17 @@ func runRecoveredWSAudit(t *testing.T, mode, policy string, allowRecovery bool) create := func(input string) string { return fmt.Sprintf(`{"type":"response.create","model":"gpt-5.1","client_metadata":{"thread_id":"fixture-audit-thread"},"tools":[{"type":"function","name":"inspect","parameters":{"type":"object","properties":{}}}],"input":%s}`, input) } - initial := fmt.Sprintf(`[{"role":"user","content":%q},{"type":"function_call","name":"inspect","call_id":"call_audit_done","arguments":"{}"},{"type":"function_call_output","call_id":"call_audit_done","output":"completed-audit-result"}]`, recoveredWSAuditCanary) + // Establish the actual provider call and successful downstream delivery + // before the client reports its completed result; opaque ownership alone + // cannot authenticate a hand-built pair. + issue715WSSend(t, h.clientConn, create(fmt.Sprintf(`[{"role":"user","content":%q}]`, recoveredWSAuditCanary))) + issued := issue715WSRead(t, h.clientConn) + require.Equal(t, "response.completed", gjson.GetBytes(issued, "type").String()) + call := gjson.GetBytes(issued, "response.output.1") + require.Equal(t, "function_call", call.Get("type").String()) + require.Equal(t, "inspect", call.Get("name").String()) + require.Equal(t, "{}", call.Get("arguments").String()) + initial := fmt.Sprintf(`[{"role":"user","content":%q},%s,%s,{"type":"function_call_output","call_id":"call_audit_done","output":"completed-audit-result"}]`, recoveredWSAuditCanary, gjson.GetBytes(issued, "response.output.0").Raw, call.Raw) issue715WSSend(t, h.clientConn, create(initial)) first := issue715WSRead(t, h.clientConn) require.Equal(t, "response.completed", gjson.GetBytes(first, "type").String()) @@ -226,7 +239,7 @@ func runRecoveredWSAudit(t *testing.T, mode, policy string, allowRecovery bool) return err == nil && strings.Contains(raw, recoveredWSAuditCanary) && strings.Contains(raw, "completed-audit-result") }, 3*time.Second, 5*time.Millisecond, "A must really deliver and commit the exact readable task before disable") owners := issue805Owners(t, probe) - require.Len(t, owners, 1) + require.Len(t, owners, 2) store.mu.Lock() store.records = nil store.mu.Unlock() @@ -270,7 +283,7 @@ func runRecoveredWSAudit(t *testing.T, mode, policy string, allowRecovery bool) case <-ctx.Done(): t.Fatal("missing final identity") } - require.Equal(t, int32(1), writesA.Load()) + require.Equal(t, int32(2), writesA.Load()) expectedB := int32(0) if allowRecovery { expectedB = 1 diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index f28aeb4c032d..ec3ada7cce62 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -80,6 +80,16 @@ func TestOpenAIWSMixedOwnerToolProvenanceCases(t *testing.T) { } } +func TestOpenAIWSShadowToolProvenance(t *testing.T) { + for _, kind := range []string{"function", "custom"} { + for _, change := range []string{"valid", "phantom", "epoch"} { + t.Run(kind+"/"+change, func(t *testing.T) { + runWSMixedOwnerContinuation(t, service.OpenAIWSIngressModeCtxPool, 2, "f1_"+kind+"_shadow_"+change) + }) + } + } +} + func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios ...string) { t.Helper() scenario := "live" @@ -87,6 +97,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios scenario = scenarios[0] } provenance := strings.HasPrefix(scenario, "f1_") + shadowProvenance := provenance && strings.Contains(scenario, "_shadow_") customProvenance := strings.HasPrefix(scenario, "f1_custom_") provenancePositive := provenance && strings.HasSuffix(scenario, "_valid") unrelatedCall := provenance && strings.HasSuffix(scenario, "_unrelated") @@ -289,7 +300,11 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios var previous string var firstTwoOwners map[string]string for warm := 1; warm < turn; warm++ { - issue715WSSend(t, h.clientConn, create([]string{httpRebuildMessage("user", "fixture warm")}, "")) + warmHistory := []string{httpRebuildMessage("user", "fixture warm")} + if shadowProvenance && warm == 1 { + warmHistory = history + } + issue715WSSend(t, h.clientConn, create(warmHistory, "")) raw, readErr := read() require.NoError(t, readErr) completed := gjson.GetBytes(raw, "response") @@ -365,6 +380,15 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios if unrelatedCall || undeliveredCall { history = append(history, foreignCall, foreignOutput) } + if undeliveredCall { + issue600Finish(t, h, headers) + dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + conn, _, dialErr := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers}) + cancel() + require.NoError(t, dialErr) + h.clientConn = conn + previous = "" + } if provenance && !provenancePositive { change := strings.TrimPrefix(scenario, "f1_function_") if customProvenance { @@ -416,6 +440,44 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } } } + if shadowProvenance { + shadowKeys, keyErr := probe.Keys(context.Background(), "openai_readable_shadow:v1:*").Result() + require.NoError(t, keyErr) + require.Eventually(t, func() bool { + shadowKeys, keyErr = probe.Keys(context.Background(), "openai_readable_shadow:v1:*").Result() + return keyErr == nil && len(shadowKeys) == 1 + }, 3*time.Second, 5*time.Millisecond) + stored, readErr := probe.Get(context.Background(), shadowKeys[0]).Result() + require.NoError(t, readErr) + require.Contains(t, stored, httpRebuildPatch) + if strings.HasSuffix(scenario, "_phantom") { + input := gjson.Get(stored, "input").Array() + inputRaw := make([]json.RawMessage, 0, len(input)+2) + for _, item := range input { + inputRaw = append(inputRaw, json.RawMessage(item.Raw)) + } + inputRaw = append(inputRaw, json.RawMessage(foreignCall), json.RawMessage(foreignOutput)) + encoded, marshalErr := json.Marshal(inputRaw) + require.NoError(t, marshalErr) + stored, setErr := sjson.SetRaw(stored, "input", string(encoded)) + require.NoError(t, setErr) + require.NoError(t, probe.Set(context.Background(), shadowKeys[0], stored, time.Minute).Err()) + } + if strings.HasSuffix(scenario, "_epoch") { + keys, err := probe.Keys(context.Background(), "openai_agent_shadow_epoch:*").Result() + require.NoError(t, err) + for _, key := range keys { + require.NoError(t, probe.Set(context.Background(), key, "ready:pending:fixture-reassociated", time.Minute).Err()) + } + } + history = []string{httpRebuildAgentB} + issue600Finish(t, h, headers) + dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + conn, _, dialErr := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers}) + cancel() + require.NoError(t, dialErr) + h.clientConn = conn + } owners = issue805Owners(t, probe) issue715WSSend(t, h.clientConn, create(history, previous)) resumed, resumeErr := read() @@ -433,7 +495,11 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios t.Log("F1_PHANTOM_PAIR_REACHED_UPSTREAM: authenticated handler projected an unissued matching tool pair") } require.Equal(t, turn, sends, "F1_UNTRUSTED_MATCHED_PAIR_DISPATCHED: opaque completed owners must not authorize a separately fabricated tool call") - require.Equal(t, "encrypted_agent_recovery_owner_conflict", gjson.GetBytes(resumed, "error.code").String()) + if shadowProvenance && strings.HasSuffix(scenario, "_epoch") { + require.Contains(t, []string{"encrypted_agent_recovery_owner_conflict", "encrypted_agent_recovery_readable_intent_missing", "encrypted_agent_recovery_owner_unavailable"}, gjson.GetBytes(resumed, "error.code").String()) + } else { + require.Equal(t, "encrypted_agent_recovery_owner_conflict", gjson.GetBytes(resumed, "error.code").String()) + } require.Equal(t, coderws.StatusPolicyViolation, coderws.CloseStatus(resumeErr)) require.Equal(t, owners, issue805Owners(t, probe)) require.Equal(t, 1, tools.patches) @@ -480,6 +546,17 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.NoError(t, resumeErr) require.Equal(t, "completed", gjson.GetBytes(resumed, "response.status").String()) second := gjson.GetBytes(resumed, "response") + if shadowProvenance { + history = []string{httpRebuildMessage("user", httpRebuildTask)} + for _, item := range first.Get("output").Array() { + history = append(history, item.Raw) + } + history = append(history, `{"type":"function_call_output","call_id":"call_mixed_patch","output":"`+httpRebuildPatch+`"}`) + if customProvenance { + history = append(history, `{"type":"custom_tool_call_output","call_id":"fixture-custom-delivered","output":"fixture custom completed once"}`) + } + history = append(history, httpRebuildAgentB) + } for _, item := range second.Get("output").Array() { history = append(history, item.Raw) } @@ -511,8 +588,12 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.NotContains(t, string(wire), "fixture-opaque-A") require.NotContains(t, string(wire), "fixture-readable-B") require.False(t, gjson.GetBytes(wire, "previous_response_id").Exists()) - for _, item := range gjson.GetBytes(wire, "input").Array() { - require.NotContains(t, item.Get("type").String(), "call", "completed tools must be inert readable history") + if shadowProvenance && i == 0 { + require.True(t, httpRebuildToolPair(wire, "apply_patch", httpRebuildPatch), "restored single-owner history retains one proven pair") + } else { + for _, item := range gjson.GetBytes(wire, "input").Array() { + require.NotContains(t, item.Get("type").String(), "call", "completed tools must be inert readable history") + } } } require.Equal(t, 1, strings.Count(string(frames[turn+1]), httpRebuildCheck)) diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index f2c50854e5ad..60bffc979dba 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -31,6 +31,7 @@ type OpenAIAgentRecoveryEpochCache interface { } type openAIAgentRecoveryDelivery struct { + toolFinal map[string]bool service *OpenAIGatewayService ctx context.Context request *openAIAgentRecoveryRequest diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go index 953b65644f6c..807332b30342 100644 --- a/backend/internal/service/openai_tool_provenance.go +++ b/backend/internal/service/openai_tool_provenance.go @@ -314,7 +314,11 @@ func (d *openAIAgentRecoveryDelivery) observeTools(body []byte, nested bool) { terminal := openAIAgentCompletedResponse(body, nested) if terminal { d.toolTerminal = true + if len(items) > 0 { + d.toolFinal = make(map[string]bool) + } } + seen := make(map[string]bool) for _, item := range items { kind := item.Get("type").String() if kind != "function_call" && kind != "custom_tool_call" { @@ -326,6 +330,13 @@ func (d *openAIAgentRecoveryDelivery) observeTools(body []byte, nested bool) { continue } key := r.toolKey(id.String()) + if seen[key] { + d.toolInvalid = true + } + seen[key] = true + if terminal && d.toolFinal != nil { + d.toolFinal[key] = true + } old, exists := d.tools[key] if !exists { if d.service.toolProofReserve(d.ctx, key, d.pending) != nil { @@ -376,7 +387,7 @@ func (d *openAIAgentRecoveryDelivery) finishTools(ctx context.Context, completed proof.ShadowDigest, proof.ShadowEpoch = openAIToolHash(shadow.raw), shadow.epoch } raw, _ := json.Marshal(proof) - d.service.toolProofFinish(ctx, key, d.pending, string(raw), valid && call.complete && len(raw) <= OpenAIToolProvenanceMaxBytes) + d.service.toolProofFinish(ctx, key, d.pending, string(raw), valid && call.complete && (d.toolFinal == nil || d.toolFinal[key]) && len(raw) <= OpenAIToolProvenanceMaxBytes) } } diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go index 076dbd42df3a..249e03b09014 100644 --- a/backend/internal/service/openai_ws_owner_conflict_test.go +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -37,6 +37,84 @@ func learnF1DeliveredCalls(t *testing.T, svc *OpenAIGatewayService, account *Acc require.True(t, json.Valid([]byte(raw)), "only completed downstream delivery commits a call proof") } +func TestOpenAIToolProvenanceDeliveryAndScope(t *testing.T) { + for _, outcome := range []string{"completed", "early_only", "write_failed", "terminal_excludes", "duplicate"} { + t.Run(outcome, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + manager, c, a := issue715WSManager(t, svc, context.Background()) + SetOpenAIWSRecoveryPrincipal(c, 715, 715) + defer manager.abort() + source := `{"model":"gpt-6-astra","input":[]}` + require.NoError(t, issue715WSBegin(t, manager, a, source, "ctx_pool")) + call := `{"type":"function_call","name":"fixture-private-tool","call_id":"fixture-private-call","arguments":"{\"private\":\"fixture-private-argument\"}"}` + item := gjson.Get(issue715OpaqueBody, "input.0").Raw + require.NoError(t, manager.write([]byte(`{"type":"response.output_item.done","item":`+call+`}`), func() error { return nil })) + key := manager.request.toolKey("fixture-private-call") + pending, err := svc.toolProofGet(context.Background(), key) + require.NoError(t, err) + require.True(t, strings.HasPrefix(pending, "pending:")) + output := item + `,` + call + if outcome == "terminal_excludes" { + output = item + } + if outcome == "duplicate" { + output += `,` + call + } + if outcome != "early_only" { + err = manager.write([]byte(`{"type":"response.completed","response":{"id":"resp_delivery_fixture","status":"completed","output":[`+output+`]}}`), func() error { + if outcome == "write_failed" { + return errors.New("fixture downstream failure") + } + return nil + }) + if outcome == "write_failed" { + require.Error(t, err) + } else { + require.NoError(t, err) + } + } + manager.abort() + raw, err := svc.toolProofGet(context.Background(), key) + require.NoError(t, err) + if outcome != "completed" { + require.Equal(t, "failed", raw) + return + } + require.True(t, json.Valid([]byte(raw))) + for _, secret := range []string{"fixture-private-tool", "fixture-private-call", "fixture-private-argument"} { + require.NotContains(t, raw, secret) + require.NotContains(t, key, secret) + } + body := []byte(`{"model":"gpt-6-astra","input":[` + item + `,` + call + `,{"type":"function_call_output","call_id":"fixture-private-call","output":"client completion report"}]}`) + ctx := svc.WithOpenAIWSAgentRecovery(context.Background(), c, body, "fixture-session", "gpt-6-astra") + original := openAIAgentRecoveryFromContext(ctx) + require.NoError(t, svc.verifyOpenAIToolInputs(ctx, original, body)) + for _, scope := range []string{"user", "key", "group", "session", "model"} { + other := *original + switch scope { + case "user": + other.userID++ + case "key": + other.keyID++ + case "group": + other.groupID++ + case "session": + other.session += "-other" + case "model": + other.model += "-other" + } + require.Error(t, svc.verifyOpenAIToolInputs(ctx, &other, body), scope) + } + require.NoError(t, svc.toolProofReserve(context.Background(), key, "pending:another-delivery")) + svc.toolProofFinish(context.Background(), key, "pending:another-delivery", raw, true) + conflict, err := svc.toolProofGet(context.Background(), key) + require.NoError(t, err) + require.Equal(t, "conflict", conflict) + require.Error(t, svc.recheckOpenAIToolProofs(ctx, original)) + }) + } +} + func TestOpenAIWSMixedOwnerFinalSendFences(t *testing.T) { for _, mutation := range []string{"none", "pending", "failed", "conflicted", "missing", "changed", "input", "tools", "call_proof"} { t.Run(mutation, func(t *testing.T) { diff --git a/docs/ws-mixed-owner-continuation.md b/docs/ws-mixed-owner-continuation.md index 5d1ab4bbf8ff..44f60fd0dede 100644 --- a/docs/ws-mixed-owner-continuation.md +++ b/docs/ws-mixed-owner-continuation.md @@ -5,7 +5,15 @@ WebSocket can rebuild a current, provably unsent turn containing opaque history from multiple completed producers. This closes the live-socket gap between the send-boundary owner check and the existing readable continuation handler. -The gateway requires a completed ownership observation for **every** supplied +The gateway requires server-observed, successfully delivered provenance for every +function/custom tool call used by WS history recovery. A matching client pair +alone is insufficient. A separate bounded record binds the authenticated user/key, +group/session/model, exact call type/ID/name/arguments, producing delivery, and +original owner/epoch/shadow associations. Pending, failed, conflicting, missing, +reissued or unrelated-task calls are refused. The client result is its completion +report, not proof that an external side effect executed. + +The gateway also requires a completed ownership observation for **every** supplied opaque item, readable current intent, and complete, unique tool call/result pairs. It discards provider pointers and historical ciphertext. In this mixed WS case, it carries completed tool names/results as inert assistant text and @@ -14,6 +22,12 @@ schemas remain available for new tool work. The client keeps its existing session identity and socket; no client confirmation or new conversation is required for this supported branch. +Call proofs are reserved before exposing provider output and committed only after +the successful downstream terminal and original owner/epoch publication. Recovery +and physical send recheck the same proof and associations. Records contain only +internal fingerprints and route/delivery metadata (128 per principal, maximum +32 KiB each, 30-minute TTL); eviction loses recoverability. They are not logged. + The permit comes from a private before-write route check. The public `encrypted_agent_recovery_owner_conflict` code alone never permits retry. Unknown ownership, pending/failed/conflicted delivery, missing/duplicate or From 5beccded25ffd78914a6c1fa38b8d2e44ca1e453 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:32:13 +0800 Subject: [PATCH 11/26] =?UTF-8?q?fix:=20=E5=9C=A8=E4=B8=8D=E5=8F=AF?= =?UTF-8?q?=E6=89=A7=E8=A1=8C=E5=8E=86=E5=8F=B2=E4=B8=AD=E4=BF=9D=E7=95=99?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E8=B0=83=E7=94=A8=E4=B8=8E=E7=BB=93=E6=9E=9C?= =?UTF-8?q?=E5=AE=8C=E6=95=B4=E5=AF=B9=E5=BA=94=E5=85=B3=E7=B3=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripts/ws-tool-association-evidence.py | 26 +++++ .github/workflows/ws-tool-association.yml | 64 +++++++++++ .../handler/openai_409_ws_oracle_test.go | 8 +- .../handler/openai_ws_owner_conflict_test.go | 104 +++++++++++++++++- .../openai_ws_readable_continuation.go | 6 +- 5 files changed, 200 insertions(+), 8 deletions(-) create mode 100644 .github/scripts/ws-tool-association-evidence.py create mode 100644 .github/workflows/ws-tool-association.yml diff --git a/.github/scripts/ws-tool-association-evidence.py b/.github/scripts/ws-tool-association-evidence.py new file mode 100644 index 000000000000..7d9b431f7b28 --- /dev/null +++ b/.github/scripts/ws-tool-association-evidence.py @@ -0,0 +1,26 @@ +"""Verify the same named actual-wire association cases before/after repair.""" +import json,sys,importlib.util +from pathlib import Path +from collections import Counter +spec=importlib.util.spec_from_file_location('clean',Path(__file__).with_name('assert-readable-continuation.py')) +clean=importlib.util.module_from_spec(spec);spec.loader.exec_module(clean) +phase,status,path=sys.argv[1:];raw=Path(path).read_text();clean.check_clean(raw) +rows=[json.loads(line) for line in raw.splitlines() if line.startswith('{')] +expected='fail' if phase=='RED' else 'pass' +assert phase in ('RED','GREEN') and int(status)==(1 if phase=='RED' else 0) +root='TestOpenAIWSMixedOwnerToolAssociation' +leaves={f'{root}/{mode}/{kind}/{variant}' for mode in ('ctx_pool','http_bridge','passthrough') for kind in ('function','custom') for variant in ('normal','swapped')} +counts=Counter((r.get('Action'),r.get('Test')) for r in rows) +for name in leaves|{root}: + assert counts['run',name]==1 and counts[expected,name]==1,name + assert counts['pass',name]+counts['fail',name]==1,name +assert counts[expected,None]==1 +for r in rows: + if r.get('Action') in ('run','pass','fail'): + assert r.get('Package')=='github.com/Wei-Shaw/sub2api/internal/handler' + assert r.get('Test') in leaves|{root,None} +if phase=='RED': + for name in leaves: + out=''.join(r.get('Output','') for r in rows if r.get('Test')==name) + assert 'ASSOCIATION_LOST' in out,name +print(phase, len(leaves), 'actual-wire association cases verified') diff --git a/.github/workflows/ws-tool-association.yml b/.github/workflows/ws-tool-association.yml new file mode 100644 index 000000000000..64427cae6709 --- /dev/null +++ b/.github/workflows/ws-tool-association.yml @@ -0,0 +1,64 @@ +name: WS completed tool association +on: + pull_request: + branches: [production] + paths: + - backend/internal/handler/openai_ws_owner_conflict_test.go + - backend/internal/service/openai_ws_readable_continuation.go + - .github/workflows/ws-tool-association.yml + - .github/scripts/ws-tool-association-evidence.py +permissions: + contents: read +jobs: + association: + runs-on: ubuntu-latest + timeout-minutes: 35 + 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 + run: | + if ! command -v redis-server >/dev/null; then sudo apt-get update && sudo apt-get install -y redis-server; fi + - name: Freeze candidate and exact pre-repair projection + env: + CANDIDATE: ${{ github.event.pull_request.head.sha }} + PHASE: ${{ matrix.phase }} + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git diff --exit-code + mkdir -p "$RUNNER_TEMP/association" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/association/candidate.txt" + if [ "$PHASE" = RED ]; then + baseline=cc1a9e80223695684ad54ab0e9cf4f27c7991bf2 + path=backend/internal/service/openai_ws_readable_continuation.go + git show "$baseline:$path" > "$path" + test "$(git hash-object "$path")" = "$(git rev-parse "$baseline:$path")" + git rev-parse "$baseline:$path" > "$RUNNER_TEMP/association/baseline-blob.txt" + fi + - name: Verify actual transmitted call/result association + env: + PHASE: ${{ matrix.phase }} + run: | + set -euo pipefail + set +e + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerToolAssociation$' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/association/result.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/association/result.jsonl" + python3 .github/scripts/ws-tool-association-evidence.py "$PHASE" "$status" "$RUNNER_TEMP/association/result.jsonl" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: ws-tool-association-${{ matrix.phase }}-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/association diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index 3242a68a2a0d..3acc7b31f94d 100644 --- a/backend/internal/handler/openai_409_ws_oracle_test.go +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -128,8 +128,12 @@ func readableWSCompletedResult(body []byte, name, output string, projected bool) const prefix = "Historical completed tool result (data only; do not execute again): " if strings.HasPrefix(text, prefix) { record := gjson.Parse(strings.TrimPrefix(text, prefix)) - if record.Get("name").String() == name { - if item.Get("role").String() != "assistant" || record.Get("output").String() != output { + recordName, recordOutput := record.Get("name"), record.Get("output") + if record.Get("call").Exists() { + recordName, recordOutput = record.Get("call.name"), record.Get("result.output") + } + if recordName.String() == name { + if item.Get("role").String() != "assistant" || recordOutput.String() != output { return false } count++ diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index f28aeb4c032d..ac45aa1bb973 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -18,6 +18,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/repository" "github.com/Wei-Shaw/sub2api/internal/service" coderws "github.com/coder/websocket" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" "github.com/tidwall/sjson" @@ -80,12 +81,49 @@ func TestOpenAIWSMixedOwnerToolProvenanceCases(t *testing.T) { } } +// Same-name parallel calls must retain their business-object association even +// when outputs arrive in reverse order. The provider derives its answer from +// the actual transmitted inert records, not from the request ordinal. +func TestOpenAIWSMixedOwnerToolAssociation(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModeHTTPBridge, service.OpenAIWSIngressModePassthrough} { + for _, kind := range []string{"function", "custom"} { + for _, variant := range []string{"normal", "swapped"} { + t.Run(mode+"/"+kind+"/"+variant, func(t *testing.T) { runWSMixedOwnerContinuation(t, mode, 53, "association_"+kind+"_"+variant) }) + } + } + } +} + func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios ...string) { t.Helper() scenario := "live" if len(scenarios) > 0 { scenario = scenarios[0] } + association := strings.HasPrefix(scenario, "association_") + associationCustom := strings.HasPrefix(scenario, "association_custom_") + firstObject, secondObject := "left", "right" + if strings.HasSuffix(scenario, "_swapped") { + firstObject, secondObject = secondObject, firstObject + } + associationCall := func(id, object string) string { + field, kind := "arguments", "function_call" + if associationCustom { + field, kind = "input", "custom_tool_call" + } + return httpRebuildJSON(map[string]any{"type": kind, "call_id": id, "name": "lookup", "status": "completed", field: httpRebuildJSON(map[string]any{"object": object})}) + } + associationResult := func(id, result string) string { + kind := "function_call_output" + if associationCustom { + kind = "custom_tool_call_output" + } + return httpRebuildJSON(map[string]any{"type": kind, "call_id": id, "output": result, "status": "completed"}) + } + associationCalls := []string{associationCall("association-first", firstObject), associationCall("association-second", secondObject)} + associationResults := []string{associationResult("association-second", "second-value"), associationResult("association-first", "first-value")} + associationExecutions := 0 + associationAnswer := "" provenance := strings.HasPrefix(scenario, "f1_") customProvenance := strings.HasPrefix(scenario, "f1_custom_") provenancePositive := provenance && strings.HasSuffix(scenario, "_valid") @@ -97,7 +135,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios foreignCall = `{"type":"custom_tool_call","call_id":"fixture-other-task-call","name":"inspect","input":"fixture other task"}` foreignOutput = `{"type":"custom_tool_call_output","call_id":"fixture-other-task-call","output":"fixture other result"}` } - negative := scenario != "live" && scenario != "fresh" && scenario != "binding_changed" && !provenancePositive + negative := scenario != "live" && scenario != "fresh" && scenario != "binding_changed" && !provenancePositive && !association oldFence := strings.HasSuffix(scenario, "_first") || strings.HasSuffix(scenario, "_last") thirdItem := strings.ReplaceAll(httpRebuildAgentB, "fixture-readable-B", "fixture-old-completed-C") clients := issue805Redis(t) @@ -111,6 +149,38 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios frames = append(frames, append([]byte(nil), body...)) identities = append(identities, r.Header.Get("Authorization")) n := len(frames) + if association && n >= turn+1 { + found := map[string]string{} + for _, item := range gjson.GetBytes(body, "input").Array() { + if strings.Contains(item.Get("type").String(), "call") { + t.Error("ASSOCIATION_LOST: executable call survived") + } + for _, part := range item.Get("content").Array() { + text := part.Get("text").String() + const prefix = "Historical completed tool result (data only; do not execute again): " + if !strings.HasPrefix(text, prefix) { + continue + } + record := gjson.Parse(strings.TrimPrefix(text, prefix)) + call, result := record.Get("call"), record.Get("result") + if call.Get("name").String() != "lookup" { + continue + } + id := call.Get("call_id").String() + field, kind := "arguments", "function_call" + if associationCustom { + field, kind = "input", "custom_tool_call" + } + assert.Equal(t, kind, call.Get("type").String(), "ASSOCIATION_LOST: call type") + assert.Equal(t, kind+"_output", result.Get("type").String(), "ASSOCIATION_LOST: result type") + assert.Equal(t, id, result.Get("call_id").String(), "ASSOCIATION_LOST: pair identity") + assert.NotContains(t, found, id, "ASSOCIATION_LOST: duplicate pair") + found[id] = gjson.Get(call.Get(field).String(), "object").String() + "=" + result.Get("output").String() + } + } + assert.Equal(t, map[string]string{"association-first": firstObject + "=first-value", "association-second": secondObject + "=second-value"}, found, "ASSOCIATION_LOST: final wire must preserve call arguments and reversed results") + associationAnswer = found["association-first"] + ";" + found["association-second"] + } output := []json.RawMessage{json.RawMessage(httpRebuildMessage("assistant", "fixture warm complete"))} switch { case n == 1: @@ -120,6 +190,11 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } case n == 2: output = []json.RawMessage{json.RawMessage(httpRebuildAgentB)} + if association { + for _, call := range associationCalls { + output = append(output, json.RawMessage(call)) + } + } case n == 3 && (unrelatedCall || undeliveredCall): output = []json.RawMessage{json.RawMessage(foreignCall)} if unrelatedCall { @@ -130,7 +205,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios case n == turn+1: output = []json.RawMessage{json.RawMessage(httpRebuildCall("run_tests", "call_mixed_verify", map[string]any{"path": "sum.go"}))} case n == turn+2: - output = []json.RawMessage{json.RawMessage(httpRebuildMessage("assistant", "fixture mixed task complete"))} + output = []json.RawMessage{json.RawMessage(httpRebuildMessage("assistant", "fixture mixed task complete "+associationAnswer))} } event, status := "response.completed", "completed" if n == 3 && undeliveredCall { @@ -215,6 +290,13 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios if customProvenance { declarations = append(declarations, map[string]any{"type": "custom", "name": "inspect", "description": "fixture inspection"}) } + if association { + tool := map[string]any{"type": "function", "name": "lookup", "parameters": map[string]any{"type": "object", "properties": map[string]any{"object": map[string]any{"type": "string"}}}} + if associationCustom { + tool = map[string]any{"type": "custom", "name": "lookup", "description": "synthetic lookup"} + } + declarations = append(declarations, tool) + } create := func(input []string, previous string) string { body := map[string]any{"type": "response.create", "model": "gpt-5.1", "store": true, "tools": declarations, "input": json.RawMessage("[" + strings.Join(input, ",") + "]"), @@ -301,6 +383,14 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios previous = completed.Get("id").String() if warm == 1 { history = append(history, completed.Get("output.0").Raw) + if association { + for i, call := range completed.Get("output").Array()[1:] { + require.JSONEq(t, associationCalls[i], call.Raw) + history = append(history, call.Raw) + associationExecutions++ + } + history = append(history, associationResults...) + } firstTwoOwners = waitOwners(2) } } @@ -488,6 +578,10 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios final, err := read() require.NoError(t, err) require.Contains(t, string(final), "fixture mixed task complete") + if association { + require.Contains(t, gjson.GetBytes(final, "response.output.0.content.0.text").String(), firstObject+"=first-value;"+secondObject+"=second-value") + require.Equal(t, 2, associationExecutions) + } require.Equal(t, 1, tools.patches) require.Equal(t, 1, tools.verifications) issue600Finish(t, h, headers) @@ -504,7 +598,11 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.JSONEq(t, httpRebuildJSON(declarations), gjson.GetBytes(wire, "tools").Raw) require.Equal(t, 1, strings.Count(string(wire), "fixture custom completed once")) } else { - require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") + if association { + require.JSONEq(t, httpRebuildJSON(declarations), gjson.GetBytes(wire, "tools").Raw, "ASSOCIATION_LOST: tool definitions survive") + } else { + require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") + } } require.Contains(t, string(wire), httpRebuildTask) require.Equal(t, 1, strings.Count(string(wire), httpRebuildPatch)) diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index 21d4926f8da0..355fb825f7bd 100644 --- a/backend/internal/service/openai_ws_readable_continuation.go +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -111,8 +111,8 @@ func WithOpenAIWSUnsentOwnerProof(ctx context.Context, err error) context.Contex } // Keep completed results as data in a new provider conversation. Historical -// callable records and arguments are unnecessary there; current declarations -// remain available for genuinely new tool work. Pairing is checked before loss. +// call type, identity and original arguments stay paired with each result as +// inert JSON text. Current declarations remain available for new tool work. func projectOpenAIWSCompletedTools(body []byte) ([]byte, error) { if !openAIWSCompletedToolInputs(body) { return nil, openAIAgentRecoveryError("owner_conflict") @@ -136,7 +136,7 @@ func projectOpenAIWSCompletedTools(body []byte) ([]byte, error) { if !openAIReadableShadowTextOnly(output) { return nil, openAIAgentRecoveryError("readable_history_unsupported") } - record, err := json.Marshal(map[string]any{"name": calls[item.Get("call_id").String()].Get("name").String(), "output": json.RawMessage(output.Raw)}) + record, err := json.Marshal(map[string]json.RawMessage{"call": json.RawMessage(calls[item.Get("call_id").String()].Raw), "result": json.RawMessage(item.Raw)}) if err != nil { return nil, openAIAgentRecoveryError("readable_history_unsupported") } From d7c8bf00aaf5b970abb344a632a382904b724d73 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:33:07 +0800 Subject: [PATCH 12/26] test: retain tool proof state and shadow route refusal fences --- .github/workflows/ws-tool-provenance.yml | 2 +- .../handler/openai_ws_owner_conflict_test.go | 23 ++++++++++++++++--- .../service/openai_agent_message_delivery.go | 4 +++- .../service/openai_tool_provenance.go | 7 +++++- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ws-tool-provenance.yml b/.github/workflows/ws-tool-provenance.yml index 7bec864cd80f..28ab2367404c 100644 --- a/.github/workflows/ws-tool-provenance.yml +++ b/.github/workflows/ws-tool-provenance.yml @@ -95,7 +95,7 @@ jobs: import json,sys rows=[json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] for kind in ('function','custom'): - for case in ('valid','id','type','name','args','epoch','unrelated','undelivered'): + for case in ('valid','id','type','name','args','epoch','unrelated','undelivered','proof_pending','proof_failed','proof_conflict','proof_missing'): name=f'TestOpenAIWSMixedOwnerToolProvenanceCases/{kind}/{case}' assert sum(r.get('Action')=='pass' and r.get('Test')==name for r in rows)==1,name assert not any(r.get('Action') in ('fail','skip') for r in rows) diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index ec3ada7cce62..d9861c8e4e83 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -65,7 +65,7 @@ func TestOpenAIWSMixedOwnerToolProvenance(t *testing.T) { func TestOpenAIWSMixedOwnerToolProvenanceCases(t *testing.T) { for _, kind := range []string{"function", "custom"} { - for _, change := range []string{"valid", "id", "type", "name", "args", "epoch", "unrelated", "undelivered"} { + for _, change := range []string{"valid", "id", "type", "name", "args", "epoch", "unrelated", "undelivered", "proof_pending", "proof_failed", "proof_conflict", "proof_missing"} { t.Run(kind+"/"+change, func(t *testing.T) { turn := 2 if change == "valid" { @@ -199,7 +199,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios other.ID, other.Priority = 2, 1 other.Credentials = map[string]any{"api_key": "fixture-mixed-B", "base_url": provider.URL} pool := []service.Account{*a, other} - if scenario == "binding_changed" { + if scenario == "binding_changed" || shadowProvenance { third := other third.ID, third.Priority = 3, 2 third.Credentials = map[string]any{"api_key": "fixture-mixed-C", "base_url": provider.URL} @@ -431,6 +431,22 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } require.NoError(t, err) } + if strings.HasPrefix(change, "proof_") { + keys, keyErr := probe.Keys(context.Background(), "openai_tool_provenance:v1:*").Result() + require.NoError(t, keyErr) + require.NotEmpty(t, keys) + for _, key := range keys { + if change == "proof_missing" { + require.NoError(t, probe.Del(context.Background(), key).Err()) + continue + } + state := strings.TrimPrefix(change, "proof_") + if state == "pending" { + state = "pending:fixture-unconfirmed" + } + require.NoError(t, probe.Set(context.Background(), key, state, time.Minute).Err()) + } + } if change == "epoch" { keys, keyErr := probe.Keys(context.Background(), "openai_agent_shadow_epoch:*").Result() require.NoError(t, keyErr) @@ -471,6 +487,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } } history = []string{httpRebuildAgentB} + accounts.disable(2) // Require restored intent on a fresh provider route. issue600Finish(t, h, headers) dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) conn, _, dialErr := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers}) @@ -573,7 +590,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.Len(t, frames, turn+2, "no extra generation or retry") for i, wire := range frames[turn:] { expectedIdentity := "Bearer fixture-mixed-B" - if scenario == "binding_changed" { + if scenario == "binding_changed" || shadowProvenance { expectedIdentity = "Bearer fixture-mixed-C" } require.Equal(t, expectedIdentity, identities[turn+i]) diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index 60bffc979dba..ac2dba2f7716 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -50,7 +50,9 @@ func newOpenAIAgentRecoveryDelivery(s *OpenAIGatewayService, ctx context.Context var anchors map[string]openAIToolAnchor valid := false if enabled { - anchors, valid = s.toolInputAnchors(ctx, r) + storeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + anchors, valid = s.toolInputAnchors(storeCtx, r) + cancel() } return &openAIAgentRecoveryDelivery{toolEnabled: enabled, toolAnchors: anchors, toolAnchorsValid: valid, service: s, ctx: ctx, request: r, binding: b, pending: "pending:" + uuid.NewString() + ":" + encodeOpenAIAgentRecoveryBinding(b), keys: make(map[[32]byte]bool), epochs: make(map[string]bool)} } diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go index 807332b30342..bafb812a7423 100644 --- a/backend/internal/service/openai_tool_provenance.go +++ b/backend/internal/service/openai_tool_provenance.go @@ -225,6 +225,9 @@ func (s *OpenAIGatewayService) toolInputAnchors(ctx context.Context, r *openAIAg anchor := openAIToolAnchor{Owner: encodeOpenAIAgentRecoveryBinding(binding)} for i, k := range source.keys { if k == key { + if i >= len(source.items) { + return nil, false + } anchor.EpochKey = source.shadowEpochKey(source.items[i]) break } @@ -303,6 +306,8 @@ func (d *openAIAgentRecoveryDelivery) observeTools(body []byte, nested bool) { if d.tools == nil { d.tools = make(map[string]openAIToolObservation) } + storeCtx, cancel := context.WithTimeout(d.ctx, 3*time.Second) + defer cancel() path := "output" if nested { path = "response.output" @@ -339,7 +344,7 @@ func (d *openAIAgentRecoveryDelivery) observeTools(body []byte, nested bool) { } old, exists := d.tools[key] if !exists { - if d.service.toolProofReserve(d.ctx, key, d.pending) != nil { + if d.service.toolProofReserve(storeCtx, key, d.pending) != nil { d.toolInvalid = true } } From b90df2c094dab3605ca878367a58a1302a838e09 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:38:13 +0800 Subject: [PATCH 13/26] =?UTF-8?q?test:=20=E5=AF=B9=E9=BD=90=20HTTP=20bridg?= =?UTF-8?q?e=20=E7=9A=84=20custom=20=E5=B7=A5=E5=85=B7=20wire=20=E5=A5=91?= =?UTF-8?q?=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/openai_ws_owner_conflict_test.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index 8b9ec86d7f70..3d8708459b85 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -203,6 +203,10 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios output = []json.RawMessage{json.RawMessage(httpRebuildAgentB)} if association { for _, call := range associationCalls { + if associationCustom && mode == service.OpenAIWSIngressModeHTTPBridge { + item := gjson.Parse(call) + call = httpRebuildCall("lookup", item.Get("call_id").String(), map[string]any{"input": item.Get("input").String()}) + } output = append(output, json.RawMessage(call)) } } @@ -400,7 +404,13 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios history = append(history, completed.Get("output.0").Raw) if association { for i, call := range completed.Get("output").Array()[1:] { - require.JSONEq(t, associationCalls[i], call.Raw) + require.Equal(t, gjson.Get(associationCalls[i], "call_id").String(), call.Get("call_id").String()) + require.Equal(t, gjson.Get(associationCalls[i], "type").String(), call.Get("type").String()) + field := "arguments" + if associationCustom { + field = "input" + } + require.Equal(t, gjson.Get(associationCalls[i], field).String(), call.Get(field).String()) history = append(history, call.Raw) associationExecutions++ } @@ -693,7 +703,12 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.Equal(t, 1, strings.Count(string(wire), "fixture custom completed once")) } else { if association { - require.JSONEq(t, httpRebuildJSON(declarations), gjson.GetBytes(wire, "tools").Raw, "ASSOCIATION_LOST: tool definitions survive") + expectedTools := declarations + if associationCustom && mode == service.OpenAIWSIngressModeHTTPBridge { + expectedTools = append([]any{}, declarations...) + expectedTools[len(expectedTools)-1] = map[string]any{"type": "function", "name": "lookup", "description": "synthetic lookup", "parameters": json.RawMessage(`{"type":"object","properties":{"input":{"type":"string","description":"The raw input for this tool, passed through verbatim."}},"required":["input"]}`)} + } + require.JSONEq(t, httpRebuildJSON(expectedTools), gjson.GetBytes(wire, "tools").Raw, "ASSOCIATION_LOST: tool definitions survive") } else { require.True(t, httpRebuildToolsAvailable(wire), "both tool definitions and parameter schemas survive the actual wire") } From 760ba70bd39f8141d32c6aad65fbbaf1ddecbd88 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:42:41 +0800 Subject: [PATCH 14/26] =?UTF-8?q?docs:=20=E8=AF=B4=E6=98=8E=E5=8F=AF?= =?UTF-8?q?=E8=AF=BB=E7=BB=AD=E6=8E=A5=E4=BF=9D=E7=95=99=E5=AE=8C=E6=95=B4?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E5=85=B3=E8=81=94=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ws-mixed-owner-continuation.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/ws-mixed-owner-continuation.md b/docs/ws-mixed-owner-continuation.md index 44f60fd0dede..3378f836143a 100644 --- a/docs/ws-mixed-owner-continuation.md +++ b/docs/ws-mixed-owner-continuation.md @@ -16,8 +16,11 @@ report, not proof that an external side effect executed. The gateway also requires a completed ownership observation for **every** supplied opaque item, readable current intent, and complete, unique tool call/result pairs. It discards provider pointers and historical ciphertext. In this mixed -WS case, it carries completed tool names/results as inert assistant text and -removes historical callable records/arguments. Current tool definitions and +WS case, it carries each complete original call and corresponding result as +inert JSON text in an assistant message. Call ID, call type, name, arguments +or custom input, result type and extensions stay associated even when same-name +parallel tools return in reverse order. No top-level callable history remains. +Current tool definitions and schemas remain available for new tool work. The client keeps its existing session identity and socket; no client confirmation or new conversation is required for this supported branch. @@ -48,7 +51,9 @@ message, logical HTTP status and WebSocket error/close contract remain intact. Regression evidence uses authenticated ingress, production forwarding, isolated Redis and loopback fake providers. It includes turn 53, fresh/live sockets, account binding changes, exactly-once client tool effects, final wire schemas, -and terminal negative controls. The CI restores exact production blobs in a +same-name parallel calls with swapped arguments and out-of-order results, +and terminal negative controls. The synthetic provider computes its answer +from the actual received call/result association. The CI restores exact production blobs in a disposable checkout for behavioral RED, then runs the candidate with the race detector. Compile errors, skips and panics are not accepted as RED. From 194e8acbeec5d183bd2c2fcc09c025e5dfc62e35 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 22:59:22 +0800 Subject: [PATCH 15/26] =?UTF-8?q?ci:=20=E5=90=8C=E6=AD=A5=E7=94=9F?= =?UTF-8?q?=E4=BA=A7=E5=9F=BA=E7=BA=BF=E5=B9=B6=E9=9A=94=E7=A6=BB=E6=97=A7?= =?UTF-8?q?=E5=8F=8D=E4=BE=8B=E4=B8=AD=E7=9A=84=E6=96=B0=E8=B4=B9=E7=94=A8?= =?UTF-8?q?=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../exclude-later-http2-red-fixtures.sh | 1 + .../scripts/prepare-free-fast-red-fixtures.sh | 26 +++++++++++++++++++ .github/workflows/ws-owner-conflict.yml | 1 + .github/workflows/ws-tool-provenance.yml | 1 + 4 files changed, 29 insertions(+) create mode 100644 .github/scripts/prepare-free-fast-red-fixtures.sh diff --git a/.github/scripts/exclude-later-http2-red-fixtures.sh b/.github/scripts/exclude-later-http2-red-fixtures.sh index d6c487651b42..18516bc2f0c5 100644 --- a/.github/scripts/exclude-later-http2-red-fixtures.sh +++ b/.github/scripts/exclude-later-http2-red-fixtures.sh @@ -9,6 +9,7 @@ candidate="${3:-$(git -C "$tree" rev-parse HEAD)}" # The same historical assembly must not retain tests for an absent QQ package. script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" bash "$script_dir/prepare-mature-red-fixtures.sh" "$baseline" "$tree" "$candidate" +bash "$script_dir/prepare-free-fast-red-fixtures.sh" "$baseline" "$tree" "$candidate" # Selective Issue715 overlays retain HTTP2 production/support, so keep its tests. if test -f "$tree/backend/internal/service/http2_gateway_test_support.go"; then exit 0 diff --git a/.github/scripts/prepare-free-fast-red-fixtures.sh b/.github/scripts/prepare-free-fast-red-fixtures.sh new file mode 100644 index 000000000000..e83bedd86fcc --- /dev/null +++ b/.github/scripts/prepare-free-fast-red-fixtures.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Isolate only the later independent Free Fast service tests when an exact +# historical production overlay lacks their private snapshot implementation. +set -euo pipefail +baseline="$1" +tree="${2:-.}" +candidate="${3:-HEAD}" +if test -f "$tree/backend/internal/service/customer_cost_details.go"; then exit 0; fi +if git -C "$tree" cat-file -e "$baseline:backend/internal/service/customer_cost_details.go" 2>/dev/null; then + echo 'baseline snapshot implementation unexpectedly absent' >&2; exit 1 +fi +contract=backend/internal/service/billing_service.go +test "$(git -C "$tree" hash-object "$contract")" = "$(git -C "$tree" rev-parse "$baseline:$contract")" +target=backend/internal/service/free_fast_customer_cost_test.go +if ! git -C "$tree" cat-file -e "$candidate:$target" 2>/dev/null; then exit 0; fi +if git -C "$tree" cat-file -e "$baseline:$target" 2>/dev/null; then + echo 'refusing to omit a baseline Free Fast fixture' >&2; exit 1 +fi +expected=$(git -C "$tree" rev-parse "$candidate:$target") +if test -f "$tree/$target"; then + test "$(git -C "$tree" hash-object "$target")" = "$expected" + rm -- "$tree/$target" +else + test "$(git -C "$tree" diff --name-only --diff-filter=D "$candidate" -- "$target")" = "$target" +fi +printf 'independent free-fast fixture baseline=%s candidate=%s path=%s blob=%s actual=absent\n' "$baseline" "$candidate" "$target" "$expected" diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index 5972abbac740..34aa10c50b33 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -56,6 +56,7 @@ jobs: fi ;; esac done + bash .github/scripts/prepare-free-fast-red-fixtures.sh "$BASELINE" "$RUNNER_TEMP/ws-owner-red" "$CANDIDATE" set +e (cd "$RUNNER_TEMP/ws-owner-red/backend" && go test -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerContinuation$/turn_2$' -count=1 -json -timeout=2m) > "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" 2>&1 status=$? diff --git a/.github/workflows/ws-tool-provenance.yml b/.github/workflows/ws-tool-provenance.yml index 28ab2367404c..d17ab6afdfbc 100644 --- a/.github/workflows/ws-tool-provenance.yml +++ b/.github/workflows/ws-tool-provenance.yml @@ -58,6 +58,7 @@ jobs: fi ;; esac done + bash .github/scripts/prepare-free-fast-red-fixtures.sh "$BASELINE" "$RUNNER_TEMP/ws-provenance-red" "$CANDIDATE" set +e (cd "$RUNNER_TEMP/ws-provenance-red/backend" && go test -p=2 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAIWSMixedOwnerToolProvenance$' -count=1 -json -timeout=2m) > "$RUNNER_TEMP/ws-provenance-evidence/red.jsonl" 2>&1 status=$? From 8fcfad669af9225467e3b8daff4e41801e709181 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:05:54 +0800 Subject: [PATCH 16/26] test: report fixed recovery stages when WS continuation contracts fail --- .../handler/openai_409_ws_audit_test.go | 3 +++ .../handler/openai_409_ws_rebuild_test.go | 17 +++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/backend/internal/handler/openai_409_ws_audit_test.go b/backend/internal/handler/openai_409_ws_audit_test.go index 51c33db55004..410a9a5fa7d2 100644 --- a/backend/internal/handler/openai_409_ws_audit_test.go +++ b/backend/internal/handler/openai_409_ws_audit_test.go @@ -249,6 +249,9 @@ func runRecoveredWSAudit(t *testing.T, mode, policy string, allowRecovery bool) require.NotContains(t, opaque, recoveredWSAuditCanary) issue715WSSend(t, h.clientConn, opaque) terminal := issue715WSRead(t, h.clientConn) + if strings.HasPrefix(gjson.GetBytes(terminal, "error.code").String(), "encrypted_agent_recovery_") { + logReadableWSRecoveryDetails(t, h) + } if allowRecovery { require.Equal(t, "response.completed", gjson.GetBytes(terminal, "type").String(), string(terminal)) require.Equal(t, int32(1), writesB.Load()) diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 709875042ec0..3f4f2c8733be 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -166,6 +166,20 @@ func logReadableWSDispatchFailure(t *testing.T, h *openAIWSPassthroughHandlerHar t.Logf("actual B dispatch error: %v; client close: %v", reported, clientErr) } +func logReadableWSRecoveryDetails(t *testing.T, h *openAIWSPassthroughHandlerHarness) { + t.Helper() + for _, entry := range h.requestLogs.FilterMessage("openai.agent_recovery_refused").All() { + fields := entry.ContextMap() + details := make(map[string]any) + for _, key := range []string{"subreason", "phase", "turn", "request_written", "shadow_lookup", "shadow_epoch", "owner_observation", "owner_total", "owner_completed", "owner_pending", "owner_failed", "owner_conflicted", "owner_unknown", "tool_calls", "tool_results", "tool_pairs", "tool_unpaired", "tool_duplicate", "tool_incomplete"} { + if value, ok := fields[key]; ok { + details[key] = value + } + } + t.Logf("current-turn recovery metadata: %v", details) + } +} + func TestOpenAI409WSInitialWithoutPointer(t *testing.T) { for _, mode := range readableWSModes { for _, state := range []string{"paused", "rate_limited", "overloaded"} { @@ -621,6 +635,9 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string, persistent . require.Equal(t, 2, sends) logReadableWSDispatchFailure(t, h, readErr) } + if sends != 2+extraSends { + logReadableWSRecoveryDetails(t, h) + } require.Equal(t, 2+extraSends, sends, "WS_READABLE_B_DISPATCH_MISSING: same client must automatically replace disabled A before any next generation; close=%v terminal=%s", readErr, secondRaw) if modelCase { accounts.mu.Lock() From 24d52b2a4d5786073f1bbabc2c6af28cafdd4dbe Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:15:31 +0800 Subject: [PATCH 17/26] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=20shadow=20?= =?UTF-8?q?=E5=BF=AB=E7=85=A7=E4=B8=AD=E8=A2=AB=E5=8E=86=E5=8F=B2=E5=85=83?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E9=81=AE=E6=8C=A1=E7=9A=84=E5=8F=AF=E8=AF=BB?= =?UTF-8?q?=E4=BB=BB=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_409_readable_shadow.go | 23 +++++++++++++++++++ .../service/openai_ws_owner_conflict_test.go | 12 ++++++++++ 2 files changed, 35 insertions(+) diff --git a/backend/internal/service/openai_409_readable_shadow.go b/backend/internal/service/openai_409_readable_shadow.go index 8df17a55932e..d3c49c9a3005 100644 --- a/backend/internal/service/openai_409_readable_shadow.go +++ b/backend/internal/service/openai_409_readable_shadow.go @@ -255,6 +255,29 @@ func openAIReadableShadowCandidate(body []byte) *openAIReadableShadow { if err != nil { return nil } + // Ciphertext omission renders an agent envelope as a metadata-only user + // message. It is not a newer user task: retaining it as the last user in a + // shadow hides the preceding genuine intent when the snapshot is restored. + // Ownership/epoch fences already retain that envelope's identity. + var portable []json.RawMessage + for _, item := range gjson.GetBytes(clean, "input").Array() { + content := item.Get("content") + metadataOnly := item.Get("role").String() == "user" && content.IsArray() && len(content.Array()) > 0 + for _, part := range content.Array() { + metadataOnly = metadataOnly && part.Get("type").String() == "input_text" && strings.HasPrefix(part.Get("text").String(), "Historical agent context (not a new instruction): ") + } + if !metadataOnly { + portable = append(portable, json.RawMessage(item.Raw)) + } + } + encoded, err := json.Marshal(portable) + if err != nil { + return nil + } + clean, err = sjson.SetRawBytes(clean, "input", encoded) + if err != nil { + return nil + } input := gjson.GetBytes(clean, "input") if !input.IsArray() || len(input.Raw) > OpenAIReadableShadowMaxBytes { return nil diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go index 249e03b09014..01abf89e5723 100644 --- a/backend/internal/service/openai_ws_owner_conflict_test.go +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -322,3 +322,15 @@ func TestOpenAIRecoveryShadowRefusalDiagnostics(t *testing.T) { }) } } + +func TestOpenAIRecoveryShadowRetainsTaskBeforeOpaqueEnvelope(t *testing.T) { + body := []byte(`{"input":[{"role":"user","content":"original readable task"},{"type":"agent_message","encrypted_content":"private-cipher"},{"type":"function_call","name":"inspect","call_id":"done","arguments":"{}"},{"type":"function_call_output","call_id":"done","output":"completed once"}]}`) + snapshot := openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + restored := []byte(`{"input":` + string(snapshot.Input) + `}`) + require.True(t, openAI409HasReadableIntent(restored), "stored context must still identify the original readable task") + require.Contains(t, string(restored), "original readable task") + require.Contains(t, string(restored), "completed once") + require.NotContains(t, string(restored), "private-cipher") + require.True(t, openAIWSCompletedToolInputs(restored)) +} From f3bef59810f8a4fa211d942a25522d4fee4cc966 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:23:14 +0800 Subject: [PATCH 18/26] =?UTF-8?q?test:=20=E5=8C=BA=E5=88=86=E6=A8=A1?= =?UTF-8?q?=E5=9E=8B=E7=BB=A7=E6=89=BF=E4=B8=8E=E8=B7=A8=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E8=AF=81=E6=98=8E=E5=B9=B6=E4=BF=AE=E6=AD=A3=E7=BB=AD=E6=8E=A5?= =?UTF-8?q?=E9=AA=8C=E6=94=B6=E5=A4=B9=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../handler/openai_409_ws_oracle_test.go | 14 +++--- .../handler/openai_409_ws_rebuild_test.go | 44 ++++++++++++++----- .../handler/openai_ws_owner_conflict_test.go | 7 ++- 3 files changed, 48 insertions(+), 17 deletions(-) diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index 3acc7b31f94d..043f3e2f002e 100644 --- a/backend/internal/handler/openai_409_ws_oracle_test.go +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -59,15 +59,19 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt } return []byte(`{"type":"response.completed","response":{"id":"resp_issue854_warm","status":"completed","model":"gpt-5.1","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"issue854-warm-B-complete"}]}],"usage":{"input_tokens":2,"output_tokens":1}}}`) } - if u.scenario == "bridge_model" && n == 2 { - if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-A" || gjson.GetBytes(body, "model").String() != "gpt-5.4" || !strings.Contains(string(body), "model-switch-warmup") { + if (u.scenario == "bridge_model" && n == 1) || (u.scenario == "bridge_model_cross_scope" && n == 2) { + expectedModel := "gpt-5.1" + if u.scenario == "bridge_model_cross_scope" { + expectedModel = "gpt-5.4" + } + if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-A" || gjson.GetBytes(body, "model").String() != expectedModel || !strings.Contains(string(body), "model-switch-warmup") { u.validationFailures++ return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_model_warmup_failed"}}}`) } - return []byte(`{"type":"response.completed","response":{"id":"resp_model_warmup","status":"completed","model":"gpt-5.4","error":null,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"model-switch-complete"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`) + return []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_model_warmup","status":"completed","model":%q,"error":null,"output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"model-switch-complete"}]}],"usage":{"input_tokens":5,"output_tokens":3}}}`, expectedModel)) } logicalTurn := n - if (u.scenario == "bridge_model" || strings.HasPrefix(u.scenario, "issue854_guard_")) && n > 2 { + if (u.scenario == "bridge_model" && n > 1) || ((u.scenario == "bridge_model_cross_scope" || strings.HasPrefix(u.scenario, "issue854_guard_")) && n > 2) { logicalTurn-- } output := []json.RawMessage{json.RawMessage(httpRebuildAgentA), json.RawMessage(httpRebuildCall("apply_patch", "call_ws_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))} @@ -75,7 +79,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt if customTools && n == 1 { output = append(output, json.RawMessage(httpRebuildCall("exec", "call_ws_exec", map[string]any{"input": "read sum.go"}))) } - if n > 1 { + if logicalTurn > 1 { if u.unrelatedEOF { return nil } diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 3f4f2c8733be..2d6a1bac7c78 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -108,6 +108,9 @@ func TestOpenAI409WSReviewRepairs(t *testing.T) { t.Run("bridge_inherited_model", func(t *testing.T) { runReadableWSContinuation(t, service.OpenAIWSIngressModeHTTPBridge, "bridge_model") }) + t.Run("bridge_cross_model_proof_refused", func(t *testing.T) { + runReadableWSContinuation(t, service.OpenAIWSIngressModeHTTPBridge, "bridge_model_cross_scope") + }) } func TestOpenAI409WSResidualRepairs(t *testing.T) { @@ -240,7 +243,7 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string, persistent . } initialNoPointer := strings.HasPrefix(scenario, "initial_no_pointer_") var initialUnavailableUntil time.Time - identityCase, modelCase := scenario == "identity" || strings.HasPrefix(scenario, "header_"), scenario == "bridge_model" + identityCase, modelCase := scenario == "identity" || strings.HasPrefix(scenario, "header_"), strings.HasPrefix(scenario, "bridge_model") customTools := strings.HasPrefix(scenario, "tools_") nativeNamespace := scenario == "native_namespace" smartMode := "" @@ -327,6 +330,14 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string, persistent . } return httpRebuildJSON(body) } + if scenario == "bridge_model" { + // Select M1, then earn the actual task/tool provenance on M2. The + // later omitted model must inherit M2, never the socket's initial M1. + issue715WSSend(t, h.clientConn, create([]string{httpRebuildMessage("user", "model-switch-warmup")}, "")) + warmup := issue715WSRead(t, h.clientConn) + require.Contains(t, string(warmup), "model-switch-complete") + requestModel = "gpt-5.4" + } history := []string{httpRebuildMessage("user", httpRebuildTask)} if scenario == "no_intent" { history = nil @@ -387,15 +398,16 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string, persistent . previous := first.Get("id").String() extraSends := 0 if modelCase { - // Establish M2 through the real transport, then omit model. In this - // bridge, BeforeTurn and final HTTP send are the two authoritative - // admission reads. Only the second read observes administrative disable. - requestModel = "gpt-5.4" - issue715WSSend(t, h.clientConn, create([]string{httpRebuildMessage("user", "model-switch-warmup")}, "")) - warmup := gjson.GetBytes(issue715WSRead(t, h.clientConn), "response") - require.Equal(t, "completed", warmup.Get("status").String()) - require.Contains(t, warmup.Raw, "model-switch-complete") - previous = warmup.Get("id").String() + if scenario == "bridge_model_cross_scope" { + // A genuine M1 call still cannot authorize an M2 replay. Preserve + // this former positive scenario as an explicit safety boundary. + requestModel = "gpt-5.4" + issue715WSSend(t, h.clientConn, create([]string{httpRebuildMessage("user", "model-switch-warmup")}, "")) + warmup := gjson.GetBytes(issue715WSRead(t, h.clientConn), "response") + require.Equal(t, "completed", warmup.Get("status").String()) + require.Contains(t, warmup.Raw, "model-switch-complete") + previous = warmup.Get("id").String() + } requestModel, extraSends = "", 1 accounts.mu.Lock() accounts.disableAdmission = 2 @@ -512,6 +524,18 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string, persistent . oracle.mu.Lock() sends := len(oracle.frames) oracle.mu.Unlock() + if scenario == "bridge_model_cross_scope" { + require.NoError(t, readErr) + require.Equal(t, "error", gjson.GetBytes(secondRaw, "type").String()) + require.Equal(t, "encrypted_agent_recovery_owner_conflict", gjson.GetBytes(secondRaw, "error.code").String()) + require.Equal(t, 2, sends, "cross-model proof must fail before B dispatch") + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + for key, raw := range owners { + require.Equal(t, raw, issue805Owners(t, probe)[key]) + } + return + } if r1Reject { require.NoError(t, readErr, "R1 refusal must be a structured business error") require.Equal(t, "error", gjson.GetBytes(secondRaw, "type").String()) diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index 3d8708459b85..1d122e606e69 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -362,7 +362,9 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.Equal(t, 1, customExecutions) } issue600Finish(t, h, headers) - accounts.disable(1) + if !shadowProvenance { + accounts.disable(1) + } dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) conn, _, err := coderws.Dial(dialCtx, h.wsURL, &coderws.DialOptions{HTTPHeader: headers}) cancel() @@ -587,6 +589,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios } } history = []string{httpRebuildAgentB} + accounts.disable(1) accounts.disable(2) // Require restored intent on a fresh provider route. issue600Finish(t, h, headers) dialCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) @@ -683,7 +686,7 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.NoError(t, err) require.Contains(t, string(final), "fixture mixed task complete") if association { - require.Contains(t, gjson.GetBytes(final, "response.output.0.content.0.text").String(), firstObject+"=first-value;"+secondObject+"=second-value") + require.Contains(t, gjson.GetBytes(final, "response.output.0.content").String(), firstObject+"=first-value;"+secondObject+"=second-value") require.Equal(t, 2, associationExecutions) } require.Equal(t, 1, tools.patches) From bd82493722f2f5c52659e73cb4fc11dc65bc51ba Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:24:25 +0800 Subject: [PATCH 19/26] =?UTF-8?q?docs:=20=E6=98=8E=E7=A1=AE=E7=BB=AD?= =?UTF-8?q?=E6=8E=A5=E8=AF=81=E6=98=8E=E5=85=BC=E5=AE=B9=E8=BE=B9=E7=95=8C?= =?UTF-8?q?=E5=B9=B6=E7=BA=B3=E5=85=A5=20shadow=20=E5=9B=9E=E5=BD=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ws-owner-conflict.yml | 4 ++-- docs/ws-mixed-owner-continuation.md | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index 34aa10c50b33..267d1d1181d7 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -96,12 +96,12 @@ jobs: set -euo pipefail (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^Test(OpenAI409(WSReadableContinuation|WSReadableBoundaries|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|FutureShadowPublicationFences|FutureShadowBoundaries|FutureShadowTaskAssociation|FutureShadowAuditProvenance)|OpenAIWSRevalidation|OpenAIResponsesWebSocketRevalidatesKeyWithoutCache|OpenAIWSKeyQueueAdmissionUsesCurrentTurnPermissions|OpenAIWSTurnPricing|Issue600ClientIdentityNetwork)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" - (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/service -run '^Test(OpenAIWSMixedOwner|OpenAIRecovery(Diagnostics|ShadowRefusalDiagnostics)|OpenAI409(RebuildRechecksOriginalDeliveryBeforeSend|WSUnsentTurnBoundary|WSTicket|ReplayInputTamperingStillFails|OAuthReplayKeepsOriginalSnapshotAndFinalControls)|Issue854BeforeSendRecoveryGuards|Issue715WS)' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" 2>&1 + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/service -run '^Test(OpenAIWSMixedOwner|OpenAIRecovery(Diagnostics|ShadowRefusalDiagnostics|ShadowRetainsTaskBeforeOpaqueEnvelope)|OpenAI409(RebuildRechecksOriginalDeliveryBeforeSend|WSUnsentTurnBoundary|WSTicket|ReplayInputTamperingStillFails|OAuthReplayKeepsOriginalSnapshotAndFinalControls)|Issue854BeforeSendRecoveryGuards|Issue715WS)' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" python3 - "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" <<'PY' import json, sys rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] - for test in ('TestOpenAIWSMixedOwnerFinalSendFences', 'TestOpenAIWSMixedOwnerProofCannotComeFromDiagnostics', 'TestOpenAIRecoveryDiagnosticsAreAllowlisted', 'TestOpenAIRecoveryShadowRefusalDiagnostics'): + for test in ('TestOpenAIWSMixedOwnerFinalSendFences', 'TestOpenAIWSMixedOwnerProofCannotComeFromDiagnostics', 'TestOpenAIRecoveryDiagnosticsAreAllowlisted', 'TestOpenAIRecoveryShadowRefusalDiagnostics', 'TestOpenAIRecoveryShadowRetainsTaskBeforeOpaqueEnvelope'): assert sum(r.get('Action') == 'pass' and r.get('Test') == test for r in rows) == 1, test PY - name: Persist safe refusal subtype with logical turn diff --git a/docs/ws-mixed-owner-continuation.md b/docs/ws-mixed-owner-continuation.md index 3378f836143a..7e61774d6b9e 100644 --- a/docs/ws-mixed-owner-continuation.md +++ b/docs/ws-mixed-owner-continuation.md @@ -13,6 +13,16 @@ original owner/epoch/shadow associations. Pending, failed, conflicting, missing, reissued or unrelated-task calls are refused. The client result is its completion report, not proof that an external side effect executed. +Proof scope is deliberately model-specific: a call delivered under M1 cannot +be replayed under M2 merely because the socket later selected M2. The inherited +model regression earns its real call on M2 before omitting the model; a separate +negative regression retains the M1-to-M2 case and requires zero B dispatches. +Calls delivered before this change, expired/evicted proofs, and calls without a +completed owner/shadow anchor cannot use this automatic WS recovery. Normal +forwarding and the existing Beta-off behavior do not acquire a replay permit. +No database migration is required. Rolling back ignores the separate proof +namespace; it does not restore proofs that have expired. + The gateway also requires a completed ownership observation for **every** supplied opaque item, readable current intent, and complete, unique tool call/result pairs. It discards provider pointers and historical ciphertext. In this mixed From cfb64db731c0a1cdaf4857add72a7bdbfd9dbfab Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:26:55 +0800 Subject: [PATCH 20/26] =?UTF-8?q?fix:=20=E5=B7=A5=E5=85=B7=E8=AF=81?= =?UTF-8?q?=E6=98=8E=E7=BC=93=E5=AD=98=E6=BB=A1=E6=97=B6=E4=BB=8D=E6=92=A4?= =?UTF-8?q?=E9=94=80=E9=87=8D=E5=A4=8D=E8=B0=83=E7=94=A8=E7=9A=84=E6=97=A7?= =?UTF-8?q?=E6=8E=88=E6=9D=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/service/openai_tool_provenance.go | 6 ++++-- backend/internal/service/openai_ws_owner_conflict_test.go | 6 ++++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go index bafb812a7423..10ab48d2b6a9 100644 --- a/backend/internal/service/openai_tool_provenance.go +++ b/backend/internal/service/openai_tool_provenance.go @@ -129,10 +129,12 @@ func (s *OpenAIGatewayService) toolProofReserve(ctx context.Context, key, token delete(state.toolProofs, k) } } - if len(state.toolProofs) >= 128 { + old := state.toolProofs[key] + if len(state.toolProofs) >= 128 && old.raw == "" { return openAIAgentRecoveryError("store_unavailable") } - old := state.toolProofs[key] + // Even at capacity, reissuing an existing identity must revoke its old + // proof. Rejecting before this update would leave the old grant usable. if old.raw != "" && old.raw != token { token = "conflict" } diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go index 01abf89e5723..6849fa3194ed 100644 --- a/backend/internal/service/openai_ws_owner_conflict_test.go +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -105,6 +105,12 @@ func TestOpenAIToolProvenanceDeliveryAndScope(t *testing.T) { } require.Error(t, svc.verifyOpenAIToolInputs(ctx, &other, body), scope) } + // Exhaust the no-shared-cache budget before a provider reissues the + // proven call. Capacity must block new grants, not old revocations. + for i := 0; i < 127; i++ { + require.NoError(t, svc.toolProofReserve(context.Background(), openAIToolHash(i), "pending:fixture-budget")) + } + require.Error(t, svc.toolProofReserve(context.Background(), "fixture-over-capacity", "pending:fixture-budget")) require.NoError(t, svc.toolProofReserve(context.Background(), key, "pending:another-delivery")) svc.toolProofFinish(context.Background(), key, "pending:another-delivery", raw, true) conflict, err := svc.toolProofGet(context.Background(), key) From d053446d9acb1df4b7f6c3ae7137ec27c69e9f64 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:30:30 +0800 Subject: [PATCH 21/26] =?UTF-8?q?test:=20=E5=8D=95=E7=8B=AC=E9=AA=8C?= =?UTF-8?q?=E6=94=B6=E6=96=B0=E6=A8=A1=E5=9E=8B=E8=AF=81=E6=98=8E=E8=BE=B9?= =?UTF-8?q?=E7=95=8C=E4=BB=A5=E4=BF=9D=E6=8C=81=E5=8E=86=E5=8F=B2=20RED=20?= =?UTF-8?q?=E5=A5=91=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ws-owner-conflict.yml | 2 +- backend/internal/handler/openai_409_ws_rebuild_test.go | 9 ++++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index 267d1d1181d7..855a339eb014 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -94,7 +94,7 @@ jobs: shell: bash run: | set -euo pipefail - (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^Test(OpenAI409(WSReadableContinuation|WSReadableBoundaries|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|FutureShadowPublicationFences|FutureShadowBoundaries|FutureShadowTaskAssociation|FutureShadowAuditProvenance)|OpenAIWSRevalidation|OpenAIResponsesWebSocketRevalidatesKeyWithoutCache|OpenAIWSKeyQueueAdmissionUsesCurrentTurnPermissions|OpenAIWSTurnPricing|Issue600ClientIdentityNetwork)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" 2>&1 + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^Test(OpenAI409(WSReadableContinuation|WSReadableBoundaries|WSCrossModelProofRefused|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|FutureShadowPublicationFences|FutureShadowBoundaries|FutureShadowTaskAssociation|FutureShadowAuditProvenance)|OpenAIWSRevalidation|OpenAIResponsesWebSocketRevalidatesKeyWithoutCache|OpenAIWSKeyQueueAdmissionUsesCurrentTurnPermissions|OpenAIWSTurnPricing|Issue600ClientIdentityNetwork)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/service -run '^Test(OpenAIWSMixedOwner|OpenAIRecovery(Diagnostics|ShadowRefusalDiagnostics|ShadowRetainsTaskBeforeOpaqueEnvelope)|OpenAI409(RebuildRechecksOriginalDeliveryBeforeSend|WSUnsentTurnBoundary|WSTicket|ReplayInputTamperingStillFails|OAuthReplayKeepsOriginalSnapshotAndFinalControls)|Issue854BeforeSendRecoveryGuards|Issue715WS)' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 2d6a1bac7c78..565187d287a6 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -108,9 +108,12 @@ func TestOpenAI409WSReviewRepairs(t *testing.T) { t.Run("bridge_inherited_model", func(t *testing.T) { runReadableWSContinuation(t, service.OpenAIWSIngressModeHTTPBridge, "bridge_model") }) - t.Run("bridge_cross_model_proof_refused", func(t *testing.T) { - runReadableWSContinuation(t, service.OpenAIWSIngressModeHTTPBridge, "bridge_model_cross_scope") - }) +} + +// Keep this new proof boundary separate from the historical review RED suite: +// that suite pins an older implementation without tool provenance. +func TestOpenAI409WSCrossModelProofRefused(t *testing.T) { + runReadableWSContinuation(t, service.OpenAIWSIngressModeHTTPBridge, "bridge_model_cross_scope") } func TestOpenAI409WSResidualRepairs(t *testing.T) { From 2ab4d417bf621553d735829ee6d3942b07d875c7 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:31:11 +0800 Subject: [PATCH 22/26] fix: preserve typed shadow context and inherited-model tool provenance --- .../handler/openai_409_ws_oracle_test.go | 6 +-- .../service/openai_409_readable_shadow.go | 41 +++++++++++++++---- .../service/openai_tool_provenance.go | 5 ++- .../service/openai_ws_owner_conflict_test.go | 14 ++++++- 4 files changed, 52 insertions(+), 14 deletions(-) diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index 043f3e2f002e..8c64afb7b03e 100644 --- a/backend/internal/handler/openai_409_ws_oracle_test.go +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -85,14 +85,14 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt } validTools := httpRebuildToolsAvailable(body) if customTools { - validTools = readableWSCustomToolsAvailable(body, logicalTurn == 3 && u.scenario != "bridge_model") + validTools = readableWSCustomToolsAvailable(body, logicalTurn == 3 && u.scenario != "bridge_model_cross_scope") } if u.scenario == "native_namespace" { validTools = true // exact native declarations/schema checked above, including A } valid := r.Header.Get("Authorization") == "Bearer fixture-readable-ws-B" && strings.Contains(string(body), httpRebuildTask) && validTools && - readableWSCompletedResult(body, "apply_patch", httpRebuildPatch, logicalTurn == 3 && u.scenario != "bridge_model") && + readableWSCompletedResult(body, "apply_patch", httpRebuildPatch, logicalTurn == 3 && u.scenario != "bridge_model_cross_scope") && !strings.Contains(string(body), "fixture-opaque-A") && !gjson.GetBytes(body, "previous_response_id").Exists() && !gjson.GetBytes(body, "conversation").Exists() if u.scenario == "bridge_model" { @@ -109,7 +109,7 @@ func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byt return nil } output = []json.RawMessage{json.RawMessage(httpRebuildAgentB), json.RawMessage(httpRebuildCall("run_tests", "call_ws_verify", map[string]any{"path": "sum.go"}))} - if logicalTurn == 3 && readableWSCompletedResult(body, "run_tests", httpRebuildCheck, u.scenario != "bridge_model") { + if logicalTurn == 3 && readableWSCompletedResult(body, "run_tests", httpRebuildCheck, u.scenario != "bridge_model_cross_scope") { output = []json.RawMessage{json.RawMessage(httpRebuildJSON(map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "ws-coding-task-complete"}}}))} } else if logicalTurn > 2 { return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_duplicate_or_missing_tool"}}}`) diff --git a/backend/internal/service/openai_409_readable_shadow.go b/backend/internal/service/openai_409_readable_shadow.go index d3c49c9a3005..1dc2c59b7799 100644 --- a/backend/internal/service/openai_409_readable_shadow.go +++ b/backend/internal/service/openai_409_readable_shadow.go @@ -242,6 +242,7 @@ func openAIReadableShadowCandidate(body []byte) *openAIReadableShadow { if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) || !openAI409HasReadableIntent(body) { return nil } + originalItems := gjson.GetBytes(body, "input").Array() clean := body if input := gjson.GetBytes(clean, "input"); input.Type == gjson.String { value, _ := json.Marshal([]any{map[string]any{"type": "message", "role": "user", "content": input.String()}}) @@ -258,17 +259,39 @@ func openAIReadableShadowCandidate(body []byte) *openAIReadableShadow { // Ciphertext omission renders an agent envelope as a metadata-only user // message. It is not a newer user task: retaining it as the last user in a // shadow hides the preceding genuine intent when the snapshot is restored. - // Ownership/epoch fences already retain that envelope's identity. + // Retain its readable metadata as assistant context; ownership/epoch fences + // retain the envelope's identity. Dropping it would lose summaries/content. var portable []json.RawMessage - for _, item := range gjson.GetBytes(clean, "input").Array() { - content := item.Get("content") - metadataOnly := item.Get("role").String() == "user" && content.IsArray() && len(content.Array()) > 0 - for _, part := range content.Array() { - metadataOnly = metadataOnly && part.Get("type").String() == "input_text" && strings.HasPrefix(part.Get("text").String(), "Historical agent context (not a new instruction): ") - } - if !metadataOnly { - portable = append(portable, json.RawMessage(item.Raw)) + items := gjson.GetBytes(clean, "input").Array() + for i, item := range items { + raw := []byte(item.Raw) + // Provenance is the original typed envelope, not a text prefix that a + // caller could also use in a genuine new user message. + if i < len(originalItems) && originalItems[i].Get("type").String() == "agent_message" { + if len(items) != len(originalItems) || item.Get("type").String() != "message" || + !strings.HasPrefix(item.Get("content.0.text").String(), "Historical agent context (not a new instruction): ") { + return nil + } + var message map[string]any + if decodeOpenAIJSONUseNumber(raw, &message) != nil { + return nil + } + message["role"] = "assistant" + parts, ok := message["content"].([]any) + if !ok { + return nil + } + for _, value := range parts { + if part, ok := value.(map[string]any); ok && part["type"] == "input_text" { + part["type"] = "output_text" + } + } + raw, err = json.Marshal(message) + if err != nil { + return nil + } } + portable = append(portable, raw) } encoded, err := json.Marshal(portable) if err != nil { diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go index bafb812a7423..2f8d3c7f62e7 100644 --- a/backend/internal/service/openai_tool_provenance.go +++ b/backend/internal/service/openai_tool_provenance.go @@ -61,7 +61,10 @@ func openAIToolHash(value any) string { } func (r *openAIAgentRecoveryRequest) toolKey(id string) string { - return r.shadowPrincipal() + ":" + openAIToolHash([]any{"tool-v1", r.userID, r.keyID, r.groupID, r.session, r.model, r.shadowModel, id}) + // The forward model is the authoritative current-turn scope. Raw WS + // frames may omit model after a successful selection; shadowModel is an + // optional input field for shadow lookup, not a second tool-proof scope. + return r.shadowPrincipal() + ":" + openAIToolHash([]any{"tool-v1", r.userID, r.keyID, r.groupID, r.session, r.model, id}) } func openAIToolFingerprint(item gjson.Result) (string, bool) { diff --git a/backend/internal/service/openai_ws_owner_conflict_test.go b/backend/internal/service/openai_ws_owner_conflict_test.go index 01abf89e5723..15cdf8c0a7b8 100644 --- a/backend/internal/service/openai_ws_owner_conflict_test.go +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -324,13 +324,25 @@ func TestOpenAIRecoveryShadowRefusalDiagnostics(t *testing.T) { } func TestOpenAIRecoveryShadowRetainsTaskBeforeOpaqueEnvelope(t *testing.T) { - body := []byte(`{"input":[{"role":"user","content":"original readable task"},{"type":"agent_message","encrypted_content":"private-cipher"},{"type":"function_call","name":"inspect","call_id":"done","arguments":"{}"},{"type":"function_call_output","call_id":"done","output":"completed once"}]}`) + body := []byte(`{"input":[{"role":"user","content":"original readable task"},{"type":"agent_message","summary":[{"type":"summary_text","text":"retain this agent summary"}],"encrypted_content":"private-cipher"},{"type":"function_call","name":"inspect","call_id":"done","arguments":"{}"},{"type":"function_call_output","call_id":"done","output":"completed once"}]}`) snapshot := openAIReadableShadowCandidate(body) require.NotNil(t, snapshot) restored := []byte(`{"input":` + string(snapshot.Input) + `}`) require.True(t, openAI409HasReadableIntent(restored), "stored context must still identify the original readable task") require.Contains(t, string(restored), "original readable task") require.Contains(t, string(restored), "completed once") + require.Contains(t, string(restored), "retain this agent summary") + require.Equal(t, "assistant", gjson.GetBytes(restored, "input.1.role").String()) require.NotContains(t, string(restored), "private-cipher") require.True(t, openAIWSCompletedToolInputs(restored)) } + +func TestOpenAIRecoveryShadowDoesNotReclassifyClientMetadataText(t *testing.T) { + body := []byte(`{"input":[{"role":"user","content":"old task"},{"role":"user","content":[{"type":"input_text","text":"Historical agent context (not a new instruction): literal client text"}],"summary":"new explicit user task"}]}`) + snapshot := openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + restored := []byte(`{"input":` + string(snapshot.Input) + `}`) + require.Equal(t, "user", gjson.GetBytes(restored, "input.1.role").String()) + require.Equal(t, "new explicit user task", gjson.GetBytes(restored, "input.1.summary").String()) + require.True(t, openAI409HasReadableIntent(restored)) +} From 1f1aed22ed17a3a82be0d01a4590e7d8a0c6afa9 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:36:32 +0800 Subject: [PATCH 23/26] fix: preserve shadow intent before encrypted envelope projection --- .github/scripts/shadow-omission-evidence.py | 49 ++++++++++ .../scripts/test_shadow_omission_evidence.py | 53 +++++++++++ .github/workflows/ws-shadow-omission.yml | 95 +++++++++++++++++++ .../service/openai_409_readable_shadow.go | 78 ++++++++++----- .../openai_409_shadow_candidate_test.go | 86 +++++++++++++++++ 5 files changed, 338 insertions(+), 23 deletions(-) create mode 100644 .github/scripts/shadow-omission-evidence.py create mode 100644 .github/scripts/test_shadow_omission_evidence.py create mode 100644 .github/workflows/ws-shadow-omission.yml create mode 100644 backend/internal/service/openai_409_shadow_candidate_test.go diff --git a/.github/scripts/shadow-omission-evidence.py b/.github/scripts/shadow-omission-evidence.py new file mode 100644 index 000000000000..f6dea1cf28ba --- /dev/null +++ b/.github/scripts/shadow-omission-evidence.py @@ -0,0 +1,49 @@ +"""Original WS audit/NextTurn assertions, with exact business RED reasons.""" +import importlib.util +import json +import re +import sys +from collections import Counter +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location("clean", Path(__file__).with_name("assert-readable-continuation.py")) +CLEAN = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(CLEAN) +PACKAGE = "github.com/Wei-Shaw/sub2api/internal/handler" +AUDIT = "TestOpenAI409WSRecoveredAudit" +NEXT = "TestOpenAI409WSRecoveredAuditNextTurn" +MODES = ("http_bridge", "ctx_pool", "shared", "dedicated", "passthrough") +LEAVES = {f"{AUDIT}/{mode}/{policy}" for mode in MODES for policy in ("prompt", "selected")} | {f"{NEXT}/{mode}" for mode in MODES} + + +def validate(phase, status, raw): + CLEAN.check_clean(raw) + if phase not in ("RED", "GREEN") or status != (1 if phase == "RED" else 0): + raise ValueError("unexpected phase or process status") + rows = [json.loads(line) for line in raw.splitlines() if line.startswith("{")] + outcome = "fail" if phase == "RED" else "pass" + tests = LEAVES | {AUDIT, NEXT} + counts = Counter((row.get("Action"), row.get("Test")) for row in rows if row.get("Package") == PACKAGE) + for name in tests: + if counts["run", name] != 1 or counts[outcome, name] != 1 or counts["pass", name] + counts["fail", name] != 1: + raise ValueError(f"missing/duplicate/wrong test outcome: {name}") + if counts[outcome, None] != 1 or counts["pass", None] + counts["fail", None] != 1: + raise ValueError("missing package completion") + for row in rows: + if row.get("Action") in ("run", "pass", "fail") and (row.get("Package") != PACKAGE or row.get("Test") not in tests | {None}): + raise ValueError("unrelated result is not evidence") + if phase == "RED": + for name in LEAVES: + output = "".join(row.get("Output", "") for row in rows if row.get("Package") == PACKAGE and row.get("Test") == name) + expected = "response.completed" if name.startswith(NEXT + "/") else "prompt_guard_blocked" if name.endswith("/prompt") else "content_policy_violation" + actual = "error" if name.startswith(NEXT + "/") else "encrypted_agent_recovery_readable_intent_missing" + if not re.search(r'expected:\s*"' + re.escape(expected) + r'"', output) or not re.search(r'actual\s*:\s*"' + re.escape(actual) + r'"', output): + raise ValueError(f"not the original shadow/audit assertion: {name}") + if "encrypted_agent_recovery_readable_intent_missing" not in output: + raise ValueError(f"missing own actual business refusal: {name}") + + +if __name__ == "__main__": + phase, status, path = sys.argv[1:] + validate(phase, int(status), Path(path).read_text()) + print(f"{phase}: all 15 original WS recovered-audit/NextTurn scenarios verified") diff --git a/.github/scripts/test_shadow_omission_evidence.py b/.github/scripts/test_shadow_omission_evidence.py new file mode 100644 index 000000000000..b700a1ca11bc --- /dev/null +++ b/.github/scripts/test_shadow_omission_evidence.py @@ -0,0 +1,53 @@ +import importlib.util +import json +import unittest +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location("evidence", Path(__file__).with_name("shadow-omission-evidence.py")) +EVIDENCE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(EVIDENCE) + + +def fixture(phase): + rows = [] + for name in sorted(EVIDENCE.LEAVES | {EVIDENCE.AUDIT, EVIDENCE.NEXT}): + rows.append({"Package": EVIDENCE.PACKAGE, "Action": "run", "Test": name}) + rows.append({"Package": EVIDENCE.PACKAGE, "Action": "fail" if phase == "RED" else "pass", "Test": name}) + if name in EVIDENCE.LEAVES: + expected = "response.completed" if name.startswith(EVIDENCE.NEXT + "/") else "prompt_guard_blocked" if name.endswith("/prompt") else "content_policy_violation" + actual = "error" if name.startswith(EVIDENCE.NEXT + "/") else "encrypted_agent_recovery_readable_intent_missing" + rows.append({"Package": EVIDENCE.PACKAGE, "Action": "output", "Test": name, "Output": f'expected: "{expected}"\nactual : "{actual}"\nMessages: encrypted_agent_recovery_readable_intent_missing'}) + rows.append({"Package": EVIDENCE.PACKAGE, "Action": "fail" if phase == "RED" else "pass"}) + return rows + + +class ShadowEvidenceTests(unittest.TestCase): + def test_complete(self): + for phase in ("RED", "GREEN"): + EVIDENCE.validate(phase, 1 if phase == "RED" else 0, "\n".join(map(json.dumps, fixture(phase)))) + + def test_false_red_rejected(self): + for mutation in ("missing", "duplicate", "wrong_refusal", "panic", "skip", "build", "unrelated"): + with self.subTest(mutation=mutation): + rows = fixture("RED") + if mutation == "missing": rows.pop(0) + if mutation == "duplicate": rows.append(rows[0]) + if mutation == "wrong_refusal": + for row in rows: + if "Output" in row: row["Output"] = row["Output"].replace("readable_intent_missing", "owner_conflict") + if mutation == "panic": rows.append({"Output": "panic: fixture"}) + if mutation == "skip": rows[1]["Action"] = "skip" + if mutation == "build": rows = [{"Output": "[build failed]"}] + if mutation == "unrelated": rows[0]["Test"] = "TestOther" + with self.assertRaises(ValueError): + EVIDENCE.validate("RED", 1, "\n".join(map(json.dumps, rows))) + + def test_partial_green_rejected(self): + rows = fixture("GREEN") + rows = [row for row in rows if row.get("Test") != EVIDENCE.NEXT + "/ctx_pool"] + with self.assertRaises(ValueError): + EVIDENCE.validate("GREEN", 0, "\n".join(map(json.dumps, rows))) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/ws-shadow-omission.yml b/.github/workflows/ws-shadow-omission.yml new file mode 100644 index 000000000000..6b8f2613f056 --- /dev/null +++ b/.github/workflows/ws-shadow-omission.yml @@ -0,0 +1,95 @@ +name: WS shadow omission intent + +on: + pull_request: + branches: [production] + paths: + - backend/internal/service/openai_409_readable_shadow.go + - backend/internal/service/openai_409_shadow_candidate_test.go + - backend/internal/handler/openai_409_ws_audit_test.go + - .github/workflows/ws-shadow-omission.yml + - .github/scripts/shadow-omission-evidence.py + - .github/scripts/test_shadow_omission_evidence.py + +permissions: + contents: read + +jobs: + shadow-intent: + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + GOMAXPROCS: '2' + CANDIDATE: ${{ github.event.pull_request.head.sha }} + BASELINE: bd82493722f2f5c52659e73cb4fc11dc65bc51ba + 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: Isolated Redis and evidence parser + run: | + set -euo pipefail + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + python3 -m unittest discover -s .github/scripts -p 'test_shadow_omission_evidence.py' + - name: Original handler assertions RED on exact bd824 shadow production + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git diff --exit-code + mkdir -p "$RUNNER_TEMP/shadow-omission-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/shadow-omission-evidence/candidate.txt" + # The actual audit and NextTurn fixture/expectations are unchanged. + fixture=backend/internal/handler/openai_409_ws_audit_test.go + test "$(git hash-object "$fixture")" = "$(git rev-parse "$BASELINE:$fixture")" + git rev-parse "$CANDIDATE:$fixture" > "$RUNNER_TEMP/shadow-omission-evidence/unchanged-handler-test.txt" + git worktree add --detach "$RUNNER_TEMP/shadow-omission-red" "$CANDIDATE" + target=backend/internal/service/openai_409_readable_shadow.go + git show "$BASELINE:$target" > "$RUNNER_TEMP/shadow-omission-red/$target" + test "$(git hash-object "$RUNNER_TEMP/shadow-omission-red/$target")" = "$(git rev-parse "$BASELINE:$target")" + git rev-parse "$BASELINE" "$BASELINE:$target" > "$RUNNER_TEMP/shadow-omission-evidence/baseline.txt" + set +e + (cd "$RUNNER_TEMP/shadow-omission-red/backend" && go test -p=1 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAI409WSRecoveredAudit(NextTurn)?$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/shadow-omission-evidence/red.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/shadow-omission-evidence/red.jsonl" + python3 .github/scripts/shadow-omission-evidence.py RED "$status" "$RUNNER_TEMP/shadow-omission-evidence/red.jsonl" + - name: Same original handler assertions GREEN on clean candidate + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE" + git diff --exit-code + set +e + (cd backend && go test -race -p=1 -tags=unit,ownerconflict ./internal/handler -run '^TestOpenAI409WSRecoveredAudit(NextTurn)?$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/shadow-omission-evidence/green.jsonl" 2>&1 + status=$? + set -e + cat "$RUNNER_TEMP/shadow-omission-evidence/green.jsonl" + python3 .github/scripts/shadow-omission-evidence.py GREEN "$status" "$RUNNER_TEMP/shadow-omission-evidence/green.jsonl" + - name: Typed source and supplied-text boundaries + shell: bash + run: | + set -euo pipefail + (cd backend && go test -race -p=1 -tags=unit,ownerconflict ./internal/service -run '^TestOpenAIRecoveryShadow(RetainsTaskBeforeOpaqueEnvelope|TypedEnvelopeOmission|PreservesSuppliedText|PreservesSummaryOnlyIntent)$' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/shadow-omission-evidence/source-boundaries.jsonl" 2>&1 + python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/shadow-omission-evidence/source-boundaries.jsonl" + python3 - "$RUNNER_TEMP/shadow-omission-evidence/source-boundaries.jsonl" <<'PY' + import json,sys + rows=[json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] + for name in ('RetainsTaskBeforeOpaqueEnvelope','TypedEnvelopeOmission','PreservesSuppliedText','PreservesSummaryOnlyIntent'): + assert sum(row.get('Action')=='pass' and row.get('Test')=='TestOpenAIRecoveryShadow'+name for row in rows)==1,name + assert not any(row.get('Action') in ('skip','fail') for row in rows) + PY + - uses: actions/upload-artifact@v7 + if: always() + with: + name: ws-shadow-omission-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/shadow-omission-evidence diff --git a/backend/internal/service/openai_409_readable_shadow.go b/backend/internal/service/openai_409_readable_shadow.go index d3c49c9a3005..a80cbb7c02d1 100644 --- a/backend/internal/service/openai_409_readable_shadow.go +++ b/backend/internal/service/openai_409_readable_shadow.go @@ -247,34 +247,38 @@ func openAIReadableShadowCandidate(body []byte) *openAIReadableShadow { value, _ := json.Marshal([]any{map[string]any{"type": "message", "role": "user", "content": input.String()}}) clean, _ = sjson.SetRawBytes(clean, "input", value) } - if omitted, changed := omitOpenAIHistoricalCiphertext(clean); changed { - clean = omitted - } - var err error - clean, err = prepareOpenAI409ReadableReplay(clean) - if err != nil { - return nil + // Inspect the original typed envelopes before omission turns them into + // ordinary user messages. An envelope with no supplied readable content + // contributes only gateway attribution/omission notices, not a newer task. + // Its identity still belongs to the original request's owner/epoch fences. + // Never identify generated messages by text: clients can supply that text. + items := gjson.GetBytes(clean, "input").Array() + portable := make([]json.RawMessage, 0, len(items)) + removed := false + for _, item := range items { + if item.Get("type").String() == "agent_message" && + openAIReadableShadowAgentTextEmpty(item.Get("content")) && + openAIReadableShadowAgentTextEmpty(item.Get("summary")) { + removed = true + continue + } + portable = append(portable, json.RawMessage(item.Raw)) } - // Ciphertext omission renders an agent envelope as a metadata-only user - // message. It is not a newer user task: retaining it as the last user in a - // shadow hides the preceding genuine intent when the snapshot is restored. - // Ownership/epoch fences already retain that envelope's identity. - var portable []json.RawMessage - for _, item := range gjson.GetBytes(clean, "input").Array() { - content := item.Get("content") - metadataOnly := item.Get("role").String() == "user" && content.IsArray() && len(content.Array()) > 0 - for _, part := range content.Array() { - metadataOnly = metadataOnly && part.Get("type").String() == "input_text" && strings.HasPrefix(part.Get("text").String(), "Historical agent context (not a new instruction): ") + if removed { + encoded, err := json.Marshal(portable) + if err != nil { + return nil } - if !metadataOnly { - portable = append(portable, json.RawMessage(item.Raw)) + clean, err = sjson.SetRawBytes(clean, "input", encoded) + if err != nil { + return nil } } - encoded, err := json.Marshal(portable) - if err != nil { - return nil + if omitted, changed := omitOpenAIHistoricalCiphertext(clean); changed { + clean = omitted } - clean, err = sjson.SetRawBytes(clean, "input", encoded) + var err error + clean, err = prepareOpenAI409ReadableReplay(clean) if err != nil { return nil } @@ -331,6 +335,34 @@ func openAIReadableShadowCandidate(body []byte) *openAIReadableShadow { return record } +// Only absence, blank text, and typed encrypted parts establish that an agent +// envelope has no readable contribution. Retain unknown representations and +// literal prefix/marker lookalikes for the existing projection/validation path. +func openAIReadableShadowAgentTextEmpty(value gjson.Result) bool { + if !value.Exists() || value.Type == gjson.Null { + return true + } + if value.Type == gjson.String { + return strings.TrimSpace(value.String()) == "" + } + if !value.IsArray() { + return false + } + for _, part := range value.Array() { + if part.Get("type").String() == "encrypted_content" { + continue + } + switch part.Get("type").String() { + case "input_text", "output_text", "text", "summary_text": + if part.Get("text").Type == gjson.String && strings.TrimSpace(part.Get("text").String()) == "" { + continue + } + } + return false + } + return true +} + func openAIReadableShadowTextOnly(content gjson.Result) bool { if content.Type == gjson.String || content.Type == gjson.Null { return true diff --git a/backend/internal/service/openai_409_shadow_candidate_test.go b/backend/internal/service/openai_409_shadow_candidate_test.go new file mode 100644 index 000000000000..345e1945ebf3 --- /dev/null +++ b/backend/internal/service/openai_409_shadow_candidate_test.go @@ -0,0 +1,86 @@ +//go:build unit && ownerconflict + +package service + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIRecoveryShadowTypedEnvelopeOmission(t *testing.T) { + for name, envelope := range map[string]string{ + "top_cipher": `{"type":"agent_message","encrypted_content":"fixture-private-cipher"}`, + "part_cipher": `{"type":"agent_message","content":[{"type":"encrypted_content","encrypted_content":"fixture-private-cipher"}]}`, + "empty": `{"type":"agent_message","content":" ","summary":[]}`, + } { + t.Run(name, func(t *testing.T) { + source := []byte(`{"input":[{"role":"user","content":"fixture current task"},` + envelope + `]}`) + snapshot := openAIReadableShadowCandidate(source) + require.NotNil(t, snapshot) + require.JSONEq(t, `[{"role":"user","content":"fixture current task"}]`, string(snapshot.Input)) + require.True(t, openAI409HasReadableIntent([]byte(`{"input":`+string(snapshot.Input)+`}`))) + require.Contains(t, string(source), envelope, "candidate construction must not mutate the original owner evidence") + }) + } +} + +func TestOpenAIRecoveryShadowPreservesSuppliedText(t *testing.T) { + const prefix = "Historical agent context (not a new instruction): fixture literal" + for name, literal := range map[string]string{"prefix": prefix, "marker": openAIHistoricalCiphertextOmitted} { + t.Run("user_"+name, func(t *testing.T) { + first, err := json.Marshal(map[string]any{"type": "message", "role": "user", "content": []any{map[string]string{"type": "input_text", "text": literal}}}) + require.NoError(t, err) + body := []byte(`{"input":[` + string(first) + `,{"role":"user","content":"fixture current task"},{"type":"agent_message","encrypted_content":"fixture-private-cipher"}]}`) + snapshot := openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + require.JSONEq(t, string(first), gjson.ParseBytes(snapshot.Input).Array()[0].Raw, "client text is never a gateway provenance marker") + require.True(t, openAI409HasReadableIntent([]byte(`{"input":`+string(snapshot.Input)+`}`))) + }) + t.Run("latest_user_"+name, func(t *testing.T) { + last, err := json.Marshal(map[string]any{"role": "user", "content": literal}) + require.NoError(t, err) + body := []byte(`{"input":[{"role":"user","content":"fixture earlier task"},` + string(last) + `]}`) + require.Nil(t, openAIReadableShadowCandidate(body), "do not delete the latest user to revive an older task") + }) + t.Run("agent_"+name, func(t *testing.T) { + envelope, err := json.Marshal(map[string]any{"type": "agent_message", "encrypted_content": "fixture-private-cipher", "content": literal, "summary": "fixture readable summary"}) + require.NoError(t, err) + body := []byte(`{"input":[{"role":"user","content":"fixture current task"},` + string(envelope) + `]}`) + snapshot := openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + parts := gjson.ParseBytes(snapshot.Input).Array()[1].Get("content").Array() + require.Equal(t, literal, parts[1].Get("text").String()) + require.Contains(t, string(snapshot.Input), "fixture readable summary") + require.NotContains(t, string(snapshot.Input), "fixture-private-cipher") + }) + } + for _, envelope := range []string{ + `{"type":"agent_message","content":"fixture readable content","encrypted_content":"fixture-private-cipher"}`, + `{"type":"agent_message","summary":[{"type":"summary_text","text":"fixture readable summary"}],"encrypted_content":"fixture-private-cipher"}`, + } { + body := []byte(`{"input":[{"role":"user","content":"fixture current task"},` + envelope + `]}`) + snapshot := openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + require.Len(t, gjson.ParseBytes(snapshot.Input).Array(), 2) + require.Contains(t, string(snapshot.Input), "fixture readable") + require.NotContains(t, string(snapshot.Input), "fixture-private-cipher") + require.True(t, openAI409HasReadableIntent([]byte(`{"input":`+string(snapshot.Input)+`}`))) + } +} + +func TestOpenAIRecoveryShadowPreservesSummaryOnlyIntent(t *testing.T) { + body := []byte(`{"input":[{"type":"agent_message","summary":[{"type":"summary_text","text":"fixture only readable task"}],"encrypted_content":"fixture-private-cipher"}]}`) + snapshot := openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + require.Contains(t, string(snapshot.Input), "fixture only readable task") + require.True(t, openAI409HasReadableIntent([]byte(`{"input":`+string(snapshot.Input)+`}`))) + body = []byte(`{"instructions":"fixture instructions task","input":[{"type":"agent_message","encrypted_content":"fixture-private-cipher"}]}`) + snapshot = openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + require.JSONEq(t, `[]`, string(snapshot.Input)) + require.JSONEq(t, `"fixture instructions task"`, string(snapshot.Instructions)) + require.True(t, openAI409HasReadableIntent([]byte(`{"instructions":`+string(snapshot.Instructions)+`,"input":`+string(snapshot.Input)+`}`))) +} From 863b1d0db2d01c63181dfaf60f978a5d4ef42a40 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 15 Nov 2026 23:38:06 +0800 Subject: [PATCH 24/26] =?UTF-8?q?ci:=20=E7=BA=B3=E5=85=A5=E7=9C=9F?= =?UTF-8?q?=E5=AE=9E=E7=94=A8=E6=88=B7=E5=85=83=E6=95=B0=E6=8D=AE=E6=96=87?= =?UTF-8?q?=E6=9C=AC=E4=B8=8D=E8=A2=AB=E6=94=B9=E5=86=99=E7=9A=84=E5=9B=9E?= =?UTF-8?q?=E5=BD=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/ws-owner-conflict.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml index 855a339eb014..c16c2d751ec6 100644 --- a/.github/workflows/ws-owner-conflict.yml +++ b/.github/workflows/ws-owner-conflict.yml @@ -96,12 +96,12 @@ jobs: set -euo pipefail (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/handler -run '^Test(OpenAI409(WSReadableContinuation|WSReadableBoundaries|WSCrossModelProofRefused|WSReviewRepairs|WSResidualRepairs|WSNativeNamespaceRecovery|WSRecoveredAudit|WSRecoveredAuditNextTurn|WSAmbiguousOracleMutations|FutureShadowPublicationFences|FutureShadowBoundaries|FutureShadowTaskAssociation|FutureShadowAuditProvenance)|OpenAIWSRevalidation|OpenAIResponsesWebSocketRevalidatesKeyWithoutCache|OpenAIWSKeyQueueAdmissionUsesCurrentTurnPermissions|OpenAIWSTurnPricing|Issue600ClientIdentityNetwork)' -count=1 -json -timeout=10m) > "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/contracts.jsonl" - (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/service -run '^Test(OpenAIWSMixedOwner|OpenAIRecovery(Diagnostics|ShadowRefusalDiagnostics|ShadowRetainsTaskBeforeOpaqueEnvelope)|OpenAI409(RebuildRechecksOriginalDeliveryBeforeSend|WSUnsentTurnBoundary|WSTicket|ReplayInputTamperingStillFails|OAuthReplayKeepsOriginalSnapshotAndFinalControls)|Issue854BeforeSendRecoveryGuards|Issue715WS)' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" 2>&1 + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./internal/service -run '^Test(OpenAIWSMixedOwner|OpenAIRecovery(Diagnostics|ShadowRefusalDiagnostics|ShadowRetainsTaskBeforeOpaqueEnvelope|ShadowDoesNotReclassifyClientMetadataText)|OpenAI409(RebuildRechecksOriginalDeliveryBeforeSend|WSUnsentTurnBoundary|WSTicket|ReplayInputTamperingStillFails|OAuthReplayKeepsOriginalSnapshotAndFinalControls)|Issue854BeforeSendRecoveryGuards|Issue715WS)' -count=1 -json -timeout=5m) > "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" 2>&1 python3 .github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" python3 - "$RUNNER_TEMP/ws-owner-evidence/service-contracts.jsonl" <<'PY' import json, sys rows = [json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')] - for test in ('TestOpenAIWSMixedOwnerFinalSendFences', 'TestOpenAIWSMixedOwnerProofCannotComeFromDiagnostics', 'TestOpenAIRecoveryDiagnosticsAreAllowlisted', 'TestOpenAIRecoveryShadowRefusalDiagnostics', 'TestOpenAIRecoveryShadowRetainsTaskBeforeOpaqueEnvelope'): + for test in ('TestOpenAIWSMixedOwnerFinalSendFences', 'TestOpenAIWSMixedOwnerProofCannotComeFromDiagnostics', 'TestOpenAIRecoveryDiagnosticsAreAllowlisted', 'TestOpenAIRecoveryShadowRefusalDiagnostics', 'TestOpenAIRecoveryShadowRetainsTaskBeforeOpaqueEnvelope', 'TestOpenAIRecoveryShadowDoesNotReclassifyClientMetadataText'): assert sum(r.get('Action') == 'pass' and r.get('Test') == test for r in rows) == 1, test PY - name: Persist safe refusal subtype with logical turn From 1dbdf7fc0642ea34ca38afd5f0b57d22eb18f2e2 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Mon, 16 Nov 2026 00:10:08 +0800 Subject: [PATCH 25/26] test: verify rotated credential and single-owner shadow wire contracts --- .../handler/openai_ws_owner_conflict_test.go | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/openai_ws_owner_conflict_test.go b/backend/internal/handler/openai_ws_owner_conflict_test.go index 1d122e606e69..8546c5904f52 100644 --- a/backend/internal/handler/openai_ws_owner_conflict_test.go +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -697,7 +697,12 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.Len(t, frames, turn+2, "no extra generation or retry") for i, wire := range frames[turn:] { expectedIdentity := "Bearer fixture-mixed-B" - if scenario == "binding_changed" || shadowProvenance { + if scenario == "binding_changed" { + // A fresh native conversation may use the still-eligible B with + // its current credential. Never reuse the old connection/token. + expectedIdentity = "Bearer fixture-mixed-B-rotated" + } + if shadowProvenance { expectedIdentity = "Bearer fixture-mixed-C" } require.Equal(t, expectedIdentity, identities[turn+i]) @@ -721,8 +726,26 @@ func runWSMixedOwnerContinuation(t *testing.T, mode string, turn int, scenarios require.NotContains(t, string(wire), "fixture-opaque-A") require.NotContains(t, string(wire), "fixture-readable-B") require.False(t, gjson.GetBytes(wire, "previous_response_id").Exists()) - if shadowProvenance && i == 0 { + if shadowProvenance { require.True(t, httpRebuildToolPair(wire, "apply_patch", httpRebuildPatch), "restored single-owner history retains one proven pair") + if i > 0 { + require.True(t, httpRebuildToolPair(wire, "run_tests", httpRebuildCheck), "next single-owner turn retains the newly delivered verification pair") + } + expectedCalls := 1 + i + if customProvenance { + expectedCalls++ + } + calls, results := 0, 0 + for _, item := range gjson.GetBytes(wire, "input").Array() { + switch item.Get("type").String() { + case "function_call", "custom_tool_call": + calls++ + case "function_call_output", "custom_tool_call_output": + results++ + } + } + require.Equal(t, expectedCalls, calls) + require.Equal(t, expectedCalls, results) } else { for _, item := range gjson.GetBytes(wire, "input").Array() { require.NotContains(t, item.Get("type").String(), "call", "completed tools must be inert readable history") From 4ea4e516efd860605d9e159ee4d9888385e599ca Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Mon, 16 Nov 2026 00:24:28 +0800 Subject: [PATCH 26/26] test: observe old-session header leaks before later replay assertions --- .../handler/openai_409_ws_rebuild_test.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 565187d287a6..f2b872088e83 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -666,6 +666,23 @@ func runReadableWSContinuation(t *testing.T, mode, scenario string, persistent . logReadableWSRecoveryDetails(t, h) } require.Equal(t, 2+extraSends, sends, "WS_READABLE_B_DISPATCH_MISSING: same client must automatically replace disabled A before any next generation; close=%v terminal=%s", readErr, secondRaw) + if strings.HasPrefix(scenario, "header_") { + // Assert the header defect on B's first actual send. A historical + // baseline must not reach a later, independent history representation + // check before the original header-leak oracle can observe its cause. + oracle.mu.Lock() + firstB := oracle.headers[1].Clone() + firstA := oracle.headers[0].Clone() + oracle.mu.Unlock() + require.NotEqual(t, headers.Get("conversation_id"), firstB.Get("conversation_id"), "WS_RESIDUAL_A_HEADER_LEAK: only outbound provider state is detached") + require.Empty(t, firstB.Get("x-codex-turn-state"), "WS_RESIDUAL_A_HEADER_LEAK: retained A state must not reach B") + if scenario == "header_oauth" { + require.NotEmpty(t, firstB.Get("session_id")) + require.NotEqual(t, headers.Get("session_id"), firstB.Get("session_id")) + require.Equal(t, firstB.Get("session_id"), firstB.Get("conversation_id"), "WS_RESIDUAL_A_HEADER_LEAK: B conversation must use B's isolated session") + require.NotEqual(t, firstA.Get("session_id"), firstB.Get("session_id")) + } + } if modelCase { accounts.mu.Lock() observed := append([]bool(nil), accounts.admissionObserved...)