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..88b98e98326c --- /dev/null +++ b/.github/scripts/prepare-ws-owner-red-fixtures.sh @@ -0,0 +1,69 @@ +#!/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_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 \ + 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/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/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/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/scripts/test_ws_owner_conflict_evidence.py b/.github/scripts/test_ws_owner_conflict_evidence.py new file mode 100644 index 000000000000..fcef7f718bb5 --- /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 | {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}) + 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..38ae35e73327 --- /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 = {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: + 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/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/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/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/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml index 7b79fcee5d22..792337f7de0e 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 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 # 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 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 # 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/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/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/.github/workflows/ws-owner-conflict.yml b/.github/workflows/ws-owner-conflict.yml new file mode 100644 index 000000000000..c16c2d751ec6 --- /dev/null +++ b/.github/workflows/ws-owner-conflict.yml @@ -0,0 +1,114 @@ +name: WS owner conflict behavior + +on: + pull_request: + branches: [production] + paths: + - 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 + +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 + 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=$? + set -e + cat "$RUNNER_TEMP/ws-owner-evidence/red.jsonl" + test "$status" -eq 1 + 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 + python3 -m unittest discover -s .github/scripts -p 'test_ws_owner_conflict_evidence.py' + set +e + (cd backend && go test -p=2 -tags=unit,ownerconflict ./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 ;; + boundaries) test_name=TestOpenAIWSMixedOwnerBoundaries ;; + transports) test_name=TestOpenAIWSMixedOwnerTransports ;; + esac + set +e + (cd backend && go test -race -p=2 -tags=unit,ownerconflict ./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 + - name: Existing policy, shadow and actual-wire contracts + shell: bash + run: | + 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|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', '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 + working-directory: backend + run: go test -race -tags=unit,ownerdiagnostics ./internal/handler -run '^TestOwnerConflictPersistence' -count=1 -v -timeout=5m + - 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/.github/workflows/ws-shadow-omission.yml b/.github/workflows/ws-shadow-omission.yml new file mode 100644 index 000000000000..45e1eedbbf5d --- /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|RetainsTaskBeforeOpaqueEnvelopeAndSummary|DoesNotReclassifyClientMetadataText|TypedEnvelopeOmission|PreservesSuppliedText|PreservesSummaryOnlyIntent|SummaryIntentBoundaries)$' -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','RetainsTaskBeforeOpaqueEnvelopeAndSummary','DoesNotReclassifyClientMetadataText','TypedEnvelopeOmission','PreservesSuppliedText','PreservesSummaryOnlyIntent','SummaryIntentBoundaries'): + 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/.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/.github/workflows/ws-tool-provenance.yml b/.github/workflows/ws-tool-provenance.yml new file mode 100644 index 000000000000..d17ab6afdfbc --- /dev/null +++ b/.github/workflows/ws-tool-provenance.yml @@ -0,0 +1,125 @@ +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: ubuntu-latest + 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 + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + - name: 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 + 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=$? + 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 -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','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) + 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: + name: ws-tool-provenance-${{ github.event.pull_request.head.sha }} + path: ${{ runner.temp }}/ws-provenance-evidence diff --git a/backend/internal/handler/openai_409_ws_audit_test.go b/backend/internal/handler/openai_409_ws_audit_test.go index 78e596d18503..410a9a5fa7d2 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() @@ -236,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()) @@ -270,7 +286,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_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go index b6de9cf11223..8c64afb7b03e 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,20 +79,20 @@ 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 } validTools := httpRebuildToolsAvailable(body) if customTools { - validTools = readableWSCustomToolsAvailable(body) + 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 && - httpRebuildToolPair(body, "apply_patch", httpRebuildPatch) && + 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" { @@ -105,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 && httpRebuildToolPair(body, "run_tests", httpRebuildCheck) { + 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"}}}`) @@ -114,7 +118,37 @@ 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)) + 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++ + } + } + } + } + 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 +161,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_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go index 709875042ec0..f2b872088e83 100644 --- a/backend/internal/handler/openai_409_ws_rebuild_test.go +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -110,6 +110,12 @@ func TestOpenAI409WSReviewRepairs(t *testing.T) { }) } +// 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) { for _, scenario := range []string{"header_apikey", "header_oauth", "tools_omitted", "tools_explicit"} { t.Run(scenario, func(t *testing.T) { @@ -166,6 +172,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"} { @@ -226,7 +246,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 := "" @@ -313,6 +333,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 @@ -373,15 +401,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 @@ -498,6 +527,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()) @@ -621,7 +662,27 @@ 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 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...) diff --git a/backend/internal/handler/openai_agent_message_recovery.go b/backend/internal/handler/openai_agent_message_recovery.go index f503daff5f43..ea6d202ef1be 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,20 @@ 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) + } + logctx := logger.IntoContext(c.Request.Context(), logger.FromContext(c.Request.Context()).With(zap.String("request_id", requestID), zap.Int("turn", turn), zap.String("protocol", protocol), zap.String("phase", phase), zap.String("request_written", writeState))) + service.LogOpenAIAgentRecoveryRefusal(logctx, recovery) 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_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_owner_conflict_diagnostics_test.go b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go new file mode 100644 index 000000000000..d9b327575ddd --- /dev/null +++ b/backend/internal/handler/openai_owner_conflict_diagnostics_test.go @@ -0,0 +1,47 @@ +//go:build unit && ownerdiagnostics + +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOwnerConflictPersistenceKeepsTurnAndSafeSubreason(t *testing.T) { + for _, tc := range []struct{ detail, want string }{{"tool_unpaired", "tool_unpaired"}, {"shadow_epoch_changed", "shadow_epoch_changed"}, {"credential-and-body-canary", "unknown"}, {"", "unknown"}} { + t.Run(tc.want+tc.detail, func(t *testing.T) { + setupOpsErrorLogTestQueue(t, 4) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/v1/responses", nil) + service.SetOpenAIClientTransport(c, service.OpenAIClientTransportWS) + service.BeginOpsStreamTurn(c, 53) + written := false + 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) + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue}) + require.Len(t, repo.entries, 1) + body := repo.entries[0].ErrorBody + require.Equal(t, tc.want, gjson.Get(body, "error.subreason").String()) + require.EqualValues(t, 53, gjson.Get(body, "error.turn").Int()) + require.EqualValues(t, 101, gjson.Get(body, "error.wire_status").Int()) + require.Equal(t, gjson.False, gjson.Get(body, "error.request_written").Type) + require.NotContains(t, body, "credential-and-body-canary") + }) + } +} 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..8546c5904f52 --- /dev/null +++ b/backend/internal/handler/openai_ws_owner_conflict_test.go @@ -0,0 +1,757 @@ +//go:build unit && ownerconflict + +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/assert" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// 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 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) }) + } + } +} + +// 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", "unrelated", "undelivered", "proof_pending", "proof_failed", "proof_conflict", "proof_missing"} { + 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) + }) + } + } +} + +// 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 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" + 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_") + shadowProvenance := provenance && strings.Contains(scenario, "_shadow_") + 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 && !association + 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 + 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) + 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: + 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)} + 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)) + } + } + 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: + 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 "+associationAnswer))} + } + 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}, + }})) + } + 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: 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 + 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} + pool := []service.Account{*a, other} + 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} + pool = append(pool, third) + } + accounts = &readableWSAccounts{issue600SwitchRepo: &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: pool}}} + *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: + } + } + }() + declarations := httpRebuildToolDefinitions() + 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, ",") + "]"), + "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)...) + 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) + 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() + 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++ { + 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") + 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) + if association { + for i, call := range completed.Get("output").Array()[1:] { + 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++ + } + history = append(history, associationResults...) + } + firstTwoOwners = waitOwners(2) + } + } + expectedOwners := 2 + if oldFence || unrelatedCall { + 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()) + } + history = append(history, thirdItem) + if strings.HasSuffix(scenario, "_first") { + history = append([]string{thirdItem}, history[:len(history)-1]...) + } + } + 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": + 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 = map[string]any{"api_key": "fixture-mixed-B-rotated", "base_url": provider.URL} + 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 + } + 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 { + 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 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) + require.NotEmpty(t, keys) + for _, key := range keys { + require.NoError(t, probe.Set(context.Background(), key, "ready:pending:fixture-reassociated", time.Minute).Err()) + } + } + } + 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} + 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) + 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 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") + 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) + 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") + 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") + 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) + 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) + } + 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") + if association { + 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) + 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:] { + expectedIdentity := "Bearer fixture-mixed-B" + 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]) + 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 { + if association { + 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") + } + } + 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()) + 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") + } + } + } + require.Equal(t, 1, strings.Count(string(frames[turn+1]), httpRebuildCheck)) + require.Equal(t, owners, issue805Owners(t, probe), "historical owner records remain unchanged") +} 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/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 2b3ccb6f14c1..1425df1b360e 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" @@ -57,14 +58,35 @@ 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, 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) + } + if websocket { + if err := s.verifyOpenAIToolInputs(ctx, r, body); err != nil { + return ctx, body, false, err + } } clean, changed := omitOpenAIHistoricalCiphertext(body) if ctx.Err() != nil { @@ -81,6 +103,16 @@ func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c if err != nil { 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, withOpenAIRecoveryDiagnostics(err, r, "tool_history_unsupported") + } + r.requireCompletedOwners = true + } fresh := context.WithValue(ctx, openAIGuardianParentAffinityContextKey{}, openAIGuardianParentAffinity{}) next := s.WithOpenAIAgentMessageRecovery(WithOpenAIEncryptedReasoningAffinity(fresh, clean), c, clean, session, model) request := openAIAgentRecoveryFromContext(next) @@ -90,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 } @@ -576,9 +609,10 @@ func openAI409UsesNativeAPIKey(ctx context.Context, account *Account) bool { (r.omittedHistory || (r.ownerBindingRequired() && r.owner.accountID == account.ID)) } -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") +func openAIRecoveryWireRefusal(ctx context.Context, stage string, details ...zap.Field) error { + fields := append([]zap.Field{zap.String("stage", stage)}, details...) + logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", fields...) + return openAIRecoveryDiagnosticError("wire_changed", stage, openAIAgentRecoveryFromContext(ctx)) } func checkOpenAIRecoveryProjectionSource(ctx context.Context, stage string, body []byte, r *openAIAgentRecoveryRequest) error { @@ -588,9 +622,8 @@ func checkOpenAIRecoveryProjectionSource(ctx context.Context, stage string, body return nil } // Fixed metadata only. Do not log the input, tools, instructions or digests. - logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", zap.String("stage", stage), + return openAIRecoveryWireRefusal(ctx, stage, zap.Bool("input_changed", inputChanged), zap.Bool("controls_changed", controlsChanged)) - return openAIAgentRecoveryError("wire_changed") } // 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..69b0a46dd5fd 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 @@ -222,14 +247,103 @@ 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) } + // 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)) + independent := make([]json.RawMessage, 0, len(items)) + removed := false + for _, item := range items { + if item.Get("type").String() != "agent_message" { + independent = append(independent, json.RawMessage(item.Raw)) + } + 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)) + } + if removed { + encoded, err := json.Marshal(portable) + if err != nil { + return nil + } + clean, err = sjson.SetRawBytes(clean, "input", encoded) + if err != nil { + return nil + } + } + // A readable agent summary can itself be the authorized intent. Only + // classify retained envelopes as assistant history when the original + // non-agent input/instructions supplies intent independently. This uses + // the unchanged latest-user rules, including opaque-user boundaries. + encoded, err := json.Marshal(independent) + if err != nil { + return nil + } + independentBody, err := sjson.SetRawBytes(clean, "input", encoded) + if err != nil { + return nil + } + hasIndependentIntent := openAI409HasReadableIntent(independentBody) + originalItems := gjson.GetBytes(clean, "input").Array() if omitted, changed := omitOpenAIHistoricalCiphertext(clean); changed { clean = omitted } - var err error clean, err = prepareOpenAI409ReadableReplay(clean) 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. + // Retain its readable metadata as assistant context; ownership/epoch fences + // retain the envelope's identity. Dropping it would lose summaries/content. + portable = portable[:0] + 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 hasIndependentIntent && 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 { + 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 @@ -283,6 +397,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..0ab4766e6f5e --- /dev/null +++ b/backend/internal/service/openai_409_shadow_candidate_test.go @@ -0,0 +1,104 @@ +//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)+`}`))) +} + +func TestOpenAIRecoveryShadowSummaryIntentBoundaries(t *testing.T) { + for _, before := range []string{"", `{"role":"user","content":[{"type":"encrypted_content","encrypted_content":"fixture-new-opaque-task"}]},`} { + body := []byte(`{"input":[` + before + `{"type":"agent_message","summary":[{"type":"summary_text","text":"fixture current summary task"}],"encrypted_content":"fixture-private-cipher"},{"type":"agent_message","encrypted_content":"fixture-trailing-cipher"}]}`) + snapshot := openAIReadableShadowCandidate(body) + require.NotNil(t, snapshot) + require.Contains(t, string(snapshot.Input), "fixture current summary task") + require.NotContains(t, string(snapshot.Input), "cipher") + require.True(t, openAI409HasReadableIntent([]byte(`{"input":`+string(snapshot.Input)+`}`))) + } + // An earlier summary cannot authorize replacing a later opaque user task. + body := []byte(`{"input":[{"type":"agent_message","summary":"fixture earlier summary"},{"role":"user","content":[{"type":"encrypted_content","encrypted_content":"fixture-new-opaque-task"}]}]}`) + require.Nil(t, openAIReadableShadowCandidate(body)) + // A simple string task stays a single genuine user message. + snapshot := openAIReadableShadowCandidate([]byte(`{"input":"fixture string task"}`)) + require.NotNil(t, snapshot) + require.JSONEq(t, `[{"type":"message","role":"user","content":"fixture string task"}]`, string(snapshot.Input)) +} 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_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index cd8123084bed..ac2dba2f7716 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -31,18 +31,30 @@ 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 + toolFinal map[string]bool + 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 { + 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)} } func (s *OpenAIGatewayService) awaitOpenAIAgentRecovery(ctx context.Context, shared OpenAIAgentRecoveryCache, state *openAIAgentRecoveryState, key [32]byte) (openAIAgentRecoveryBinding, bool, error) { @@ -107,6 +119,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 +227,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 36947164e9ce..d93d5223fdf4 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" @@ -40,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 { @@ -87,6 +90,11 @@ type openAIAgentRecoveryRequest struct { groupID int64 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 } // WithOpenAIAgentMessageRecovery observes only opaque item identities. A route @@ -121,9 +129,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...) @@ -141,8 +153,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 { @@ -150,6 +168,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) { @@ -161,12 +180,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 @@ -292,8 +338,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. @@ -376,6 +429,9 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con return noop, err } 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 { @@ -491,6 +547,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) @@ -498,17 +557,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 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 { @@ -518,11 +581,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 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) } } } @@ -604,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_agent_message_recovery_error.go b/backend/internal/service/openai_agent_message_recovery_error.go index 31192894f23a..2c57346dfe51 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() } @@ -90,3 +91,11 @@ type openAINonStreamingDeliveryError struct{ err error } func (e *openAINonStreamingDeliveryError) Error() string { return e.err.Error() } func (e *openAINonStreamingDeliveryError) Unwrap() error { return e.err } + +// InternalSubreason exposes only a fixed diagnostic category for persistence. +func (e *OpenAIAgentRecoveryError) InternalSubreason() string { + if e == nil || e.diagnostic == nil { + return "unknown" + } + return safeOpenAIRecoverySubreason(e.diagnostic.subreason) +} 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..ccfcd6a7065a --- /dev/null +++ b/backend/internal/service/openai_agent_recovery_diagnostics.go @@ -0,0 +1,191 @@ +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 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_recovery_subreason.go b/backend/internal/service/openai_recovery_subreason.go new file mode 100644 index 000000000000..24b0652947a8 --- /dev/null +++ b/backend/internal/service/openai_recovery_subreason.go @@ -0,0 +1,19 @@ +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 "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", + "shadow_store_unavailable", "input_invalid", "input_integrity", "controls_integrity", "readable_intent_missing", + "http_projection_source", "apikey_projection_source", "oauth_projection_source": + return value + default: + return "unknown" + } +} diff --git a/backend/internal/service/openai_tool_provenance.go b/backend/internal/service/openai_tool_provenance.go new file mode 100644 index 000000000000..611dd2c21bfd --- /dev/null +++ b/backend/internal/service/openai_tool_provenance.go @@ -0,0 +1,505 @@ +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 { + // 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) { + 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) + } + } + old := state.toolProofs[key] + if len(state.toolProofs) >= 128 && old.raw == "" { + return openAIAgentRecoveryError("store_unavailable") + } + // 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" + } + 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 { + if i >= len(source.items) { + return nil, false + } + 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) + } + storeCtx, cancel := context.WithTimeout(d.ctx, 3*time.Second) + defer cancel() + 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 + 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" { + 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()) + 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(storeCtx, 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 && (d.toolFinal == nil || d.toolFinal[key]) && 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 e1a43bb8bfdc..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")} @@ -316,6 +322,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.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 != "" { 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..d29aa0fa1857 --- /dev/null +++ b/backend/internal/service/openai_ws_owner_conflict_test.go @@ -0,0 +1,366 @@ +//go:build unit && ownerconflict + +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" +) + +// 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 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) + } + // 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) + 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) { + 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") + 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"}, + {"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)}) + 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) + 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") + 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 + 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 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)) + 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") + }) + } +} + +func TestOpenAIRecoveryShadowRetainsTaskBeforeOpaqueEnvelopeAndSummary(t *testing.T) { + 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)) +} + +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)) +} diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go index 9e57ed6050e9..355fb825f7bd 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 { @@ -60,7 +61,11 @@ 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 + completedSource *openAIAgentRecoveryRequest +} func (e *openAIWSOwnerRouteError) Error() string { return e.cause.Error() } func (e *openAIWSOwnerRouteError) Unwrap() error { return e.cause } @@ -79,6 +84,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 @@ -86,7 +95,66 @@ 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 +// 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") + } + 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]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") + } + 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 { @@ -136,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 } @@ -192,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") @@ -213,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") 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 diff --git a/docs/ws-mixed-owner-continuation.md b/docs/ws-mixed-owner-continuation.md new file mode 100644 index 000000000000..9f780798e1b8 --- /dev/null +++ b/docs/ws-mixed-owner-continuation.md @@ -0,0 +1,90 @@ +# 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 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. + +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 +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. + +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 +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, +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. + +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. + +Shadow snapshots omit original typed agent envelopes with no readable content +or summary. Retained agent metadata and readable text become assistant history +when the original non-agent input/instructions independently supplies intent. +A readable agent summary that supplies the only available intent keeps its +portable user representation. Genuine user text is never reclassified based on +a gateway-like prefix or marker. Ownership and epoch fences retain the original +envelopes, and the latest-user intent rules are unchanged. + +Tool provenance uses the current resolved forward model. An active WebSocket +may omit the optional model field after selecting it; that omission does not +create a new proof scope. A different resolved model still cannot borrow the +old proof. HTTP projection refusals retain their fixed stage in Ops metadata, +with input/controls change booleans confined to the diagnostic journal.