diff --git a/.github/scripts/assert-future-shadow.py b/.github/scripts/assert-future-shadow.py new file mode 100644 index 000000000000..20e0960a9c19 --- /dev/null +++ b/.github/scripts/assert-future-shadow.py @@ -0,0 +1,76 @@ +"""Exact named network evidence for the future-shadow TDD increment.""" + +import importlib.util +import json +import sys +from collections import Counter +from pathlib import Path + + +SPEC = importlib.util.spec_from_file_location("shadow_evidence_common", Path(__file__).with_name("assert-readable-continuation.py")) +COMMON = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(COMMON) +ROOT = "TestOpenAI409FutureShadowHTTP" +BOUNDARIES = "TestOpenAI409FutureShadowBoundaries" +LEAVES = {f"{ROOT}/stream={stream}" for stream in ("false", "true")} +BOUNDARY_NAMES = ("other_user", "other_key", "other_group", "other_model", "other_session", "other_task", "expired", "write_failed", "pending_owner", "failed_owner", "conflicted_owner", "off", "fresh_intent") +BOUNDARY_LEAVES = {f"{BOUNDARIES}/stream={stream}/{case}" for stream in ("false", "true") for case in BOUNDARY_NAMES} +RESOURCES = "TestOpenAI409FutureShadowResources" +RESOURCE_LEAVES = {f"{RESOURCES}/stream={stream}/{case}" for stream in ("false", "true") for case in ("capacity_oldest", "capacity_latest", "store_write_failed", "store_read_failed", "oversize", "pending_tool", "pending_output", "conflicting_output", "echoed_task")} +ASSOCIATION = "TestOpenAI409FutureShadowTaskAssociation" +ASSOCIATION_LEAVES = {f"{ASSOCIATION}/stream={stream}" for stream in ("false", "true")} + + +def validate(phase, code, raw, boundaries=False, resources=False, association=False): + if phase not in ("RED", "GREEN") or ((boundaries or resources) and phase != "GREEN") or sum((boundaries, resources, association)) > 1: + raise ValueError("invalid shadow evidence phase") + COMMON.check_clean(raw) + events = [] + for line in raw.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(event, dict): + raise ValueError("invalid event") + events.append(event) + root, leaves = (BOUNDARIES, BOUNDARY_LEAVES) if boundaries else (ROOT, LEAVES) + if resources: + root, leaves = RESOURCES, RESOURCE_LEAVES + if association: + root, leaves = ASSOCIATION, ASSOCIATION_LEAVES + terminal = "fail" if phase == "RED" else "pass" + if code != (1 if phase == "RED" else 0): + raise ValueError("unexpected exit status") + actions = Counter((event.get("Action"), event.get("Test")) for event in events if event.get("Package") == COMMON.PACKAGE) + for name in leaves | {root}: + if actions["run", name] != 1: + raise ValueError(f"missing or duplicate named run: {name}") + for name in leaves | {root, None}: + if actions[terminal, name] != 1 or actions["pass", name] + actions["fail", name] != 1: + raise ValueError(f"incorrect terminal event: {name}") + for event in events: + if event.get("Action") == "fail" and (phase == "GREEN" or event.get("Package") != COMMON.PACKAGE or event.get("Test") not in leaves | {root, None}): + raise ValueError("unrelated failure") + if phase == "RED": + for name in leaves: + output = "".join(event.get("Output", "") for event in events if event.get("Package") == COMMON.PACKAGE and event.get("Test") == name) + required = ("SHADOW_TASK_ASSOCIATION_MISMATCH",) if association else ("FUTURE_SHADOW_B_DISPATCH_MISSING", "encrypted_agent_recovery_readable_intent_missing") + if any(marker not in output for marker in required): + raise ValueError(f"missing named shadow business assertion: {name}") + + +def main(): + phase, code, filename, *options = sys.argv[1:] + if options not in ([], ["--boundaries"], ["--resources"], ["--association"]): + raise ValueError("invalid option") + validate(phase, int(code), Path(filename).read_text(), options == ["--boundaries"], options == ["--resources"], options == ["--association"]) + leaves = ASSOCIATION_LEAVES if options == ["--association"] else RESOURCE_LEAVES if options == ["--resources"] else BOUNDARY_LEAVES if options else LEAVES + print(f"{phase}: {len(leaves)} named shadow scenarios verified") + + +if __name__ == "__main__": + try: + main() + except ValueError as error: + raise SystemExit(str(error)) from error diff --git a/.github/scripts/assert-http-task-rebuild.py b/.github/scripts/assert-http-task-rebuild.py new file mode 100644 index 000000000000..7186f8f8f412 --- /dev/null +++ b/.github/scripts/assert-http-task-rebuild.py @@ -0,0 +1,147 @@ +"""Named HTTP task-rebuild TDD evidence; reuse the reviewed pollution gate.""" + +import importlib.util +import json +import sys +from collections import Counter +from pathlib import Path + + +SPEC = importlib.util.spec_from_file_location( + "readable_evidence", Path(__file__).with_name("assert-readable-continuation.py") +) +COMMON = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(COMMON) +ROOT = "TestOpenAI409HTTPTaskRebuild" +BOUNDARIES = "TestOpenAI409HTTPRebuildBoundaries" +TOOLS = "TestOpenAI409HTTPToolDefinitionOracle" +MIXED = "TestOpenAI409HTTPMixedDeliveryFences" +NORMALIZATION = "TestOpenAI409HTTPControlNormalization" +POINTER_WAIVER = "TestOpenAI409HTTPUnownedPointerMustDetach" +PACKAGE = COMMON.PACKAGE +LEAVES = { + f"{ROOT}/{account}/stream={stream}/{pointer}/{outcome}" + for account in ("apikey", "oauth") + for stream in ("false", "true") + for pointer in ("intent", "previous", "conversation") + for outcome in ("completed", "rejected", "write_failed") +} +BOUNDARY_LEAVES = { + f"{BOUNDARIES}/{account}/stream={stream}/{boundary}" + for account in ("apikey", "oauth") + for stream in ("false", "true") + for boundary in ("pointer_only", "opaque_only", "delivery_pending", "delivery_failed", "b_disabled") +} +TOOL_LEAVES = { + f"{TOOLS}/{account}/stream={stream}/{mutation}" + for account in ("apikey", "oauth") for stream in ("false", "true") + for mutation in ("drop_tools", "change_schema") +} +MIXED_LEAVES = { + f"{MIXED}/{account}/stream={stream}/{owner}/{state}/{order}" + for account in ("apikey", "oauth") for stream in ("false", "true") + for owner in ("A", "B") for state in ("pending", "failed", "conflict") + for order in ("forward", "reverse") +} +NORMALIZATION_LEAVES = { + f"{NORMALIZATION}/{account}/stream={stream}/{case}" + for account, case in (("apikey", "blank_parts"), ("oauth", "blank_parts"), ("oauth", "nested_choice"), ("apikey", "no_tools_parallel")) + for stream in ("false", "true") +} +POINTER_WAIVER_LEAVES = {f"{POINTER_WAIVER}/setting_error={value}" for value in ("false", "true")} +SUITES = {"boundaries": (BOUNDARIES, BOUNDARY_LEAVES), "tool-oracle": (TOOLS, TOOL_LEAVES), "mixed-fences": (MIXED, MIXED_LEAVES), + "normalization": (NORMALIZATION, NORMALIZATION_LEAVES), "pointer-waiver": (POINTER_WAIVER, POINTER_WAIVER_LEAVES)} +MUTANTS = { + "newest-only": f"{MIXED}/apikey/stream=false/A/failed/forward", + "break-on-owner-mismatch": f"{MIXED}/apikey/stream=false/A/failed/reverse", +} +DIAGNOSTIC = "HTTP_REBUILD_B_DISPATCH_MISSING" +OLD_REFUSALS = ( + "encrypted_agent_recovery_owner_unavailable", + "encrypted_agent_recovery_http_previous_response_unsupported", + "encrypted_agent_recovery_wire_changed", +) + + +def validate(phase, exit_code, transcript, boundaries=False, suite=None, mutant=None): + if boundaries: + suite = "boundaries" + if phase not in {"RED", "GREEN", "MUTANT"} or (suite is not None and (suite not in SUITES or (phase != "GREEN" and not (phase == "RED" and suite in {"normalization", "pointer-waiver"})))): + raise ValueError("invalid task-rebuild phase") + if (phase == "MUTANT") != (mutant in MUTANTS) or (mutant is not None and mutant not in MUTANTS): + raise ValueError("invalid source mutant") + COMMON.check_clean(transcript) + events = [] + for line in transcript.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(event, dict): + raise ValueError("invalid go-test event") + events.append(event) + root, leaves = SUITES[suite] if suite else (ROOT, LEAVES) + if mutant: + root, leaves = MIXED, {MUTANTS[mutant]} + terminal = "pass" if phase == "GREEN" else "fail" + expected_exit = 0 if phase == "GREEN" else 1 + if exit_code != expected_exit: + raise ValueError("unexpected go-test exit status") + actions = Counter( + (event.get("Action"), event.get("Test")) + for event in events if event.get("Package") == PACKAGE + ) + for name in leaves | {root}: + if actions["run", name] != 1: + raise ValueError(f"missing/repeated named test: {name}") + for name in leaves | {root, None}: + if actions[terminal, name] != 1 or actions["pass", name] + actions["fail", name] != 1: + raise ValueError(f"missing or incorrect test/package terminal: {name}") + for event in events: + if event.get("Action") == "fail" and ( + phase == "GREEN" or event.get("Package") != PACKAGE or event.get("Test") not in leaves | {root, None} + ): + raise ValueError("unexpected failure outside named task-rebuild RED") + if phase != "GREEN": + for name in leaves: + output = "".join( + event.get("Output", "") for event in events + if event.get("Package") == PACKAGE and event.get("Test") == name + ) + if phase == "MUTANT": + if "HTTP_REBUILD_FENCE_BYPASSED" not in output or "coding-task-complete" not in output: + raise ValueError(f"missing actual extra-generation counterexample: {name}") + elif suite == "pointer-waiver": + if "UNOWNED_POINTER_WAIVER_LEAK" not in output: + raise ValueError(f"missing actual unowned-pointer dispatch: {name}") + elif suite == "normalization": + marker = "automatic next tool turn must finish" if name.endswith("/no_tools_parallel") else DIAGNOSTIC + code = "encrypted_agent_recovery_readable_intent_missing" if name.endswith("/blank_parts") else "encrypted_agent_recovery_wire_changed" + if marker not in output or code not in output: + raise ValueError(f"missing normalization business refusal: {name}") + elif DIAGNOSTIC not in output or not any(code in output for code in OLD_REFUSALS): + raise ValueError(f"missing named B-dispatch refusal assertion: {name}") + + +def main(): + phase, code, filename, *options = sys.argv[1:] + if len(options) > 1: + raise ValueError("unknown option") + suite, mutant = None, None + if options: + if options[0].startswith("--mutant="): + mutant = options[0].split("=", 1)[1] + else: + suite = options[0].removeprefix("--") + if suite not in SUITES: + raise ValueError("unknown suite") + validate(phase, int(code), Path(filename).read_text(), suite=suite, mutant=mutant) + count = 1 if mutant else len(SUITES[suite][1] if suite else LEAVES) + print(f"{phase}: {count} named task-rebuild scenarios verified") + + +if __name__ == "__main__": + try: + main() + except ValueError as exc: + raise SystemExit(str(exc)) from exc diff --git a/.github/scripts/assert-readable-continuation.py b/.github/scripts/assert-readable-continuation.py new file mode 100644 index 000000000000..d56f52538990 --- /dev/null +++ b/.github/scripts/assert-readable-continuation.py @@ -0,0 +1,119 @@ +"""CI-only evidence gate: compilation failures, skips and empty runs are not RED.""" + +import json +import re +import sys +from collections import Counter +from pathlib import Path + + +ROOT = "TestOpenAI409ReadableContinuationHTTP" +PACKAGE = "github.com/Wei-Shaw/sub2api/internal/handler" +LEAVES = { + f"{ROOT}/{fixture}/stream={stream}/{outcome}" + for fixture in ("summary", "content", "stored_content") + for stream in ("false", "true") + for outcome in ("completed", "rejected", "write_failed") +} +POLLUTION = re.compile( + r"panic|data\s+race|race\s+detected|race\s+detector|ThreadSanitizer|" + r"fatal\s+(?:error|runtime)|runtime\s+error|runtime:\s*out of memory|" + r"SIG(?:SEGV|ABRT|BUS|ILL|QUIT)|segmentation\s+(?:fault|violation)|" + r"stack\s+overflow|core\s+dumped|crash|test\s+timed\s+out|" + r"signal:\s*(?:killed|aborted|terminated|interrupt)|\bKilled\b|" + r"build\s+failed|setup\s+failed|undefined:|no\s+tests\s+to\s+run|" + r"---\s*SKIP:|\[SKIP\]", + re.IGNORECASE, +) + + +def check_clean(transcript): + # Inspect raw stderr AND decoded go-test Output. A recovered panic can be + # a structured application log inside JSON, even with exit=0 and PASS. + outputs = [] + for line in transcript.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(event, dict): + if event.get("Action") == "skip": + raise ValueError("skipped tests cannot prove RED/GREEN") + output = event.get("Output", "") + if isinstance(output, str): + outputs.append(output) + if POLLUTION.search(transcript) or POLLUTION.search("".join(outputs)): + raise ValueError("contaminated evidence: runtime/build/skip diagnostic") + + +def validate(phase, exit_code, transcript): + if phase not in {"RED", "GREEN"}: + raise ValueError("unknown phase") + check_clean(transcript) + events = [] + for line in transcript.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + # Raw stderr was scanned above. Required test/package terminal + # events below reject truncated and compilation-only evidence. + continue + if not isinstance(event, dict): + raise ValueError("invalid go-test event") + events.append(event) + + actions = Counter( + (event.get("Action"), event.get("Test")) + for event in events + if event.get("Package") == PACKAGE + ) + for name in LEAVES | {ROOT}: + if actions["run", name] != 1: + raise ValueError("missing or repeated named HTTP behavior test") + if actions["pass", name] + actions["fail", name] != 1: + raise ValueError("missing or repeated test terminal event") + for event in events: + if event.get("Action") == "fail" and ( + event.get("Package") != PACKAGE or event.get("Test") not in LEAVES | {ROOT, None} + ): + raise ValueError("unrelated failure in HTTP evidence") + expected = "pass" if phase == "GREEN" else "fail" + if actions[expected, None] != 1 or actions["pass", None] + actions["fail", None] != 1: + raise ValueError("missing or incorrect package terminal event") + + if phase == "GREEN": + if exit_code != 0 or actions["pass", ROOT] != 1: + raise ValueError("candidate HTTP regression did not pass") + if not all(actions["pass", name] == 1 for name in LEAVES): + raise ValueError("not all candidate HTTP scenarios passed") + if any(event.get("Action") == "fail" for event in events): + raise ValueError("unexpected failure in GREEN evidence") + else: + if exit_code != 1 or actions["fail", ROOT] != 1: + raise ValueError("pinned production did not fail the behavior test") + for fixture in ("summary", "content", "stored_content"): + for stream in ("false", "true"): + name = f"{ROOT}/{fixture}/stream={stream}/completed" + output = "".join( + event.get("Output", "") for event in events + if event.get("Package") == PACKAGE and event.get("Test") == name + ) + if actions["fail", name] != 1 or "encrypted_agent_recovery_wire_changed" not in output: + raise ValueError(f"missing named input-integrity business failure: {name}") + + +def main(): + if len(sys.argv) == 3 and sys.argv[1] == "--clean-log": + check_clean(Path(sys.argv[2]).read_text()) + print("No runtime/build/skip contamination found") + return + phase, exit_code, filename = sys.argv[1:] + validate(phase, int(exit_code), Path(filename).read_text()) + print(f"{phase}: named HTTP JSON/SSE behavior evidence accepted ({len(LEAVES)} scenarios)") + + +if __name__ == "__main__": + try: + main() + except ValueError as exc: + raise SystemExit(str(exc)) from exc diff --git a/.github/scripts/assert-ws-readable.py b/.github/scripts/assert-ws-readable.py new file mode 100644 index 000000000000..143465d65b1a --- /dev/null +++ b/.github/scripts/assert-ws-readable.py @@ -0,0 +1,132 @@ +"""Named transport evidence for the next WS and OAuth/pointer increment.""" + +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) +MODES = ("http_bridge", "ctx_pool", "shared", "dedicated", "passthrough") +SUITES = { + "ws": ("TestOpenAI409WSReadableContinuation", {mode for mode in MODES}), + "ws-boundaries": ("TestOpenAI409WSReadableBoundaries", {f"{mode}/{case}" for mode in MODES for case in ("off", "no_intent", "b_disabled", "pending_owner", "failed_owner", "ambiguous_B")}), + "ws-review": ("TestOpenAI409WSReviewRepairs", {f"identity/{mode}" for mode in MODES} | {f"smart/{mode}" for mode in ("auto", "ws", "http")} | {"bridge_inherited_model"}), + "ws-residual": ("TestOpenAI409WSResidualRepairs", {"header_apikey", "header_oauth", "tools_omitted", "tools_explicit"}), + "ws-ticket": ("TestOpenAI409WSTicketBoundEgress", {"ctx_pool", "shared", "dedicated"}), + "ws-native-namespace": ("TestOpenAI409WSNativeNamespaceRecovery", {"ctx_pool", "shared", "dedicated", "passthrough"}), + "ws-recovered-audit": ("TestOpenAI409WSRecoveredAudit", {f"{mode}/{policy}" for mode in MODES for policy in ("prompt", "selected")}), + "ws-recovered-audit-next": ("TestOpenAI409WSRecoveredAuditNextTurn", set(MODES)), + "oauth-shadow": ("TestOpenAI409FutureShadowOAuth", {f"stream={stream}/{case}" for stream in ("false", "true") for case in ("recover", "write_failed", "pending_owner", "store_read_failed", "two_known_tasks", "fresh_intent")}), + "pointer": ("TestOpenAI409HTTPReadablePointerWithoutOpaque", {f"{account}/stream={stream}/{pointer}" for account in ("apikey", "oauth") for stream in ("false", "true") for pointer in ("previous", "conversation")}), + "pointer-boundaries": ("TestOpenAI409HTTPPointerWithoutOpaqueBoundaries", {f"{account}/stream={stream}/{case}" for account in ("apikey", "oauth") for stream in ("false", "true") for case in ("strict", "pointer_only", "foreign_user", "b_disabled")}), + "strict-pointer": ("TestOpenAI409HTTPPointerWithoutOpaqueBoundaries", {f"{account}/stream={stream}/strict" for account in ("apikey", "oauth") for stream in ("false", "true")}), + "shadow-races": ("TestOpenAI409FutureShadowPublicationFences", {f"stream={stream}/{case}" for stream in ("false", "true") for case in ("first_publication", "invalidate_after_restore", "reused_exposure", "store_failure_existing", "delayed_publisher")}), + "audit-provenance": ("TestOpenAI409FutureShadowAuditProvenance", {f"stream={stream}" for stream in ("false", "true")}), + "audit-persistence": ("TestRecoveredContextAuditPersistence", {"blocking_allow", "blocking_risk", "async"}), + "audit-async": ("TestRecoveredContextAsyncEnforcement", {"admission", "penalty"}), + "ws-oracle": ("TestOpenAI409WSAmbiguousOracleMutations", {f"{transport}/{mutation}" for transport in ("http_bridge", "socket") for mutation in ("valid", "wrong_credential", "old_pointer", "missing_result", "unrelated_eof")}), +} +RED_SUITES = {"ws", "ws-review", "ws-residual", "ws-ticket", "ws-native-namespace", "ws-recovered-audit", "shadow-races", "audit-provenance", "audit-persistence", "audit-async"} +# Fixed e593 source in shadow-review-repair.yml. These outcomes were accepted +# from actual provider-wire evidence; never infer them from the observed log. +STRICT_POINTER_BASELINE = { + "apikey/stream=false/strict": "fail", + "apikey/stream=true/strict": "fail", + "oauth/stream=false/strict": "pass", + "oauth/stream=true/strict": "pass", +} + + +def diagnostic(suite, name): + if suite == "ws-recovered-audit": + return ("WS_RECOVERED_AUDIT_DISPATCHED", "audit-fixture-B-received-restored") + if suite == "ws-native-namespace": + return ("WS_NATIVE_NAMESPACE_B_DISPATCH_MISSING", "namespace tool", "conflicts with a top-level tool of the same name") + if suite == "ws-ticket": + return ("WS_RESIDUAL_TICKET_EGRESS_LOST", "ordinary-Q") + if suite == "ws-residual": + if "/header_" in name: + return ("WS_RESIDUAL_A_HEADER_LEAK",) + return ("WS_RESIDUAL_TOOL_PROJECTION_REFUSED", "The proven encrypted agent transport changed.") + if suite == "ws-review": + if "/identity/" in name: + return ("WS_REVIEW_CLIENT_IDENTITY_LOST", "evt_cyber_session_identity_rejected") + if "/smart/" in name: + return ("WS_REVIEW_SMART_SESSION_STALE", "session authorization changed") + return ("WS_REVIEW_INHERITED_MODEL_LOST", "gpt-5.1") + if suite == "ws": + return ("WS_READABLE_B_DISPATCH_MISSING", "account eligibility changed") + if suite == "strict-pointer": + return ("HTTP_POINTER_STRICT_A_STATE_LEAK",) + if suite == "audit-provenance": + return ("SHADOW_AUDIT_PROVENANCE_MISSING",) + if suite == "audit-persistence": + return ("SHADOW_AUDIT_BODY_RETAINED",) + if suite == "audit-async": + return ("RECOVERED_ASYNC_ADMISSION_BLOCKED",) if name.endswith("/admission") else ("RECOVERED_ASYNC_PENALTY_MISSING",) + if name.endswith("/first_publication"): + return ("SHADOW_PUBLICATION_RACE_REFUSED",) + if name.endswith("/reused_exposure"): + return ("SHADOW_REUSED_EXPOSURE_LEAK",) + if name.endswith("/delayed_publisher"): + return ("SHADOW_DELAYED_PUBLICATION_REVIVED",) + return ("SHADOW_INVALIDATED_ASSOCIATION_DISPATCH",) + + +def validate(phase, code, raw, suite): + baseline = phase == "BASELINE" and suite == "strict-pointer" + if (phase not in ("RED", "GREEN") and not baseline) or suite not in SUITES or (phase == "RED" and suite not in RED_SUITES): + raise ValueError("invalid WS evidence phase/suite") + COMMON.check_clean(raw) + root, names = SUITES[suite] + package = COMMON.PACKAGE.replace("/handler", "/securityaudit") if suite in {"audit-persistence", "audit-async"} else COMMON.PACKAGE + if suite == "ws-ticket": + package = COMMON.PACKAGE.replace("/handler", "/service") + leaves = {f"{root}/{name}" for name in names} + events = [] + for line in raw.splitlines(): + try: + event = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(event, dict): + raise ValueError("invalid event") + events.append(event) + counts = Counter((e.get("Action"), e.get("Test")) for e in events if e.get("Package") == package) + if baseline: + if set(STRICT_POINTER_BASELINE) != names: + raise ValueError("strict baseline inventory changed") + failed = {f"{root}/{name}" for name, outcome in STRICT_POINTER_BASELINE.items() if outcome == "fail"} + else: + failed = leaves if phase == "RED" else set() + terminal = "fail" if failed else "pass" + if code != (1 if failed else 0): + raise ValueError("unexpected exit") + for name in leaves | {root}: + if counts["run", name] != 1: + raise ValueError(f"missing named run {name}") + for name in leaves | {root, None}: + expected = ("fail" if name in failed else "pass") if name in leaves else terminal + if counts[expected, name] != 1 or counts["pass", name] + counts["fail", name] != 1: + raise ValueError(f"incorrect terminal {name}") + for event in events: + if event.get("Action") == "fail" and (phase == "GREEN" or event.get("Package") != package or event.get("Test") not in leaves | {root, None}): + raise ValueError("unrelated failure") + if baseline and event.get("Action") == "run" and (event.get("Package") != package or event.get("Test") not in leaves | {root}): + raise ValueError("unrelated baseline run") + if baseline and event.get("Action") in {"pass", "fail"} and (event.get("Package") != package or event.get("Test") not in leaves | {root, None}): + raise ValueError("unrelated baseline terminal") + if phase == "RED" or baseline: + for name in failed: + output = "".join(e.get("Output", "") for e in events if e.get("Package") == package and e.get("Test") == name) + if any(marker not in output for marker in diagnostic(suite, name)): + raise ValueError(f"missing own unsent-turn refusal diagnostic {name}") + + +if __name__ == "__main__": + phase, code, filename, suite = sys.argv[1:] + validate(phase, int(code), Path(filename).read_text(), suite) + print(f"{phase}: {len(SUITES[suite][1])} named {suite} scenarios verified") diff --git a/.github/scripts/ci-ubuntu-mirrors.sh b/.github/scripts/ci-ubuntu-mirrors.sh index 253a47e2ef32..25547811b17a 100644 --- a/.github/scripts/ci-ubuntu-mirrors.sh +++ b/.github/scripts/ci-ubuntu-mirrors.sh @@ -1,12 +1,13 @@ #!/usr/bin/env bash -# Ubuntu's authoritative DNS outage can block both Azure and primary mirrors. -# Keep MIT and Ubuntu HTTPS mirrors so a single mirror outage cannot block CI. -# apt retains Ubuntu's signed -# Release/package verification. Never apply this helper to a production host. +# Use Ubuntu's HTTPS archive directly: the mirror transport can repeatedly +# choose an unavailable mirror for individual indexes even after a fallback. +# Bound network waits and retain signed Release/package verification. +# Never apply this helper to a production host. set -euo pipefail [[ "${GITHUB_ACTIONS:-}" == "true" ]] || { echo "CI-only helper" >&2; exit 1; } for mirror_list in /etc/apt/apt-mirrors.txt /etc/apt/apt-security-mirrors.txt; do if [[ -f "$mirror_list" ]]; then - printf '%s\n' 'https://mirrors.mit.edu/ubuntu' 'https://archive.ubuntu.com/ubuntu' | sudo tee "$mirror_list" >/dev/null + printf '%s\n' 'https://archive.ubuntu.com/ubuntu' | sudo tee "$mirror_list" >/dev/null fi done +printf '%s\n' 'Acquire::http::Timeout "30";' 'Acquire::https::Timeout "30";' 'Acquire::Retries "2";' | sudo tee /etc/apt/apt.conf.d/99-sub2api-ci-timeouts >/dev/null diff --git a/.github/scripts/exclude-later-400-red-fixtures.sh b/.github/scripts/exclude-later-400-red-fixtures.sh new file mode 100644 index 000000000000..f6916a80dda4 --- /dev/null +++ b/.github/scripts/exclude-later-400-red-fixtures.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Only for disposable historical production overlays. Independent 400 fixtures +# can require newer recovery fields; all selected 409/WS tests remain intact. +set -euo pipefail +tree="${2:-.}" +baseline=$(git -C "$tree" rev-parse "$1^{commit}") +candidate=$(git -C "$tree" rev-parse "${3:-HEAD}^{commit}") +recovery=backend/internal/service/openai_agent_message_recovery.go +for target in backend/internal/handler/openai_400_omit_history_test.go backend/internal/service/openai_400_omit_history_test.go; do + reason= + if ! git -C "$tree" cat-file -e "$baseline:$target" 2>/dev/null; then + reason=absent_in_baseline + elif [ "$target" = backend/internal/service/openai_400_omit_history_test.go ] && + git -C "$tree" grep -q apiInputDigest "$candidate" -- "$target" && + ! git -C "$tree" grep -q apiInputDigest "$baseline" -- "$recovery"; then + # The 400 test exists in this baseline, but its candidate adapter assertions + # depend on a recovery field introduced later. Never backport that field. + reason=baseline_lacks_api_input_digest + else + continue + fi + expected_recovery=$(git -C "$tree" rev-parse "$baseline:$recovery") + actual_recovery=$(git -C "$tree" hash-object "$recovery") + test "$expected_recovery" = "$actual_recovery" + expected=$(git -C "$tree" rev-parse "$candidate:$target") + actual=$(git -C "$tree" hash-object "$target") + test "$expected" = "$actual" + printf 'unrelated 400 fixture exclusion baseline=%s candidate=%s path=%s reason=%s expected=%s actual=%s recovery_blob=%s\n' "$baseline" "$candidate" "$target" "$reason" "$expected" "$actual" "$actual_recovery" + rm -- "$tree/$target" + test ! -e "$tree/$target" +done diff --git a/.github/scripts/exclude-later-http2-red-fixtures.sh b/.github/scripts/exclude-later-http2-red-fixtures.sh new file mode 100644 index 000000000000..53570c104bd5 --- /dev/null +++ b/.github/scripts/exclude-later-http2-red-fixtures.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Only a disposable historical production overlay may omit these independent +# PR833 tests. Candidate GREEN retains every test. Never omit a selected 409/WS +# assertion or treat the resulting compilation status as behavioral evidence. +set -euo pipefail +baseline="$1" +tree="${2:-.}" +candidate="${3:-$(git -C "$tree" rev-parse HEAD)}" +# Selective Issue715 overlays retain HTTP2 production/support, so keep its tests. +if test -f "$tree/backend/internal/service/http2_gateway_test_support.go"; then + exit 0 +fi +for target in backend/internal/handler/http2_peer_reset_test.go backend/internal/service/http2_peer_reset_test.go backend/internal/service/http2_peer_reset_adapters_test.go backend/internal/service/http2_peer_reset_followup_test.go; do + if git -C "$tree" cat-file -e "$baseline:$target" 2>/dev/null; then + printf 'refusing to exclude baseline HTTP2 test: %s\n' "$target" >&2 + exit 1 + fi + expected=$(git -C "$tree" rev-parse "$candidate:$target") + actual=$(git -C "$tree" hash-object "$target") + test "$expected" = "$actual" + printf 'unrelated later HTTP2 fixture baseline=%s candidate=%s path=%s expected=%s actual=%s\n' "$baseline" "$candidate" "$target" "$expected" "$actual" + rm -- "$tree/$target" + test ! -e "$tree/$target" +done diff --git a/.github/scripts/mutate-future-shadow.py b/.github/scripts/mutate-future-shadow.py new file mode 100644 index 000000000000..8002608b6231 --- /dev/null +++ b/.github/scripts/mutate-future-shadow.py @@ -0,0 +1,35 @@ +"""CI-only counterexample: latest task per session despite committed item owners.""" + +import hashlib +import json +import os +import sys +from pathlib import Path + + +def main(): + root = Path(sys.argv[1]).resolve() + temporary = os.environ.get("RUNNER_TEMP") + if os.environ.get("GITHUB_ACTIONS") != "true" or not temporary or not root.is_relative_to(Path(temporary).resolve()): + raise SystemExit("source mutations require a disposable Actions RUNNER_TEMP checkout") + changes = ( + ("backend/internal/service/openai_409_readable_shadow.go", + "r.groupID, r.shadowModel, r.session, hex.EncodeToString(item[:])", + 'r.groupID, r.shadowModel, r.session, "session-latest-task"'), + ("backend/internal/repository/gateway_cache_readable_shadow.go", + "local old = redis.call('GET', KEYS[1])", "local old = false"), + ) + for name, anchor, replacement in changes: + target = root / name + original = target.read_text() + if original.count(anchor) != 1: + raise SystemExit(f"mutation anchor changed: {name}") + mutated = original.replace(anchor, replacement) + target.write_text(mutated) + print(json.dumps({"mutation": "session-last-task", "target": name, + "candidate_sha256": hashlib.sha256(original.encode()).hexdigest(), + "mutant_sha256": hashlib.sha256(mutated.encode()).hexdigest()})) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/mutate-http-rebuild-owner-scan.py b/.github/scripts/mutate-http-rebuild-owner-scan.py new file mode 100644 index 000000000000..810f146c1c36 --- /dev/null +++ b/.github/scripts/mutate-http-rebuild-owner-scan.py @@ -0,0 +1,46 @@ +"""CI-only unsafe source mutants; never modify the clean candidate checkout.""" + +import hashlib +import json +import os +import sys +from pathlib import Path + + +def main(): + root, mode = Path(sys.argv[1]).resolve(), sys.argv[2] + temporary = os.environ.get("RUNNER_TEMP") + if os.environ.get("GITHUB_ACTIONS") != "true" or not temporary or not root.is_relative_to(Path(temporary).resolve()): + raise SystemExit("source mutations require a disposable Actions RUNNER_TEMP checkout") + target = root / "backend/internal/service/openai_agent_message_recovery.go" + original = target.read_text() + begin = original.index("func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(") + end = original.index("func openAIAgentRecoveryFromContext(") + function = original[begin:end] + if mode == "newest-only": + anchor = "\tstate := &s.agentMessageRecovery\n" + if function.count(anchor) != 1: + raise SystemExit("newest-only mutation anchor changed") + function = function.replace(anchor, "\tif len(request.keys) > 0 {\n\t\trequest.keys = request.keys[len(request.keys)-1:]\n\t}\n" + anchor) + elif mode == "break-on-owner-mismatch": + loop = "for _, key := range request.keys {" + anchor = "request.mixedOwners = true" + if function.count(loop) != 1 or function.count(anchor) != 1: + raise SystemExit("owner-mismatch mutation anchor changed") + function = function.replace(loop, "for index, key := range request.keys {") + # Model the unsafe shortcut retaining only the inspected prefix for + # both rebuild and final revalidation. The later fenced item is lost. + function = function.replace(anchor, anchor + "\n\t\t\trequest.keys = request.keys[:index+1]\n\t\t\tbreak") + else: + raise SystemExit("unknown source mutation") + mutated = original[:begin] + function + original[end:] + if mutated == original: + raise SystemExit("source mutant did not change the candidate") + target.write_text(mutated) + print(json.dumps({"mutation": mode, "target": str(target.relative_to(root)), + "candidate_sha256": hashlib.sha256(original.encode()).hexdigest(), + "mutant_sha256": hashlib.sha256(mutated.encode()).hexdigest()})) + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/oauth429-weekly-only-bridge-compat.patch b/.github/scripts/oauth429-weekly-only-bridge-compat.patch new file mode 100644 index 000000000000..f8831fd00e17 --- /dev/null +++ b/.github/scripts/oauth429-weekly-only-bridge-compat.patch @@ -0,0 +1,5 @@ +diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go +--- a/backend/internal/service/openai_ws_http_bridge.go ++++ b/backend/internal/service/openai_ws_http_bridge.go +@@ -33,0 +34 @@ ++ ClientTools json.RawMessage diff --git a/.github/scripts/oauth429-weekly-only-bridge-compat.sh b/.github/scripts/oauth429-weekly-only-bridge-compat.sh new file mode 100644 index 000000000000..e85265389d90 --- /dev/null +++ b/.github/scripts/oauth429-weekly-only-bridge-compat.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Historical RED only. Retained readable-continuation code must compile against +# the old bridge type. This adds storage only: the original bridge never writes +# ClientTools, so it stays nil. No 429 parser, observation, scheduling, forwarding +# or selected test is changed. GREEN never invokes this compatibility patch. +set -euo pipefail +tree=$(git -C "$1" rev-parse --show-toplevel) +baseline="$2" +target=backend/internal/service/openai_ws_http_bridge.go +script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd) +patch="$script_dir/oauth429-weekly-only-bridge-compat.patch" +before=$(git -C "$tree" rev-parse "$baseline:$target") +case "$before" in + ed1708f3c2ee470d80ab97b377ff610050e383fc) after=efe2dce796b21dcdac9c0fa6268887423fe65780 ;; # weekly RED / expiry + c91d1b2481d3ca0fae69c35290d196984c0fac4e) after=f18f5c8edd520122bc7c15e382b3e33d148d08f1 ;; # Issue715 pre-WS RED + *) printf 'unreviewed historical bridge blob: %s\n' "$before" >&2; exit 1 ;; +esac +test "$(git hash-object "$tree/$target")" = "$before" +grep -Fq 'state.ClientTools' "$tree/backend/internal/service/openai_ws_readable_continuation.go" +git -C "$tree" diff --exit-code -- '*_test.go' +printf 'bridge compatibility baseline=%s path=%s original=%s patch=%s\n' "$baseline" "$target" "$before" "$(git hash-object "$patch")" +cat "$patch" +# The insertion is line-exact only because the complete original blob was +# checked above; the complete expected post-patch blob is checked below. +git -C "$tree" apply --unidiff-zero --check "$patch" +git -C "$tree" apply --unidiff-zero "$patch" +actual=$(git hash-object "$tree/$target") +test "$actual" = "$after" +printf 'bridge compatibility expected_post=%s actual_post=%s\n' "$after" "$actual" +git -C "$tree" diff --exit-code -- '*_test.go' diff --git a/.github/scripts/prepare-moderation-red-fixtures.sh b/.github/scripts/prepare-moderation-red-fixtures.sh new file mode 100644 index 000000000000..7fb254a40b80 --- /dev/null +++ b/.github/scripts/prepare-moderation-red-fixtures.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Disposable historical source overlays only. Candidate GREEN and the focused +# 112d handler-only RED retain all moderation/recovered-audit tests unchanged. +set -euo pipefail +baseline="$1" +tree="${2:-.}" +candidate="${3:-$(git -C "$tree" rev-parse HEAD)}" +if test -f "$tree/backend/internal/service/content_moderation_upstream_scope.go"; then + exit 0 +fi +production=backend/internal/service/content_moderation.go +expected=$(git -C "$tree" rev-parse "$baseline:$production") +test "$(git -C "$tree" hash-object "$production")" = "$expected" +printf 'moderation fixture overlay baseline=%s candidate=%s production=%s blob=%s\n' "$baseline" "$candidate" "$production" "$expected" + +# These exact feature fixtures require the absent selected-upstream contract. +# The new recovered-WS audit suite targets 112d, where the contract exists; it +# must not become a compile blocker in unrelated, older recovery counterexamples. +while IFS= read -r target; do + if git -C "$tree" cat-file -e "$baseline:$target" 2>/dev/null; then + printf 'refusing to exclude baseline moderation fixture: %s\n' "$target" >&2 + exit 1 + fi + expected=$(git -C "$tree" rev-parse "$candidate:$target") + actual=$(git -C "$tree" hash-object "$target") + test "$actual" = "$expected" + printf 'excluded path=%s baseline=absent candidate=%s actual=%s\n' "$target" "$expected" "$actual" + rm -- "$tree/$target" + test ! -e "$tree/$target" +done < <(git -C "$tree" ls-files 'backend/internal/handler/moderation_upstream*_test.go' 'backend/internal/handler/admin/moderation_upstream_scope_test.go' 'backend/internal/service/content_moderation_upstream_scope_test.go' 'backend/internal/repository/moderation_upstream_scope*_test.go' 'backend/internal/handler/openai_409_ws_audit_test.go') + +# This pre-PR848 fixture retains PR834's actual error observer and all existing +# recovery harness entry points, with the historical eight-argument constructor. +fixture_base=afa7dbd6fccffef950febadc666b9243bba2454d +target=backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go +if ! git -C "$tree" cat-file -e "$fixture_base^{commit}" 2>/dev/null; then + git -C "$tree" fetch --no-tags --depth=1 origin "$fixture_base" +fi +candidate_blob=$(git -C "$tree" rev-parse "$candidate:$target") +test "$(git -C "$tree" hash-object "$target")" = "$candidate_blob" +expected=$(git -C "$tree" rev-parse "$fixture_base:$target") +git -C "$tree" show "$fixture_base:$target" > "$tree/$target" +actual=$(git -C "$tree" hash-object "$target") +test "$actual" = "$expected" +printf 'compatible path=%s fixture_base=%s candidate=%s expected=%s actual=%s\n' "$target" "$fixture_base" "$candidate_blob" "$expected" "$actual" diff --git a/.github/scripts/test_assert_future_shadow.py b/.github/scripts/test_assert_future_shadow.py new file mode 100644 index 000000000000..be70fc7f2c72 --- /dev/null +++ b/.github/scripts/test_assert_future_shadow.py @@ -0,0 +1,91 @@ +"""Remote-only evidence-validator tests; no fixture or provider is executed here.""" + +import importlib.util +import json +import unittest +from pathlib import Path + + +SPEC = importlib.util.spec_from_file_location("shadow_gate", Path(__file__).with_name("assert-future-shadow.py")) +GATE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(GATE) + + +def evidence(phase, boundaries=False, resources=False, association=False): + root, leaves = (GATE.BOUNDARIES, GATE.BOUNDARY_LEAVES) if boundaries else (GATE.ROOT, GATE.LEAVES) + if resources: + root, leaves = GATE.RESOURCES, GATE.RESOURCE_LEAVES + if association: + root, leaves = GATE.ASSOCIATION, GATE.ASSOCIATION_LEAVES + terminal = "fail" if phase == "RED" else "pass" + events = [{"Action": "run", "Test": root}] + for name in leaves: + events.append({"Action": "run", "Test": name}) + if phase == "RED": + output = "SHADOW_TASK_ASSOCIATION_MISMATCH" if association else "FUTURE_SHADOW_B_DISPATCH_MISSING: encrypted_agent_recovery_readable_intent_missing" + events.append({"Action": "output", "Test": name, "Output": output}) + events.append({"Action": terminal, "Test": name}) + events.extend([{"Action": terminal, "Test": root}, {"Action": terminal}]) + for event in events: + event["Package"] = GATE.COMMON.PACKAGE + return events + + +def transcript(events): + return "".join(json.dumps(event) + "\n" for event in events) + + +class FutureShadowEvidenceTest(unittest.TestCase): + def test_valid_evidence(self): + GATE.validate("RED", 1, transcript(evidence("RED"))) + GATE.validate("GREEN", 0, transcript(evidence("GREEN"))) + GATE.validate("GREEN", 0, transcript(evidence("GREEN", True)), True) + GATE.validate("GREEN", 0, transcript(evidence("GREEN", resources=True)), resources=True) + for phase, code in (("RED", 1), ("GREEN", 0)): + GATE.validate(phase, code, transcript(evidence(phase, association=True)), association=True) + + def test_association_mutant_needs_content_failure_for_each_task(self): + for name in GATE.ASSOCIATION_LEAVES: + events = evidence("RED", association=True) + for event in events: + if event.get("Test") == name and event["Action"] == "output": + event["Output"] = "FUTURE_SHADOW_B_DISPATCH_MISSING: encrypted_agent_recovery_readable_intent_missing" + with self.assertRaises(ValueError): + GATE.validate("RED", 1, transcript(events), association=True) + + def test_resources_require_every_named_leaf(self): + for name in GATE.RESOURCE_LEAVES: + events = [event for event in evidence("GREEN", resources=True) if event.get("Test") != name] + with self.assertRaises(ValueError): + GATE.validate("GREEN", 0, transcript(events), resources=True) + + def test_each_business_failure_needs_its_own_diagnostic(self): + for name in GATE.LEAVES: + for output in ("FUTURE_SHADOW_B_DISPATCH_MISSING", "encrypted_agent_recovery_readable_intent_missing", "unrelated error"): + with self.subTest(name=name, output=output): + events = evidence("RED") + for event in events: + if event.get("Test") == name and event["Action"] == "output": + event["Output"] = output + with self.assertRaises(ValueError): + GATE.validate("RED", 1, transcript(events)) + + def test_pollution_in_raw_and_json_output(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + for diagnostic in ("panic: fixture", "openai.usage_record_task_panic_recovered", "WARNING: DATA RACE", "fatal error: crash", "signal: killed", "--- SKIP: fixture", "undefined: fixture", "[no tests to run]"): + for encoded in (False, True): + with self.subTest(phase=phase, diagnostic=diagnostic, encoded=encoded): + poison = transcript([{"Action": "output", "Output": diagnostic}]) if encoded else diagnostic + with self.assertRaises(ValueError): + GATE.validate(phase, code, transcript(evidence(phase)) + poison) + + def test_missing_run_terminal_and_skip(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + events = evidence(phase) + for bad in (events[1:], events[:-1], events + [{"Action": "skip"}]): + with self.assertRaises(ValueError): + GATE.validate(phase, code, transcript(bad)) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/test_assert_http_task_rebuild.py b/.github/scripts/test_assert_http_task_rebuild.py new file mode 100644 index 000000000000..a0cc2bdbfa4d --- /dev/null +++ b/.github/scripts/test_assert_http_task_rebuild.py @@ -0,0 +1,124 @@ +"""Remote-only self-tests for the HTTP task-rebuild evidence manifest.""" + +import importlib.util +import json +import unittest +from pathlib import Path + + +SPEC = importlib.util.spec_from_file_location( + "task_rebuild_evidence", Path(__file__).with_name("assert-http-task-rebuild.py") +) +GATE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(GATE) + + +def evidence(phase, boundaries=False): + root, leaves = (GATE.BOUNDARIES, GATE.BOUNDARY_LEAVES) if boundaries else (GATE.ROOT, GATE.LEAVES) + terminal = "fail" if phase == "RED" else "pass" + events = [{"Action": "run", "Test": root, "Package": GATE.PACKAGE}] + for name in sorted(leaves): + events.append({"Action": "run", "Test": name, "Package": GATE.PACKAGE}) + if phase == "RED": + events.append({"Action": "output", "Test": name, "Package": GATE.PACKAGE, + "Output": GATE.DIAGNOSTIC + ": response=" + GATE.OLD_REFUSALS[0] + "\n"}) + events.append({"Action": terminal, "Test": name, "Package": GATE.PACKAGE}) + events.extend([{"Action": terminal, "Test": root, "Package": GATE.PACKAGE}, + {"Action": terminal, "Package": GATE.PACKAGE}]) + return events + + +def transcript(events): + return "".join(json.dumps(event) + "\n" for event in events) + + +class HTTPTaskRebuildEvidenceTest(unittest.TestCase): + def test_valid_red_green_and_boundaries(self): + GATE.validate("RED", 1, transcript(evidence("RED"))) + GATE.validate("GREEN", 0, transcript(evidence("GREEN"))) + GATE.validate("GREEN", 0, transcript(evidence("GREEN", True)), True) + + def test_each_named_red_requires_assertion_and_refusal(self): + for name in GATE.LEAVES: + for replacement in (GATE.DIAGNOSTIC, GATE.OLD_REFUSALS[0], "unrelated assertion"): + with self.subTest(name=name, replacement=replacement): + events = evidence("RED") + for event in events: + if event.get("Test") == name and event["Action"] == "output": + event["Output"] = replacement + with self.assertRaisesRegex(ValueError, "missing named B-dispatch"): + GATE.validate("RED", 1, transcript(events)) + + def test_contamination_is_never_business_red_or_green(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + for diagnostic in ("panic: failed", "openai.usage_record_task_panic_recovered", "WARNING: DATA RACE", "fatal error: crash", "signal: killed", "--- SKIP: fixture", "undefined: fixture", "[no tests to run]"): + for raw in (False, True): + with self.subTest(phase=phase, diagnostic=diagnostic, raw=raw): + poison = diagnostic if raw else transcript([{"Action": "output", "Package": GATE.PACKAGE, "Output": diagnostic}]) + with self.assertRaises(ValueError): + GATE.validate(phase, code, transcript(evidence(phase)) + poison) + + def test_missing_run_package_terminal_and_skip(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + events = evidence(phase) + for altered in (events[1:], events[:-1], events + [{"Action": "skip", "Package": GATE.PACKAGE}]): + with self.subTest(phase=phase): + with self.assertRaises(ValueError): + GATE.validate(phase, code, transcript(altered)) + + def test_mutant_requires_actual_extra_generation_assertion(self): + for mutant, name in GATE.MUTANTS.items(): + values = [ + {"Action": "run", "Test": GATE.MIXED, "Package": GATE.PACKAGE}, + {"Action": "run", "Test": name, "Package": GATE.PACKAGE}, + {"Action": "output", "Test": name, "Package": GATE.PACKAGE, + "Output": "HTTP_REBUILD_FENCE_BYPASSED: response=coding-task-complete"}, + {"Action": "fail", "Test": name, "Package": GATE.PACKAGE}, + {"Action": "fail", "Test": GATE.MIXED, "Package": GATE.PACKAGE}, + {"Action": "fail", "Package": GATE.PACKAGE}, + ] + GATE.validate("MUTANT", 1, transcript(values), mutant=mutant) + for bad in ("unrelated assertion", "HTTP_REBUILD_FENCE_BYPASSED", "panic: coding-task-complete"): + with self.subTest(mutant=mutant, bad=bad): + values[2]["Output"] = bad + with self.assertRaises(ValueError): + GATE.validate("MUTANT", 1, transcript(values), mutant=mutant) + + def test_all_new_green_inventory_is_required(self): + for suite, (root, leaves) in GATE.SUITES.items(): + values = [{"Action": "run", "Test": root, "Package": GATE.PACKAGE}] + for name in leaves: + values.extend([{"Action": "run", "Test": name, "Package": GATE.PACKAGE}, + {"Action": "pass", "Test": name, "Package": GATE.PACKAGE}]) + values.extend([{"Action": "pass", "Test": root, "Package": GATE.PACKAGE}, + {"Action": "pass", "Package": GATE.PACKAGE}]) + GATE.validate("GREEN", 0, transcript(values), suite=suite) + with self.assertRaises(ValueError): + GATE.validate("GREEN", 0, transcript(values[1:]), suite=suite) + + def test_review_red_requires_specific_failure(self): + for suite in ("normalization", "pointer-waiver"): + root, leaves = GATE.SUITES[suite] + events = [{"Action": "run", "Test": root, "Package": GATE.PACKAGE}] + for name in leaves: + if suite == "pointer-waiver": + output = "UNOWNED_POINTER_WAIVER_LEAK: response=completed" + elif name.endswith("/blank_parts"): + output = "HTTP_REBUILD_B_DISPATCH_MISSING encrypted_agent_recovery_readable_intent_missing" + elif name.endswith("/no_tools_parallel"): + output = "automatic next tool turn must finish encrypted_agent_recovery_wire_changed" + else: + output = "HTTP_REBUILD_B_DISPATCH_MISSING encrypted_agent_recovery_wire_changed" + events.extend([{"Action": "run", "Test": name, "Package": GATE.PACKAGE}, + {"Action": "output", "Test": name, "Package": GATE.PACKAGE, "Output": output}, + {"Action": "fail", "Test": name, "Package": GATE.PACKAGE}]) + events.extend([{"Action": "fail", "Test": root, "Package": GATE.PACKAGE}, + {"Action": "fail", "Package": GATE.PACKAGE}]) + GATE.validate("RED", 1, transcript(events), suite=suite) + events[2]["Output"] = "arbitrary failure" + with self.assertRaises(ValueError): + GATE.validate("RED", 1, transcript(events), suite=suite) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/test_assert_readable_continuation.py b/.github/scripts/test_assert_readable_continuation.py new file mode 100644 index 000000000000..98391fe729d1 --- /dev/null +++ b/.github/scripts/test_assert_readable_continuation.py @@ -0,0 +1,136 @@ +"""Run only in remote CI; exercise accepted evidence and poisoned transcripts.""" + +import importlib.util +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + + +SCRIPT = Path(__file__).with_name("assert-readable-continuation.py") +SPEC = importlib.util.spec_from_file_location("readable_evidence", SCRIPT) +GATE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(GATE) + + +def event(action, name=None, output=None): + value = {"Action": action, "Package": GATE.PACKAGE} + if name is not None: + value["Test"] = name + if output is not None: + value["Output"] = output + return value + + +def evidence(phase): + terminal = "fail" if phase == "RED" else "pass" + events = [event("run", GATE.ROOT)] + for name in sorted(GATE.LEAVES): + events.append(event("run", name)) + if phase == "RED": + events.append(event("output", name, "response: encrypted_agent_recovery_wire_changed\n")) + events.append(event(terminal, name)) + events.extend([event(terminal, GATE.ROOT), event(terminal)]) + return events + + +def transcript(events): + return "".join(json.dumps(value) + "\n" for value in events) + + +class ReadableEvidenceTest(unittest.TestCase): + def test_valid_red_and_green(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + with self.subTest(phase=phase): + GATE.validate(phase, code, transcript(evidence(phase))) + + def test_raw_and_json_output_pollution_in_both_phases(self): + diagnostics = ( + "panic: unexpected nil pointer", + 'openai.usage_record_task_panic_recovered {"panic":"nil pointer"}', + "WARNING: DATA RACE", + "race detected during execution of test", + "fatal error: concurrent map writes", + "runtime error: invalid memory address", + "runtime: out of memory", + "SIGSEGV: segmentation violation", + "signal: killed", + "Killed", + "test timed out after 5m0s", + "process crash: exit status 2", + "FAIL [build failed]", + "undefined: omit409SettingsRepo", + "[no tests to run]", + "--- SKIP: TestOpenAI409ReadableContinuationHTTP", + ) + for phase, code in (("RED", 1), ("GREEN", 0)): + for diagnostic in diagnostics: + for encoded in (False, True): + with self.subTest(phase=phase, diagnostic=diagnostic, encoded=encoded): + poison = transcript([event("output", GATE.ROOT, diagnostic + "\n")]) if encoded else diagnostic + "\n" + with self.assertRaisesRegex(ValueError, "contaminated"): + GATE.validate(phase, code, transcript(evidence(phase)) + poison) + + def test_split_diagnostic_and_skip_event(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + for poison in ( + [event("output", GATE.ROOT, "WARNING: DATA "), event("output", GATE.ROOT, "RACE\n")], + [event("skip", GATE.ROOT)], + ): + with self.subTest(phase=phase, poison=poison): + with self.assertRaises(ValueError): + GATE.validate(phase, code, transcript(evidence(phase) + poison)) + + def test_missing_or_misattributed_red_diagnostics(self): + for name in sorted(GATE.LEAVES): + if not name.endswith("/completed"): + continue + for misattribute in (False, True): + with self.subTest(name=name, misattribute=misattribute): + values = evidence("RED") + values = [value for value in values if not (value["Action"] == "output" and value.get("Test") == name)] + if misattribute: + values.append(event("output", GATE.ROOT, "encrypted_agent_recovery_wire_changed")) + with self.assertRaisesRegex(ValueError, "missing named input-integrity"): + GATE.validate("RED", 1, transcript(values)) + + def test_missing_run_or_terminal_and_wrong_exit(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + values = evidence(phase) + leaf_terminal = next(index for index, value in enumerate(values) if value["Action"] in {"pass", "fail"} and value.get("Test") in GATE.LEAVES) + for index in (0, 1, leaf_terminal, len(values) - 2, len(values) - 1): + with self.subTest(phase=phase, missing=index): + with self.assertRaises(ValueError): + GATE.validate(phase, code, transcript(values[:index] + values[index + 1:])) + with self.subTest(phase=phase, wrong_exit=True): + with self.assertRaises(ValueError): + GATE.validate(phase, 2, transcript(values)) + + def test_unrelated_failure_cannot_hide_in_red(self): + values = evidence("RED") + [event("fail", "TestUnrelatedFailure")] + with self.assertRaisesRegex(ValueError, "unrelated failure"): + GATE.validate("RED", 1, transcript(values)) + + def test_cli_exit_status_for_valid_and_contaminated_logs(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "evidence.jsonl" + for phase, code in (("RED", 1), ("GREEN", 0)): + for poisoned in (False, True): + with self.subTest(phase=phase, poisoned=poisoned): + path.write_text(transcript(evidence(phase)) + ("panic: injected\n" if poisoned else "")) + result = subprocess.run( + [sys.executable, str(SCRIPT), phase, str(code), str(path)], + capture_output=True, text=True, timeout=5, check=False, + ) + self.assertEqual(result.returncode, int(poisoned), result.stdout + result.stderr) + clean = subprocess.run( + [sys.executable, str(SCRIPT), "--clean-log", str(path)], + capture_output=True, text=True, timeout=5, check=False, + ) + self.assertEqual(clean.returncode, int(poisoned), clean.stdout + clean.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/test_assert_ws_readable.py b/.github/scripts/test_assert_ws_readable.py new file mode 100644 index 000000000000..cd3ab772cf96 --- /dev/null +++ b/.github/scripts/test_assert_ws_readable.py @@ -0,0 +1,164 @@ +"""Run only on Actions; validate clean per-leaf WS RED and exact GREEN.""" + +import importlib.util +import json +import unittest +from pathlib import Path + +SPEC = importlib.util.spec_from_file_location("gate", Path(__file__).with_name("assert-ws-readable.py")) +GATE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(GATE) + + +def evidence(phase, suite): + root, names = GATE.SUITES[suite] + terminal = "fail" if phase == "RED" else "pass" + events = [{"Action": "run", "Test": root}] + for suffix in names: + name = f"{root}/{suffix}" + events.append({"Action": "run", "Test": name}) + if phase == "RED": + events.append({"Action": "output", "Test": name, "Output": " ".join(GATE.diagnostic(suite, name))}) + events.append({"Action": terminal, "Test": name}) + events.extend([{"Action": terminal, "Test": root}, {"Action": terminal}]) + for event in events: + event["Package"] = GATE.COMMON.PACKAGE.replace("/handler", "/securityaudit") if suite in {"audit-persistence", "audit-async"} else GATE.COMMON.PACKAGE + if suite == "ws-ticket": + event["Package"] = GATE.COMMON.PACKAGE.replace("/handler", "/service") + return events + + +def raw(events): + return "".join(json.dumps(event) + "\n" for event in events) + + +class WSReadableEvidenceTest(unittest.TestCase): + def test_recovered_audit_red_requires_actual_restored_B_completion(self): + suite = "ws-recovered-audit" + events = evidence("RED", suite) + GATE.validate("RED", 1, raw(events), suite) + for event in events: + if event["Action"] != "output": + continue + original = event["Output"] + event["Output"] = "WS_RECOVERED_AUDIT_DISPATCHED: unrelated client close" + with self.assertRaises(ValueError): + GATE.validate("RED", 1, raw(events), suite) + event["Output"] = original + + def strict_baseline(self, failures): + events = evidence("GREEN", "strict-pointer") + root, _ = GATE.SUITES["strict-pointer"] + names = {f"{root}/{suffix}" for suffix in failures} + for event in events: + if event["Action"] == "pass" and (event.get("Test") in names or (failures and event.get("Test") in {root, None})): + event["Action"] = "fail" + for name in names: + events.append({"Package": GATE.COMMON.PACKAGE, "Action": "output", "Test": name, "Output": "HTTP_POINTER_STRICT_A_STATE_LEAK"}) + return events + + def test_strict_baseline_pins_each_expected_leaf(self): + names = GATE.SUITES["strict-pointer"][1] + failures = {"apikey/stream=false/strict", "apikey/stream=true/strict"} + events = self.strict_baseline(failures) + GATE.validate("BASELINE", 1, raw(events), "strict-pointer") + GATE.validate("GREEN", 0, raw(evidence("GREEN", "strict-pointer")), "strict-pointer") + for incorrect in (set(), names, names - failures, {"apikey/stream=false/strict", "oauth/stream=true/strict"}): + with self.assertRaises(ValueError): + GATE.validate("BASELINE", int(bool(incorrect)), raw(self.strict_baseline(incorrect)), "strict-pointer") + for code in (0, 1): + with self.assertRaises(ValueError): + GATE.validate("GREEN", code, raw(events), "strict-pointer") + with self.assertRaises(ValueError): + GATE.validate("RED", 1, raw(self.strict_baseline(names)), "strict-pointer") + for index, original in enumerate(events): + if original["Action"] in {"run", "pass", "fail", "output"}: + with self.assertRaises(ValueError): + GATE.validate("BASELINE", 1, raw(events[:index] + events[index + 1:]), "strict-pointer") + if original["Action"] in {"run", "pass", "fail"}: + with self.assertRaises(ValueError): + GATE.validate("BASELINE", 1, raw(events + [original]), "strict-pointer") + if original["Action"] in {"pass", "fail"}: + wrong = dict(original, Action="pass" if original["Action"] == "fail" else "fail") + with self.assertRaises(ValueError): + GATE.validate("BASELINE", 1, raw(events[:index] + [wrong] + events[index + 1:]), "strict-pointer") + for wrong_exit in (0, 2, 137): + with self.assertRaises(ValueError): + GATE.validate("BASELINE", wrong_exit, raw(events), "strict-pointer") + for poison in ("panic: fixture", "WARNING: DATA RACE", "openai.usage_record_task_panic_recovered", "fatal error: crash", "signal: killed", "undefined: fixture", "[no tests to run]", "--- SKIP: fixture"): + for contamination in (poison, raw([{"Action": "output", "Output": poison}])): + with self.assertRaises(ValueError): + GATE.validate("BASELINE", 1, raw(events) + contamination, "strict-pointer") + for action in ("run", "pass", "fail", "skip"): + with self.assertRaises(ValueError): + GATE.validate("BASELINE", 1, raw(events + [{"Package": GATE.COMMON.PACKAGE, "Action": action, "Test": "Unrelated"}]), "strict-pointer") + with self.assertRaises(ValueError): + GATE.validate("BASELINE", 1, raw(events + [{"Package": "unrelated/package", "Action": "pass"}]), "strict-pointer") + + def test_valid(self): + GATE.validate("RED", 1, raw(evidence("RED", "ws")), "ws") + for suite in GATE.SUITES: + GATE.validate("GREEN", 0, raw(evidence("GREEN", suite)), suite) + for suite in GATE.RED_SUITES: + GATE.validate("RED", 1, raw(evidence("RED", suite)), suite) + + def test_repair_red_needs_each_own_business_diagnostic(self): + for suite in GATE.RED_SUITES: + for index, original in enumerate(evidence("RED", suite)): + if original.get("Action") != "output": + continue + events = evidence("RED", suite) + events[index]["Output"] = "unrelated error" + with self.assertRaises(ValueError): + GATE.validate("RED", 1, raw(events), suite) + + def test_tool_red_requires_actual_transport_message_on_both_leaves(self): + # Keep this independent of diagnostic(): the actual baseline emits + # ClientMessage(), not its internal wire_changed reason identifier. + message = "The proven encrypted agent transport changed." + marker = "WS_RESIDUAL_TOOL_PROJECTION_REFUSED" + events = evidence("RED", "ws-residual") + for event in events: + if event.get("Action") == "output" and "/tools_" in event.get("Test", ""): + event["Output"] = f"{marker}: {message} Preserve this task and context." + GATE.validate("RED", 1, raw(events), "ws-residual") + for leaf in ("tools_omitted", "tools_explicit"): + for wrong in (marker, message, f"{marker}: wire_changed", f"{marker}: upstream failed"): + changed = [dict(event) for event in events] + for event in changed: + if event.get("Action") == "output" and event.get("Test", "").endswith("/" + leaf): + event["Output"] = wrong + with self.assertRaises(ValueError): + GATE.validate("RED", 1, raw(changed), "ws-residual") + for poison in ("undefined: fixture", "panic: fixture", "WARNING: DATA RACE", "--- SKIP: fixture"): + with self.assertRaises(ValueError): + GATE.validate("RED", 1, raw(events) + poison, "ws-residual") + + def test_each_leaf_requires_both_diagnostics(self): + for suffix in GATE.SUITES["ws"][1]: + for diagnostic in ("WS_READABLE_B_DISPATCH_MISSING", "account eligibility changed", "other"): + events = evidence("RED", "ws") + for event in events: + if event.get("Test", "").endswith("/" + suffix) and event["Action"] == "output": + event["Output"] = diagnostic + with self.assertRaises(ValueError): + GATE.validate("RED", 1, raw(events), "ws") + + def test_each_green_leaf_required(self): + for suite, (root, names) in GATE.SUITES.items(): + for suffix in names: + events = [e for e in evidence("GREEN", suite) if e.get("Test") != f"{root}/{suffix}"] + with self.assertRaises(ValueError): + GATE.validate("GREEN", 0, raw(events), suite) + + def test_contamination(self): + for phase, code in (("RED", 1), ("GREEN", 0)): + for poison in ("panic: fixture", "WARNING: DATA RACE", "openai.usage_record_task_panic_recovered", "fatal error: crash", "signal: killed", "undefined: fixture", "[no tests to run]", "--- SKIP: fixture"): + for encoded in (False, True): + contamination = raw([{"Action": "output", "Output": poison}]) if encoded else poison + with self.assertRaises(ValueError): + GATE.validate(phase, code, raw(evidence(phase, "ws")) + contamination, "ws") + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/backend-ci.yml b/.github/workflows/backend-ci.yml index 0363a47eb70a..c99365638d6a 100644 --- a/.github/workflows/backend-ci.yml +++ b/.github/workflows/backend-ci.yml @@ -92,6 +92,23 @@ jobs: test: runs-on: ubuntu-latest + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: fixture + POSTGRES_PASSWORD: fixture + POSTGRES_DB: shadow_audit + ports: ['15432:5432'] + options: >- + --health-cmd "pg_isready -U fixture -d shadow_audit" + --health-interval 5s --health-timeout 5s --health-retries 10 + redis: + image: redis:7-alpine + ports: ['16379:6379'] + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s --health-timeout 5s --health-retries 10 steps: - uses: actions/checkout@v6 with: @@ -168,6 +185,8 @@ jobs: - name: Integration tests working-directory: backend env: + PROMPT_AUDIT_TEST_POSTGRES_DSN: 'postgres://fixture:fixture@127.0.0.1:15432/shadow_audit?sslmode=disable' + PROMPT_AUDIT_TEST_REDIS_ADDR: '127.0.0.1:16379' # Keep real network timing fixtures isolated from other package/DB workloads. # Every integration package and its existing assertions still run. GOFLAGS: '-p=1' diff --git a/.github/workflows/encrypted-history-400.yml b/.github/workflows/encrypted-history-400.yml index 20eb5150c413..b5491452b136 100644 --- a/.github/workflows/encrypted-history-400.yml +++ b/.github/workflows/encrypted-history-400.yml @@ -26,6 +26,8 @@ jobs: timeout-minutes: 20 steps: - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} - uses: actions/setup-go@v6 with: go-version-file: backend/go.mod @@ -37,7 +39,9 @@ jobs: sudo apt-get install -y --no-install-recommends redis-server - name: Native recovery and unchanged 409 regressions working-directory: backend - run: go test -race -p 2 -tags=unit ./internal/service ./internal/handler ./internal/handler/admin -run '^Test(OpenAI400|OpenAI409|OmitOpenAIHistorical|ForwardEncryptedContentSSERetry|UpdateSettingsOpenAI400|UpdateSettingsOpenAI409)' -count=1 -timeout=5m + run: | + git rev-parse HEAD + go test -race -json -p 2 -tags=unit ./internal/service ./internal/handler ./internal/handler/admin -run '^Test(OpenAI400|OpenAI409|OmitOpenAIHistorical|ForwardEncryptedContentSSERetry|UpdateSettingsOpenAI400|UpdateSettingsOpenAI409)' -count=1 -timeout=5m settings: runs-on: ubuntu-latest timeout-minutes: 15 diff --git a/.github/workflows/encrypted-history-409.yml b/.github/workflows/encrypted-history-409.yml index df0e21117c68..93d6e66b26f9 100644 --- a/.github/workflows/encrypted-history-409.yml +++ b/.github/workflows/encrypted-history-409.yml @@ -44,10 +44,28 @@ jobs: run: | set -euo pipefail baseline=11f250894eab310cbd4508946c44c9e2a3a2eb48 - target=backend/internal/service/openai_409_omit_history.go - cp "$target" "$RUNNER_TEMP/omit-history-candidate.go" - trap 'cp "$RUNNER_TEMP/omit-history-candidate.go" "$target"' EXIT + callers=96ba36a85edab665ad5a035788fc07a40fd18762 git fetch --no-tags --depth=1 origin "$baseline" + git fetch --no-tags --depth=1 origin "$callers" + git worktree add --detach "$RUNNER_TEMP/omit-metadata-red" HEAD + cd "$RUNNER_TEMP/omit-metadata-red" + # Keep the pre-rebuild callers coherent with the old omission API. + # The historical metadata regression itself remains the candidate's. + for target in backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_agent_message_recovery_error.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_codex_transform.go backend/internal/handler/openai_gateway_handler.go; do + git show "$callers:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$callers:$target")" + done + for target in backend/internal/service/openai_ws_agent_recovery.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; do + git show "$callers:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$callers:$target")" + done + ! git cat-file -e "$callers:backend/internal/service/openai_ws_readable_continuation.go" 2>/dev/null + rm -- backend/internal/service/openai_ws_readable_continuation.go + for target in backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go; do + ! git cat-file -e "$callers:$target" 2>/dev/null + rm -- "$target" + done + target=backend/internal/service/openai_409_omit_history.go git show "$baseline:$target" > "$target" test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" set +e @@ -56,6 +74,7 @@ jobs: set -e cat "$RUNNER_TEMP/omit-history-red.log" test "$result" -ne 0 + ! grep -Eiq 'build failed|no tests to run|undefined:|panic|data race|--- SKIP:' "$RUNNER_TEMP/omit-history-red.log" grep -q -- '--- FAIL: TestOpenAI409ReplayMetadataHTTP' "$RUNNER_TEMP/omit-history-red.log" grep -q 'encrypted_agent_recovery_wire_changed' "$RUNNER_TEMP/omit-history-red.log" - uses: actions/upload-artifact@v7 diff --git a/.github/workflows/future-shadow.yml b/.github/workflows/future-shadow.yml new file mode 100644 index 000000000000..ed89efc17d9b --- /dev/null +++ b/.github/workflows/future-shadow.yml @@ -0,0 +1,202 @@ +name: Future readable shadow TDD + +on: + workflow_dispatch: + inputs: + phase: + type: choice + options: [RED, GREEN, BOTH] + default: BOTH + description: Fixed baseline RED and exact candidate GREEN + pull_request: + paths: + - 'backend/internal/handler/openai_409_shadow*' + - 'backend/internal/handler/openai_gateway_handler.go' + - 'backend/internal/service/openai_agent_message_*' + - 'backend/internal/service/openai_409_*' + - 'backend/internal/repository/gateway_cache_agent*' + - 'backend/internal/repository/gateway_cache_readable_shadow*' + - '.github/scripts/assert-future-shadow.py' + - '.github/scripts/test_assert_future_shadow.py' + - '.github/scripts/mutate-future-shadow.py' + - '.github/scripts/prepare-moderation-red-fixtures.sh' + - '.github/workflows/future-shadow.yml' +permissions: + contents: read + +jobs: + validator: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Evidence self-tests + shell: bash + run: | + set -euo pipefail + python3 -B -m unittest discover -s .github/scripts -p 'test_assert_future_shadow.py' -v 2>&1 | tee "$RUNNER_TEMP/shadow-validator.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: shadow-validator-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/shadow-validator.log + if-no-files-found: error + http: + name: Future shadow HTTP ${{ matrix.phase }} + needs: validator + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + phase: ${{ fromJSON(inputs.phase == 'RED' && '["RED"]' || inputs.phase == 'GREEN' && '["GREEN"]' || '["RED","GREEN"]') }} + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + BASELINE_SHA: 84e47f1b57acba77f1cfae08a63e8dd9d32a7991 + PHASE: ${{ matrix.phase }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - 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: Freeze candidate tests and disposable baseline source + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/shadow-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/shadow-evidence/candidate.txt" + git rev-parse "$BASELINE_SHA" > "$RUNNER_TEMP/shadow-evidence/baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/shadow-red" "$CANDIDATE_SHA" + cd "$RUNNER_TEMP/shadow-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$BASELINE_SHA:$target" 2>/dev/null; then + git show "$BASELINE_SHA:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$BASELINE_SHA:$target")" + else + rm -- "$target" + fi + done < <(git diff --no-renames --name-only "$BASELINE_SHA" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git diff --exit-code "$BASELINE_SHA" -- 'backend/**/*.go' ':!backend/**/*_test.go' + fi + git diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA" + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-evidence/moderation-fixtures.txt" + fi + for target in backend/internal/handler/openai_409_shadow_http_test.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_409_omit_history.go; do + git hash-object "$target" >> "$RUNNER_TEMP/shadow-evidence/blobs.txt" + done + - name: Actual cross-node HTTP continuation + shell: bash + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + if [ "$PHASE" = RED ]; then tested_tree="$RUNNER_TEMP/shadow-red"; fi + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409FutureShadowHTTP$' -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-evidence/transport.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-evidence/transport.jsonl" + python3 .github/scripts/assert-future-shadow.py "$PHASE" "$result" "$RUNNER_TEMP/shadow-evidence/transport.jsonl" + - name: GREEN scope and delivery boundaries + if: matrix.phase == 'GREEN' + shell: bash + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409FutureShadowBoundaries$' -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-evidence/boundaries.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-evidence/boundaries.jsonl" + python3 .github/scripts/assert-future-shadow.py GREEN "$result" "$RUNNER_TEMP/shadow-evidence/boundaries.jsonl" --boundaries + - name: GREEN bounded storage and exact delivered task association + if: matrix.phase == 'GREEN' + shell: bash + run: | + set -euo pipefail + for suite in resources association; do + if [ "$suite" = resources ]; then root=TestOpenAI409FutureShadowResources; else root=TestOpenAI409FutureShadowTaskAssociation; fi + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run "^${root}$" -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-evidence/$suite.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-evidence/$suite.jsonl" + python3 .github/scripts/assert-future-shadow.py GREEN "$result" "$RUNNER_TEMP/shadow-evidence/$suite.jsonl" "--$suite" + done + - uses: actions/upload-artifact@v7 + if: always() + with: + name: future-shadow-${{ matrix.phase }}-${{ env.CANDIDATE_SHA }} + path: ${{ runner.temp }}/shadow-evidence/ + if-no-files-found: error + task-association-mutation: + name: Reject session-last-task production mutant + needs: http + if: inputs.phase != 'RED' + runs-on: ubuntu-latest + timeout-minutes: 25 + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - 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: Mutate only disposable production and require wrong-task network failure + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/shadow-mutation-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/shadow-mutation-evidence/candidate.txt" + git worktree add --detach "$RUNNER_TEMP/shadow-mutant" "$CANDIDATE_SHA" + python3 .github/scripts/mutate-future-shadow.py "$RUNNER_TEMP/shadow-mutant" > "$RUNNER_TEMP/shadow-mutation-evidence/mutation.jsonl" + git -C "$RUNNER_TEMP/shadow-mutant" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + git -C "$RUNNER_TEMP/shadow-mutant" diff --stat > "$RUNNER_TEMP/shadow-mutation-evidence/delta.txt" + git hash-object backend/internal/handler/openai_409_shadow_http_test.go > "$RUNNER_TEMP/shadow-mutation-evidence/test-blob.txt" + set +e + (cd "$RUNNER_TEMP/shadow-mutant/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409FutureShadowTaskAssociation$' -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-mutation-evidence/association.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-mutation-evidence/association.jsonl" + python3 .github/scripts/assert-future-shadow.py RED "$result" "$RUNNER_TEMP/shadow-mutation-evidence/association.jsonl" --association + test -z "$(git status --porcelain)" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: future-shadow-task-mutation-${{ env.CANDIDATE_SHA }} + path: ${{ runner.temp }}/shadow-mutation-evidence/ + if-no-files-found: error diff --git a/.github/workflows/http-task-rebuild.yml b/.github/workflows/http-task-rebuild.yml new file mode 100644 index 000000000000..f6cdd164f1d7 --- /dev/null +++ b/.github/workflows/http-task-rebuild.yml @@ -0,0 +1,293 @@ +name: HTTP readable task rebuild TDD + +on: + workflow_dispatch: + inputs: + phase: + description: Paired immutable-baseline RED and production-candidate GREEN + type: choice + options: [RED, GREEN, BOTH] + default: BOTH + pull_request: + paths: + - 'backend/internal/handler/openai_409_*' + - 'backend/internal/handler/openai_gateway_handler.go' + - 'backend/internal/handler/openai_responses_failover_cancel_test.go' + - 'backend/internal/service/openai_409_*' + - 'backend/internal/service/openai_agent_message_*' + - 'backend/internal/service/openai_gateway_forward.go' + - 'backend/internal/service/openai_gateway_response_handling.go' + - 'backend/internal/service/openai_account_scheduler.go' + - 'backend/internal/service/openai_codex_transform.go' + - '.github/scripts/assert-http-task-rebuild.py' + - '.github/scripts/test_assert_http_task_rebuild.py' + - '.github/scripts/mutate-http-rebuild-owner-scan.py' + - '.github/scripts/assert-readable-continuation.py' + - '.github/scripts/prepare-moderation-red-fixtures.sh' + - '.github/workflows/http-task-rebuild.yml' + +permissions: + contents: read + +jobs: + validator: + name: Task rebuild evidence self-tests + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Evidence manifest and contamination self-tests + shell: bash + run: | + set -euo pipefail + python3 -B -m unittest discover -s .github/scripts -p 'test_assert_http_task_rebuild.py' -v 2>&1 | tee "$RUNNER_TEMP/http-task-validator.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: http-task-validator-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/http-task-validator.log + if-no-files-found: error + transport: + name: Native HTTP ${{ matrix.phase }} + needs: validator + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + phase: ${{ fromJSON(inputs.phase == 'RED' && '["RED"]' || inputs.phase == 'GREEN' && '["GREEN"]' || '["RED","GREEN"]') }} + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + BASELINE_SHA: 96ba36a85edab665ad5a035788fc07a40fd18762 + PHASE: ${{ matrix.phase }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated Redis fixture + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + - name: Keep clean candidate and prepare disposable RED source + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/http-task-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/http-task-evidence/candidate.txt" + git rev-parse "$BASELINE_SHA" > "$RUNNER_TEMP/http-task-evidence/baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/http-task-red" "$CANDIDATE_SHA" + cd "$RUNNER_TEMP/http-task-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$BASELINE_SHA:$target" 2>/dev/null; then + git show "$BASELINE_SHA:$target" > "$target" + expected=$(git rev-parse "$BASELINE_SHA:$target") + test "$(git hash-object "$target")" = "$expected" + echo "$target baseline=$expected" >> "$RUNNER_TEMP/http-task-evidence/red-blobs.txt" + else + rm -- "$target" + echo "$target baseline=absent" >> "$RUNNER_TEMP/http-task-evidence/red-blobs.txt" + fi + done < <(git diff --no-renames --name-only "$BASELINE_SHA" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git diff --exit-code "$BASELINE_SHA" -- 'backend/**/*.go' ':!backend/**/*_test.go' + # Record the real refusal/normalization callsites even on the + # initial test-only head, where no production blob needs changing. + for target in backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_codex_transform.go; do + expected=$(git rev-parse "$BASELINE_SHA:$target") + test "$(git hash-object "$target")" = "$expected" + echo "$target baseline=$expected" >> "$RUNNER_TEMP/http-task-evidence/red-blobs.txt" + done + fi + git diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA" + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/http-task-evidence/moderation-fixtures.txt" + fi + for target in backend/internal/handler/openai_409_http_rebuild_test.go backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_responses_failover_cancel_test.go; do + expected=$(git rev-parse "$CANDIDATE_SHA:$target") + test "$(git hash-object "$target")" = "$expected" + echo "$target candidate=$expected" >> "$RUNNER_TEMP/http-task-evidence/test-blobs.txt" + done + - name: Same composed network regression + shell: bash + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + if [ "$PHASE" = RED ]; then tested_tree="$RUNNER_TEMP/http-task-red"; fi + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409HTTPTaskRebuild$' -count=1 -timeout=5m) > "$RUNNER_TEMP/http-task-evidence/transport.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http-task-evidence/transport.jsonl" + python3 .github/scripts/assert-http-task-rebuild.py "$PHASE" "$result" "$RUNNER_TEMP/http-task-evidence/transport.jsonl" + - name: GREEN intent and delivery boundaries + if: matrix.phase == 'GREEN' + shell: bash + run: | + set -euo pipefail + test -z "$(git status --porcelain)" + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409HTTPRebuildBoundaries$' -count=1 -timeout=5m) > "$RUNNER_TEMP/http-task-evidence/boundaries.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http-task-evidence/boundaries.jsonl" + python3 .github/scripts/assert-http-task-rebuild.py GREEN "$result" "$RUNNER_TEMP/http-task-evidence/boundaries.jsonl" --boundaries + - name: GREEN mixed producer fences and tool-definition wire mutations + if: matrix.phase == 'GREEN' + shell: bash + run: | + set -euo pipefail + for suite in mixed-fences tool-oracle normalization pointer-waiver; do + test_name=TestOpenAI409HTTPMixedDeliveryFences + if [ "$suite" = tool-oracle ]; then test_name=TestOpenAI409HTTPToolDefinitionOracle; fi + if [ "$suite" = normalization ]; then test_name=TestOpenAI409HTTPControlNormalization; fi + if [ "$suite" = pointer-waiver ]; then test_name=TestOpenAI409HTTPUnownedPointerMustDetach; fi + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run "^$test_name$" -count=1 -timeout=5m) > "$RUNNER_TEMP/http-task-evidence/$suite.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http-task-evidence/$suite.jsonl" + python3 .github/scripts/assert-http-task-rebuild.py GREEN "$result" "$RUNNER_TEMP/http-task-evidence/$suite.jsonl" "--$suite" + done + - uses: actions/upload-artifact@v7 + if: always() + with: + name: http-task-rebuild-${{ matrix.phase }}-${{ env.CANDIDATE_SHA }} + path: ${{ runner.temp }}/http-task-evidence/ + if-no-files-found: error + review-counterexamples: + name: HTTP review counterexamples on 84e47 + needs: validator + runs-on: ubuntu-latest + timeout-minutes: 25 + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + REVIEW_BASELINE: 84e47f1b57acba77f1cfae08a63e8dd9d32a7991 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated Redis fixture + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + - name: Reproduce concrete HTTP review failures in disposable baseline + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/http-review-red-evidence" + git rev-parse HEAD "$REVIEW_BASELINE" > "$RUNNER_TEMP/http-review-red-evidence/provenance.txt" + git worktree add --detach "$RUNNER_TEMP/http-review-red" "$CANDIDATE_SHA" + cd "$RUNNER_TEMP/http-review-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$REVIEW_BASELINE:$target" 2>/dev/null; then + git show "$REVIEW_BASELINE:$target" > "$target" + else + rm -- "$target" + fi + done < <(git diff --no-renames --name-only "$REVIEW_BASELINE" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git diff --exit-code "$REVIEW_BASELINE" -- 'backend/**/*.go' ':!backend/**/*_test.go' + git diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$REVIEW_BASELINE" + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$REVIEW_BASELINE" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$REVIEW_BASELINE" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/http-review-red-evidence/moderation-fixtures.txt" + for suite in pointer-waiver normalization; do + test_name=TestOpenAI409HTTPUnownedPointerMustDetach + if [ "$suite" = normalization ]; then test_name=TestOpenAI409HTTPControlNormalization; fi + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run "^$test_name$" -count=1 -timeout=5m) > "$RUNNER_TEMP/http-review-red-evidence/$suite.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http-review-red-evidence/$suite.jsonl" + python3 "$GITHUB_WORKSPACE/.github/scripts/assert-http-task-rebuild.py" RED "$result" "$RUNNER_TEMP/http-review-red-evidence/$suite.jsonl" "--$suite" + done + - uses: actions/upload-artifact@v7 + if: always() + with: + name: http-review-counterexamples-${{ env.CANDIDATE_SHA }} + path: ${{ runner.temp }}/http-review-red-evidence/ + if-no-files-found: error + owner-scan-mutations: + name: Reject ${{ matrix.mutant }} owner scanner + needs: transport + if: inputs.phase != 'RED' + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + mutant: [newest-only, break-on-owner-mismatch] + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + MUTANT: ${{ matrix.mutant }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated Redis fixture + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + - name: Execute unsafe source mutant with unchanged composed HTTP oracle + shell: bash + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/http-mutant-evidence" + git worktree add --detach "$RUNNER_TEMP/http-owner-mutant" "$CANDIDATE_SHA" + python3 .github/scripts/mutate-http-rebuild-owner-scan.py "$RUNNER_TEMP/http-owner-mutant" "$MUTANT" > "$RUNNER_TEMP/http-mutant-evidence/mutation.json" + git -C "$RUNNER_TEMP/http-owner-mutant" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + git -C "$RUNNER_TEMP/http-owner-mutant" diff > "$RUNNER_TEMP/http-mutant-evidence/source.diff" + git rev-parse HEAD > "$RUNNER_TEMP/http-mutant-evidence/candidate.txt" + order=forward + if [ "$MUTANT" = break-on-owner-mismatch ]; then order=reverse; fi + set +e + (cd "$RUNNER_TEMP/http-owner-mutant/backend" && go test -race -json -tags=unit ./internal/handler -run "^TestOpenAI409HTTPMixedDeliveryFences$/^apikey$/^stream=false$/^A$/^failed$/^$order$" -count=1 -timeout=5m) > "$RUNNER_TEMP/http-mutant-evidence/transport.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/http-mutant-evidence/transport.jsonl" + python3 .github/scripts/assert-http-task-rebuild.py MUTANT "$result" "$RUNNER_TEMP/http-mutant-evidence/transport.jsonl" "--mutant=$MUTANT" + test -z "$(git status --porcelain)" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: http-owner-mutant-${{ matrix.mutant }}-${{ env.CANDIDATE_SHA }} + path: ${{ runner.temp }}/http-mutant-evidence/ + if-no-files-found: error diff --git a/.github/workflows/issue715-agent-recovery.yml b/.github/workflows/issue715-agent-recovery.yml index 738791bc77f2..c1cfe5ab849a 100644 --- a/.github/workflows/issue715-agent-recovery.yml +++ b/.github/workflows/issue715-agent-recovery.yml @@ -98,8 +98,9 @@ jobs: git rev-parse HEAD original=6df0cd5bb0ce4d774d34004008f9dd661d236468 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/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_400_omit_history.go backend/internal/service/openai_history_omission.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) # Pin this unrelated leaf to its pre-admission version, preserving all # Issue715 business-chain blobs and the retained handler regressions. analysis_compat=e395038e98fbc5a0c44944f0edcfbfe714570f71 @@ -250,6 +251,7 @@ jobs: ws_targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go) # Neither helper exists on the restored historical socket structure. ws_added=(backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_search_activation.go) + ws_added+=(backend/internal/service/openai_ws_readable_continuation.go) # 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. @@ -257,7 +259,7 @@ jobs: scheduler_leaf=backend/internal/service/openai_account_scheduler.go wait_added=backend/internal/service/openai_agent_message_recovery_wait.go # The Beta helper depends on fields absent in this historical recovery struct. - omission_added=(backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go) + omission_added=(backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go) git fetch --no-tags --depth=1 origin "$original" git fetch --no-tags --depth=1 origin "$ws_original" git fetch --no-tags --depth=1 origin "$scheduler_compat" @@ -270,6 +272,10 @@ jobs: echo "compatibility_leaf_baseline=$scheduler_compat path=$scheduler_leaf expected_blob=$expected tested_blob=$actual" test "$expected" = "$actual" rm -- "$added" "${ws_added[@]}" "$wait_added" "${omission_added[@]}" + for target in "${omission_added[@]}"; do + test ! -e "$target" + echo "candidate-only shadow dependency removed: $target" + done test ! -e "$wait_added" for target in "${targets[@]}"; do expected=$(git rev-parse "$original:$target") @@ -343,9 +349,13 @@ jobs: original=e7f54240d83765c90a98e961ad5e33b0fa35ab56 target=backend/internal/service/openai_ws_agent_recovery.go caller=backend/internal/service/openai_ws_forwarder_ingress.go + passthrough=backend/internal/service/openai_ws_v2_passthrough_adapter.go git fetch --no-tags --depth=1 origin "$original" - trap 'git restore --source=HEAD -- "$target" "$caller"; git diff --exit-code' EXIT - git restore --source="$original" -- "$target" "$caller" + # Manager fields and readable-payload methods live together. Restore + # both transport callers with that manager; retain candidate tests and + # standalone admission/principal helpers required by current HTTP. + trap 'git restore --source=HEAD -- "$target" "$caller" "$passthrough"; git diff --exit-code' EXIT + git restore --source="$original" -- "$target" "$caller" "$passthrough" expected=$(git rev-parse "$original:$target") actual=$(git hash-object "$target") echo "baseline=$original path=$target expected_blob=$expected tested_blob=$actual" @@ -354,6 +364,11 @@ jobs: actual_caller=$(git hash-object "$caller") echo "baseline=$original path=$caller expected_blob=$expected_caller tested_blob=$actual_caller" test "$expected_caller" = "$actual_caller" + expected_passthrough=$(git rev-parse "$original:$passthrough") + actual_passthrough=$(git hash-object "$passthrough") + echo "baseline=$original path=$passthrough expected_blob=$expected_passthrough tested_blob=$actual_passthrough" + test "$expected_passthrough" = "$actual_passthrough" + git diff --exit-code HEAD -- backend/internal/service/openai_ws_agent_recovery_test.go set +e (cd backend && go test -tags=unit ./internal/service -run '^TestIssue715WSBridgeValidatesBuiltPayload$' -count=1 -v -timeout=5m) > "$RUNNER_TEMP/issue715-ws-wire-red.log" 2>&1 result=$? @@ -412,8 +427,10 @@ jobs: git rev-parse HEAD original=a575df898ccd0876c4c0eb1559da38cedfdfe99d targets=(backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_ws_forwarder_ingress.go backend/internal/service/openai_ws_v2_passthrough_adapter.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_pool.go) - # Search activation was introduced with fields absent in this pool. - added=(backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_search_activation.go) + # Search activation references fields absent in this pool. Retain the + # standalone recovery helpers needed by current HTTP code; the pinned + # pre-WS handler/transports never call them or publish WS ownership. + added=(backend/internal/service/openai_ws_search_activation.go) git fetch --no-tags --depth=1 origin "$original" trap 'git restore --source=HEAD -- "${targets[@]}" "${added[@]}"; git diff --exit-code' EXIT git restore --source="$original" -- "${targets[@]}" @@ -424,6 +441,10 @@ jobs: echo "baseline=$original path=$target expected_blob=$expected tested_blob=$actual" test "$expected" = "$actual" done + # Current HTTP retains the readable helper; the pinned pre-WS bridge + # never populates this field or calls that recovery path. Keep all + # behavior blobs above exact except this audited zero-value storage. + bash .github/scripts/oauth429-weekly-only-bridge-compat.sh . "$original" | tee "$RUNNER_TEMP/issue715-ws-bridge-compat.log" set +e (cd backend && go test -race -tags=unit ./internal/handler -run '^TestIssue715WSGeneratedTaskContinuation$/.*/cross-node=true$' -count=1 -v -timeout=5m) > "$RUNNER_TEMP/issue715-ws-red.log" 2>&1 result=$? diff --git a/.github/workflows/issue805-owner-policy.yml b/.github/workflows/issue805-owner-policy.yml index 292e805d75b4..8157ca045e6a 100644 --- a/.github/workflows/issue805-owner-policy.yml +++ b/.github/workflows/issue805-owner-policy.yml @@ -5,6 +5,7 @@ on: branches: [production] paths: - 'backend/**' + - '.github/scripts/prepare-moderation-red-fixtures.sh' - '.github/workflows/issue805-owner-policy.yml' workflow_dispatch: @@ -70,6 +71,8 @@ jobs: fi done < <(git diff --no-renames --name-only "$baseline" "$EXPECTED_HEAD_SHA" -- 'backend/**/*.go') git diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' + git diff --exit-code "$EXPECTED_HEAD_SHA" -- 'backend/**/*_test.go' + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue805-evidence/http2-exclusions.txt" # These unrelated context-policy tests require newer production symbols. # Use their baseline versions only in this disposable RED checkout so # compilation can reach the unchanged Issue805 business assertions. @@ -80,48 +83,22 @@ jobs: echo "$target test=baseline expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" test "$expected" = "$actual" done - # These later Beta tests reference settings absent from the old - # production baseline. Exclude only these unrelated files in RED; - # the clean GREEN checkout and dedicated Beta workflow retain them. - for omission_test in backend/internal/handler/openai_409_omit_history_test.go backend/internal/handler/openai_400_omit_history_test.go; do + # The later omission fixtures require a Beta setting absent from this + # baseline. The readable/task-rebuild fixtures import its settings and + # usage helpers. Exclude this exact dependency set only in the old + # Issue805 RED; GREEN and each feature's own TDD job retain them. + for omission_test in backend/internal/handler/openai_409_omit_history_test.go backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_409_http_rebuild_test.go backend/internal/handler/openai_409_shadow_http_test.go backend/internal/handler/openai_409_shadow_race_test.go backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/handler/openai_400_omit_history_test.go; do git cat-file -e "$EXPECTED_HEAD_SHA:$omission_test" rm -- "$omission_test" test ! -e "$omission_test" echo "$omission_test test=candidate-only actual=absent" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" done - # HTTP2 handler regressions depend on candidate-only unit helpers - # removed by the exact production overlay above. They are unrelated - # to Issue805 and are omitted only in this disposable old-source RED. - omission_test=backend/internal/handler/http2_peer_reset_test.go - if git cat-file -e "$EXPECTED_HEAD_SHA:$omission_test" 2>/dev/null; then - if git cat-file -e "$baseline:$omission_test" 2>/dev/null; then exit 1; fi - candidate=$(git rev-parse "$EXPECTED_HEAD_SHA:$omission_test") - rm -- "$omission_test" - test ! -e "$omission_test" - echo "$omission_test test=candidate-only candidate=$candidate actual=absent reason=unavailable-unit-helpers" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" - fi - # Account-scope tests require production symbols introduced after - # this baseline. Keep them in GREEN and their dedicated acceptance; - # omit only this unrelated feature from the disposable old-source RED. - while IFS= read -r target; do - candidate=$(git rev-parse "$EXPECTED_HEAD_SHA:$target") - rm -- "$target" - test ! -e "$target" - echo "$target test=candidate-only candidate=$candidate actual=absent reason=moderation-scope-not-in-baseline" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" - done < <(git ls-files 'backend/internal/handler/moderation_upstream*_test.go') - # The shared WS fixture gained an optional moderation repository only - # in PR848; its pre-feature version preserves the Issue805 contract. - target=backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go - fixture_base=4189ed821d6e4308b2f5fc3791b73d2eb53cda8a - git fetch --no-tags --depth=1 origin "$fixture_base" - git show "$fixture_base:$target" > "$target" - expected=$(git rev-parse "$fixture_base:$target") - actual=$(git hash-object "$target") - test "$expected" = "$actual" - echo "$target test=pre-moderation-scope expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" + # The pinned HTTP2 exclusion helper above already handles the handler + # fixture absent from this baseline; do not remove it a second time. + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$baseline" . "$EXPECTED_HEAD_SHA" | tee "$RUNNER_TEMP/issue805-evidence/moderation-fixtures.txt" # The selected regression and its shared harness must remain exact # candidate blobs. The clean GREEN checkout retains all new tests. - for target in backend/internal/handler/openai_issue805_delivery_test.go backend/internal/handler/openai_issue805_owner_policy_test.go backend/internal/handler/openai_issue805_ws_test.go backend/internal/handler/openai_issue715_recovery_test.go; do + for target in backend/internal/handler/openai_issue805_delivery_test.go backend/internal/handler/openai_issue805_owner_policy_test.go backend/internal/handler/openai_issue805_ws_test.go backend/internal/handler/openai_issue715_recovery_test.go backend/internal/handler/openai_responses_failover_cancel_test.go; do expected=$(git rev-parse "$EXPECTED_HEAD_SHA:$target") actual=$(git hash-object "$target") echo "$target test=candidate expected=$expected actual=$actual" >> "$RUNNER_TEMP/issue805-evidence/red-blobs.txt" diff --git a/.github/workflows/oauth429-weekly-only.yml b/.github/workflows/oauth429-weekly-only.yml index 0bb7535e097d..48a063c65b18 100644 --- a/.github/workflows/oauth429-weekly-only.yml +++ b/.github/workflows/oauth429-weekly-only.yml @@ -81,6 +81,9 @@ jobs: printf '%s %s\n' "$candidate_blob" "$test_file" >> evidence/retained-test-blobs.txt done < evidence/retained-tests.txt git -C "$RUNNER_TEMP/oauth429-red" diff --exit-code -- '*_test.go' + # The retained helper references the new storage field. Add only that + # zero-value field after proving every original production blob above. + bash .github/scripts/oauth429-weekly-only-bridge-compat.sh "$RUNNER_TEMP/oauth429-red" "$BASELINE" | tee evidence/bridge-compat.txt # This later, unrelated regression requires the candidate-only WS # stream-phase helper. Exclude it only from this disposable old-source # checkout; GREEN explicitly runs all six tests with candidate sources. @@ -142,6 +145,7 @@ jobs: ed1708f3c2ee470d80ab97b377ff610050e383fc backend/internal/service/openai_ws_http_bridge.go BLOBS git -C "$RUNNER_TEMP/oauth429-expiry-red" diff --exit-code -- '*_test.go' + bash .github/scripts/oauth429-weekly-only-bridge-compat.sh "$RUNNER_TEMP/oauth429-expiry-red" "$before" | tee evidence/expiry-bridge-compat.txt git -C "$RUNNER_TEMP/oauth429-expiry-red" diff --stat > evidence/expiry-red-diff.txt set +e (cd "$RUNNER_TEMP/oauth429-expiry-red/backend" && go test -json -tags=unit ./internal/service -run '^TestOAuth429WeeklyOnlyHTTPStreamExpiredObservation$' -count=1 -timeout=10m) > evidence/red-http-expiry.jsonl 2> evidence/red-http-expiry.stderr diff --git a/.github/workflows/readable-continuation-409.yml b/.github/workflows/readable-continuation-409.yml new file mode 100644 index 000000000000..f1e841787221 --- /dev/null +++ b/.github/workflows/readable-continuation-409.yml @@ -0,0 +1,131 @@ +name: Readable continuation 409 RED GREEN + +on: + workflow_dispatch: + pull_request: + paths: + - 'backend/internal/service/openai_409_*' + - 'backend/internal/service/openai_agent_message_*' + - 'backend/internal/service/openai_gateway_forward.go' + - 'backend/internal/service/openai_gateway_request_body.go' + - 'backend/internal/handler/openai_409_*' + - 'backend/internal/handler/openai_gateway_handler.go' + - 'backend/internal/handler/openai_responses_failover_cancel_test.go' + - '.github/scripts/assert-readable-continuation.py' + - '.github/scripts/test_assert_readable_continuation.py' + - '.github/workflows/readable-continuation-409.yml' + +permissions: + contents: read + +jobs: + evidence-validator: + name: Evidence validator self-tests + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Accept valid evidence and reject injected contamination + shell: bash + run: | + set -euo pipefail + python3 -B -m unittest discover -s .github/scripts -p 'test_assert_readable_continuation.py' -v 2>&1 | tee "$RUNNER_TEMP/readable-validator-self-tests.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: readable-validator-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/readable-validator-self-tests.log + if-no-files-found: error + http: + name: HTTP ${{ matrix.phase }} + needs: evidence-validator + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + phase: [RED, GREEN] + steps: + # Each job has a disposable independent checkout of the identical head. + # RED restores pinned production callers and retains the candidate tests. + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated Redis fixture + run: | + bash .github/scripts/ci-ubuntu-mirrors.sh + if ! command -v redis-server >/dev/null; then + sudo apt-get update + sudo apt-get install -y --no-install-recommends redis-server + fi + - name: Pin candidate and unchanged behavioral test + env: + PHASE: ${{ matrix.phase }} + run: | + set -euo pipefail + git diff --exit-code + test -z "$(git status --porcelain)" + git rev-parse HEAD > "$RUNNER_TEMP/readable-$PHASE-provenance.txt" + for target in backend/internal/handler/openai_409_readable_continuation_test.go backend/internal/handler/openai_responses_failover_cancel_test.go; do + test "$(git hash-object "$target")" = "$(git rev-parse "HEAD:$target")" + git rev-parse "HEAD:$target" >> "$RUNNER_TEMP/readable-$PHASE-provenance.txt" + done + - name: Restore fixed production blob in RED checkout only + if: matrix.phase == 'RED' + run: | + set -euo pipefail + baseline=dbed7697aa56e76c6eb48c4914fa441496b67bdd + # Restore the matching production callers too: later HTTP rebuild + # APIs must not turn the original reasoning RED into a compile error. + for target in backend/internal/service/openai_409_omit_history.go backend/internal/service/openai_agent_message_recovery.go backend/internal/service/openai_agent_message_delivery.go backend/internal/service/openai_agent_message_recovery_error.go backend/internal/service/openai_account_scheduler.go backend/internal/service/openai_gateway_forward.go backend/internal/service/openai_codex_transform.go backend/internal/handler/openai_gateway_handler.go; do + git show "$baseline:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" + git rev-parse "$baseline:$target" >> "$RUNNER_TEMP/readable-RED-provenance.txt" + done + # Future shadow calls/fields do not exist in this original baseline. + for target in backend/internal/service/openai_ws_agent_recovery.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; do + git show "$baseline:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$baseline:$target")" + done + ! git cat-file -e "$baseline:backend/internal/service/openai_ws_readable_continuation.go" 2>/dev/null + rm -- backend/internal/service/openai_ws_readable_continuation.go + # Keep the selected HTTP tests intact and remove only new production. + for target in backend/internal/service/openai_409_readable_shadow.go backend/internal/repository/gateway_cache_readable_shadow.go backend/internal/repository/gateway_cache_agent_shadow_epoch.go backend/internal/service/openai_400_omit_history.go backend/internal/service/openai_history_omission.go; do + ! git cat-file -e "$baseline:$target" 2>/dev/null + rm -- "$target" + done + - name: Same HTTP JSON and SSE behavior in both checkouts + env: + PHASE: ${{ matrix.phase }} + shell: bash + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409ReadableContinuationHTTP$' -count=1 -timeout=5m) > "$RUNNER_TEMP/readable-$PHASE.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/readable-$PHASE.jsonl" + python3 .github/scripts/assert-readable-continuation.py "$PHASE" "$result" "$RUNNER_TEMP/readable-$PHASE.jsonl" + - name: GREEN omission and delivery safeguards + if: matrix.phase == 'GREEN' + working-directory: backend + shell: bash + run: | + set -euo pipefail + go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin -run '^Test(OmitOpenAIHistorical|OpenAI409(OmitHistory|Replay|Omission|ReadableReasoning|Rebuild|OAuth)|UpdateSettingsOpenAI409|Issue715(OutputPending|PendingLookup|ObservedPending|HTTPFailedDelivery|HTTPRecoveryKeepsHardRestrictions|HTTPRecoveryCannotBypassLongContext|HTTPPartialOutput))' -count=1 -v -timeout=5m 2>&1 | tee "$RUNNER_TEMP/readable-GREEN-safeguards.log" + python3 ../.github/scripts/assert-readable-continuation.py --clean-log "$RUNNER_TEMP/readable-GREEN-safeguards.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: readable-continuation-${{ matrix.phase }}-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/readable-* + if-no-files-found: error diff --git a/.github/workflows/shadow-review-repair.yml b/.github/workflows/shadow-review-repair.yml new file mode 100644 index 000000000000..f2a0c26d79d0 --- /dev/null +++ b/.github/workflows/shadow-review-repair.yml @@ -0,0 +1,202 @@ +name: Shadow delivery and privacy review repairs + +on: + workflow_dispatch: + pull_request: + paths: + - 'backend/internal/handler/openai_409_*' + - 'backend/internal/handler/security_audit_helper.go' + - 'backend/internal/service/openai_409_*' + - 'backend/internal/service/openai_agent_message*' + - 'backend/internal/service/openai_gateway_forward.go' + - 'backend/internal/service/openai_codex_account_identity*' + - 'backend/internal/service/recovered_context_privacy.go' + - 'backend/internal/service/content_moderation.go' + - 'backend/internal/repository/gateway_cache_agent_shadow_epoch.go' + - 'backend/internal/securityaudit/**' + - '.github/scripts/assert-ws-readable.py' + - '.github/scripts/test_assert_ws_readable.py' + - '.github/scripts/prepare-moderation-red-fixtures.sh' + - '.github/workflows/shadow-review-repair.yml' +permissions: + contents: read + +jobs: + repair: + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + phase: [RED, GREEN] + services: + postgres: + image: postgres:16-alpine + env: + POSTGRES_USER: fixture + POSTGRES_PASSWORD: fixture + POSTGRES_DB: shadow_audit + ports: ['5432:5432'] + options: --health-cmd "pg_isready -U fixture -d shadow_audit" --health-interval 5s --health-timeout 5s --health-retries 10 + redis: + image: redis:7-alpine + ports: ['6379:6379'] + options: --health-cmd "redis-cli ping" --health-interval 5s --health-timeout 5s --health-retries 10 + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + BASELINE_SHA: e59321cbf7e919f980ca90690ec70159180761f2 + PHASE: ${{ matrix.phase }} + PROMPT_AUDIT_TEST_POSTGRES_DSN: postgres://fixture:fixture@127.0.0.1:5432/shadow_audit?sslmode=disable + PROMPT_AUDIT_TEST_REDIS_ADDR: 127.0.0.1:6379 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@v6 + with: + go-version-file: backend/go.mod + cache-dependency-path: backend/go.sum + - name: Install isolated HTTP fixture 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: Validator and immutable baseline assembly + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/shadow-repair-evidence" + python3 -B -m unittest discover -s .github/scripts -p 'test_assert_ws_readable.py' -v 2>&1 | tee "$RUNNER_TEMP/shadow-repair-evidence/validator.log" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/shadow-repair-evidence/candidate.txt" + git rev-parse "$BASELINE_SHA" > "$RUNNER_TEMP/shadow-repair-evidence/baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/shadow-review-red" "$CANDIDATE_SHA" + cd "$RUNNER_TEMP/shadow-review-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$BASELINE_SHA:$target" 2>/dev/null; then + git show "$BASELINE_SHA:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$BASELINE_SHA:$target")" + else + rm -- "$target" + fi + done < <(git diff --no-renames --name-only "$BASELINE_SHA" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git diff --exit-code "$BASELINE_SHA" -- 'backend/**/*.go' ':!backend/**/*_test.go' + fi + git diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA" + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-repair-evidence/moderation-fixtures.txt" + fi + for target in backend/internal/handler/openai_409_shadow_race_test.go backend/internal/handler/openai_409_shadow_http_test.go backend/internal/securityaudit/prompt_recovered_context_test.go backend/internal/service/openai_409_readable_shadow.go; do + git hash-object "$target" >> "$RUNNER_TEMP/shadow-repair-evidence/blobs.txt" + done + - name: Actual publication races and persistent audit canaries + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + if [ "$PHASE" = RED ]; then tested_tree="$RUNNER_TEMP/shadow-review-red"; fi + for suite in shadow-races audit-provenance audit-persistence; do + package=handler + tags=unit + case "$suite" in + shadow-races) root=TestOpenAI409FutureShadowPublicationFences ;; + audit-provenance) root=TestOpenAI409FutureShadowAuditProvenance ;; + audit-persistence) root=TestRecoveredContextAuditPersistence; package=securityaudit; tags=integration ;; + esac + set +e + (cd "$tested_tree/backend" && go test -race -json -tags="$tags" "./internal/$package" -run "^${root}$" -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-repair-evidence/$suite.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-repair-evidence/$suite.jsonl" + python3 .github/scripts/assert-ws-readable.py "$PHASE" "$result" "$RUNNER_TEMP/shadow-repair-evidence/$suite.jsonl" "$suite" + done + - name: GREEN native OAuth session identity boundaries + if: ${{ !cancelled() && matrix.phase == 'GREEN' }} + run: | + set -euo pipefail + (cd backend && go test -race -json ./internal/service -run '^TestBuildUpstreamRequestOAuthHeaderOnlySession$' -count=1 -timeout=5m) 2>&1 | tee "$RUNNER_TEMP/shadow-repair-evidence/oauth-session-identity.jsonl" + - name: GREEN OAuth final-wire shadow and pointers without opaque owners + if: ${{ !cancelled() && matrix.phase == 'GREEN' }} + run: | + set -euo pipefail + for suite in oauth-shadow pointer pointer-boundaries; do + case "$suite" in + oauth-shadow) root=TestOpenAI409FutureShadowOAuth ;; + pointer) root=TestOpenAI409HTTPReadablePointerWithoutOpaque ;; + pointer-boundaries) root=TestOpenAI409HTTPPointerWithoutOpaqueBoundaries ;; + esac + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run "^${root}$" -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-repair-evidence/$suite.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-repair-evidence/$suite.jsonl" + python3 .github/scripts/assert-ws-readable.py GREEN "$result" "$RUNNER_TEMP/shadow-repair-evidence/$suite.jsonl" "$suite" + done + - name: Async penalty and admission counterexamples on reviewed d023 + if: ${{ !cancelled() }} + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + baseline=d023408b8a48eac7247faad17086e2aa7c7107e9 + git rev-parse "$baseline" > "$RUNNER_TEMP/shadow-repair-evidence/async-baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/async-review-red" "$CANDIDATE_SHA" + tested_tree="$RUNNER_TEMP/async-review-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$baseline:$target" 2>/dev/null; then + git show "$baseline:$target" > "$tested_tree/$target" + test "$(git hash-object "$tested_tree/$target")" = "$(git rev-parse "$baseline:$target")" + else + rm -- "$tested_tree/$target" + fi + done < <(git diff --no-renames --name-only "$baseline" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git -C "$tested_tree" diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' + fi + git -C "$tested_tree" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash .github/scripts/exclude-later-http2-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" + bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/shadow-repair-evidence/async-moderation-fixtures.txt" + fi + for target in backend/internal/securityaudit/prompt_service.go backend/internal/securityaudit/prompt_repository.go backend/internal/securityaudit/prompt_recovered_context_test.go; do + git hash-object "$tested_tree/$target" >> "$RUNNER_TEMP/shadow-repair-evidence/async-blobs.txt" + done + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=integration ./internal/securityaudit -run '^TestRecoveredContextAsyncEnforcement$' -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-repair-evidence/async-enforcement.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-repair-evidence/async-enforcement.jsonl" + python3 .github/scripts/assert-ws-readable.py "$PHASE" "$result" "$RUNNER_TEMP/shadow-repair-evidence/async-enforcement.jsonl" audit-async + - name: Actual HTTP and socket ambiguous-oracle mutations + if: ${{ !cancelled() }} + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSAmbiguousOracleMutations$' -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-repair-evidence/ws-oracle.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-repair-evidence/ws-oracle.jsonl" + python3 .github/scripts/assert-ws-readable.py GREEN "$result" "$RUNNER_TEMP/shadow-repair-evidence/ws-oracle.jsonl" ws-oracle + - name: Inspect strict pointer baseline without inventing a RED + if: matrix.phase == 'RED' + run: | + set -euo pipefail + set +e + (cd "$RUNNER_TEMP/shadow-review-red/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409HTTPPointerWithoutOpaqueBoundaries$/.*/.*/strict$' -count=1 -timeout=5m) > "$RUNNER_TEMP/shadow-repair-evidence/strict-pointer.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/shadow-repair-evidence/strict-pointer.jsonl" + python3 .github/scripts/assert-ws-readable.py BASELINE "$result" "$RUNNER_TEMP/shadow-repair-evidence/strict-pointer.jsonl" strict-pointer + - uses: actions/upload-artifact@v7 + if: always() + with: + name: shadow-review-repair-${{ matrix.phase }}-${{ env.CANDIDATE_SHA }} + path: ${{ runner.temp }}/shadow-repair-evidence/ + if-no-files-found: error diff --git a/.github/workflows/ws-readable-continuation.yml b/.github/workflows/ws-readable-continuation.yml new file mode 100644 index 000000000000..716d7c26cfb2 --- /dev/null +++ b/.github/workflows/ws-readable-continuation.yml @@ -0,0 +1,316 @@ +name: WS readable continuation TDD + +on: + workflow_dispatch: + inputs: + phase: + type: choice + options: [RED, GREEN, BOTH] + default: BOTH + description: Five real WS adapters against accepted baseline and production candidate + pull_request: + paths: + - 'backend/internal/handler/openai_409_*' + - 'backend/internal/handler/openai_gateway_handler.go' + - 'backend/internal/service/openai_ws*' + - 'backend/internal/service/openai_409_*' + - 'backend/internal/service/openai_agent_message*' + - '.github/scripts/assert-ws-readable.py' + - '.github/scripts/test_assert_ws_readable.py' + - '.github/scripts/exclude-later-400-red-fixtures.sh' + - '.github/scripts/exclude-later-http2-red-fixtures.sh' + - 'backend/internal/service/openai_gateway_passthrough.go' + - '.github/scripts/prepare-moderation-red-fixtures.sh' + - '.github/workflows/ws-readable-continuation.yml' +permissions: + contents: read + +jobs: + validator: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + - name: Evidence self-tests + run: | + set -euo pipefail + python3 -B -m unittest discover -s .github/scripts -p 'test_assert_ws_readable.py' -v 2>&1 | tee "$RUNNER_TEMP/ws-validator.log" + - uses: actions/upload-artifact@v7 + if: always() + with: + name: ws-readable-validator-${{ github.event.pull_request.head.sha || github.sha }} + path: ${{ runner.temp }}/ws-validator.log + if-no-files-found: error + transport: + needs: validator + runs-on: ubuntu-latest + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + phase: ${{ fromJSON(inputs.phase == 'RED' && '["RED"]' || inputs.phase == 'GREEN' && '["GREEN"]' || '["RED","GREEN"]') }} + env: + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + BASELINE_SHA: 5e83d0b73611a447b425ad5692f883de120da9ed + PHASE: ${{ matrix.phase }} + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - 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: Immutable candidate tests and baseline production + run: | + set -euo pipefail + test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA" + test -z "$(git status --porcelain)" + mkdir -p "$RUNNER_TEMP/ws-evidence" + git rev-parse HEAD HEAD^{tree} > "$RUNNER_TEMP/ws-evidence/candidate.txt" + git rev-parse "$BASELINE_SHA" > "$RUNNER_TEMP/ws-evidence/baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/ws-red" "$CANDIDATE_SHA" + cd "$RUNNER_TEMP/ws-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$BASELINE_SHA:$target" 2>/dev/null; then + git show "$BASELINE_SHA:$target" > "$target" + test "$(git hash-object "$target")" = "$(git rev-parse "$BASELINE_SHA:$target")" + else + rm -- "$target" + fi + done < <(git diff --no-renames --name-only "$BASELINE_SHA" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git diff --exit-code "$BASELINE_SHA" -- 'backend/**/*.go' ':!backend/**/*_test.go' + fi + git diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-400-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/transport-400-exclusions.txt" + bash "$GITHUB_WORKSPACE/.github/scripts/exclude-later-http2-red-fixtures.sh" "$BASELINE_SHA" + bash "$GITHUB_WORKSPACE/.github/scripts/prepare-moderation-red-fixtures.sh" "$BASELINE_SHA" . "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/transport-moderation-fixtures.txt" + fi + for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/handler/openai_gateway_handler.go; do + git hash-object "$target" >> "$RUNNER_TEMP/ws-evidence/blobs.txt" + done + - name: Same-client five-adapter actual continuation + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + if [ "$PHASE" = RED ]; then tested_tree="$RUNNER_TEMP/ws-red"; fi + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSReadableContinuation$' -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/transport.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/transport.jsonl" + python3 .github/scripts/assert-ws-readable.py "$PHASE" "$result" "$RUNNER_TEMP/ws-evidence/transport.jsonl" ws + - name: GREEN delivery and eligibility boundaries + if: matrix.phase == 'GREEN' + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSReadableBoundaries$' -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/boundaries.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/boundaries.jsonl" + python3 .github/scripts/assert-ws-readable.py GREEN "$result" "$RUNNER_TEMP/ws-evidence/boundaries.jsonl" ws-boundaries + - name: GREEN typed current-frame admission guards + if: ${{ !cancelled() && matrix.phase == 'GREEN' }} + run: | + set -euo pipefail + (cd backend && go test -race -json ./internal/service -run '^TestOpenAI409WSUnsentTurnBoundary$' -count=1 -timeout=5m) 2>&1 | tee "$RUNNER_TEMP/ws-evidence/unsent-guards.jsonl" + - name: Reject actual-wire ambiguous oracle mutations + if: ${{ !cancelled() }} + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSAmbiguousOracleMutations$' -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/oracle.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/oracle.jsonl" + python3 .github/scripts/assert-ws-readable.py GREEN "$result" "$RUNNER_TEMP/ws-evidence/oracle.jsonl" ws-oracle + - name: Actual transport review counterexamples and repaired candidate + if: ${{ !cancelled() }} + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + baseline=b5892afda5d176cf4ec5c346b07add48f224ab28 + git rev-parse "$baseline" > "$RUNNER_TEMP/ws-evidence/review-baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/ws-review-red" "$CANDIDATE_SHA" + tested_tree="$RUNNER_TEMP/ws-review-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$baseline:$target" 2>/dev/null; then + git show "$baseline:$target" > "$tested_tree/$target" + test "$(git hash-object "$tested_tree/$target")" = "$(git rev-parse "$baseline:$target")" + else + rm -- "$tested_tree/$target" + fi + done < <(git diff --no-renames --name-only "$baseline" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git -C "$tested_tree" diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' + fi + git -C "$tested_tree" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash .github/scripts/exclude-later-400-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/review-400-exclusions.txt" + bash .github/scripts/exclude-later-http2-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" + bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/review-moderation-fixtures.txt" + fi + for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/handler/openai_gateway_handler.go backend/internal/service/openai_ws_http_bridge.go backend/internal/service/openai_ws_forwarder_payload.go; do + git hash-object "$tested_tree/$target" >> "$RUNNER_TEMP/ws-evidence/review-blobs.txt" + done + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSReviewRepairs$' -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/review.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/review.jsonl" + python3 .github/scripts/assert-ws-readable.py "$PHASE" "$result" "$RUNNER_TEMP/ws-evidence/review.jsonl" ws-review + - name: Residual headers tools and ticket actual transport counterexamples + if: ${{ !cancelled() }} + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + baseline=94bb4a53e9e5057990cd851ab0620d99b116ad41 + git rev-parse "$baseline" > "$RUNNER_TEMP/ws-evidence/residual-baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/ws-residual-red" "$CANDIDATE_SHA" + tested_tree="$RUNNER_TEMP/ws-residual-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$baseline:$target" 2>/dev/null; then + git show "$baseline:$target" > "$tested_tree/$target" + test "$(git hash-object "$tested_tree/$target")" = "$(git rev-parse "$baseline:$target")" + else + rm -- "$tested_tree/$target" + fi + done < <(git diff --no-renames --name-only "$baseline" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git -C "$tested_tree" diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' + fi + git -C "$tested_tree" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash .github/scripts/exclude-later-400-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/residual-400-exclusions.txt" + bash .github/scripts/exclude-later-http2-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" + bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/residual-moderation-fixtures.txt" + # The service test package also compiles unrelated fixtures added by + # newer production. Match their historical APIs in this disposable + # RED only; keep every selected 409/ticket test and all GREEN tests. + for target in backend/internal/service/temp_unsched_pending_test.go backend/internal/service/temp_unsched_stream_timing_test.go backend/internal/service/temp_unsched_ws_forward_test.go backend/internal/service/openai_auth_connection_status_test.go backend/internal/service/openai_auth_connections_account_type_test.go backend/internal/service/account_ops_balance_test.go backend/internal/service/openai_excel_bps_bridge_failure_test.go backend/internal/service/quality_5xx_immediate_test.go; do + candidate_blob=$(git rev-parse "$CANDIDATE_SHA:$target") + test "$(git hash-object "$tested_tree/$target")" = "$candidate_blob" + if git cat-file -e "$baseline:$target" 2>/dev/null; then + expected=$(git rev-parse "$baseline:$target") + git show "$baseline:$target" > "$tested_tree/$target" + actual=$(git hash-object "$tested_tree/$target") + test "$actual" = "$expected" + printf 'path=%s baseline=%s candidate=%s candidate_blob=%s expected=%s actual=%s\n' "$target" "$baseline" "$CANDIDATE_SHA" "$candidate_blob" "$expected" "$actual" >> "$RUNNER_TEMP/ws-evidence/residual-service-fixtures.txt" + else + rm -- "$tested_tree/$target" + test ! -e "$tested_tree/$target" + printf 'path=%s baseline=%s candidate=%s candidate_blob=%s baseline_blob=absent actual=absent\n' "$target" "$baseline" "$CANDIDATE_SHA" "$candidate_blob" >> "$RUNNER_TEMP/ws-evidence/residual-service-fixtures.txt" + fi + done + fi + for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/service/openai_409_ws_ticket_test.go backend/internal/service/openai_ws_agent_recovery.go backend/internal/service/openai_ws_forwarder_payload.go backend/internal/service/openai_gateway_passthrough.go; do + git hash-object "$tested_tree/$target" >> "$RUNNER_TEMP/ws-evidence/residual-blobs.txt" + done + # Run both independently even when one oracle fails. Neither a + # compilation failure nor a missing diagnostic is accepted as RED. + failed=0 + for suite in ws-residual ws-ticket; do + package=handler + test_name=TestOpenAI409WSResidualRepairs + if [ "$suite" = ws-ticket ]; then package=service; test_name=TestOpenAI409WSTicketBoundEgress; fi + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=unit "./internal/$package" -run "^$test_name$" -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/$suite.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/$suite.jsonl" + python3 .github/scripts/assert-ws-readable.py "$PHASE" "$result" "$RUNNER_TEMP/ws-evidence/$suite.jsonl" "$suite" || failed=1 + done + test "$failed" = 0 + - name: Native namespace semantics against ceed and candidate + if: ${{ !cancelled() }} + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + baseline=ceed61d478116dc0ef1ccf5c830bb6bb3d995270 + git rev-parse "$baseline" > "$RUNNER_TEMP/ws-evidence/native-namespace-baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/ws-native-namespace-red" "$CANDIDATE_SHA" + tested_tree="$RUNNER_TEMP/ws-native-namespace-red" + while IFS= read -r target; do + case "$target" in *_test.go) continue ;; esac + if git cat-file -e "$baseline:$target" 2>/dev/null; then + git show "$baseline:$target" > "$tested_tree/$target" + test "$(git hash-object "$tested_tree/$target")" = "$(git rev-parse "$baseline:$target")" + else + rm -- "$tested_tree/$target" + fi + done < <(git diff --no-renames --name-only "$baseline" "$CANDIDATE_SHA" -- 'backend/**/*.go') + git -C "$tested_tree" diff --exit-code "$baseline" -- 'backend/**/*.go' ':!backend/**/*_test.go' + fi + git -C "$tested_tree" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + if [ "$PHASE" = RED ]; then + bash .github/scripts/exclude-later-400-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/namespace-400-exclusions.txt" + bash .github/scripts/prepare-moderation-red-fixtures.sh "$baseline" "$tested_tree" "$CANDIDATE_SHA" | tee "$RUNNER_TEMP/ws-evidence/namespace-moderation-fixtures.txt" + fi + for target in backend/internal/handler/openai_409_ws_rebuild_test.go backend/internal/handler/openai_409_ws_oracle_test.go backend/internal/service/openai_ws_agent_recovery.go; do + git hash-object "$tested_tree/$target" >> "$RUNNER_TEMP/ws-evidence/native-namespace-blobs.txt" + done + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSNativeNamespaceRecovery$' -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/native-namespace.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/native-namespace.jsonl" + python3 .github/scripts/assert-ws-readable.py "$PHASE" "$result" "$RUNNER_TEMP/ws-evidence/native-namespace.jsonl" ws-native-namespace + - name: Restored same-client task must pass current audit before B dispatch + if: ${{ !cancelled() }} + run: | + set -euo pipefail + tested_tree="$GITHUB_WORKSPACE" + baseline=112d342e9d1fb1ac5c2796d980eded4d71f646d9 + target=backend/internal/handler/openai_gateway_handler.go + git rev-parse "$baseline" > "$RUNNER_TEMP/ws-evidence/recovered-audit-baseline.txt" + if [ "$PHASE" = RED ]; then + git worktree add --detach "$RUNNER_TEMP/ws-recovered-audit-red" "$CANDIDATE_SHA" + tested_tree="$RUNNER_TEMP/ws-recovered-audit-red" + git show "$baseline:$target" > "$tested_tree/$target" + test "$(git hash-object "$tested_tree/$target")" = "$(git rev-parse "$baseline:$target")" + fi + git -C "$tested_tree" diff --exit-code "$CANDIDATE_SHA" -- 'backend/**/*_test.go' + for target in backend/internal/handler/openai_gateway_handler.go backend/internal/handler/openai_409_ws_audit_test.go backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go; do + printf '%s %s\n' "$target" "$(git hash-object "$tested_tree/$target")" >> "$RUNNER_TEMP/ws-evidence/recovered-audit-blobs.txt" + done + set +e + (cd "$tested_tree/backend" && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSRecoveredAudit$' -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/recovered-audit.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/recovered-audit.jsonl" + python3 .github/scripts/assert-ws-readable.py "$PHASE" "$result" "$RUNNER_TEMP/ws-evidence/recovered-audit.jsonl" ws-recovered-audit + - name: GREEN restored audit keeps original identity and fresh next-turn policy + if: ${{ !cancelled() && matrix.phase == 'GREEN' }} + run: | + set -euo pipefail + set +e + (cd backend && go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409WSRecoveredAuditNextTurn$' -count=1 -timeout=5m) > "$RUNNER_TEMP/ws-evidence/recovered-audit-next.jsonl" 2>&1 + result=$? + set -e + cat "$RUNNER_TEMP/ws-evidence/recovered-audit-next.jsonl" + python3 .github/scripts/assert-ws-readable.py GREEN "$result" "$RUNNER_TEMP/ws-evidence/recovered-audit-next.jsonl" ws-recovered-audit-next + - uses: actions/upload-artifact@v7 + if: always() + with: + name: ws-readable-${{ matrix.phase }}-${{ env.CANDIDATE_SHA }} + path: ${{ runner.temp }}/ws-evidence/ + if-no-files-found: error diff --git a/backend/internal/handler/openai_400_omit_history_test.go b/backend/internal/handler/openai_400_omit_history_test.go index 445b4fa22166..de7eb96b1dce 100644 --- a/backend/internal/handler/openai_400_omit_history_test.go +++ b/backend/internal/handler/openai_400_omit_history_test.go @@ -135,13 +135,21 @@ func TestOpenAI400OmitHistoryHTTP(t *testing.T) { require.Equal(t, http.StatusOK, first.Code, first.Body.String()) owners := issue805Owners(t, clients()) require.Len(t, owners, 1) - if scenario != "standalone" { + if scenario == "after409" { accounts[0].Schedulable = false } answer := issue758Request(t, newNode(scenario != "400_off"), followup) mu.Lock() defer mu.Unlock() - if scenario == "400_off" { + if scenario == "after409" { + // The readable 409 rebuild now converts reasoning as well. B + // accepts its first portable payload; there is no 400 to retry. + require.Equal(t, http.StatusOK, answer.Code, answer.Body.String()) + require.Len(t, bodies, 2, "one producer and one readable B continuation") + require.NotEqual(t, identities[0], identities[1]) + require.NotContains(t, string(bodies[1]), "fixture-400-reasoning") + require.Contains(t, answer.Body.String(), "continued from readable history") + } else if scenario == "400_off" { require.Equal(t, http.StatusBadRequest, answer.Code, answer.Body.String()) require.Len(t, bodies, 2, "one producer, one rejected continuation") } else { diff --git a/backend/internal/handler/openai_409_http_rebuild_test.go b/backend/internal/handler/openai_409_http_rebuild_test.go new file mode 100644 index 000000000000..fe9f505e76e4 --- /dev/null +++ b/backend/internal/handler/openai_409_http_rebuild_test.go @@ -0,0 +1,831 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "go/ast" + "go/parser" + "go/token" + "io" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +const ( + httpRebuildSession = "fixture-unattended-coding-thread" + httpRebuildTask = "Fix sum.go so Sum(2, 3) returns 5, then run verification. Reuse completed tool results." + httpRebuildSystem = "Use the supplied coding task and recorded results. Never repeat a completed patch or verification." + httpRebuildSource = "package fixture\nfunc Sum(a, b int) int { return a + b }\n" + httpRebuildPatch = "sum.go patched once: return a + b" + httpRebuildCheck = "Sum(2,3)=5; PASS" + httpRebuildAgentA = `{"type":"agent_message","author":"/root","recipient":"/root/worker","encrypted_content":"fixture-opaque-A"}` + httpRebuildAgentB = `{"type":"agent_message","author":"/root","recipient":"/root/worker","encrypted_content":"fixture-readable-B"}` + httpRebuildAgentAExtra = `{"type":"agent_message","author":"/root","recipient":"/root/worker","encrypted_content":"fixture-opaque-A-extra"}` +) + +type httpRebuildWire struct { + account int64 + url string + header http.Header + body []byte +} + +// OAuth must use the real native builder and final send gate. Only at the +// HTTPUpstream boundary do we redirect its fixed production URL to localhost; +// the body and identity headers are unchanged. No external destination is ever +// dialed. The loopback provider independently observes the resulting request. +type httpRebuildTransport struct { + service.HTTPUpstream + target *url.URL + mu sync.Mutex + wires []httpRebuildWire + mutation string // test-only final-wire mutation, never a runtime option +} + +func (u *httpRebuildTransport) Do(req *http.Request, proxy string, account int64, concurrency int) (*http.Response, error) { + if proxy != "" || (req.URL.String() != "https://chatgpt.com/backend-api/codex/responses" && + req.URL.String() != u.target.String()+"/v1/responses") { + return nil, fmt.Errorf("fixture refuses unexpected transport destination") + } + reader, err := req.GetBody() + if err != nil { + return nil, err + } + body, err := io.ReadAll(reader) + _ = reader.Close() + if err != nil { + return nil, err + } + u.mu.Lock() + u.wires = append(u.wires, httpRebuildWire{account: account, url: req.URL.String(), header: req.Header.Clone(), body: body}) + u.mu.Unlock() + local := req.Clone(req.Context()) + address := *req.URL + address.Scheme, address.Host = u.target.Scheme, u.target.Host + local.URL = &address + if account == 2 && u.mutation != "" { + mutated := body + switch u.mutation { + case "drop_tools": + mutated, err = sjson.DeleteBytes(body, "tools") + case "change_schema": + mutated, err = sjson.SetBytes(body, "tools.1.parameters.properties.path.type", "integer") + default: + return nil, fmt.Errorf("unknown fixture wire mutation") + } + if err != nil { + return nil, err + } + local.Body = io.NopCloser(bytes.NewReader(mutated)) + local.ContentLength = int64(len(mutated)) + local.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(mutated)), nil } + } + return u.HTTPUpstream.Do(local, "", account, concurrency) +} + +func httpRebuildToolDefinitions() []any { + return []any{ + map[string]any{"type": "function", "name": "apply_patch", "parameters": map[string]any{ + "type": "object", "properties": map[string]any{"path": map[string]any{"type": "string", "enum": []string{"sum.go"}}, "source": map[string]any{"type": "string"}}, + "required": []string{"path", "source"}, "additionalProperties": false, + }}, + map[string]any{"type": "function", "name": "run_tests", "parameters": map[string]any{ + "type": "object", "properties": map[string]any{"path": map[string]any{"type": "string", "enum": []string{"sum.go"}}}, + "required": []string{"path"}, "additionalProperties": false, + }}, + } +} + +func httpRebuildToolsAvailable(body []byte) bool { + actual := gjson.GetBytes(body, "tools").Array() + expected := gjson.Parse(httpRebuildJSON(httpRebuildToolDefinitions())).Array() + if len(actual) != len(expected) { + return false + } + for _, want := range expected { + matches := 0 + for _, got := range actual { + if got.Get("type").String() == "function" && got.Get("name").String() == want.Get("name").String() && + reflect.DeepEqual(got.Get("parameters").Value(), want.Get("parameters").Value()) { + matches++ + } + } + if matches != 1 { + return false + } + } + return true // Native optional description/strict defaults are not schemas. +} + +func (u *httpRebuildTransport) DoWithTLS(req *http.Request, proxy string, account int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxy, account, concurrency) +} + +func (u *httpRebuildTransport) snapshot() []httpRebuildWire { + u.mu.Lock() + defer u.mu.Unlock() + return append([]httpRebuildWire(nil), u.wires...) +} + +func httpRebuildJSON(value any) string { + encoded, err := json.Marshal(value) + if err != nil { + panic(err) // Only fixed JSON fixture values are passed here. + } + return string(encoded) +} + +func httpRebuildMessage(role, text string) string { + return httpRebuildJSON(map[string]any{"type": "message", "role": role, "content": text}) +} + +func httpRebuildCall(name, id string, arguments map[string]any) string { + return httpRebuildJSON(map[string]any{"type": "function_call", "name": name, "call_id": id, "arguments": httpRebuildJSON(arguments)}) +} + +func httpRebuildToolPair(body []byte, name, output string) bool { + items := gjson.GetBytes(body, "input").Array() + calls, results := 0, 0 + for _, call := range items { + if call.Get("type").String() != "function_call" || call.Get("name").String() != name || call.Get("call_id").String() == "" { + continue + } + calls++ + arguments := gjson.Parse(call.Get("arguments").String()) + if arguments.Get("path").String() != "sum.go" || (name == "apply_patch" && arguments.Get("source").String() != httpRebuildSource) { + return false + } + for _, result := range items { + if result.Get("type").String() == "function_call_output" && result.Get("call_id").String() == call.Get("call_id").String() && result.Get("output").String() == output { + results++ + } + } + } + return calls == 1 && results == 1 +} + +// A bounded client-side coding tool loop: one in-memory source edit and one +// AST-based verification. No external command, repository edit or real effect. +type httpRebuildTools struct { + source string + patches int + verifications int +} + +func (tools *httpRebuildTools) execute(t *testing.T, response gjson.Result) []string { + t.Helper() + var results []string + for _, call := range response.Get("output").Array() { + if call.Get("type").String() != "function_call" { + continue + } + arguments := gjson.Parse(call.Get("arguments").String()) + require.Equal(t, "sum.go", arguments.Get("path").String()) + var output string + switch call.Get("name").String() { + case "apply_patch": + require.Zero(t, tools.patches, "completed patch must never execute again") + tools.source = arguments.Get("source").String() + require.Equal(t, httpRebuildSource, tools.source) + tools.patches++ + output = httpRebuildPatch + case "run_tests": + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications, "completed verification must never execute again") + parsed, err := parser.ParseFile(token.NewFileSet(), "sum.go", tools.source, 0) + require.NoError(t, err) + require.Len(t, parsed.Decls, 1) + fn, ok := parsed.Decls[0].(*ast.FuncDecl) + require.True(t, ok) + require.Equal(t, "Sum", fn.Name.Name) + require.Len(t, fn.Body.List, 1) + statement, ok := fn.Body.List[0].(*ast.ReturnStmt) + require.True(t, ok) + require.Len(t, statement.Results, 1) + expression, ok := statement.Results[0].(*ast.BinaryExpr) + require.True(t, ok) + require.Equal(t, token.ADD, expression.Op) + left, leftOK := expression.X.(*ast.Ident) + right, rightOK := expression.Y.(*ast.Ident) + require.True(t, leftOK && rightOK) + require.Equal(t, "a", left.Name) + require.Equal(t, "b", right.Name) + values := map[string]int{"a": 2, "b": 3} + output = fmt.Sprintf("Sum(2,3)=%d; PASS", values[left.Name]+values[right.Name]) + tools.verifications++ + default: + t.Fatalf("unexpected fixture tool: %s", call.Get("name").String()) + } + results = append(results, httpRebuildJSON(map[string]any{"type": "function_call_output", "call_id": call.Get("call_id").String(), "output": output})) + } + return results +} + +func TestOpenAI409HTTPTaskRebuild(t *testing.T) { + for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, pointer := range []string{"intent", "previous", "conversation"} { + for _, outcome := range []string{"completed", "rejected", "write_failed"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s/%s", accountType, stream, pointer, outcome), func(t *testing.T) { + runHTTPRebuildFixture(t, accountType, stream, pointer, outcome, "", "") + }) + } + } + } + } +} + +func TestOpenAI409HTTPControlNormalization(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + t.Run(fmt.Sprintf("%s/stream=%t/blank_parts", accountType, stream), func(t *testing.T) { + runHTTPRebuildFixture(t, accountType, stream, "blank_parts", "completed", "", "") + }) + } + t.Run(fmt.Sprintf("oauth/stream=%t/nested_choice", stream), func(t *testing.T) { + runHTTPRebuildFixture(t, service.AccountTypeOAuth, stream, "nested_choice", "completed", "", "") + }) + t.Run(fmt.Sprintf("apikey/stream=%t/no_tools_parallel", stream), func(t *testing.T) { + runHTTPRebuildFixture(t, service.AccountTypeAPIKey, stream, "no_tools_parallel", "completed", "", "") + }) + } +} + +type httpRebuildFlippingSettings struct { + omit409SettingsRepo + mu sync.Mutex + reads int + fail bool +} + +func (s *httpRebuildFlippingSettings) GetValue(ctx context.Context, key string) (string, error) { + if key != service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled { + return s.omit409SettingsRepo.GetValue(ctx, key) + } + s.mu.Lock() + defer s.mu.Unlock() + s.reads++ + if s.reads <= 2 { + return "true", nil // Waiver and recovery setup, before rebuilding. + } + if s.fail { + return "", errors.New("fixture persisted setting unavailable") + } + return "false", nil +} + +func TestOpenAI409HTTPUnownedPointerMustDetach(t *testing.T) { + for _, fail := range []bool{false, true} { + t.Run(fmt.Sprintf("setting_error=%t", fail), func(t *testing.T) { + clients := issue805Redis(t) + var mu sync.Mutex + sends := 0 + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu.Lock() + sends++ + mu.Unlock() + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"resp_waiver_leak","model":"gpt-5.1","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`) + })) + defer provider.Close() + accounts := issue715AccountsOfType(service.AccountTypeAPIKey) + for i := range accounts { + accounts[i].Credentials["base_url"] = provider.URL + } + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + settingsRepo := &httpRebuildFlippingSettings{omit409SettingsRepo: omit409SettingsRepo{enabled: true}, fail: fail} + cache := repository.NewGatewayCache(clients()) + store := service.NewOpenAIWSStateStore(cache) + require.NoError(t, store.BindResponseAccount(context.Background(), 3132, "resp_orphan", 1, time.Minute)) + _, _, found, err := store.GetHTTPResponseOwner(context.Background(), 3132, "resp_orphan") + require.NoError(t, err) + require.False(t, found, "live provider-account mapping must have no downstream user grant") + h := newOpenAIResponsesFailoverTestHandlerWithSettings(t, testutil.NewRealHTTPUpstream(cfg), cache, service.NewSettingService(settingsRepo, cfg), accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + template, _ := newIssue715Context(t, "{}") + done := make(chan struct{}, 1) + router := gin.New() + router.POST("/v1/responses", func(c *gin.Context) { + defer func() { done <- struct{}{} }() + for key, value := range template.Keys { + c.Set(key, value) + } + h.Responses(c) + }) + gateway := httptest.NewServer(router) + defer gateway.Close() + req, err := http.NewRequest(http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(`{"model":"gpt-5.1","stream":false,"previous_response_id":"resp_orphan","input":"Continue only my supplied readable task"}`)) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("session_id", "fixture-unowned-pointer") + client := gateway.Client() + client.Timeout = 10 * time.Second + response, err := client.Do(req) + require.NoError(t, err) + answer, err := io.ReadAll(response.Body) + _ = response.Body.Close() + require.NoError(t, err) + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("waiver fixture did not finish") + } + settingsRepo.mu.Lock() + reads := settingsRepo.reads + settingsRepo.mu.Unlock() + require.GreaterOrEqual(t, reads, 3, "exercise the policy change after the initial waiver") + mu.Lock() + defer mu.Unlock() + require.Zero(t, sends, "UNOWNED_POINTER_WAIVER_LEAK: failed detachment must never use provider state; response=%s", answer) + require.Equal(t, http.StatusBadRequest, response.StatusCode, string(answer)) + require.Contains(t, string(answer), "safely detached") + }) + } +} + +func TestOpenAI409HTTPRebuildBoundaries(t *testing.T) { + for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, boundary := range []string{"pointer_only", "opaque_only", "delivery_pending", "delivery_failed", "b_disabled"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", accountType, stream, boundary), func(t *testing.T) { + runHTTPRebuildFixture(t, accountType, stream, "previous", "completed", boundary, "") + }) + } + } + } +} + +// The original composed fixture also had an encrypted-agent owner. These +// actual-wire cases deliberately produce no opaque item on A, so only HTTP +// response authorization and the provider pointer can constrain selection. +func TestOpenAI409HTTPReadablePointerWithoutOpaque(t *testing.T) { + for _, account := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, pointer := range []string{"previous", "conversation"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", account, stream, pointer), func(t *testing.T) { + runHTTPRebuildFixture(t, account, stream, pointer+"_no_opaque", "completed", "", "") + }) + } + } + } +} + +func TestOpenAI409HTTPPointerWithoutOpaqueBoundaries(t *testing.T) { + for _, account := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, boundary := range []string{"strict", "pointer_only", "foreign_user", "b_disabled"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", account, stream, boundary), func(t *testing.T) { + runHTTPRebuildFixture(t, account, stream, "previous_no_opaque", "completed", boundary, "") + }) + } + } + } +} + +func TestOpenAI409HTTPToolDefinitionOracle(t *testing.T) { + for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, mutation := range []string{"drop_tools", "change_schema"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", accountType, stream, mutation), func(t *testing.T) { + runHTTPRebuildFixture(t, accountType, stream, "previous", "completed", "", mutation) + }) + } + } + } +} + +func TestOpenAI409HTTPMixedDeliveryFences(t *testing.T) { + for _, accountType := range []string{service.AccountTypeAPIKey, service.AccountTypeOAuth} { + for _, stream := range []bool{false, true} { + for _, owner := range []string{"A", "B"} { + for _, state := range []string{"pending", "failed", "conflict"} { + for _, order := range []string{"forward", "reverse"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s/%s/%s", accountType, stream, owner, state, order), func(t *testing.T) { + runHTTPRebuildFixture(t, accountType, stream, "previous", "completed", "mixed/"+owner+"/"+state+"/"+order, "") + }) + } + } + } + } + } +} + +// Address an existing fixture record, not manufacture ownership. Scope and +// payload hashes locate the actual Lua-written key, which callers verify exists +// before changing its delivery fence. No production cache APIs are overridden. +func httpRebuildOwnerKey(t *testing.T, h *OpenAIGatewayHandler, agent string) string { + t.Helper() + c, _ := newIssue715Context(t, "{}") + c.Request.Header.Set("session_id", httpRebuildSession) + session := h.gatewayService.GenerateSessionHash(c, []byte(`{"model":"gpt-5.1"}`)) + var item any + require.NoError(t, json.Unmarshal([]byte(agent), &item)) + itemHash := sha256.Sum256([]byte(httpRebuildJSON(item))) + scope := httpRebuildJSON([]string{"99", "3132", session, "gpt-5.1", hex.EncodeToString(itemHash[:])}) + key := sha256.Sum256([]byte(scope)) + return "openai_agent_owner:v1:" + hex.EncodeToString(key[:]) +} + +func runHTTPRebuildFixture(t *testing.T, accountType string, stream bool, pointer, outcome, boundary, mutation string) { + t.Helper() + noOpaque := strings.HasSuffix(pointer, "_no_opaque") + pointer = strings.TrimSuffix(pointer, "_no_opaque") + mixed := strings.HasPrefix(boundary, "mixed/") + clients := issue805Redis(t) + observer := clients() + patchCall := httpRebuildCall("apply_patch", "call_patch_once", map[string]any{"path": "sum.go", "source": httpRebuildSource}) + checkCall := httpRebuildCall("run_tests", "call_verify_once", map[string]any{"path": "sum.go"}) + var mu sync.Mutex + var providerBodies [][]byte + var providerHeaders []http.Header + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + mu.Lock() + providerBodies = append(providerBodies, body) + providerHeaders = append(providerHeaders, r.Header.Clone()) + n := len(providerBodies) + mu.Unlock() + noToolsFinal := pointer == "no_tools_parallel" && n == 3 + if (!noToolsFinal && !httpRebuildToolsAvailable(body)) || (noToolsFinal && (gjson.GetBytes(body, "tools").Exists() || gjson.GetBytes(body, "parallel_tool_calls").Exists())) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","message":"fixture rejected missing or changed tool declarations"}}`) + return + } + id, conversation := "resp_rebuild_A", "conv_rebuild_A" + output := []json.RawMessage{json.RawMessage(patchCall), json.RawMessage(httpRebuildAgentA)} + if noOpaque { + output = []json.RawMessage{json.RawMessage(patchCall)} + } + if mixed { + output = append(output, json.RawMessage(httpRebuildAgentAExtra)) + } + if n > 1 { + readable := gjson.GetBytes(body, "input").Raw + " " + gjson.GetBytes(body, "instructions").String() + valid := r.Header.Get("Authorization") == "Bearer fixture-rebuild-B" && + strings.Contains(readable, httpRebuildTask) && strings.Contains(readable, httpRebuildSystem) && + !strings.Contains(string(body), "fixture-opaque-A") && + !strings.Contains(string(body), "resp_rebuild_A") && !strings.Contains(string(body), "conv_rebuild_A") && + httpRebuildToolPair(body, "apply_patch", httpRebuildPatch) + if n == 2 { + valid = valid && !gjson.GetBytes(body, "previous_response_id").Exists() && !gjson.GetBytes(body, "conversation").Exists() + if pointer == "nested_choice" { + valid = valid && gjson.GetBytes(body, "tool_choice.name").String() == "run_tests" && !gjson.GetBytes(body, "tool_choice.function").Exists() + } + } + if accountType == service.AccountTypeOAuth { + valid = valid && r.URL.Path == "/backend-api/codex/responses" && r.Host == "chatgpt.com" && + r.Header.Get("ChatGPT-Account-ID") == "fixture-chatgpt-B" && + gjson.GetBytes(body, "stream").Bool() && gjson.GetBytes(body, "store").Type == gjson.False && + gjson.GetBytes(body, `input.#(role==system)`).Type == gjson.Null + } + if n == 3 { + valid = valid && httpRebuildToolPair(body, "run_tests", httpRebuildCheck) + } + if !valid || outcome == "rejected" || n > 3 { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","message":"fixture rejected final task, identity or provider pointer"}}`) + return + } + id, conversation = "resp_rebuild_B", "conv_rebuild_B" + output = []json.RawMessage{json.RawMessage(checkCall), json.RawMessage(httpRebuildAgentB)} + if n == 3 { + id = "resp_rebuild_done" + output = []json.RawMessage{json.RawMessage(httpRebuildJSON(map[string]any{ + "type": "message", "role": "assistant", "content": []any{map[string]any{ + "type": "output_text", "text": "coding-task-complete: Sum(2,3)=5; patch and verification each executed once", + }}, + }))} + } + } + payload := httpRebuildJSON(map[string]any{"id": id, "conversation": map[string]any{"id": conversation}, "status": "completed", "error": nil, "model": "gpt-5.1", "output": output, "usage": map[string]int{"input_tokens": 5, "output_tokens": 3}}) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", payload) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, payload) + } + })) + defer provider.Close() + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + target, err := url.Parse(provider.URL) + require.NoError(t, err) + transport := &httpRebuildTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target, mutation: mutation} + accounts := issue715AccountsOfType(accountType) + for i, label := range []string{"A", "B"} { + accounts[i].Credentials = map[string]any{"base_url": provider.URL, "api_key": "fixture-rebuild-" + label, "access_token": "fixture-rebuild-" + label, "chatgpt_account_id": "fixture-chatgpt-" + label} + } + settings := service.NewSettingService(&omit409SettingsRepo{enabled: boundary != "strict"}, cfg) + usage := &readable409UsageRepo{} + h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, transport, repository.NewGatewayCache(clients()), settings, usage, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + template, _ := newIssue715Context(t, "{}") + done := make(chan struct{}, 1) + var sessions []string + pendingBeforeWrite := false + var observeErr error + router := gin.New() + router.POST("/v1/responses", func(c *gin.Context) { + defer func() { done <- struct{}{} }() + sessions = append(sessions, c.GetHeader("session_id")) + for key, value := range template.Keys { + c.Set(key, value) + } + if c.GetHeader("X-Fixture-Foreign-User") == "true" { + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 101}) + } + c.Writer = &readable409DeliveryWriter{ResponseWriter: c.Writer, fail: outcome == "write_failed", observe: func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + var keys []string + keys, observeErr = observer.Keys(ctx, "openai_agent_owner:*").Result() + for _, key := range keys { + var value string + value, observeErr = observer.Get(ctx, key).Result() + if observeErr != nil { + return + } + pendingBeforeWrite = pendingBeforeWrite || (strings.HasPrefix(value, "pending:") && strings.Contains(value, ":[1,2,")) + } + }} + h.Responses(c) + }) + gateway := httptest.NewServer(router) + defer gateway.Close() + client := gateway.Client() + client.Timeout = 10 * time.Second + request := func(history []string, previous gjson.Result) (int, string) { + body := map[string]any{"model": "gpt-5.1", "stream": stream, "store": false, "prompt_cache_key": httpRebuildSession, "tools": httpRebuildToolDefinitions()} + if previous.Exists() && pointer == "blank_parts" { + history = append(append([]string(nil), history...), `{"role":"user","content":[{"type":"input_text","text":" \n\t "}]}`) + } + if pointer == "nested_choice" && previous.Get("id").String() == "resp_rebuild_A" { + body["tool_choice"] = map[string]any{"type": "function", "function": map[string]any{"name": "run_tests"}} + } + if pointer == "no_tools_parallel" && previous.Get("id").String() == "resp_rebuild_B" { + delete(body, "tools") + body["parallel_tool_calls"] = true + } + body["input"] = json.RawMessage("[" + strings.Join(history, ",") + "]") + if previous.Exists() && (pointer == "previous" || boundary == "pointer_only") { + body["previous_response_id"] = previous.Get("id").String() + } + if previous.Exists() && pointer == "conversation" { + body["conversation"] = map[string]any{"id": previous.Get("conversation.id").String()} + } + req, err := http.NewRequest(http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(httpRebuildJSON(body))) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("session_id", httpRebuildSession) + if boundary == "foreign_user" && previous.Exists() { + req.Header.Set("X-Fixture-Foreign-User", "true") + } + response, err := client.Do(req) + require.NoError(t, err) + answer, err := io.ReadAll(response.Body) + _ = response.Body.Close() + require.NoError(t, err) + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("fixture handler did not finish") + } + return response.StatusCode, string(answer) + } + history := []string{httpRebuildMessage("system", httpRebuildSystem), httpRebuildMessage("user", httpRebuildTask)} + status, answer := request(history, gjson.Result{}) + require.Equal(t, http.StatusOK, status, answer) + first := issue758CompletedResponse(t, answer, stream) + require.Equal(t, "resp_rebuild_A", first.Get("id").String()) + require.Equal(t, "conv_rebuild_A", first.Get("conversation.id").String()) + initialWire := transport.snapshot() + require.Len(t, initialWire, 1) + require.Equal(t, int64(1), initialWire[0].account) + require.Equal(t, "Bearer fixture-rebuild-A", initialWire[0].header.Get("Authorization")) + if accountType == service.AccountTypeOAuth { + require.Equal(t, "https://chatgpt.com/backend-api/codex/responses", initialWire[0].url) + require.Equal(t, "fixture-chatgpt-A", initialWire[0].header.Get("ChatGPT-Account-ID")) + } + tools := &httpRebuildTools{} + for _, item := range first.Get("output").Array() { + history = append(history, item.Raw) + } + history = append(history, tools.execute(t, first)...) + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + require.Len(t, usage.snapshot(), 1, "A must finish the real usage path") + ownersA := issue805Owners(t, observer) + if noOpaque { + require.Empty(t, ownersA, "pointer-only ownership path must have no encrypted-agent owner to hide behind") + require.NotContains(t, strings.Join(history, ","), "agent_message") + owned, err := h.gatewayService.ValidateOpenAIHTTPResponseOwner(context.Background(), 3132, first.Get("id").String(), 100, 99) + require.NoError(t, err) + require.True(t, owned, "the actual A response must have downstream HTTP authorization") + } else if mixed { + require.Len(t, ownersA, 2) + } else { + require.Len(t, ownersA, 1) + } + accounts[0].Schedulable = false + disabled, err := (openAIImagesFailoverAccountRepo{accounts: accounts}).GetByID(context.Background(), 1) + require.NoError(t, err) + require.False(t, disabled.Schedulable) + switch boundary { + case "pointer_only": + history = nil + case "opaque_only": + history = []string{httpRebuildAgentA} + case "delivery_pending", "delivery_failed": + for key, owner := range ownersA { + value := "failed" + if boundary == "delivery_pending" { + value = "pending:fixture-unconfirmed:" + owner + } + require.NoError(t, observer.Set(context.Background(), key, value, time.Minute).Err()) + ownersA[key] = value + } + case "b_disabled": + accounts[1].Schedulable = false + } + status, answer = request(history, first) + if boundary != "" && !mixed { + if boundary == "strict" { + require.Len(t, transport.snapshot(), 1, "HTTP_POINTER_STRICT_A_STATE_LEAK: disabled A pointer must never reach B under default strict policy; response=%s", answer) + } + require.GreaterOrEqual(t, status, 400, "unrecoverable input/delivery must not pretend completion: %s", answer) + require.NotEmpty(t, gjson.Get(answer, "error.message").String(), answer) + require.NotContains(t, answer, "response.completed") + require.Len(t, transport.snapshot(), 1, "boundary must refuse before any B generation") + require.Equal(t, ownersA, issue805Owners(t, observer), "refusal must not clear pending/failed/old owner") + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + return + } + wires := transport.snapshot() + require.Len(t, wires, 2, "HTTP_REBUILD_B_DISPATCH_MISSING: automatic continuation with readable intent must reach B exactly once; response=%s", answer) + require.Equal(t, int64(1), wires[0].account) + require.Equal(t, int64(2), wires[1].account) + require.Equal(t, "Bearer fixture-rebuild-B", wires[1].header.Get("Authorization")) + require.NotContains(t, string(wires[1].body), "fixture-opaque-A") + require.False(t, gjson.GetBytes(wires[1].body, "previous_response_id").Exists()) + require.False(t, gjson.GetBytes(wires[1].body, "conversation").Exists()) + require.True(t, httpRebuildToolPair(wires[1].body, "apply_patch", httpRebuildPatch), "completed call/result relation must survive") + if accountType == service.AccountTypeOAuth { + require.Equal(t, "https://chatgpt.com/backend-api/codex/responses", wires[1].url) + require.NotEmpty(t, wires[1].header.Get("session_id")) + require.NotEqual(t, wires[0].header.Get("session_id"), wires[1].header.Get("session_id"), "upstream account namespace changes while the client session stays fixed") + } + owners := issue805Owners(t, observer) + for key, owner := range ownersA { + require.Equal(t, owner, owners[key], "old A owner remains intact") + delete(owners, key) + } + if mutation != "" { + require.Equal(t, http.StatusBadRequest, status, "wire mutant must not get a false GREEN: %s", answer) + require.Contains(t, answer, "missing or changed tool declarations") + require.Empty(t, owners, "provider must reject before generating a new tool or opaque item") + require.Len(t, usage.snapshot(), 1) + require.Zero(t, tools.verifications) + mu.Lock() + defer mu.Unlock() + require.Len(t, providerBodies, 2) + require.True(t, httpRebuildToolsAvailable(wires[1].body), "unmutated builder output must be valid") + require.False(t, httpRebuildToolsAvailable(providerBodies[1]), "mutation must actually reach the network provider") + require.JSONEq(t, gjson.GetBytes(wires[1].body, "input").Raw, gjson.GetBytes(providerBodies[1], "input").Raw) + t.Log("tool-definition wire mutation reached provider and was rejected before tool emission") + return + } + if outcome == "rejected" { + require.Equal(t, http.StatusBadRequest, status, answer) + require.Contains(t, answer, "fixture rejected") + require.Empty(t, owners) + require.Len(t, usage.snapshot(), 1) + return + } + require.NoError(t, observeErr) + require.True(t, pendingBeforeWrite, "B output must be reserved before exposure") + require.Len(t, owners, 1) + require.Len(t, usage.snapshot(), 2, "completed B usage survives downstream failure") + for _, owner := range owners { + if outcome == "write_failed" { + require.Equal(t, "failed", owner, "failed downstream write must not commit B") + } else { + require.True(t, strings.HasPrefix(owner, "[1,2,"), owner) + } + } + if outcome == "write_failed" { + require.NotContains(t, answer, "coding-task-complete") + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + return + } + require.Equal(t, http.StatusOK, status, answer) + second := issue758CompletedResponse(t, answer, stream) + for _, item := range second.Get("output").Array() { + history = append(history, item.Raw) + } + history = append(history, tools.execute(t, second)...) + if mixed { + parts := strings.Split(boundary, "/") + fenced := httpRebuildAgentA + if parts[1] == "B" { + fenced = httpRebuildAgentB + } + key := httpRebuildOwnerKey(t, h, fenced) + expected := issue805Owners(t, observer) + require.Len(t, expected, 3, "two delivered A items and a delivered B item") + require.Contains(t, expected, key, "fence an actually delivered item") + value := parts[2] + if value == "pending" { + value = "pending:fixture-mixed-unconfirmed:" + expected[key] + } + require.NoError(t, observer.Set(context.Background(), key, value, time.Minute).Err()) + expected[key] = value + if parts[3] == "reverse" { + var indices []int + for i, item := range history { + if gjson.Get(item, "type").String() == "agent_message" { + indices = append(indices, i) + } + } + for left, right := 0, len(indices)-1; left < right; left, right = left+1, right-1 { + history[indices[left]], history[indices[right]] = history[indices[right]], history[indices[left]] + } + } + // In reverse A-fenced order: completed B, completed A-extra, fenced A. + // A reader that stops at the first owner mismatch misses the last fence. + status, answer = request(history, second) + require.Len(t, transport.snapshot(), 2, "HTTP_REBUILD_FENCE_BYPASSED: every mixed-history fence must stop the next generation; response=%s", answer) + require.GreaterOrEqual(t, status, 400, answer) + require.NotEmpty(t, gjson.Get(answer, "error.message").String(), answer) + require.NotContains(t, answer, "response.completed") + require.Equal(t, expected, issue805Owners(t, observer), "all Redis records must remain byte-identical on refusal") + require.Equal(t, 1, tools.patches) + require.Equal(t, 1, tools.verifications) + require.Len(t, usage.snapshot(), 2) + return + } + // No new user text, no retry and no client/session reset. This next tool turn + // includes delivered A and B opaque history; both producer records survive. + status, answer = request(history, second) + require.Equal(t, http.StatusOK, status, "automatic next tool turn must finish: %s", answer) + final := issue758CompletedResponse(t, answer, stream) + require.Contains(t, final.Raw, "coding-task-complete") + require.Empty(t, tools.execute(t, final), "final output must not request completed tools again") + require.Equal(t, 1, tools.patches) + require.Equal(t, 1, tools.verifications) + require.Equal(t, []string{httpRebuildSession, httpRebuildSession, httpRebuildSession}, sessions) + require.False(t, accounts[0].Schedulable) + wires = transport.snapshot() + require.Len(t, wires, 3, "one A generation and exactly two B generations") + require.Equal(t, int64(2), wires[2].account) + require.True(t, httpRebuildToolPair(wires[2].body, "run_tests", httpRebuildCheck)) + require.Len(t, usage.snapshot(), 3) + finalOwners := issue805Owners(t, observer) + for key, owner := range ownersA { + require.Equal(t, owner, finalOwners[key]) + } + for key, owner := range owners { + require.Equal(t, owner, finalOwners[key], "completed B owner cannot be overwritten by subsequent consumption") + } + mu.Lock() + defer mu.Unlock() + require.Len(t, providerBodies, 3) + for i, wire := range wires { + require.JSONEq(t, string(wire.body), string(providerBodies[i]), "provider must receive the final builder payload unchanged") + require.Equal(t, wire.header.Get("Authorization"), providerHeaders[i].Get("Authorization")) + } +} diff --git a/backend/internal/handler/openai_409_omit_history_test.go b/backend/internal/handler/openai_409_omit_history_test.go index a7dc05d135d6..75a8a07170f1 100644 --- a/backend/internal/handler/openai_409_omit_history_test.go +++ b/backend/internal/handler/openai_409_omit_history_test.go @@ -107,9 +107,13 @@ func TestOpenAI409OmitHistoryHTTP(t *testing.T) { mu.Lock() defer mu.Unlock() switch scenario { - case "off", "current_task": + case "off": require.Equal(t, http.StatusConflict, answer.Code, answer.Body.String()) require.Len(t, bodies, 1) + case "current_task": + require.Equal(t, http.StatusUnprocessableEntity, answer.Code, answer.Body.String()) + require.Contains(t, answer.Body.String(), "readable_intent_missing") + require.Len(t, bodies, 1) case "no_accounts": require.GreaterOrEqual(t, answer.Code, 400) require.Len(t, bodies, 1) @@ -178,7 +182,8 @@ func TestOpenAI409ReplayMetadataHTTP(t *testing.T) { mu.Unlock() if n > 1 { rule := gjson.GetBytes(body, "input.5") - valid := !rule.Get("id").Exists() && !rule.Get("status").Exists() && rule.Get("summary").IsArray() && + valid := !rule.Get("id").Exists() && !rule.Get("status").Exists() && rule.Get("type").String() == "message" && + !rule.Get("encrypted_content").Exists() && !gjson.GetBytes(body, "input.1.id").Exists() && !gjson.GetBytes(body, "input.1.call_id").Exists() && gjson.GetBytes(body, "input.1.sequence").Raw == "9007199254740993" && strings.Contains(string(body), "Historical encrypted content omitted") && @@ -232,7 +237,7 @@ func TestOpenAI409ReplayMetadataHTTP(t *testing.T) { require.Equal(t, http.StatusOK, answer.Code, answer.Body.String()) issue758CompletedResponse(t, answer.Body.String(), stream) } - for _, path := range []string{"input.1.content", "input.1.sequence", "input.2", "input.3", "input.4", "input.5.encrypted_content"} { + for _, path := range []string{"input.1.content", "input.1.sequence", "input.2", "input.3", "input.4"} { require.JSONEq(t, gjson.Get(followup, path).Raw, gjson.GetBytes(bodies[1], path).Raw, path) } require.Equal(t, owners, issue805Owners(t, clients()), "old ownership remains intact") diff --git a/backend/internal/handler/openai_409_readable_continuation_test.go b/backend/internal/handler/openai_409_readable_continuation_test.go new file mode 100644 index 000000000000..bd3252f442ba --- /dev/null +++ b/backend/internal/handler/openai_409_readable_continuation_test.go @@ -0,0 +1,276 @@ +//go:build unit + +package handler + +import ( + "context" + "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" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type readable409DeliveryWriter struct { + gin.ResponseWriter + observe func() + fail bool +} + +func (w *readable409DeliveryWriter) Write(body []byte) (int, error) { + if strings.Contains(string(body), "fixture-readable-B") { + w.observe() + if w.fail { + return 0, io.ErrClosedPipe + } + } + return w.ResponseWriter.Write(body) +} + +func (w *readable409DeliveryWriter) WriteString(body string) (int, error) { + return w.Write([]byte(body)) +} + +// Keep the real pricing/RecordUsage path observable. A recovered usage panic +// must not pass merely because the response already reached the client. +type readable409UsageRepo struct { + service.UsageLogRepository + mu sync.Mutex + rows []service.UsageLog +} + +func (r *readable409UsageRepo) Create(_ context.Context, row *service.UsageLog) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.rows = append(r.rows, *row) + return true, nil +} + +func (r *readable409UsageRepo) snapshot() []service.UsageLog { + r.mu.Lock() + defer r.mu.Unlock() + return append([]service.UsageLog(nil), r.rows...) +} + +// Both sides use real localhost HTTP, plus the production Redis ownership Lua. +// Authentication and persistence use isolated fixtures; pricing and usage run +// through production services. No real credentials, provider, customer history +// or tool side effects are involved. +func TestOpenAI409ReadableContinuationHTTP(t *testing.T) { + for _, fixture := range []struct { + name, reasoning string + store bool + }{ + {"summary", `{"type":"reasoning","id":"rs_fixture_A","summary":[{"type":"summary_text","text":"Use the recorded ledger result; never apply the addition twice."}]}`, false}, + {"content", `{"type":"reasoning","id":"rs_fixture_A","status":"completed","encrypted_content":"fixture-reasoning-A","summary":[{"type":"summary_text","text":"Use the recorded ledger result; never apply the addition twice."}],"content":[{"type":"reasoning_text","text":"The readable calculation is 11 + 7 = 18."}]}`, false}, + {"stored_content", `{"type":"reasoning","id":"rs_fixture_A","encrypted_content":"fixture-reasoning-A","content":[{"type":"reasoning_text","text":"Use the recorded ledger result; never apply the addition twice."}]}`, true}, + } { + for _, stream := range []bool{false, true} { + for _, outcome := range []string{"completed", "rejected", "write_failed"} { + t.Run(fmt.Sprintf("%s/stream=%t/%s", fixture.name, stream, outcome), func(t *testing.T) { + clients := issue805Redis(t) + observer := clients() + const system = `{"type":"message","role":"system","content":"Report the existing balance. Do not repeat completed operations."}` + const originalTask = `{"type":"message","role":"user","content":"Keep ledger balance 11; add 7 exactly once","sequence":9007199254740993}` + const call = `{"type":"function_call","name":"update_ledger","call_id":"fc_715_once","arguments":"{\"add\":7}"}` + const assistant = `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"I will use the recorded result on continuation."}]}` + const result = `{"type":"function_call_output","call_id":"fc_715_once","output":"ledger balance 18; applied once"}` + const current = `{"type":"message","role":"user","content":"Continue the same task and confirm the existing balance"}` + bAgent := strings.ReplaceAll(issue715Agent, "fixture-task-reference-715", "fixture-readable-B") + var mu sync.Mutex + var sent [][]byte + var identities []string + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + mu.Lock() + sent = append(sent, body) + identities = append(identities, r.Header.Get("Authorization")) + n := len(sent) + mu.Unlock() + output := "[" + issue715Agent + "," + fixture.reasoning + "," + assistant + "," + call + "]" + if n > 1 { + valid := r.Header.Get("Authorization") == "Bearer fixture-key-2" && + !strings.Contains(string(body), "fixture-task-reference-715") && + !strings.Contains(string(body), "fixture-reasoning-A") && + !strings.Contains(string(body), "rs_fixture_A") && + !gjson.GetBytes(body, "previous_response_id").Exists() && + !gjson.GetBytes(body, "conversation").Exists() && + strings.Contains(string(body), "Use the recorded ledger result; never apply the addition twice.") && + gjson.GetBytes(body, "input.6.output").String() == "ledger balance 18; applied once" + if !valid || outcome == "rejected" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"type":"invalid_request_error","message":"fixture refuses nonportable history or identity"}}`) + return + } + output = "[" + bAgent + `,{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Existing balance is 18; the completed tool was not repeated."}]}]` + } + payload := fmt.Sprintf(`{"id":"resp_readable_%d","status":"completed","error":null,"model":"gpt-5.1","output":%s,"usage":{"input_tokens":5,"output_tokens":3}}`, n, output) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "event: response.completed\ndata: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", payload) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, payload) + } + })) + defer provider.Close() + accounts := issue715AccountsOfType(service.AccountTypeAPIKey) + for i := range accounts { + accounts[i].Credentials["base_url"] = provider.URL + } + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + settings := service.NewSettingService(&omit409SettingsRepo{enabled: true}, cfg) + usage := &readable409UsageRepo{} + h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, testutil.NewRealHTTPUpstream(cfg), repository.NewGatewayCache(clients()), settings, usage, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + template, _ := newIssue715Context(t, "{}") + done := make(chan struct{}, 1) + pendingBeforeWrite := false + var observeErr error + router := gin.New() + router.POST("/v1/responses", func(c *gin.Context) { + defer func() { done <- struct{}{} }() + for key, value := range template.Keys { + c.Set(key, value) + } + c.Writer = &readable409DeliveryWriter{ResponseWriter: c.Writer, fail: outcome == "write_failed", observe: func() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + var keys []string + keys, observeErr = observer.Keys(ctx, "openai_agent_owner:*").Result() + for _, key := range keys { + var value string + value, observeErr = observer.Get(ctx, key).Result() + if observeErr != nil { + return + } + pendingBeforeWrite = pendingBeforeWrite || (strings.HasPrefix(value, "pending:") && strings.Contains(value, ":[1,2,")) + } + }} + h.Responses(c) + }) + gateway := httptest.NewServer(router) + defer gateway.Close() + client := gateway.Client() + client.Timeout = 10 * time.Second + request := func(input string) (int, string) { + body := fmt.Sprintf(`{"model":"gpt-5.1","store":%t,"stream":%t,"input":[%s]}`, fixture.store, stream, input) + req, err := http.NewRequest(http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(body)) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("session_id", "fixture-readable-same-thread") + resp, err := client.Do(req) + require.NoError(t, err) + answer, readErr := io.ReadAll(resp.Body) + _ = resp.Body.Close() + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("gateway handler did not finish") + } + require.NoError(t, readErr) + return resp.StatusCode, string(answer) + } + status, first := request(system + "," + originalTask) + require.Equal(t, http.StatusOK, status, first) + firstUsage := usage.snapshot() + require.Len(t, firstUsage, 1, "A usage must reach persistence through real pricing") + require.Equal(t, int64(1), firstUsage[0].AccountID) + require.Equal(t, 5, firstUsage[0].InputTokens) + require.Equal(t, 3, firstUsage[0].OutputTokens) + require.Greater(t, firstUsage[0].TotalCost, 0.0) + response := issue758CompletedResponse(t, first, stream) + toolExecutions, balance := 0, 11 + for _, item := range response.Get("output").Array() { + if item.Get("type").String() == "function_call" { + require.Equal(t, "fc_715_once", item.Get("call_id").String()) + toolExecutions++ + balance += int(gjson.Get(item.Get("arguments").String(), "add").Int()) + } + } + require.Equal(t, 1, toolExecutions) + require.Equal(t, 18, balance) + ownersA := issue805Owners(t, observer) + require.Len(t, ownersA, 1) + // The repository owns this backing slice. Its authoritative GetByID + // and admission reads now see A disabled, not merely a sticky miss. + accounts[0].Schedulable = false + disabled, err := (openAIImagesFailoverAccountRepo{accounts: accounts}).GetByID(context.Background(), 1) + require.NoError(t, err) + require.False(t, disabled.Schedulable) + history := strings.TrimSuffix(strings.TrimPrefix(response.Get("output").Raw, "["), "]") + status, answer := request(system + "," + originalTask + "," + history + "," + result + "," + current) + mu.Lock() + defer mu.Unlock() + require.Len(t, sent, 2, "readable continuation must reach B exactly once; response=%s", answer) + require.Equal(t, []string{"Bearer fixture-key-1", "Bearer fixture-key-2"}, identities) + rows := usage.snapshot() + if outcome == "rejected" { + require.Len(t, rows, 1, "upstream rejection must not invent completed usage") + } else { + require.Len(t, rows, 2, "B completed usage survives even a downstream write failure") + require.Equal(t, int64(2), rows[1].AccountID) + require.Equal(t, 5, rows[1].InputTokens) + require.Equal(t, 3, rows[1].OutputTokens) + require.Greater(t, rows[1].TotalCost, 0.0) + } + for index, expected := range map[int]string{0: system, 1: originalTask, 4: assistant, 5: call, 6: result, 7: current} { + require.JSONEq(t, expected, gjson.GetBytes(sent[1], fmt.Sprintf("input.%d", index)).Raw) + } + require.Contains(t, string(sent[1]), "Historical encrypted content omitted") + for _, field := range []string{"summary", "content"} { + for _, part := range gjson.Get(fixture.reasoning, field).Array() { + require.Contains(t, gjson.GetBytes(sent[1], "input.3").Raw, part.Get("text").String()) + } + } + owners := issue805Owners(t, observer) + for key, owner := range ownersA { + require.Equal(t, owner, owners[key], "old A owner must not change") + delete(owners, key) + } + switch outcome { + case "rejected": + require.Equal(t, http.StatusBadRequest, status, answer) + require.Contains(t, answer, "fixture refuses") + require.Empty(t, owners, "rejection must not publish B or replay in the pool") + default: + require.NoError(t, observeErr) + require.True(t, pendingBeforeWrite, "B output must be reserved before downstream exposure") + require.Len(t, owners, 1) + for _, owner := range owners { + if outcome == "write_failed" { + require.Equal(t, "failed", owner, "failed delivery cannot commit B") + } else { + require.True(t, strings.HasPrefix(owner, "[1,2,"), owner) + } + } + if outcome == "completed" { + require.Equal(t, http.StatusOK, status, answer) + completed := issue758CompletedResponse(t, answer, stream) + require.Contains(t, completed.Raw, "Existing balance is 18") + require.NotContains(t, completed.Raw, `"type":"function_call"`, "completed tools must not run again") + } + } + }) + } + } + } +} diff --git a/backend/internal/handler/openai_409_shadow_http_test.go b/backend/internal/handler/openai_409_shadow_http_test.go new file mode 100644 index 000000000000..e7b9450046d9 --- /dev/null +++ b/backend/internal/handler/openai_409_shadow_http_test.go @@ -0,0 +1,552 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/securityaudit" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const shadowHTTPAgent = `{"type":"agent_message","author":"/root","recipient":"/root/worker","encrypted_content":"fixture-shadow-current-task"}` +const shadowOtherTask = "Verify the existing sum.go only; do not edit it. This is independent task Y." + +type shadowAuditProbe struct{ evaluated, private atomic.Bool } + +func (*shadowAuditProbe) EffectiveMode() securityaudit.Mode { return securityaudit.ModeBlocking } +func (*shadowAuditProbe) Enqueue(context.Context, securityaudit.Request) error { + return errors.New("unexpected asynchronous fixture") +} +func (p *shadowAuditProbe) Evaluate(_ context.Context, req securityaudit.Request) (*securityaudit.PromptDecision, error) { + if strings.Contains(string(req.Body), httpRebuildTask) { + p.evaluated.Store(true) + } + field := reflect.ValueOf(req).FieldByName("NoBodyRetention") + if field.IsValid() && field.Bool() { + p.private.Store(true) + } + return &securityaudit.PromptDecision{Kind: securityaudit.DecisionAllow, AllowNextStage: true}, nil +} + +func TestOpenAI409FutureShadowAuditProvenance(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { runFutureShadowHTTP(t, stream, "privacy") }) + } +} + +// Observe the real downstream write; the shadow must not become recoverable +// merely because the provider returned a terminal payload. +type shadowHTTPWriter struct { + gin.ResponseWriter + fail bool + observe func() +} + +func (w *shadowHTTPWriter) Write(body []byte) (int, error) { + if strings.Contains(string(body), "fixture-shadow-current-task") { + w.observe() + if w.fail { + return 0, io.ErrClosedPipe + } + } + return w.ResponseWriter.Write(body) +} + +func (w *shadowHTTPWriter) WriteString(body string) (int, error) { return w.Write([]byte(body)) } + +func TestOpenAI409FutureShadowHTTP(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { + runFutureShadowHTTP(t, stream, "recover") + }) + } +} + +func TestOpenAI409FutureShadowOAuth(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, scenario := range []string{"recover", "write_failed", "pending_owner", "store_read_failed", "two_known_tasks", "fresh_intent"} { + t.Run(fmt.Sprintf("stream=%t/%s", stream, scenario), func(t *testing.T) { + runFutureShadowTransport(t, service.AccountTypeOAuth, stream, scenario) + }) + } + } +} + +func TestOpenAI409FutureShadowTaskAssociation(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(fmt.Sprintf("stream=%t", stream), func(t *testing.T) { + runFutureShadowHTTP(t, stream, "two_known_tasks") + }) + } +} + +func TestOpenAI409FutureShadowBoundaries(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, boundary := range []string{"other_user", "other_key", "other_group", "other_model", "other_session", "other_task", "expired", "write_failed", "pending_owner", "failed_owner", "conflicted_owner", "off", "fresh_intent"} { + t.Run(fmt.Sprintf("stream=%t/%s", stream, boundary), func(t *testing.T) { + runFutureShadowHTTP(t, stream, boundary) + }) + } + } +} + +// Faults apply only to the optional shared shadow namespace. Owner, billing, +// scheduling and actual HTTP delivery still use the real Redis/transport. +type shadowStoreFailure struct{ calls atomic.Int64 } + +func (h *shadowStoreFailure) DialHook(next redis.DialHook) redis.DialHook { return next } +func (h *shadowStoreFailure) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return next +} +func (h *shadowStoreFailure) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + for _, arg := range cmd.Args() { + value, _ := arg.(string) + if strings.HasPrefix(value, "openai_readable_shadow:") || strings.HasPrefix(value, "openai_readable_shadow_index:") { + h.calls.Add(1) + return errors.New("fixture shadow store unavailable") + } + } + return next(ctx, cmd) + } +} + +func TestOpenAI409FutureShadowResources(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, scenario := range []string{"capacity_oldest", "capacity_latest", "store_write_failed", "store_read_failed", "oversize", "pending_tool", "pending_output", "conflicting_output", "echoed_task"} { + t.Run(fmt.Sprintf("stream=%t/%s", stream, scenario), func(t *testing.T) { + runFutureShadowHTTP(t, stream, scenario) + }) + } + } +} + +func runFutureShadowHTTP(t *testing.T, stream bool, scenario string) { + t.Helper() + runFutureShadowTransport(t, service.AccountTypeAPIKey, stream, scenario) +} + +func runFutureShadowTransport(t *testing.T, accountType string, stream bool, scenario string) { + t.Helper() + clients := issue805Redis(t) + probe := clients() + var mu sync.Mutex + var bodies [][]byte + var identities []string + var providerHeaders []http.Header + reusedOutput := scenario == "conflicting_output" || scenario == "echoed_task" + twoTasks := scenario == "two_known_tasks" || reusedOutput + patch := httpRebuildCall("apply_patch", "call_shadow_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}) + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + mu.Lock() + bodies = append(bodies, body) + identities = append(identities, r.Header.Get("Authorization")) + providerHeaders = append(providerHeaders, r.Header.Clone()) + n := len(bodies) + mu.Unlock() + output := []json.RawMessage{json.RawMessage(patch)} + switch { + case twoTasks && n == 3: + if !strings.Contains(string(body), shadowOtherTask) || strings.Contains(string(body), httpRebuildTask) { + w.WriteHeader(http.StatusBadRequest) + return + } + output = []json.RawMessage{json.RawMessage(httpRebuildCall("run_tests", "call_shadow_Y_verify", map[string]any{"path": "sum.go"}))} + case r.Header.Get("Authorization") == "Bearer fixture-shadow-A" && n >= 2: + validPair := httpRebuildToolPair(body, "apply_patch", httpRebuildPatch) + if twoTasks && n == 4 { + validPair = httpRebuildToolPair(body, "run_tests", httpRebuildCheck) && strings.Contains(string(body), shadowOtherTask) + } + if !validPair { + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"message":"fixture requires the actual completed patch"}}`) + return + } + agent := shadowHTTPAgent + if n > 2 && !reusedOutput { + agent = strings.ReplaceAll(agent, "fixture-shadow-current-task", fmt.Sprintf("fixture-shadow-current-task-%d", n)) + } + output = []json.RawMessage{json.RawMessage(agent)} + if scenario == "pending_output" { + output = append(output, json.RawMessage(httpRebuildCall("run_tests", "call_unconfirmed_output", map[string]any{"path": "sum.go"}))) + } + case r.Header.Get("Authorization") == "Bearer fixture-shadow-B": + valid := r.Header.Get("Authorization") == "Bearer fixture-shadow-B" && + !strings.Contains(string(body), "fixture-shadow-current-task") && + !gjson.GetBytes(body, "previous_response_id").Exists() && !gjson.GetBytes(body, "conversation").Exists() && + httpRebuildToolsAvailable(body) + if accountType == service.AccountTypeOAuth { + valid = valid && r.URL.Path == "/backend-api/codex/responses" && r.Host == "chatgpt.com" && + r.Header.Get("ChatGPT-Account-ID") == "fixture-shadow-account-B" && + gjson.GetBytes(body, "stream").Bool() && gjson.GetBytes(body, "store").Type == gjson.False && + gjson.GetBytes(body, `input.#(role==system)`).Type == gjson.Null && + r.Header.Get("x-codex-turn-state") != "fixture-shadow-A-state" && r.Header.Get("conversation_id") != "fixture-shadow-A-conversation" + } + if scenario == "fresh_intent" { + valid = valid && strings.Contains(string(body), "Report only the supplied fresh task") && !strings.Contains(string(body), httpRebuildTask) + } else { + valid = valid && strings.Contains(string(body), httpRebuildTask) && httpRebuildToolPair(body, "apply_patch", httpRebuildPatch) + } + if scenario == "two_known_tasks" { + associationValid := strings.Contains(string(body), httpRebuildTask) && httpRebuildToolPair(body, "apply_patch", httpRebuildPatch) && + !strings.Contains(string(body), shadowOtherTask) && !strings.Contains(string(body), "call_shadow_Y_verify") && !strings.Contains(string(body), httpRebuildCheck) + if !associationValid { + t.Log("SHADOW_TASK_ASSOCIATION_MISMATCH: real B received the wrong delivered task/result pair") + } + valid = valid && associationValid + } + if !valid { + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error":{"message":"fixture rejects guessed task or missing completed result"}}`) + return + } + output = []json.RawMessage{json.RawMessage(httpRebuildJSON(map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "shadow-task-complete; patch already applied once"}}}))} + default: + if n > 3 { + w.WriteHeader(http.StatusBadRequest) + return + } + } + response := httpRebuildJSON(map[string]any{"id": fmt.Sprintf("resp_shadow_%d", n), "model": "gpt-5.1", "status": "completed", "error": nil, "output": output, "usage": map[string]int{"input_tokens": 5, "output_tokens": 3}}) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", response) + } else { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, response) + } + })) + defer provider.Close() + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + target, err := url.Parse(provider.URL) + require.NoError(t, err) + transport := &httpRebuildTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + accounts := issue715AccountsOfType(accountType) + for i, label := range []string{"A", "B"} { + accounts[i].Credentials = map[string]any{"base_url": provider.URL, "api_key": "fixture-shadow-" + label, + "access_token": "fixture-shadow-" + label, "chatgpt_account_id": "fixture-shadow-account-" + label} + } + storeFailure := &shadowStoreFailure{} + newNode := func(failStore bool) *OpenAIGatewayHandler { + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + settings := service.NewSettingService(&omit409SettingsRepo{enabled: scenario != "off"}, cfg) + client := clients() + if failStore { + client.AddHook(storeFailure) + } + h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, transport, repository.NewGatewayCache(client), settings, &readable409UsageRepo{}, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + return h + } + producer, consumer := newNode(scenario == "store_write_failed"), newNode(scenario == "store_read_failed") // independent service state/Redis clients + auditProbe := &shadowAuditProbe{} + if scenario == "privacy" { + consumer.securityAuditCoordinator = securityaudit.NewCoordinator(nil, auditProbe) + } + done := make(chan struct{}, 1) + var beforeDelivery []string + var captureErr error + deliveryObserved := false + router := gin.New() + router.POST("/v1/responses", func(c *gin.Context) { + defer func() { done <- struct{}{} }() + clientIdentity := c.Request.Header.Clone() + defer func() { + for _, name := range []string{"session_id", "session-id", "thread-id"} { + require.Equal(t, clientIdentity.Values(name), c.Request.Header.Values(name), "client identity must survive upstream rebuilding: %s", name) + } + }() + keyID, userID, groupID := int64(99), int64(100), int64(3132) + if c.GetHeader("X-Fixture-Node") == "consumer" { + switch scenario { + case "other_user": + userID++ + case "other_key": + keyID++ + case "other_group": + groupID = 3131 // still a schedulable group; scope is what must deny + } + } + c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: keyID, UserID: userID, GroupID: &groupID, + Group: &service.Group{ID: groupID, Platform: service.PlatformOpenAI}, User: &service.User{ID: userID}, AllowLongContext: true}) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: userID}) + if c.GetHeader("X-Fixture-Node") == "consumer" { + consumer.Responses(c) + } else { + c.Writer = &shadowHTTPWriter{ResponseWriter: c.Writer, fail: scenario == "write_failed", observe: func() { + deliveryObserved = true + beforeDelivery, captureErr = probe.Keys(context.Background(), "openai_readable_shadow:v1:*").Result() + }} + producer.Responses(c) + } + }) + gateway := httptest.NewServer(router) + defer gateway.Close() + client := gateway.Client() + client.Timeout = 10 * time.Second + currentSession := "fixture-shadow-thread" + request := func(input []string, consume bool) (int, string) { + model, session := "gpt-5.1", currentSession + if consume && scenario == "other_model" { + model = "gpt-5.4" + } + if consume && scenario == "other_session" { + session += "-unrelated" + } + body := httpRebuildJSON(map[string]any{"model": model, "stream": stream, "store": false, "tools": httpRebuildToolDefinitions(), "input": json.RawMessage("[" + strings.Join(input, ",") + "]")}) + req, err := http.NewRequest(http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(body)) + require.NoError(t, err) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("session_id", session) + if consume { + req.Header.Set("X-Fixture-Node", "consumer") + if accountType == service.AccountTypeOAuth { + req.Header.Set("x-codex-turn-state", "fixture-shadow-A-state") + req.Header.Set("conversation_id", "fixture-shadow-A-conversation") + } + } + response, err := client.Do(req) + require.NoError(t, err) + answer, err := io.ReadAll(response.Body) + _ = response.Body.Close() + require.NoError(t, err) + select { + case <-done: + case <-time.After(10 * time.Second): + t.Fatal("shadow fixture handler did not finish") + } + return response.StatusCode, string(answer) + } + task := httpRebuildTask + if scenario == "oversize" { + task += strings.Repeat(" fixture long task", 5000) + } + history := []string{httpRebuildMessage("user", task)} + status, answer := request(history, false) + require.Equal(t, http.StatusOK, status, answer) + first := issue758CompletedResponse(t, answer, stream) + tool := &httpRebuildTools{} + for _, item := range first.Get("output").Array() { + history = append(history, item.Raw) + } + history = append(history, tool.execute(t, first)...) + require.Equal(t, 1, tool.patches) + if scenario == "pending_tool" { + history = append(history, httpRebuildCall("run_tests", "call_unconfirmed_side_effect", map[string]any{"path": "sum.go"})) + } + status, answer = request(history, false) + require.True(t, deliveryObserved, "must reach the actual opaque-output downstream write") + require.NoError(t, captureErr) + require.Empty(t, beforeDelivery, "future task context is committed only after successful terminal delivery") + if scenario != "write_failed" { + require.Equal(t, http.StatusOK, status, answer) + second := issue758CompletedResponse(t, answer, stream) + require.Contains(t, second.Get("output").Raw, "fixture-shadow-current-task") + } + opaque := shadowHTTPAgent + producerRequests := 2 + if twoTasks { + otherHistory := []string{httpRebuildMessage("user", shadowOtherTask)} + if scenario == "echoed_task" { + otherHistory = append([]string{shadowHTTPAgent}, otherHistory...) + } + status, answer = request(otherHistory, false) + require.Equal(t, http.StatusOK, status, answer) + otherCall := issue758CompletedResponse(t, answer, stream) + for _, item := range otherCall.Get("output").Array() { + otherHistory = append(otherHistory, item.Raw) + } + otherHistory = append(otherHistory, tool.execute(t, otherCall)...) + status, answer = request(otherHistory, false) + require.Equal(t, http.StatusOK, status, answer) + otherDone := issue758CompletedResponse(t, answer, stream) + if reusedOutput { + require.JSONEq(t, shadowHTTPAgent, otherDone.Get("output.0").Raw) + } else { + require.Contains(t, otherDone.Get("output").Raw, "fixture-shadow-current-task-4") + } + require.Equal(t, 1, tool.verifications) + producerRequests = 4 + } + capacity := strings.HasPrefix(scenario, "capacity_") + if capacity { + for i := 0; i < 140; i++ { + currentSession = fmt.Sprintf("fixture-shadow-thread-%d", i) + status, answer = request(history, false) + require.Equal(t, http.StatusOK, status, answer) + second := issue758CompletedResponse(t, answer, stream) + opaque = second.Get("output.0").Raw + require.Contains(t, opaque, "fixture-shadow-current-task-") + producerRequests++ + } + if scenario == "capacity_oldest" { + currentSession, opaque = "fixture-shadow-thread", shadowHTTPAgent + } + } + owners := issue805Owners(t, probe) + ownerCount := producerRequests - 1 + if scenario == "two_known_tasks" { + ownerCount = 2 + } else if reusedOutput { + ownerCount = 1 + } + require.Len(t, owners, ownerCount) + if scenario != "write_failed" { + for _, owner := range owners { + require.True(t, json.Valid([]byte(owner)) && gjson.Parse(owner).IsArray(), "every produced task must have an actual committed owner") + } + } + accounts[0].Schedulable = false + shadowKeys, err := probe.Keys(context.Background(), "openai_readable_shadow:v1:*").Result() + require.NoError(t, err) + if reusedOutput { + require.Len(t, shadowKeys, 1) + value, err := probe.Get(context.Background(), shadowKeys[0]).Result() + require.NoError(t, err) + require.Equal(t, "conflict", value, "same opaque output must not silently acquire another task") + } + if capacity { + epochKeys, err := probe.Keys(context.Background(), "openai_agent_shadow_epoch:v1:*").Result() + require.NoError(t, err) + require.Len(t, epochKeys, 128, "association metadata must also be bounded across sessions") + indexes, err := probe.Keys(context.Background(), "openai_agent_shadow_index:v1:*").Result() + require.NoError(t, err) + require.Len(t, indexes, 1) + count, err := probe.ZCard(context.Background(), indexes[0]).Result() + require.NoError(t, err) + require.EqualValues(t, 128, count) + ttl, err := probe.PTTL(context.Background(), indexes[0]).Result() + require.NoError(t, err) + require.Greater(t, ttl, time.Duration(0)) + require.LessOrEqual(t, ttl, 30*time.Minute) + require.Len(t, shadowKeys, 8, "SHADOW_CAPACITY_UNBOUNDED: all sessions/models share the principal's eight-record budget") + total := 0 + for _, key := range shadowKeys { + value, err := probe.Get(context.Background(), key).Result() + require.NoError(t, err) + total += len(value) + } + require.LessOrEqual(t, total, 512*1024, "shadow payload bytes must be bounded across sessions") + } + if scenario == "store_read_failed" { + require.NotEmpty(t, shadowKeys, "read fault must operate on a real committed record") + } + if scenario == "expired" { + require.NotEmpty(t, shadowKeys, "expiry test must expire an actual committed future shadow") + for _, key := range shadowKeys { + require.NoError(t, probe.PExpire(context.Background(), key, -time.Millisecond).Err()) + } + } + if scenario == "failed_owner" || scenario == "pending_owner" || scenario == "conflicted_owner" { + for key, owner := range owners { + value := "failed" + if scenario == "pending_owner" { + value = "pending:fixture-shadow-unknown:" + owner + } else if scenario == "conflicted_owner" { + value = "conflict" + } + require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err()) + owners[key] = value + } + } + if scenario == "other_task" { + opaque = strings.ReplaceAll(opaque, "fixture-shadow-current-task", "fixture-shadow-unrelated-task") + } + input := []string{opaque} + if scenario == "fresh_intent" { + input = append(input, httpRebuildMessage("user", "Report only the supplied fresh task")) + } + status, answer = request(input, true) + mu.Lock() + defer mu.Unlock() + if scenario == "recover" || scenario == "fresh_intent" || scenario == "capacity_latest" || scenario == "two_known_tasks" || scenario == "privacy" { + require.Len(t, bodies, producerRequests+1, "FUTURE_SHADOW_B_DISPATCH_MISSING: committed same-task context must reach B without manual input; response=%s", answer) + require.Equal(t, http.StatusOK, status, answer) + completed := issue758CompletedResponse(t, answer, stream) + require.Contains(t, completed.Raw, "shadow-task-complete") + require.NotContains(t, completed.Raw, `"type":"function_call"`) + require.Equal(t, "Bearer fixture-shadow-B", identities[len(identities)-1]) + for _, identity := range identities[:producerRequests] { + require.Equal(t, "Bearer fixture-shadow-A", identity) + } + wires := transport.snapshot() + require.Len(t, wires, len(bodies)) + for i, wire := range wires { + require.JSONEq(t, string(wire.body), string(bodies[i]), "native final-send payload must reach the network unchanged") + if accountType == service.AccountTypeOAuth { + if wire.account == 2 { + require.NotEmpty(t, wire.header.Get("session_id"), "rebuilt B send must carry its isolated session") + } + require.Equal(t, wire.header.Get("session_id"), providerHeaders[i].Get("session_id"), "isolated session must reach the actual provider") + require.NotEqual(t, "fixture-shadow-thread", wire.header.Get("session_id"), "raw client session must not be forwarded") + } + } + if accountType == service.AccountTypeOAuth { + last := wires[len(wires)-1] + require.Equal(t, "https://chatgpt.com/backend-api/codex/responses", last.url) + require.Equal(t, int64(2), last.account) + require.Equal(t, "fixture-shadow-account-B", last.header.Get("ChatGPT-Account-ID")) + require.NotEmpty(t, last.header.Get("session_id")) + require.NotEqual(t, wires[0].header.Get("session_id"), last.header.Get("session_id"), "B must receive a new upstream account namespace") + } + require.Equal(t, 1, tool.patches, "completed side effect was reused, never executed again") + if scenario == "recover" { + require.NotEmpty(t, shadowKeys, "cross-node recovery must use the shared store") + for _, key := range shadowKeys { + ttl, err := probe.PTTL(context.Background(), key).Result() + require.NoError(t, err) + require.Greater(t, ttl, time.Duration(0)) + require.LessOrEqual(t, ttl, 30*time.Minute, "shadow retention must be bounded") + value, err := probe.Get(context.Background(), key).Result() + require.NoError(t, err) + require.LessOrEqual(t, len(value), 64*1024, "each shadow record must be bounded") + } + } + } else { + require.GreaterOrEqual(t, status, 400, answer) + require.NotEmpty(t, gjson.Get(answer, "error.message").String(), answer) + require.Len(t, bodies, producerRequests, "scope/expiry/delivery must refuse before any B send") + require.NotContains(t, answer, "shadow-task-complete") + if scenario == "write_failed" || scenario == "off" || scenario == "store_write_failed" || scenario == "oversize" || scenario == "pending_tool" || scenario == "pending_output" { + require.Empty(t, shadowKeys, "unconfirmed/disabled capture must not persist task plaintext") + } + } + if scenario == "privacy" { + require.True(t, auditProbe.evaluated.Load(), "restored text must reach the actual HTTP moderation stage") + require.True(t, auditProbe.private.Load(), "SHADOW_AUDIT_PROVENANCE_MISSING: restored plaintext must be evaluated without persistent body retention") + } + if scenario == "store_write_failed" || scenario == "store_read_failed" { + require.Positive(t, storeFailure.calls.Load(), "must inject a fault in the actual shared shadow data plane") + } + require.Equal(t, owners, issue805Owners(t, probe), "shadow lookup must not clear or rewrite producer/delivery records") +} diff --git a/backend/internal/handler/openai_409_shadow_race_test.go b/backend/internal/handler/openai_409_shadow_race_test.go new file mode 100644 index 000000000000..cd7ff36e2d30 --- /dev/null +++ b/backend/internal/handler/openai_409_shadow_race_test.go @@ -0,0 +1,477 @@ +//go:build unit + +package handler + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/securityaudit" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/internal/testutil" + "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type shadowRaceRedis struct { + mode string + armed atomic.Bool + entered, release chan struct{} + once sync.Once +} + +type shadowRaceRead struct { + seen chan string + once sync.Once + hold <-chan struct{} +} + +// Observe the actual handler body after RestoreOpenAIReadableShadow returns, +// before its ordinary admission/send path. Do not synthesize readable input or +// depend on a user-slot callback: this fixture's concurrency=0 skips that cache. +type shadowRestoredRequestBarrier struct { + observed chan []byte + release <-chan struct{} +} + +func (b *shadowRestoredRequestBarrier) Check(ctx context.Context, req securityaudit.Request) (*securityaudit.LegacyDecision, error) { + select { + case b.observed <- append([]byte(nil), req.Body...): + case <-ctx.Done(): + return nil, ctx.Err() + } + select { + case <-b.release: + return nil, nil // Preserve this fixture's existing allow decision. + case <-ctx.Done(): + return nil, ctx.Err() + } +} + +func (h *shadowRaceRead) DialHook(next redis.DialHook) redis.DialHook { return next } +func (h *shadowRaceRead) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return next +} +func (h *shadowRaceRead) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + err := next(ctx, cmd) + if cmd.Name() == "get" && len(cmd.Args()) > 1 { + key, _ := cmd.Args()[1].(string) + if strings.HasPrefix(key, "openai_agent_shadow_epoch:") || strings.HasPrefix(key, "openai_readable_shadow:") { + state := "miss-or-record" + if value, ok := cmd.(*redis.StringCmd); ok && strings.HasPrefix(value.Val(), "pending:") { + state = "pending" + } + first := false + h.once.Do(func() { first = true; h.seen <- state }) + if first && h.hold != nil { + select { + case <-h.hold: + case <-ctx.Done(): + return ctx.Err() + } + } + } + } + return err + } +} +func (h *shadowRaceRedis) DialHook(next redis.DialHook) redis.DialHook { return next } +func (h *shadowRaceRedis) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook { + return next +} +func (h *shadowRaceRedis) ProcessHook(next redis.ProcessHook) redis.ProcessHook { + return func(ctx context.Context, cmd redis.Cmder) error { + if h.armed.Load() && (cmd.Name() == "eval" || cmd.Name() == "evalsha") { + shadow, publication := false, false + for _, arg := range cmd.Args() { + text, _ := arg.(string) + shadow = shadow || strings.HasPrefix(text, "openai_readable_shadow:v1:") + publication = publication || (strings.HasPrefix(text, "{") && strings.Contains(text, `"version":`)) + } + if shadow { + if h.mode == "store_failure_existing" { + h.once.Do(func() { close(h.entered) }) + return errors.New("fixture optional shadow unavailable") + } + if publication && (h.mode == "first_publication" || h.mode == "delayed_publisher") { + block := false + h.once.Do(func() { block = true; close(h.entered) }) + if block { + select { + case <-h.release: + case <-ctx.Done(): + return ctx.Err() + } + } + } + } + } + return next(ctx, cmd) + } +} + +type shadowRaceWriter struct { + gin.ResponseWriter + before func() +} + +func (w *shadowRaceWriter) Write(body []byte) (int, error) { + if strings.Contains(string(body), "fixture-shadow-current-task") && w.before != nil { + w.before() + } + n, err := w.ResponseWriter.Write(body) + w.ResponseWriter.Flush() // client can see a terminal while publication waits + return n, err +} +func (w *shadowRaceWriter) WriteString(body string) (int, error) { return w.Write([]byte(body)) } + +func TestOpenAI409FutureShadowPublicationFences(t *testing.T) { + for _, stream := range []bool{false, true} { + for _, scenario := range []string{"first_publication", "invalidate_after_restore", "reused_exposure", "store_failure_existing", "delayed_publisher"} { + t.Run(fmt.Sprintf("stream=%t/%s", stream, scenario), func(t *testing.T) { runShadowPublicationRace(t, stream, scenario) }) + } + } +} + +func runShadowPublicationRace(t *testing.T, stream bool, scenario string) { + clients := issue805Redis(t) + probe := clients() + var mu sync.Mutex + var identities []string + provider := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + mu.Lock() + identities = append(identities, r.Header.Get("Authorization")) + mu.Unlock() + output := json.RawMessage(shadowHTTPAgent) + if r.Header.Get("Authorization") == "Bearer fixture-race-B" { + if !strings.Contains(string(body), "fixture task X") || strings.Contains(string(body), "fixture task Y") || strings.Contains(string(body), "fixture-shadow-current-task") { + w.WriteHeader(http.StatusBadRequest) + return + } + output = json.RawMessage(httpRebuildJSON(map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": "race-task-complete"}}})) + } + outputs := []json.RawMessage{output} + if scenario == "delayed_publisher" && strings.Contains(string(body), "fixture task Y") { + outputs = append(outputs, json.RawMessage(httpRebuildCall("run_tests", "call_unknown_side_effect", map[string]any{"path": "sum.go"}))) + } + answer := httpRebuildJSON(map[string]any{"id": "resp_race", "status": "completed", "model": "gpt-5.1", "error": nil, "output": outputs, "usage": map[string]int{"input_tokens": 2, "output_tokens": 1}}) + if gjson.GetBytes(body, "stream").Bool() { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprintf(w, "data: {\"type\":\"response.completed\",\"response\":%s}\n\ndata: [DONE]\n\n", answer) + } else { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, answer) + } + })) + defer provider.Close() + hook := &shadowRaceRedis{mode: scenario, entered: make(chan struct{}), release: make(chan struct{})} + readHook := &shadowRaceRead{seen: make(chan string, 1)} + consumerRelease := make(chan struct{}) + var consumerOnce sync.Once + releaseConsumer := func() { consumerOnce.Do(func() { close(consumerRelease) }) } + defer releaseConsumer() + if scenario == "reused_exposure" { + readHook.hold = consumerRelease + } + var releaseOnce sync.Once + release := func() { releaseOnce.Do(func() { close(hook.release) }) } + defer release() + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + node := func(consumer bool) *OpenAIGatewayHandler { + accounts := issue715AccountsOfType(service.AccountTypeAPIKey) + for i, label := range []string{"A", "B"} { + accounts[i].Credentials = map[string]any{"base_url": provider.URL, "api_key": "fixture-race-" + label} + } + // The second node observes A's administrative disablement; the producer + // is already completing an admitted generation when barriers are held. + accounts[0].Schedulable = !consumer + client := clients() + if !consumer { + client.AddHook(hook) + } else { + client.AddHook(readHook) + } + h := newOpenAIResponsesFailoverTestHandlerWithUsage(t, testutil.NewRealHTTPUpstream(cfg), repository.NewGatewayCache(client), service.NewSettingService(&omit409SettingsRepo{enabled: true}, cfg), &readable409UsageRepo{}, accounts...) + h.cfg.Security.URLAllowlist.AllowInsecureHTTP = true + return h + } + producer, consumer := node(false), node(true) + restored, continueSend := make(chan []byte, 1), make(chan struct{}) + var resumeOnce sync.Once + resume := func() { resumeOnce.Do(func() { close(continueSend) }) } + defer resume() + if scenario == "invalidate_after_restore" { + consumer.securityAuditCoordinator = securityaudit.NewCoordinator(&shadowRestoredRequestBarrier{ + observed: restored, release: continueSend, + }, nil) + } + var exposeY atomic.Bool + yEntered, yRelease := make(chan struct{}), make(chan struct{}) + var yOnce, yReleaseOnce sync.Once + releaseY := func() { yReleaseOnce.Do(func() { close(yRelease) }) } + defer releaseY() + template, _ := newIssue715Context(t, "{}") + producerCompleted := make(chan struct{}, 2) + router := gin.New() + router.POST("/v1/responses", func(c *gin.Context) { + for key, value := range template.Keys { + c.Set(key, value) + } + if c.GetHeader("X-Fixture-Node") == "consumer" { + consumer.Responses(c) + return + } + c.Writer = &shadowRaceWriter{ResponseWriter: c.Writer, before: func() { + if exposeY.Load() { + yOnce.Do(func() { close(yEntered) }) + <-yRelease + } + }} + producer.Responses(c) + if scenario == "invalidate_after_restore" { + producerCompleted <- struct{}{} // publication has finished, not just the client write + } + }) + gateway := httptest.NewServer(router) + defer func() { release(); resume(); releaseY(); releaseConsumer(); gateway.Close() }() + client := gateway.Client() + client.Timeout = 10 * time.Second + type result struct { + status int + body string + err error + } + request := func(input string, consume bool, visible chan<- struct{}) result { + body := httpRebuildJSON(map[string]any{"model": "gpt-5.1", "stream": stream, "tools": httpRebuildToolDefinitions(), "input": json.RawMessage("[" + input + "]")}) + req, err := http.NewRequest(http.MethodPost, gateway.URL+"/v1/responses", strings.NewReader(body)) + if err != nil { + return result{err: err} + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("session_id", "fixture-race-session") + if consume { + req.Header.Set("X-Fixture-Node", "consumer") + } + resp, err := client.Do(req) + if err != nil { + return result{err: err} + } + defer resp.Body.Close() + var answer string + if strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") { + reader := bufio.NewReader(resp.Body) + for { + line, e := reader.ReadString('\n') + answer += line + if strings.Contains(line, `"type":"response.completed"`) { + if visible != nil { + close(visible) + visible = nil + } + } + if e != nil { + if e != io.EOF { + return result{err: e} + } + break + } + } + } else { + var value json.RawMessage + if err = json.NewDecoder(resp.Body).Decode(&value); err != nil { + return result{err: err} + } + answer = string(value) + if visible != nil && gjson.Get(answer, "status").String() == "completed" { + close(visible) + } + _, err = io.Copy(io.Discard, resp.Body) + } + return result{status: resp.StatusCode, body: answer, err: err} + } + x := httpRebuildMessage("user", "fixture task X: report saved work without repeating it") + y := httpRebuildMessage("user", "fixture task Y: a distinct task") + await := func(ch <-chan struct{}) { + t.Helper() + select { + case <-ch: + case <-time.After(2 * time.Second): + t.Fatal("SHADOW_RACE_BARRIER_MISSING") + } + } + consume := func() <-chan result { + done := make(chan result, 1) + go func() { done <- request(shadowHTTPAgent, true, nil) }() + return done + } + if scenario == "first_publication" || scenario == "delayed_publisher" { + hook.armed.Store(true) + visible, produced := make(chan struct{}), make(chan result, 1) + go func() { produced <- request(x, false, visible) }() + await(visible) + await(hook.entered) + if scenario == "delayed_publisher" { + second := request(y, false, nil) + require.NoError(t, second.err) + require.Equal(t, http.StatusOK, second.status, second.body) + require.Contains(t, second.body, "call_unknown_side_effect") + release() + require.NoError(t, (<-produced).err) + got := request(shadowHTTPAgent, true, nil) + require.NoError(t, got.err) + mu.Lock() + sends := len(identities) + mu.Unlock() + require.Equal(t, 2, sends, "SHADOW_DELAYED_PUBLICATION_REVIVED: an earlier publisher cannot revive context after a newer unknown tool output; response=%s", got.body) + require.GreaterOrEqual(t, got.status, 400, got.body) + return + } + done := consume() + select { + case state := <-readHook.seen: + if state != "pending" { + early := <-done + t.Fatalf("SHADOW_PUBLICATION_RACE_REFUSED: no shared publication wait after visible terminal: %+v", early) + } + case <-time.After(2 * time.Second): + t.Fatal("SHADOW_RACE_BARRIER_MISSING: consumer did not read shared state") + } + select { + case early := <-done: + t.Fatalf("SHADOW_PUBLICATION_RACE_REFUSED: consumer ended before successful publication: %+v", early) + case <-time.After(50 * time.Millisecond): + } + release() + p := <-produced + require.NoError(t, p.err) + require.Equal(t, http.StatusOK, p.status, p.body) + got := <-done + require.NoError(t, got.err) + require.Equal(t, http.StatusOK, got.status, got.body) + require.Contains(t, got.body, "race-task-complete") + return + } + first := request(x, false, nil) + require.NoError(t, first.err) + require.Equal(t, http.StatusOK, first.status, first.body) + if scenario == "invalidate_after_restore" { + await(producerCompleted) + } + keys, err := probe.Keys(context.Background(), "openai_readable_shadow:v1:*").Result() + require.NoError(t, err) + require.Len(t, keys, 1) + original := issue805Owners(t, probe) + require.Len(t, original, 1) + var done <-chan result + if scenario == "invalidate_after_restore" { + done = consume() + select { + case body := <-restored: + // The HTTP client sent only the opaque item. Seeing X here proves + // real cross-node recovery, not just a cache read or a slot attempt. + require.JSONEq(t, "["+x+","+shadowHTTPAgent+"]", gjson.GetBytes(body, "input").Raw, + "SHADOW_RESTORE_OBSERVATION_MISSING: actual audit input must contain the recovered X task and original opaque item") + case early := <-done: + t.Fatalf("SHADOW_RACE_BARRIER_MISSING: consumer ended before post-restore observation: %+v", early) + case <-time.After(2 * time.Second): + t.Fatal("SHADOW_RACE_BARRIER_MISSING: post-restore audit stage was not reached") + } + mu.Lock() + heldIdentities := append([]string(nil), identities...) + mu.Unlock() + require.Equal(t, []string{"Bearer fixture-race-A"}, heldIdentities, + "consumer must be held after restoration and before any B send") + } + if scenario == "store_failure_existing" { + hook.armed.Store(true) + } + if scenario == "reused_exposure" { + exposeY.Store(true) + produced := make(chan result, 1) + go func() { produced <- request(y, false, nil) }() + await(yEntered) + done = consume() + var state string + select { + case state = <-readHook.seen: + case <-time.After(2 * time.Second): + t.Fatal("SHADOW_RACE_BARRIER_MISSING: consumer never read the held association") + } + mu.Lock() + heldSends := len(identities) + mu.Unlock() + require.Equal(t, 2, heldSends, "SHADOW_REUSED_EXPOSURE_LEAK: B was sent while the consumer read and Y exposure were held") + if state != "pending" { + // e593 reads old X here. Keep Y held until that exact consumer + // finishes, so its unsafe B send cannot be hidden by invalidation. + releaseConsumer() + early := <-done + require.NoError(t, early.err) + mu.Lock() + earlySends := len(identities) + mu.Unlock() + require.Equal(t, 2, earlySends, "SHADOW_REUSED_EXPOSURE_LEAK: consumer used stale X before Y's actual downstream write; response=%s", early.body) + t.Fatal("SHADOW_REUSED_EXPOSURE_LEAK: reused association was not pending at its observed read") + } + releaseY() + require.NoError(t, (<-produced).err) + releaseConsumer() + } else { + second := request(y, false, nil) + require.NoError(t, second.err) + require.Equal(t, http.StatusOK, second.status, second.body) + } + if scenario == "store_failure_existing" { + await(hook.entered) + } + if scenario == "invalidate_after_restore" { + await(producerCompleted) + invalidated, err := probe.Get(context.Background(), keys[0]).Result() + require.NoError(t, err) + require.Equal(t, "conflict", invalidated, "Y must invalidate the actual shared association before consumer release") + require.Equal(t, original, issue805Owners(t, probe), "Y invalidation must preserve original owner bytes") + mu.Lock() + heldIdentities := append([]string(nil), identities...) + mu.Unlock() + require.Equal(t, []string{"Bearer fixture-race-A", "Bearer fixture-race-A"}, heldIdentities, + "only X and Y may reach the provider while the consumer is held") + } + resume() + if done == nil { + done = consume() + } + got := <-done + require.NoError(t, got.err) + mu.Lock() + sends := len(identities) + mu.Unlock() + diagnostic := "SHADOW_INVALIDATED_ASSOCIATION_DISPATCH" + if scenario == "reused_exposure" { + diagnostic = "SHADOW_REUSED_EXPOSURE_LEAK" + } + require.Equal(t, 2, sends, "%s: stale X must not reach B after Y invalidates the same opaque identity; response=%s", diagnostic, got.body) + require.GreaterOrEqual(t, got.status, 400, got.body) + require.Equal(t, original, issue805Owners(t, probe), "association changes must not rewrite original owner routes") +} diff --git a/backend/internal/handler/openai_409_ws_audit_test.go b/backend/internal/handler/openai_409_ws_audit_test.go new file mode 100644 index 000000000000..78e596d18503 --- /dev/null +++ b/backend/internal/handler/openai_409_ws_audit_test.go @@ -0,0 +1,313 @@ +//go:build unit + +package handler + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + "github.com/Wei-Shaw/sub2api/internal/securityaudit" + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const recoveredWSAuditCanary = "fixture-restored-unsafe-task-834" +const recoveredWSAuditNext = "fixture-new-turn-must-be-audited-834" +const recoveredWSAuditAgent = `{"type":"agent_message","author":"/root","recipient":"/root/worker","encrypted_content":"fixture-ws-audit-exact-task"}` + +// Record the production evaluator's actual persistence arguments. The existing +// securityaudit integration suite separately verifies the PostgreSQL writes. +type recoveredWSAuditStore struct { + securityaudit.JobRepository + mu sync.Mutex + records []securityaudit.Event +} + +func (r *recoveredWSAuditStore) RecordBlocking(_ context.Context, snapshot securityaudit.PromptSnapshot, _ int64, result *securityaudit.NormalizedResult, _ bool) (*securityaudit.Event, error) { + r.mu.Lock() + defer r.mu.Unlock() + event := securityaudit.Event{Snapshot: snapshot, ScannerEvidence: result.ScannerEvidence} + r.records = append(r.records, event) + return &event, nil +} + +type recoveredWSAuditPrompt struct { + armed atomic.Bool + deny bool + restored atomic.Int32 + private atomic.Bool + group atomic.Int64 + evaluator *securityaudit.GuardEvaluator +} + +func (*recoveredWSAuditPrompt) EffectiveMode() securityaudit.Mode { return securityaudit.ModeBlocking } +func (*recoveredWSAuditPrompt) Enqueue(context.Context, securityaudit.Request) error { + return errors.New("unexpected asynchronous audit") +} +func (p *recoveredWSAuditPrompt) Evaluate(ctx context.Context, req securityaudit.Request) (*securityaudit.PromptDecision, error) { + if p.armed.Load() && strings.Contains(string(req.Body), recoveredWSAuditCanary) { + p.restored.Add(1) + p.private.Store(req.NoBodyRetention && service.HasRecoveredContextPrivacy(ctx)) + if req.GroupID != nil { + p.group.Store(*req.GroupID) + } + } + snapshot, err := securityaudit.ExtractBlockingPromptSnapshot(req, false) + if errors.Is(err, securityaudit.ErrNoPromptText) { + return &securityaudit.PromptDecision{Kind: securityaudit.DecisionAllow, AllowNextStage: true}, nil + } + if err != nil { + return nil, err + } + return p.evaluator.Evaluate(ctx, securityaudit.ActiveConfig{ + Enabled: true, RiskControlEnabled: true, BlockingEnabled: true, StorePassEvents: true, + GroupIDs: []int64{4301}, Scanners: []string{"jailbreak"}, ConfigVersion: 1, + Endpoints: []securityaudit.ActiveEndpoint{{ID: "fixture", Enabled: true, TimeoutMS: 1000, InputLimit: 8192}}, + }, snapshot) +} +func (p *recoveredWSAuditPrompt) Scan(_ context.Context, _ securityaudit.ActiveEndpoint, text string, _ []string) (*securityaudit.NormalizedResult, error) { + result := &securityaudit.NormalizedResult{ + Decision: securityaudit.EventPass, RiskLevel: securityaudit.RiskLow, Action: securityaudit.ActionAllow, + Safety: "Safe", Categories: []string{}, MatchedScanners: []string{}, ScannerScores: map[string]float64{}, + ScannerEvidence: map[string]string{"fixture": text}, + } + if p.armed.Load() && p.deny && strings.Contains(text, recoveredWSAuditCanary) { + result.Decision, result.RiskLevel, result.Action = securityaudit.EventCritical, securityaudit.RiskCritical, securityaudit.ActionBlock + result.Safety, result.Categories, result.MatchedScanners = "Unsafe", []string{"jailbreak"}, []string{"jailbreak"} + result.ScannerScores["jailbreak"] = 1 + } + return result, nil +} + +func TestOpenAI409WSRecoveredAudit(t *testing.T) { + for _, mode := range readableWSModes { + for _, policy := range []string{"prompt", "selected"} { + t.Run(mode+"/"+policy, func(t *testing.T) { runRecoveredWSAudit(t, mode, policy, false) }) + } + } +} + +func TestOpenAI409WSRecoveredAuditNextTurn(t *testing.T) { + for _, mode := range readableWSModes { + t.Run(mode, func(t *testing.T) { runRecoveredWSAudit(t, mode, "selected", true) }) + } +} + +func runRecoveredWSAudit(t *testing.T, mode, policy string, allowRecovery bool) { + t.Helper() + clients := issue805Redis(t) + probe := clients() + store := &recoveredWSAuditStore{} + prompt := &recoveredWSAuditPrompt{deny: policy == "prompt"} + prompt.evaluator = securityaudit.NewGuardEvaluator(prompt, store, securityaudit.NewAtomicMetrics()) + var writesA, writesB, selectedRestored atomic.Int32 + var bBodyMu sync.Mutex + var bBodies [][]byte + answer := func(r *http.Request, body []byte) []byte { + output := recoveredWSAuditAgent + id := "resp_audit_A" + if r.Header.Get("Authorization") == "Bearer fixture-audit-A" { + writesA.Add(1) + } else { + writesB.Add(1) + bBodyMu.Lock() + bBodies = append(bBodies, append([]byte(nil), body...)) + bBodyMu.Unlock() + if r.Header.Get("Authorization") != "Bearer fixture-audit-B" || !strings.Contains(string(body), recoveredWSAuditCanary) || !strings.Contains(string(body), "completed-audit-result") || strings.Contains(string(body), "fixture-ws-audit-exact-task") { + return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_wrong_restored_task"}}}`) + } + id, output = "resp_audit_B", `{"type":"message","role":"assistant","content":[{"type":"output_text","text":"audit-fixture-B-received-restored"}]}` + } + return []byte(fmt.Sprintf(`{"type":"response.completed","response":{"id":%q,"model":"gpt-5.1","status":"completed","output":[%s],"usage":{"input_tokens":2,"output_tokens":1}}}`, id, output)) + } + 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", answer(r, body)) + return + } + conn, err := coderws.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer conn.CloseNow() //nolint:errcheck // Fixture teardown. + for { + _, body, err := conn.Read(r.Context()) + if err != nil { + return + } + if err := conn.Write(r.Context(), coderws.MessageText, answer(r, body)); err != nil { + return + } + } + })) + defer provider.Close() + audit := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + if err != nil { + t.Error(err) + return + } + text := string(body) + if strings.Contains(text, recoveredWSAuditCanary) { + selectedRestored.Add(1) + } + score := "0.01" + if (!allowRecovery && strings.Contains(text, recoveredWSAuditCanary)) || strings.Contains(text, recoveredWSAuditNext) { + score = "0.99" + } + _, _ = fmt.Fprintf(w, `{"results":[{"category_scores":{"sexual":%s}}]}`, score) + })) + defer audit.Close() + settings := map[string]string{service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true", service.SettingKeyCyberSessionIdentityStrictEnabled: "true"} + if policy == "selected" { + settings[service.SettingKeyContentModerationConfig] = fmt.Sprintf(`{"enabled":true,"mode":"pre_block","all_groups":false,"group_ids":[4301],"sample_rate":100,"record_non_hits":true,"base_url":%q,"api_keys":["fixture"],"upstream_account_scope":"selected","upstream_account_ids":[2],"upstream_account_bindings":{"2":{"platform":"openai","type":"apikey","group_ids":[4301]}}}`, audit.URL) + } + headers := http.Header{"Session_id": {"fixture-audit-session"}, "Thread-Id": {"fixture-audit-thread"}, "Conversation_id": {"fixture-audit-thread"}} + var accounts *readableWSAccounts + h := newOpenAIWSPassthroughHandlerHarnessWithAudit(t, provider.URL, headers, settings, repository.NewGatewayCache(clients()), + func(key *service.APIKey) { key.AllowLongContext = true }, + func(h *OpenAIGatewayHandler) { + h.securityAuditCoordinator = securityaudit.NewCoordinator(securityaudit.NewLegacyModerationAdapter(h.contentModerationService), prompt) + }, + func(a *service.Account, cfg *config.Config, _ *service.HTTPUpstream, repo *service.AccountRepository) { + a.ID, a.Priority = 1, 0 + a.Credentials["api_key"] = "fixture-audit-A" + a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode + a.Extra["codex_fingerprint_mode"] = "off" + cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 15 + cfg.Gateway.MaxAccountSwitches = 2 + cfg.Gateway.Scheduling.OpenAITurnAdmissionCacheTTLSeconds = 0 + b := *a + b.ID, b.Priority = 2, 1 + b.Credentials = map[string]any{"api_key": "fixture-audit-B", "base_url": provider.URL} + accounts = &readableWSAccounts{issue600SwitchRepo: &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, b}}}} + *repo = accounts + }) + finished := false + defer func() { + if !finished { + issue600Finish(t, h, headers) + } + }() + 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) + issue715WSSend(t, h.clientConn, create(initial)) + first := issue715WSRead(t, h.clientConn) + require.Equal(t, "response.completed", gjson.GetBytes(first, "type").String()) + require.Equal(t, recoveredWSAuditAgent, gjson.GetBytes(first, "response.output.0").Raw) + require.Eventually(t, func() bool { + keys, err := probe.Keys(context.Background(), "openai_readable_shadow:v1:*").Result() + if err != nil || len(keys) != 1 { + return false + } + raw, err := probe.Get(context.Background(), keys[0]).Result() + 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) + store.mu.Lock() + store.records = nil + store.mu.Unlock() + prompt.armed.Store(true) + accounts.disable(1) + opaque := create("[" + recoveredWSAuditAgent + "]") + require.NotContains(t, opaque, recoveredWSAuditCanary) + issue715WSSend(t, h.clientConn, opaque) + terminal := issue715WSRead(t, h.clientConn) + if allowRecovery { + require.Equal(t, "response.completed", gjson.GetBytes(terminal, "type").String(), string(terminal)) + require.Equal(t, int32(1), writesB.Load()) + issue715WSSend(t, h.clientConn, create(fmt.Sprintf(`[{"role":"user","content":%q}]`, recoveredWSAuditNext))) + terminal = issue715WSRead(t, h.clientConn) + } else { + require.Zero(t, writesB.Load(), "WS_RECOVERED_AUDIT_DISPATCHED: restored unsafe task must be denied before any B generation; terminal=%s", terminal) + } + require.Equal(t, "error", gjson.GetBytes(terminal, "type").String(), string(terminal)) + wantCode := "content_policy_violation" + wantClose := coderws.StatusPolicyViolation + if policy == "prompt" { + wantCode = "prompt_guard_blocked" + wantClose = coderws.StatusCode(4403) + } + require.Equal(t, wantCode, gjson.GetBytes(terminal, "error.code").String()) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _, _, err := h.clientConn.Read(ctx) + require.Equal(t, wantClose, coderws.CloseStatus(err)) + select { + case <-h.handlerDone: + case <-ctx.Done(): + t.Fatal("audit denial did not terminate naturally") + } + finished = true + select { + case final := <-h.finalHeaders: + for key, values := range headers { + require.Equal(t, values, final.Values(key), "original client identity survives recovery") + } + case <-ctx.Done(): + t.Fatal("missing final identity") + } + require.Equal(t, int32(1), writesA.Load()) + expectedB := int32(0) + if allowRecovery { + expectedB = 1 + } + require.Equal(t, expectedB, writesB.Load(), "denied turn must never be sent or retried") + require.Positive(t, prompt.restored.Load(), "prompt audit must inspect restored content") + require.True(t, prompt.private.Load()) + require.Equal(t, int64(4301), prompt.group.Load()) + store.mu.Lock() + stored := append([]securityaudit.Event(nil), store.records...) + store.mu.Unlock() + require.NotEmpty(t, stored) + for _, event := range stored { + require.True(t, event.Snapshot.NoBodyRetention) + require.NotNil(t, event.Snapshot.GroupID) + require.EqualValues(t, 4301, *event.Snapshot.GroupID) + require.Empty(t, event.Snapshot.ScanText) + require.Equal(t, "[Recovered context withheld]", event.Snapshot.FullPrompt) + require.Equal(t, "[Recovered context withheld]", event.Snapshot.RedactedPreview) + require.Empty(t, event.ScannerEvidence) + } + if policy == "selected" { + require.Equal(t, int32(1), selectedRestored.Load(), "selected B audit must inspect the restored task exactly once") + require.Eventually(t, func() bool { return len(h.moderationRepo.logSnapshot()) >= 1 }, 3*time.Second, 5*time.Millisecond) + for _, log := range h.moderationRepo.logSnapshot() { + require.NotNil(t, log.GroupID) + require.EqualValues(t, 4301, *log.GroupID) + require.Equal(t, "[Recovered context withheld]", log.InputExcerpt) + require.NotContains(t, log.Error, recoveredWSAuditCanary) + } + } + require.Equal(t, owners, issue805Owners(t, probe), "A owner records must remain unchanged") + if allowRecovery { + bBodyMu.Lock() + defer bBodyMu.Unlock() + require.Len(t, bBodies, 1) + require.Equal(t, 2, strings.Count(string(bBodies[0]), "call_audit_done"), "one completed call/result pair survives; no duplicate tool work") + require.Equal(t, "fixture-audit-thread", gjson.GetBytes(bBodies[0], "client_metadata.thread_id").String()) + } +} diff --git a/backend/internal/handler/openai_409_ws_oracle_test.go b/backend/internal/handler/openai_409_ws_oracle_test.go new file mode 100644 index 000000000000..3a0b5c5cf473 --- /dev/null +++ b/backend/internal/handler/openai_409_ws_oracle_test.go @@ -0,0 +1,336 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +type readableWSOracle struct { + mu sync.Mutex + frames [][]byte + identities []string + headers []http.Header + httpSends, wsSends int + validatedDisconnects int + disconnectsInjected int + validationFailures int + scenario string + unrelatedEOF bool +} + +func (u *readableWSOracle) response(r *http.Request, body []byte, ws bool) []byte { + u.mu.Lock() + defer u.mu.Unlock() + u.frames = append(u.frames, append([]byte(nil), body...)) + u.identities = append(u.identities, r.Header.Get("Authorization")) + u.headers = append(u.headers, r.Header.Clone()) + if ws { + u.wsSends++ + } else { + u.httpSends++ + } + n := len(u.frames) + if u.scenario == "native_namespace" && (!ws || !reflect.DeepEqual(gjson.GetBytes(body, "tools").Value(), gjson.Parse(httpRebuildJSON(readableWSNativeNamespaceTools())).Value())) { + u.validationFailures++ + return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_native_namespace_changed"}}}`) + } + if u.scenario == "bridge_model" && n == 2 { + if r.Header.Get("Authorization") != "Bearer fixture-readable-ws-A" || gjson.GetBytes(body, "model").String() != "gpt-5.4" || !strings.Contains(string(body), "model-switch-warmup") { + u.validationFailures++ + 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}}}`) + } + logicalTurn := n + if u.scenario == "bridge_model" && 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}))} + customTools := strings.HasPrefix(u.scenario, "tools_") + 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 u.unrelatedEOF { + return nil + } + validTools := httpRebuildToolsAvailable(body) + if customTools { + validTools = readableWSCustomToolsAvailable(body) + } + 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) && + !strings.Contains(string(body), "fixture-opaque-A") && + !gjson.GetBytes(body, "previous_response_id").Exists() && !gjson.GetBytes(body, "conversation").Exists() + if u.scenario == "bridge_model" { + valid = valid && gjson.GetBytes(body, "model").String() == "gpt-5.4" + } + if !valid { + u.validationFailures++ + return []byte(`{"type":"response.failed","response":{"status":"failed","error":{"code":"fixture_wrong_task_or_pointer","message":"wrong WS task, result, owner or pointer"}}}`) + } + if u.scenario == "ambiguous_B" { + // This observation is after every wire check and immediately before + // the server intentionally closes the accepted B generation. + u.validatedDisconnects++ + 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) { + 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"}}}`) + } + } + 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 { + tools := gjson.GetBytes(body, "tools").Array() + if len(tools) != 3 || tools[2].Get("type").String() != "function" || tools[2].Get("name").String() != "exec" { + return false + } + expected := gjson.Parse(`{"type":"object","properties":{"input":{"type":"string","description":"The raw input for this tool, passed through verbatim."}},"required":["input"]}`) + if !reflect.DeepEqual(expected.Value(), tools[2].Get("parameters").Value()) { + return false + } + functions, err := sjson.DeleteBytes(body, "tools.2") + if err != nil || !httpRebuildToolsAvailable(functions) { + return false + } + calls, outputs := 0, 0 + for _, item := range gjson.GetBytes(body, "input").Array() { + if item.Get("call_id").String() != "call_ws_exec" { + continue + } + if item.Get("type").String() == "function_call" && item.Get("name").String() == "exec" && gjson.Get(item.Get("arguments").String(), "input").String() == "read sum.go" { + calls++ + } + if item.Get("type").String() == "function_call_output" && item.Get("output").String() == "custom-exec-once" { + outputs++ + } + } + return calls == 1 && outputs == 1 +} + +func (u *readableWSOracle) server(t *testing.T) *httptest.Server { + t.Helper() + return 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 + } + answer := u.response(r, body, false) + if answer == nil { + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + u.mu.Lock() + u.disconnectsInjected++ + u.mu.Unlock() + _ = conn.Close() + } else { + t.Error(err) + } + return + } + w.Header().Set("Content-Type", "text/event-stream") + _, _ = fmt.Fprintf(w, "data: %s\n\ndata: [DONE]\n\n", answer) + return + } + conn, err := coderws.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer conn.CloseNow() //nolint:errcheck // Fixture teardown. + for { + _, body, err := conn.Read(r.Context()) + if err != nil { + return + } + answer := u.response(r, body, true) + if answer == nil { + u.mu.Lock() + u.disconnectsInjected++ + u.mu.Unlock() + return + } + if conn.Write(r.Context(), coderws.MessageText, answer) != nil { + return + } + } + })) +} + +// Called only after the gateway handler has terminated (or the direct oracle +// socket has closed). A second recorded frame alone proves nothing about B. +func (u *readableWSOracle) ambiguousEvidence(mode string, terminal []byte) error { + u.mu.Lock() + defer u.mu.Unlock() + if len(u.frames) != 2 || len(u.identities) != 2 || u.identities[0] != "Bearer fixture-readable-ws-A" || u.identities[1] != "Bearer fixture-readable-ws-B" || + u.validatedDisconnects != 1 || u.disconnectsInjected != 1 || u.validationFailures != 0 || strings.Contains(string(terminal), "fixture_") || strings.Contains(string(terminal), "response.completed") { + return errors.New("WS_AMBIGUOUS_ORACLE_REJECTED: no exactly-once validated B disconnect") + } + if (mode == service.OpenAIWSIngressModeHTTPBridge && (u.httpSends != 2 || u.wsSends != 0)) || + (mode != service.OpenAIWSIngressModeHTTPBridge && (u.wsSends != 2 || u.httpSends != 0)) { + return errors.New("WS_AMBIGUOUS_ORACLE_REJECTED: wrong actual adapter") + } + return nil +} + +func readableWSRefusalEvidence(scenario string, terminal []byte, readErr error) error { + if strings.Contains(string(terminal), "fixture_") || strings.Contains(string(terminal), "response.completed") { + return errors.New("provider rejection/completion is not local policy evidence") + } + codes := map[string][]string{ + "off": {"encrypted_agent_recovery_owner_unavailable"}, + "no_intent": {"encrypted_agent_recovery_readable_intent_missing"}, + "b_disabled": {"encrypted_agent_recovery_owner_unavailable"}, + "pending_owner": {"encrypted_agent_recovery_delivery_pending", "encrypted_agent_recovery_owner_conflict"}, + "failed_owner": {"encrypted_agent_recovery_owner_unavailable", "encrypted_agent_recovery_owner_conflict"}, + } + for _, path := range []string{"error.code", "response.error.code"} { + for _, code := range codes[scenario] { + if gjson.GetBytes(terminal, path).String() == code { + return nil + } + } + } + var closeErr coderws.CloseError + if errors.As(readErr, &closeErr) { + if closeErr.Code == coderws.StatusTryAgainLater && (scenario == "off" || scenario == "b_disabled") && + (strings.Contains(closeErr.Reason, "account eligibility changed") || strings.Contains(closeErr.Reason, "no available account")) { + return nil + } + if closeErr.Code == coderws.StatusPolicyViolation { + for _, code := range codes[scenario] { + if strings.Contains(closeErr.Reason, code) { + return nil + } + } + reasons := map[string][]string{ + "off": {"original compatible owner", "owner is currently unavailable"}, + "no_intent": {"no readable task or summary"}, + "b_disabled": {"owner is currently unavailable"}, + "pending_owner": {"producer has not confirmed delivery", "conflicting compatible owners"}, + "failed_owner": {"owner is currently unavailable", "conflicting compatible owners"}, + } + for _, reason := range reasons[scenario] { + if strings.Contains(closeErr.Reason, reason) { + return nil + } + } + } + } + return fmt.Errorf("WS_REFUSAL_ORACLE_REJECTED: missing %s policy reason", scenario) +} + +// Actual socket/HTTP oracle mutations execute even before WS recovery exists. +// The same accepted-B observation used by the full handler is the authority. +func TestOpenAI409WSAmbiguousOracleMutations(t *testing.T) { + for _, transport := range []string{"http_bridge", "socket"} { + for _, mutation := range []string{"valid", "wrong_credential", "old_pointer", "missing_result", "unrelated_eof"} { + t.Run(transport+"/"+mutation, func(t *testing.T) { + u := &readableWSOracle{scenario: "ambiguous_B", unrelatedEOF: mutation == "unrelated_eof"} + srv := u.server(t) + defer srv.Close() + send := func(credential, body string) []byte { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if transport == "http_bridge" { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, srv.URL, strings.NewReader(body)) + require.NoError(t, err) + req.Header.Set("Authorization", credential) + res, err := srv.Client().Do(req) + if err != nil { + return nil + } + defer res.Body.Close() + raw, err := io.ReadAll(res.Body) + require.NoError(t, err) + return raw + } + conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http"), &coderws.DialOptions{HTTPHeader: http.Header{"Authorization": {credential}}}) + require.NoError(t, err) + defer conn.CloseNow() + require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(body))) + _, raw, err := conn.Read(ctx) + require.NotErrorIs(t, err, context.DeadlineExceeded) + return raw + } + first := send("Bearer fixture-readable-ws-A", `{"type":"response.create","model":"gpt-5.1","input":[]}`) + require.Contains(t, string(first), "response.completed") + input := []json.RawMessage{json.RawMessage(httpRebuildMessage("user", httpRebuildTask)), json.RawMessage(httpRebuildCall("apply_patch", "call_ws_patch", map[string]any{"path": "sum.go", "source": httpRebuildSource}))} + if mutation != "missing_result" { + input = append(input, json.RawMessage(httpRebuildJSON(map[string]any{"type": "function_call_output", "call_id": "call_ws_patch", "output": httpRebuildPatch}))) + } + body := map[string]any{"type": "response.create", "model": "gpt-5.1", "input": input, "tools": httpRebuildToolDefinitions()} + if mutation == "old_pointer" { + body["previous_response_id"] = "resp_readable_ws_1" + } + credential := "Bearer fixture-readable-ws-B" + if mutation == "wrong_credential" { + credential = "Bearer fixture-readable-ws-A" + } + terminal := send(credential, httpRebuildJSON(body)) + u.mu.Lock() + frameCount, accepted, rejected := len(u.frames), u.validatedDisconnects, u.validationFailures + httpCount, wsCount := u.httpSends, u.wsSends + u.mu.Unlock() + require.Equal(t, 2, frameCount, "mutation must traverse the actual provider transport") + if transport == "http_bridge" { + require.Equal(t, 2, httpCount) + require.Zero(t, wsCount) + } else { + require.Equal(t, 2, wsCount) + require.Zero(t, httpCount) + } + if mutation == "valid" { + require.Equal(t, 1, accepted) + require.Zero(t, rejected) + } else { + require.Zero(t, accepted, "invalid frame/EOF must never emit a validated B disconnect observation") + if mutation == "unrelated_eof" { + require.Zero(t, rejected) + } else { + require.Equal(t, 1, rejected) + require.Contains(t, string(terminal), "fixture_wrong_task_or_pointer") + } + } + err := u.ambiguousEvidence(transport, terminal) + if mutation == "valid" { + require.NoError(t, err) + } else { + require.ErrorContains(t, err, "WS_AMBIGUOUS_ORACLE_REJECTED") + } + for _, scenario := range []string{"off", "no_intent", "b_disabled", "pending_owner", "failed_owner"} { + require.Error(t, readableWSRefusalEvidence(scenario, nil, io.EOF), "arbitrary EOF cannot pass a refusal boundary") + } + }) + } + } +} diff --git a/backend/internal/handler/openai_409_ws_rebuild_test.go b/backend/internal/handler/openai_409_ws_rebuild_test.go new file mode 100644 index 000000000000..28bcca3df809 --- /dev/null +++ b/backend/internal/handler/openai_409_ws_rebuild_test.go @@ -0,0 +1,495 @@ +//go:build unit + +package handler + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "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" + "github.com/Wei-Shaw/sub2api/internal/testutil" + coderws "github.com/coder/websocket" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +var readableWSModes = []string{service.OpenAIWSIngressModeHTTPBridge, service.OpenAIWSIngressModeCtxPool, + service.OpenAIWSIngressModeShared, service.OpenAIWSIngressModeDedicated, service.OpenAIWSIngressModePassthrough} + +// Mutate administrative scheduling state under a lock while a real client +// connection remains open. Every authoritative repository read sees the update. +type readableWSAccounts struct { + *issue600SwitchRepo + mu sync.Mutex + disableAdmission int + admissionObserved []bool +} + +func (r *readableWSAccounts) disable(id int64) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + if r.accounts[i].ID == id { + r.accounts[i].Schedulable = false + } + } +} +func (r *readableWSAccounts) GetByID(ctx context.Context, id int64) (*service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + return r.issue600SwitchRepo.GetByID(ctx, id) +} +func (r *readableWSAccounts) GetOpenAITurnAdmission(ctx context.Context, id int64) (*service.Account, *service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + if id == 1 && r.disableAdmission > 0 { + r.disableAdmission-- + if r.disableAdmission == 0 { + for i := range r.accounts { + if r.accounts[i].ID == 1 { + r.accounts[i].Schedulable = false + } + } + } + r.admissionObserved = append(r.admissionObserved, r.disableAdmission > 0) + } + a, err := r.issue600SwitchRepo.GetByID(ctx, id) + return a, nil, err +} +func (r *readableWSAccounts) ListSchedulableByPlatform(ctx context.Context, platform string) ([]service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + return r.issue600SwitchRepo.ListSchedulableByPlatform(ctx, platform) +} +func (r *readableWSAccounts) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, platform string) ([]service.Account, error) { + return r.ListSchedulableByPlatform(ctx, platform) +} +func (r *readableWSAccounts) ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]service.Account, error) { + return r.ListSchedulableByPlatform(ctx, platform) +} +func (r *readableWSAccounts) SetRateLimited(ctx context.Context, id int64, until time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + return r.issue600SwitchRepo.SetRateLimited(ctx, id, until) +} + +func TestOpenAI409WSReadableContinuation(t *testing.T) { + for _, mode := range readableWSModes { + t.Run(mode, func(t *testing.T) { runReadableWSContinuation(t, mode, "completed") }) + } +} + +func TestOpenAI409WSReadableBoundaries(t *testing.T) { + for _, mode := range readableWSModes { + for _, boundary := range []string{"off", "no_intent", "b_disabled", "pending_owner", "failed_owner", "ambiguous_B"} { + t.Run(mode+"/"+boundary, func(t *testing.T) { runReadableWSContinuation(t, mode, boundary) }) + } + } +} + +func TestOpenAI409WSReviewRepairs(t *testing.T) { + for _, mode := range readableWSModes { + t.Run("identity/"+mode, func(t *testing.T) { runReadableWSContinuation(t, mode, "identity") }) + } + for _, mode := range []string{"auto", "ws", "http"} { + t.Run("smart/"+mode, func(t *testing.T) { runReadableWSContinuation(t, service.OpenAIWSIngressModeCtxPool, "smart_"+mode) }) + } + t.Run("bridge_inherited_model", func(t *testing.T) { + runReadableWSContinuation(t, service.OpenAIWSIngressModeHTTPBridge, "bridge_model") + }) +} + +func TestOpenAI409WSResidualRepairs(t *testing.T) { + for _, scenario := range []string{"header_apikey", "header_oauth", "tools_omitted", "tools_explicit"} { + t.Run(scenario, func(t *testing.T) { + runReadableWSContinuation(t, service.OpenAIWSIngressModeHTTPBridge, scenario) + }) + } +} + +func TestOpenAI409WSNativeNamespaceRecovery(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModeCtxPool, service.OpenAIWSIngressModeShared, service.OpenAIWSIngressModeDedicated, service.OpenAIWSIngressModePassthrough} { + t.Run(mode, func(t *testing.T) { runReadableWSContinuation(t, mode, "native_namespace") }) + } +} + +func readableWSNativeNamespaceTools() []any { + return append(httpRebuildToolDefinitions(), + map[string]any{"type": "namespace", "name": "files", "tools": []any{ + map[string]any{"type": "function", "name": "read", "parameters": map[string]any{ + "type": "object", "properties": map[string]any{"path": map[string]any{"type": "string", "enum": []string{"sum.go"}}}, + "required": []string{"path"}, "additionalProperties": false, + }}, + }}, + map[string]any{"type": "function", "name": "files__read", "parameters": map[string]any{ + "type": "object", "properties": map[string]any{"name": map[string]any{"type": "string", "enum": []string{"README.md"}}}, + "required": []string{"name"}, "additionalProperties": false, + }}, + ) +} + +// A wire close intentionally omits internal causes. Attribute the observed +// close to the real B dispatch error, never synthesize a diagnostic from the +// scenario name: historical RED must still prove its specific underlying cause. +func logReadableWSDispatchFailure(t *testing.T, h *openAIWSPassthroughHandlerHarness, clientErr error) { + t.Helper() + var peerClose coderws.CloseError + require.ErrorAs(t, clientErr, &peerClose) + require.Equal(t, coderws.StatusPolicyViolation, peerClose.Code) + entries := h.requestLogs.FilterMessage("openai.websocket_proxy_failed").All() + require.Len(t, entries, 1, "expected one actual failed B dispatch") + require.Equal(t, int64(2), entries[0].ContextMap()["account_id"]) + var reported error + for _, field := range entries[0].Context { + if field.Key == "error" { + reported, _ = field.Interface.(error) + } + } + var serverClose *service.OpenAIWSClientCloseError + require.ErrorAs(t, reported, &serverClose) + require.Equal(t, peerClose.Code, serverClose.StatusCode()) + require.Equal(t, peerClose.Reason, serverClose.Reason()) + require.NotNil(t, errors.Unwrap(serverClose), "dispatch refusal must retain its underlying cause") + t.Logf("actual B dispatch error: %v; client close: %v", reported, clientErr) +} + +func runReadableWSContinuation(t *testing.T, mode, scenario string) { + t.Helper() + clients := issue805Redis(t) + probe := clients() + oracle := &readableWSOracle{scenario: scenario} + provider := oracle.server(t) + defer provider.Close() + headers := http.Header{"Session_id": {"fixture-readable-ws-session"}, "Thread-Id": {"fixture-readable-ws-thread"}} + settings := map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: fmt.Sprint(scenario != "off")} + identityCase, modelCase := scenario == "identity" || strings.HasPrefix(scenario, "header_"), scenario == "bridge_model" + customTools := strings.HasPrefix(scenario, "tools_") + nativeNamespace := scenario == "native_namespace" + smartMode := "" + if strings.HasPrefix(scenario, "smart_") { + smartMode = strings.TrimPrefix(scenario, "smart_") + } + if customTools { + smartMode = "http" + } + if identityCase { + headers.Del("thread-id") + headers.Set("conversation_id", "fixture-client-conversation-T") + headers.Set("x-codex-turn-state", "fixture-original-A-state") + settings[service.SettingKeyCyberSessionBlockEnabled] = "true" + settings[service.SettingKeyCyberSessionIdentityStrictEnabled] = "true" + } + var accounts *readableWSAccounts + h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, provider.URL, headers, + settings, + repository.NewGatewayCache(clients()), func(key *service.APIKey) { key.AllowLongContext = true }, + func(a *service.Account, cfg *config.Config, upstream *service.HTTPUpstream, repo *service.AccountRepository) { + a.ID, a.Priority = 1, 0 + a.Credentials["api_key"] = "fixture-readable-ws-A" + a.Extra["openai_apikey_responses_websockets_v2_mode"] = mode + a.Extra["codex_fingerprint_mode"] = "off" + cfg.Gateway.OpenAIWS.IngressInterTurnIdleTimeoutSeconds = 15 + cfg.Gateway.MaxAccountSwitches = 2 + cfg.Gateway.Scheduling.OpenAITurnAdmissionCacheTTLSeconds = 0 + if smartMode != "" { + cfg.Gateway.OpenAIWS.HTTPBridgeEnabled = true + cfg.Gateway.OpenAIWS.SmartProtocol = config.GatewayOpenAIWSSmartProtocolConfig{Enabled: true, Mode: smartMode} + a.Extra["openai_responses_supported"] = true + } + require.Equal(t, mode, a.ResolveOpenAIResponsesWebSocketV2Mode(cfg.Gateway.OpenAIWS.IngressModeDefault)) + other := *a + other.ID, other.Priority = 2, 1 + other.Credentials = map[string]any{"api_key": "fixture-readable-ws-B", "base_url": provider.URL} + if scenario == "header_oauth" { + cfg.Gateway.OpenAIWS.OAuthEnabled = true + for i, account := range []*service.Account{a, &other} { + account.Type = service.AccountTypeOAuth + account.Credentials["access_token"] = []string{"fixture-readable-ws-A", "fixture-readable-ws-B"}[i] + account.Credentials["chatgpt_account_id"] = fmt.Sprintf("fixture-ws-account-%d", i) + account.Extra["openai_oauth_responses_websockets_v2_enabled"] = true + account.Extra["openai_oauth_responses_websockets_v2_mode"] = mode + } + target, err := url.Parse(provider.URL) + require.NoError(t, err) + *upstream = &httpRebuildTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target} + } + accounts = &readableWSAccounts{issue600SwitchRepo: &issue600SwitchRepo{&openAIWSFailoverHandlerAccountRepoStub{accounts: []service.Account{*a, other}}}} + *repo = accounts + }) + finished := false + defer func() { + if !finished { + issue600Finish(t, h, headers) + } + }() + requestModel := "gpt-5.1" + declarations := httpRebuildToolDefinitions() + if nativeNamespace { + declarations = readableWSNativeNamespaceTools() + } + if customTools { + declarations = append(declarations, map[string]any{"type": "custom", "name": "exec", "description": "Read the completed patch exactly once"}) + } + omitTools := false + create := func(input []string, previous string) string { + body := map[string]any{"type": "response.create", "store": smartMode != "", + "tools": declarations, + "input": json.RawMessage("[" + strings.Join(input, ",") + "]")} + if omitTools { + delete(body, "tools") + } + if requestModel != "" { + body["model"] = requestModel + } + if !identityCase { + body["client_metadata"] = map[string]string{"thread_id": "fixture-readable-ws-thread"} + } + if previous != "" { + body["previous_response_id"] = previous + } + return httpRebuildJSON(body) + } + history := []string{httpRebuildMessage("user", httpRebuildTask)} + if scenario == "no_intent" { + history = nil + } // No earlier readable intent exists in the connection either. + 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)...) + if customTools { + customCalls := 0 + for _, item := range first.Get("output").Array() { + if item.Get("type").String() == "custom_tool_call" { + customCalls++ + require.Equal(t, "exec", item.Get("name").String()) + require.Equal(t, "read sum.go", item.Get("input").String()) + history = append(history, `{"type":"custom_tool_call_output","call_id":"call_ws_exec","output":"custom-exec-once"}`) + } + } + require.Equal(t, 1, customCalls, "A must actually deliver the completed custom tool") + omitTools = scenario == "tools_omitted" + } + require.Eventually(t, func() bool { + owners := issue805Owners(t, probe) + if len(owners) != 1 { + return false + } + for _, raw := range owners { + if !json.Valid([]byte(raw)) || !gjson.Parse(raw).IsArray() || gjson.Get(raw, "1").Int() != 1 { + return false + } + } + return true + }, time.Second, 5*time.Millisecond) + owners := issue805Owners(t, probe) + 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() + requestModel, extraSends = "", 1 + accounts.mu.Lock() + accounts.disableAdmission = 2 + accounts.mu.Unlock() + } else { + accounts.disable(1) + } + if scenario == "b_disabled" { + accounts.disable(2) + } + if scenario == "no_intent" { + history = []string{httpRebuildAgentA} + } + if scenario == "pending_owner" || scenario == "failed_owner" { + for key, raw := range owners { + value := "failed" + if scenario == "pending_owner" { + value = "pending:fixture-unknown:" + raw + } + require.NoError(t, probe.Set(context.Background(), key, value, time.Minute).Err()) + owners[key] = value + } + } + readTerminal := func() ([]byte, error) { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + for { + _, raw, err := h.clientConn.Read(ctx) + if err != nil { + return raw, err + } + kind := gjson.GetBytes(raw, "type").String() + if kind == "response.completed" || kind == "response.failed" || kind == "error" { + return raw, nil + } + } + } + issue715WSSend(t, h.clientConn, create(history, previous)) + secondRaw, readErr := readTerminal() + oracle.mu.Lock() + sends := len(oracle.frames) + oracle.mu.Unlock() + if scenario != "completed" && !identityCase && !modelCase && !nativeNamespace && smartMode == "" { + require.NotErrorIs(t, readErr, context.DeadlineExceeded) + closeCtx, cancelClose := context.WithTimeout(context.Background(), 5*time.Second) + defer cancelClose() + if readErr == nil { + // A structured refusal precedes synchronous coderws.Close. Keep + // reading so the peer close is acknowledged before awaiting return. + for readErr == nil { + var extra []byte + _, extra, readErr = h.clientConn.Read(closeCtx) + require.NotContains(t, string(extra), "response.completed") + } + require.NotErrorIs(t, readErr, context.DeadlineExceeded) + } + // Observe natural handler termination before counting B sends. Closing + // the test client here could hide an automatic retry still in flight. + select { + case <-h.handlerDone: + case <-closeCtx.Done(): + t.Fatal("WS boundary handler did not terminate") + } + finished = true + select { + case final := <-h.finalHeaders: + require.Equal(t, headers.Get("session_id"), final.Get("session_id")) + require.Equal(t, headers.Get("thread-id"), final.Get("thread-id")) + default: + t.Fatal("missing final client identity") + } + if scenario == "ambiguous_B" { + require.NoError(t, oracle.ambiguousEvidence(mode, secondRaw), "B must accept one valid frame before the intentional disconnect") + } else { + require.NoError(t, readableWSRefusalEvidence(scenario, secondRaw, readErr)) + oracle.mu.Lock() + finalSends := len(oracle.frames) + oracle.mu.Unlock() + require.Equal(t, 1, finalSends, "unsafe task or current eligibility must refuse before B") + } + require.NotContains(t, string(secondRaw), "response.completed") + for key, raw := range owners { + require.Equal(t, raw, issue805Owners(t, probe)[key]) + } + require.Equal(t, 1, tools.patches) + require.Zero(t, tools.verifications) + return + } + if (nativeNamespace || customTools) && sends != 2 { + require.Equal(t, 1, sends, "refused rebuilt B dispatch must not emit a generation") + logReadableWSDispatchFailure(t, h, readErr) + } + if nativeNamespace { + require.Equal(t, 2, sends, "WS_NATIVE_NAMESPACE_B_DISPATCH_MISSING: close=%v terminal=%s", readErr, secondRaw) + } else if customTools { + require.Equal(t, 2, sends, "WS_RESIDUAL_TOOL_PROJECTION_REFUSED: close=%v terminal=%s", readErr, secondRaw) + } else if smartMode != "" { + require.Equal(t, 2, sends, "WS_REVIEW_SMART_SESSION_STALE: close=%v terminal=%s", readErr, secondRaw) + } + require.Equal(t, 2+extraSends, sends, "WS_READABLE_B_DISPATCH_MISSING: same client must automatically replace disabled A before any next generation; close=%v terminal=%s", readErr, secondRaw) + if modelCase { + accounts.mu.Lock() + observed := append([]bool(nil), accounts.admissionObserved...) + accounts.mu.Unlock() + require.Equal(t, []bool{true, false}, observed, "fixture must reach the final bridge admission after a healthy BeforeTurn") + oracle.mu.Lock() + actualModel := gjson.GetBytes(oracle.frames[2], "model").String() + oracle.mu.Unlock() + require.Equal(t, "gpt-5.4", actualModel, "WS_REVIEW_INHERITED_MODEL_LOST: B must receive the last successfully selected client model") + } + require.NoError(t, readErr) + second := gjson.GetBytes(secondRaw, "response") + require.Equal(t, "completed", second.Get("status").String(), string(secondRaw)) + if customTools { + require.NotContains(t, second.Raw, "custom_tool_call", "completed custom effect must never execute again") + } + 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 := readTerminal() + if identityCase { + oracle.mu.Lock() + finalSends := len(oracle.frames) + oracle.mu.Unlock() + if !assert.Equal(t, 3, finalSends, "WS_REVIEW_CLIENT_IDENTITY_LOST: close=%v terminal=%s", err, final) { + // The historical identity defect also mutates upgrade headers. Check + // teardown on the normal stack, before FailNow unwinds deferred calls. + finished = true + issue600Finish(t, h, headers) + return + } + } + require.NoError(t, err) + require.Equal(t, "response.completed", gjson.GetBytes(final, "type").String(), string(final)) + require.Contains(t, string(final), "ws-coding-task-complete") + if customTools { + require.NotContains(t, string(final), "custom_tool_call") + } + require.Empty(t, tools.execute(t, gjson.GetBytes(final, "response"))) + require.Equal(t, 1, tools.patches) + require.Equal(t, 1, tools.verifications) + a, err := accounts.GetByID(context.Background(), 1) + require.NoError(t, err) + require.False(t, a.Schedulable) + oracle.mu.Lock() + defer oracle.mu.Unlock() + expectedIdentities := []string{"Bearer fixture-readable-ws-A", "Bearer fixture-readable-ws-B", "Bearer fixture-readable-ws-B"} + if modelCase { + expectedIdentities = append([]string{"Bearer fixture-readable-ws-A"}, expectedIdentities...) + require.Equal(t, "gpt-5.4", gjson.GetBytes(oracle.frames[1], "model").String(), "A actually accepted M2 before the later omission") + require.Equal(t, "gpt-5.4", gjson.GetBytes(oracle.frames[3], "model").String()) + } + require.Equal(t, expectedIdentities, oracle.identities) + if nativeNamespace { + for _, frame := range oracle.frames { + require.JSONEq(t, httpRebuildJSON(declarations), gjson.GetBytes(frame, "tools").Raw, "native declarations and both distinct schemas must survive A/B/B") + } + } + if identityCase { + for _, header := range oracle.headers[1:] { + require.NotEqual(t, headers.Get("conversation_id"), header.Get("conversation_id"), "WS_RESIDUAL_A_HEADER_LEAK: only outbound provider state is detached") + require.Empty(t, header.Get("x-codex-turn-state"), "WS_RESIDUAL_A_HEADER_LEAK: retained A state must not reach B") + if scenario == "header_oauth" { + require.NotEmpty(t, header.Get("session_id")) + require.NotEqual(t, headers.Get("session_id"), header.Get("session_id")) + require.Equal(t, header.Get("session_id"), header.Get("conversation_id"), "WS_RESIDUAL_A_HEADER_LEAK: B conversation must use B's isolated session") + require.NotEqual(t, oracle.headers[0].Get("session_id"), header.Get("session_id")) + } + } + } + if mode == service.OpenAIWSIngressModeHTTPBridge || smartMode == "http" { + require.Equal(t, 3+extraSends, oracle.httpSends) + require.Zero(t, oracle.wsSends) + } else { + require.Equal(t, 3+extraSends, oracle.wsSends) + require.Zero(t, oracle.httpSends) + } + for key, raw := range owners { + require.Equal(t, raw, issue805Owners(t, probe)[key], "A owner is never overwritten") + } +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 741b64c508da..3b15d85be21f 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -816,6 +816,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { defer stopHeaderWait() reqLog = reqLog.With(zap.String("model", reqModel), zap.Bool("stream", reqStream)) previousResponseID := strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) + mustDiscardUnownedPointer := false if previousResponseID != "" { previousResponseIDKind := service.ClassifyOpenAIPreviousResponseIDKind(previousResponseID) reqLog = reqLog.With( @@ -844,13 +845,21 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { if ownershipErr != nil { reqLog.Warn("openai.previous_response_owner_lookup_failed", zap.Error(ownershipErr)) } - if !owned { + if !owned && ownershipErr == nil && openAICompatibleRequestPlatform(c.Request.Context(), apiKey) == service.PlatformOpenAI { + mustDiscardUnownedPointer = h.gatewayService.CanDiscardOpenAI409ResponsePointer(c.Request.Context(), body, groupID, previousResponseID) + } + if !owned && !mustDiscardUnownedPointer { reqLog.Warn("openai.request_validation_failed", zap.String("reason", "previous_response_owner_mismatch")) h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "previous_response_id is not available for this user") return } } service.SetOpenAIHTTPResponseOwner(c, subject.UserID, apiKey.ID) + if openAICompatibleRequestPlatform(c.Request.Context(), apiKey) == service.PlatformOpenAI { + shadowCtx, restored := h.gatewayService.RestoreOpenAIReadableShadow(c.Request.Context(), c, body, h.gatewayService.GenerateSessionHash(c, sessionHashBody)) + c.Request = c.Request.WithContext(shadowCtx) + body = restored + } setOpsRequestContext(c, reqModel, reqStream) bindOpenAIPriorityObservation(c, apiKey.GroupID, reqModel, body) @@ -993,6 +1002,46 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { pricingCtx, pricingAt := h.gatewayService.WithOpenAIRequestPricingContext(c.Request.Context(), apiKey.GroupID) c.Request = c.Request.WithContext(service.WithOpenAIEncryptedReasoningAffinity(pricingCtx, body)) c.Request = c.Request.WithContext(h.gatewayService.WithOpenAIAgentMessageRecovery(c.Request.Context(), c, body, sessionHash, forwardModel)) + applyReadableRebuild := func(next context.Context, clean []byte) error { + // Keep the channel model mapping, but detach provider state atomically + // from both body copies, the selection argument and recovery context. + mapped, err := sjson.SetRawBytes(forwardBody, "input", []byte(gjson.GetBytes(clean, "input").Raw)) + if err != nil { + return err + } + for _, field := range []string{"previous_response_id", "conversation"} { + mapped, err = sjson.DeleteBytes(mapped, field) + if err != nil { + return err + } + } + body, forwardBody = clean, mapped + previousResponseID = "" + omittedEncryptedHistory = true + c.Request = c.Request.WithContext(next) + reqLog.Info("openai.encrypted_history_409_omitted", zap.Bool("context_loss", true)) + return nil + } + if requestPlatform == service.PlatformOpenAI { + next, clean, changed, rebuildErr := h.gatewayService.PrepareOpenAI409ReadableContinuation(c.Request.Context(), c, body, sessionHash, forwardModel) + if rebuildErr != nil { + h.handleOpenAIAgentRecoveryError(c, rebuildErr, streamStarted) + return + } + if changed { + if err := applyReadableRebuild(next, clean); err != nil { + h.handleStreamingAwareError(c, http.StatusInternalServerError, "api_error", "Unable to prepare readable continuation", streamStarted) + return + } + } + } + if mustDiscardUnownedPointer && (!omittedEncryptedHistory || previousResponseID != "" || + gjson.GetBytes(body, "previous_response_id").Exists() || gjson.GetBytes(forwardBody, "previous_response_id").Exists()) { + // Permission to discard never grants permission to consume provider + // state. A changed/failed setting or unsupported rebuild must deny. + h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "previous_response_id could not be safely detached for this user") + return + } for { // Streaming Forward intentionally detaches the upstream request so usage can @@ -1022,14 +1071,10 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { ) if err != nil { if !omittedEncryptedHistory && !upstreamAttempted && !streamStarted && !c.Writer.Written() && requestPlatform == service.PlatformOpenAI { - if next, clean, changed := h.gatewayService.TryOmitOpenAI409History(c.Request.Context(), c, body, sessionHash, forwardModel, err); changed { - // Preserve the channel's model mapping while replacing only input. - mapped, mapErr := sjson.SetRawBytes(forwardBody, "input", []byte(gjson.GetBytes(clean, "input").Raw)) - if mapErr == nil { - body, forwardBody = clean, mapped - omittedEncryptedHistory = true - c.Request = c.Request.WithContext(next) - reqLog.Info("openai.encrypted_history_409_omitted", zap.Bool("context_loss", true)) + if next, clean, changed, rebuildErr := h.gatewayService.TryRebuildOpenAI409History(c.Request.Context(), c, body, sessionHash, forwardModel, err); rebuildErr != nil { + err = rebuildErr + } else if changed { + if mapErr := applyReadableRebuild(next, clean); mapErr == nil { continue } } @@ -3054,6 +3099,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "model is required in first response.create payload") return } + service.SetOpenAIWSRecoveryPrincipal(c, subject.UserID, apiKey.ID) + shadowSession := h.gatewayService.GenerateSessionHashWithFallback(c, firstMessage, + openAIWSIngressFallbackSessionSeed(subject.UserID, apiKey.ID, apiKey.GroupID)) + ctx, firstMessage = h.gatewayService.RestoreOpenAIReadableShadow(ctx, c, firstMessage, shadowSession) + c.Request = c.Request.WithContext(ctx) if err := h.gatewayService.CheckAPIKeyLongContext(c.Request.Context(), apiKey, firstMessage, reqModel, service.MapAPIKeyModel(apiKey, reqModel)); err != nil { service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate) rejectAPIKeyLongContextWS(wsConn, err) @@ -3299,6 +3349,14 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { ) ctx = h.gatewayService.WithOpenAIWSAgentRecovery(ctx, c, firstMessage, sessionHash, wsForwardModel) ctx = service.WithOpenAIGuardianParentAffinity(ctx, c, firstMessage, reqModel) + if next, clean, changed, rebuildErr := h.gatewayService.PrepareOpenAI409ReadableContinuation(ctx, c, firstMessage, sessionHash, wsForwardModel); rebuildErr != nil { + h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr) + return + } else if changed { + ctx, firstMessage, previousResponseID = next, clean, "" + ctx = service.ResetOpenAIWSReadableProviderSession(ctx, c) + c.Request = c.Request.WithContext(ctx) + } maxAccountSwitches := h.maxAccountSwitches switchCount := 0 var forbiddenBudget grokForbiddenFailoverBudget @@ -3625,6 +3683,9 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { closeOpenAIClientWS(wsConn, securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision)) return } + // Only the explicit unsent-rebuild recheck supplies restored audit text. + // Client identity continues to resolve from the immutable original frame. + var rebuiltAuditBody []byte hooks := &service.OpenAIWSIngressHooks{ ClientLifecycleContext: clientLifecycleCtx, InitialRequestModel: reqModel, @@ -3741,7 +3802,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed) return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for your account in this group", denied), nil) } - if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, clientPayload, "subsequent_turn"); decision != nil && !decision.AllowNextStage { + auditBody := clientPayload + if rebuiltAuditBody != nil { + auditBody = rebuiltAuditBody + } + if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, auditBody, "subsequent_turn"); decision != nil && !decision.AllowNextStage { writeSecurityAuditWSError(ctx, wsConn, decision) return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), errOpenAIWSLocalAdmissionRejected) } @@ -4005,6 +4070,105 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { reqLog.Info("openai.websocket_ingress_closed", zap.Int64("account_id", account.ID)) return } + if raw, currentModel, turn, unsent := service.OpenAIWSUnsentTurnPayload(err); unsent && requestPlatform == service.PlatformOpenAI { + // This is an explicitly unsent CURRENT frame returned by the + // transport, never the connection's warmup or a failed generation. + releaseTurnSlots() + if switchCount >= maxAccountSwitches || !service.OpenAIWSIngressCanFailover(ctx, c) { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account eligibility changed; continuation budget exhausted") + return + } + if currentModel = strings.TrimSpace(currentModel); currentModel == "" { + currentModel = reqModel + } + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite && currentModel != reqModel { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "model route changed during continuation") + return + } + if err := hooks.BeforePayloadParse(turn, raw, currentModel); err != nil { + closeOpenAIWSAdmissionError(wsConn, reqLog, "openai.websocket_rebuild_auth_rejected", err) + return + } + currentRouteModel := service.MapAPIKeyModel(apiKey, currentModel) + if apiKey.Group != nil && apiKey.Group.Platform == service.PlatformComposite { + currentRouteModel = wsRouteModel + } + mapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(ctx, apiKey.GroupID, currentRouteModel) + currentForwardModel := openAIChannelForwardModel(mapping, currentRouteModel) + if gjson.GetBytes(raw, "model").String() == "" { + var modelErr error + raw, modelErr = sjson.SetBytes(raw, "model", currentModel) + if modelErr != nil { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "invalid current request model") + return + } + } + next, clean, changed, rebuildErr := h.gatewayService.RebuildOpenAIWSUnsentTurn(ctx, c, raw, sessionHash, currentForwardModel) + if rebuildErr != nil { + h.handleOpenAIWSAgentRecoveryError(ctx, wsConn, rebuildErr) + return + } + if !changed { + closeOpenAIClientWS(wsConn, coderws.StatusTryAgainLater, "account eligibility changed; reconnect with complete context") + return + } + c.Request = c.Request.WithContext(next) + if err := h.gatewayService.CheckAPIKeyLongContext(next, apiKey, clean, currentModel, currentRouteModel, currentForwardModel); err != nil { + rejectAPIKeyLongContextWS(wsConn, err) + return + } + // Re-run current-frame identity/model/moderation checks on restored + // readable text, carrying its no-retention provenance. + rebuiltAuditBody = clean + auditErr := hooks.BeforeRequestWithClientPayload(turn, clean, raw, currentModel) + rebuiltAuditBody = nil + if auditErr != nil { + closeOpenAIWSAdmissionError(wsConn, reqLog, "openai.websocket_rebuild_policy_rejected", auditErr) + return + } + cyberTurn := takeCyberTurnBody(turn) + firstIdentityDecision.effective = cyberTurn.identity + setCyberTurnBody(1, clean, cyberTurn.identity) + permissions := openAIWSQueueTurnPermissions(currentModel, clean) + permissions.Models = service.APIKeyModelCandidates(apiKey, permissions.Models) + ctx = service.WithAPIKeyQueueRequestPermissions(next, permissions) + ctx, _ = h.gatewayService.WithOpenAIRequestPricingContext(ctx, apiKey.GroupID) + ctx = service.WithOpenAIForwardModel(ctx, currentForwardModel, false) + ctx = service.ResetOpenAIWSReadableProviderSession(ctx, c) + c.Request = c.Request.WithContext(ctx) + if err := h.concurrencyHelper.RevalidateTurnAuth(ctx); err != nil { + closeOpenAIWSAdmissionError(wsConn, reqLog, "openai.websocket_rebuild_auth_rejected", err) + return + } + if err := h.checkRegionalBillingEligibility(ctx, apiKey, subscription); err != nil { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "billing check failed") + return + } + imageIntent = permissions.Capabilities&service.APIKeyQueueCapabilityImageGeneration != 0 + if imageIntent && !service.GroupAllowsImageGeneration(apiKey.Group) { + closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, service.ImageGenerationPermissionMessage()) + return + } + requiredCapability = service.OpenAIEndpointCapabilityChatCompletions + if imageIntent { + requiredCapability = service.OpenAIEndpointCapabilityResponses + ctx = service.WithOpenAIImageGenerationRequest(ctx, currentModel, clean) + } + if started := getTurnStart(turn); !started.IsZero() { + firstTurnStartedAt, firstFrameArrivedAt = started, started + } + reqModel, wsRouteModel, wsForwardModel = currentModel, currentRouteModel, currentForwardModel + channelMappingWS = mapping + wsAttemptMessage, previousResponseID, previousResponseCanMove = clean, "", true + failedAccountIDs[account.ID] = struct{}{} + switchCount++ + h.gatewayService.RecordOpenAIAccountSwitch() + if !ensureUserSlotHeld() { + return + } + reqLog.Info("openai.websocket_readable_continuation", zap.Bool("context_loss", true), zap.Int("switch_count", switchCount)) + break + } if isOpenAIRPMError(err) { releaseTurnSlots() reason := "OpenAI OAuth RPM protection is temporarily unavailable; retry later" diff --git a/backend/internal/handler/openai_images_failover_test.go b/backend/internal/handler/openai_images_failover_test.go index 68ad15cbb47e..28196544547d 100644 --- a/backend/internal/handler/openai_images_failover_test.go +++ b/backend/internal/handler/openai_images_failover_test.go @@ -64,6 +64,24 @@ func (r openAIImagesFailoverAccountRepo) accountsForPlatform(platform string) [] return out } +func (r openAIImagesFailoverAccountRepo) ListModelAvailabilityCandidates(_ context.Context, groupID *int64, platforms []string, includeGrouped bool) ([]service.Account, error) { + var out []service.Account + for _, platform := range platforms { + for _, account := range r.accountsForPlatform(platform) { + matches := groupID == nil && (includeGrouped || len(account.GroupIDs) == 0) + if groupID != nil { + for _, id := range account.GroupIDs { + matches = matches || id == *groupID + } + } + if matches { + out = append(out, account) + } + } + } + return out, nil +} + type openAIImagesFailoverHTTPUpstream struct { service.HTTPUpstream mu sync.Mutex diff --git a/backend/internal/handler/openai_responses_failover_cancel_test.go b/backend/internal/handler/openai_responses_failover_cancel_test.go index 4c739b82c1e2..40f39b1ab5ce 100644 --- a/backend/internal/handler/openai_responses_failover_cancel_test.go +++ b/backend/internal/handler/openai_responses_failover_cancel_test.go @@ -60,6 +60,11 @@ func newOpenAIResponsesFailoverTestHandlerWithCache(t *testing.T, upstream servi } func newOpenAIResponsesFailoverTestHandlerWithSettings(t *testing.T, upstream service.HTTPUpstream, cache service.GatewayCache, settings *service.SettingService, fixtureAccounts ...service.Account) *OpenAIGatewayHandler { + t.Helper() + return newOpenAIResponsesFailoverTestHandlerWithUsage(t, upstream, cache, settings, nil, fixtureAccounts...) +} + +func newOpenAIResponsesFailoverTestHandlerWithUsage(t *testing.T, upstream service.HTTPUpstream, cache service.GatewayCache, settings *service.SettingService, usage service.UsageLogRepository, fixtureAccounts ...service.Account) *OpenAIGatewayHandler { t.Helper() accounts := []service.Account{ { @@ -97,7 +102,7 @@ func newOpenAIResponsesFailoverTestHandlerWithSettings(t *testing.T, upstream se gatewayService := service.NewOpenAIGatewayService( accountRepo, nil, - nil, + usage, nil, nil, nil, @@ -106,11 +111,11 @@ func newOpenAIResponsesFailoverTestHandlerWithSettings(t *testing.T, upstream se cfg, nil, nil, - nil, + service.NewBillingService(cfg, nil), nil, nil, upstream, - nil, + &service.DeferredService{}, nil, nil, nil, diff --git a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go index 775ae83d5ab2..39a4f33bab4d 100644 --- a/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go +++ b/backend/internal/handler/openai_ws_v2_passthrough_cyber_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" "github.com/Wei-Shaw/sub2api/internal/testutil" @@ -17,6 +18,9 @@ import ( "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest/observer" ) type openAIWSPassthroughHandlerHarness struct { @@ -29,6 +33,7 @@ type openAIWSPassthroughHandlerHarness struct { apiKey *service.APIKey finalHeaders <-chan http.Header usageLogs <-chan *service.UsageLog + requestLogs *observer.ObservedLogs } func newOpenAIWSPassthroughHandlerHarness(t *testing.T, upstreamURL string, settings ...map[string]string) *openAIWSPassthroughHandlerHarness { @@ -51,6 +56,10 @@ func newOpenAIWSPassthroughHandlerHarnessWithCache(t *testing.T, upstreamURL str } func newOpenAIWSPassthroughHandlerHarnessWithKey(t *testing.T, upstreamURL string, clientHeaders http.Header, extraSettings map[string]string, gatewayCache service.GatewayCache, configureKey func(*service.APIKey), configure ...func(*service.Account, *config.Config, *service.HTTPUpstream, *service.AccountRepository)) *openAIWSPassthroughHandlerHarness { + return newOpenAIWSPassthroughHandlerHarnessWithAudit(t, upstreamURL, clientHeaders, extraSettings, gatewayCache, configureKey, nil, configure...) +} + +func newOpenAIWSPassthroughHandlerHarnessWithAudit(t *testing.T, upstreamURL string, clientHeaders http.Header, extraSettings map[string]string, gatewayCache service.GatewayCache, configureKey func(*service.APIKey), configureHandler func(*OpenAIGatewayHandler), configure ...func(*service.Account, *config.Config, *service.HTTPUpstream, *service.AccountRepository)) *openAIWSPassthroughHandlerHarness { t.Helper() if gatewayCache == nil { gatewayCache = testutil.NewRedisGatewayCache(t) @@ -139,13 +148,24 @@ func newOpenAIWSPassthroughHandlerHarnessWithKey(t *testing.T, upstreamURL strin GroupID: &groupID, User: &service.User{ID: 1751, Status: service.StatusActive}, } + if configureHandler != nil { + configureHandler(h) + } if configureKey != nil { configureKey(apiKey) } finalHeaders := make(chan http.Header, 4) handlerDone := make(chan struct{}, 4) + requestCore, requestLogs := observer.New(zap.WarnLevel) router := gin.New() router.Use(func(c *gin.Context) { + // Observe the real handler error boundary without replacing its logger + // or changing the client-visible close frame. + base := logger.FromContext(c.Request.Context()) + observed := base.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core { + return zapcore.NewTee(core, requestCore) + })) + c.Request = c.Request.WithContext(logger.IntoContext(c.Request.Context(), observed)) c.Set(string(middleware.ContextKeyAPIKey), apiKey) c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) c.Next() @@ -175,6 +195,7 @@ func newOpenAIWSPassthroughHandlerHarnessWithKey(t *testing.T, upstreamURL strin apiKey: apiKey, finalHeaders: finalHeaders, usageLogs: usageRepo.created, + requestLogs: requestLogs, } } diff --git a/backend/internal/handler/security_audit_helper.go b/backend/internal/handler/security_audit_helper.go index bbcd5353526e..72050673a168 100644 --- a/backend/internal/handler/security_audit_helper.go +++ b/backend/internal/handler/security_audit_helper.go @@ -171,6 +171,7 @@ func buildSecurityAuditRequest(c *gin.Context, apiKey *service.APIKey, subject m APIKeyID: legacy.APIKeyID, APIKeyName: legacy.APIKeyName, GroupID: cloneSecurityAuditGroupID(legacy.GroupID), GroupName: legacy.GroupName, Provider: legacy.Provider, Endpoint: legacy.Endpoint, Protocol: legacy.Protocol, Model: legacy.Model, Body: body, Stage: strings.TrimSpace(stage), + NoBodyRetention: service.HasRecoveredContextPrivacy(c.Request.Context()), } if apiKey != nil && apiKey.User != nil { request.Username = apiKey.User.Username diff --git a/backend/internal/repository/gateway_cache_agent_shadow_epoch.go b/backend/internal/repository/gateway_cache_agent_shadow_epoch.go new file mode 100644 index 000000000000..743888c8ef36 --- /dev/null +++ b/backend/internal/repository/gateway_cache_agent_shadow_epoch.go @@ -0,0 +1,101 @@ +package repository + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/redis/go-redis/v9" +) + +// No customer content. A separate bounded metadata budget spans all of a +// principal's sessions. Eviction loses future recovery, never owner authority. +func openAIAgentShadowEpochKeys(key string) (string, string, error) { + parts := strings.Split(key, ":") + if len(parts) != 2 { + return "", "", errors.New("invalid association scope") + } + for _, part := range parts { + if _, err := openAIAgentRecoveryKey(part); err != nil { + return "", "", err + } + } + scope := "{" + parts[0] + "}" + return "openai_agent_shadow_epoch:v1:" + scope + ":" + parts[1], "openai_agent_shadow_index:v1:" + scope, nil +} + +var reserveOpenAIAgentShadowEpoch = 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 +redis.call('ZADD', KEYS[2], millis + ttl, KEYS[1]) +redis.call('PEXPIRE', KEYS[2], math.max(ttl, redis.call('PTTL', KEYS[2]))) +if old and (old == 'conflict' or string.sub(old, 1, 8) == 'pending:') then + redis.call('SET', KEYS[1], 'conflict', 'PX', ttl) + return 0 +end +redis.call('SET', KEYS[1], ARGV[1], 'PX', ttl) +return 1 +`) + +var finishOpenAIAgentShadowEpoch = redis.NewScript(` +if redis.call('GET', KEYS[1]) ~= ARGV[1] then return 0 end +local value = 'failed:' .. ARGV[1] +if ARGV[2] == '1' then value = 'ready:' .. ARGV[1] end +redis.call('SET', KEYS[1], value, 'PX', math.max(tonumber(ARGV[3]), redis.call('PTTL', KEYS[1]))) +local now = redis.call('TIME') +local millis = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) +redis.call('ZADD', KEYS[2], millis + redis.call('PTTL', KEYS[1]), KEYS[1]) +redis.call('PEXPIRE', KEYS[2], math.max(tonumber(ARGV[3]), redis.call('PTTL', KEYS[2]))) +return 1 +`) + +func (c *gatewayCache) ReserveOpenAIAgentRecoveryEpoch(ctx context.Context, key, token string, ttl time.Duration) error { + ttl = min(ttl, service.OpenAIReadableShadowTTL) + key, index, err := openAIAgentShadowEpochKeys(key) + if err != nil { + return err + } + // A successfully stored conflict revokes shadow eligibility; it must not + // change an otherwise valid original response or its owner semantics. + return reserveOpenAIAgentShadowEpoch.Run(ctx, c.rdb, []string{key, index}, token, ttl.Milliseconds()).Err() +} + +func (c *gatewayCache) FinishOpenAIAgentRecoveryEpoch(ctx context.Context, key, token string, completed bool, ttl time.Duration) error { + ttl = min(ttl, service.OpenAIReadableShadowTTL) + key, index, err := openAIAgentShadowEpochKeys(key) + if err != nil { + return err + } + flag := 0 + if completed { + flag = 1 + } + return finishOpenAIAgentShadowEpoch.Run(ctx, c.rdb, []string{key, index}, token, flag, ttl.Milliseconds()).Err() +} + +func (c *gatewayCache) GetOpenAIAgentRecoveryEpoch(ctx context.Context, key string) (string, error) { + key, _, err := openAIAgentShadowEpochKeys(key) + if err != nil { + return "", err + } + value, err := c.rdb.Get(ctx, key).Result() + if errors.Is(err, redis.Nil) { + return "", nil + } + return value, err +} + +var _ service.OpenAIAgentRecoveryEpochCache = (*gatewayCache)(nil) diff --git a/backend/internal/repository/gateway_cache_readable_shadow.go b/backend/internal/repository/gateway_cache_readable_shadow.go new file mode 100644 index 000000000000..1ae1cf126fed --- /dev/null +++ b/backend/internal/repository/gateway_cache_readable_shadow.go @@ -0,0 +1,93 @@ +package repository + +import ( + "context" + "encoding/hex" + "errors" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/redis/go-redis/v9" +) + +// Both keys and every indexed member share the principal's Redis Cluster slot. +// Index cardinality is bounded even when callers continually change sessions. +func openAIReadableShadowKeys(principal, task string) (string, string, error) { + for _, value := range []string{principal, task} { + decoded, err := hex.DecodeString(value) + if err != nil || len(decoded) != 32 { + return "", "", errors.New("invalid readable shadow key") + } + } + scope := "{" + principal + "}" + return "openai_readable_shadow:v1:" + scope + ":" + task, "openai_readable_shadow_index:v1:" + scope, nil +} + +var putOpenAIReadableShadowScript = redis.NewScript(` +local now = redis.call('TIME') +local millis = tonumber(now[1]) * 1000 + math.floor(tonumber(now[2]) / 1000) +local ttl = tonumber(ARGV[2]) +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]) +if old then + if old ~= ARGV[1] then + local remaining = redis.call('PTTL', KEYS[1]) + if remaining > 0 then redis.call('SET', KEYS[1], 'conflict', 'PX', remaining) end + end + return 0 +end +while redis.call('ZCARD', KEYS[2]) >= tonumber(ARGV[3]) do + local oldest = redis.call('ZRANGE', KEYS[2], 0, 0) + redis.call('DEL', oldest[1]) + redis.call('ZREM', KEYS[2], oldest[1]) +end +redis.call('SET', KEYS[1], ARGV[1], '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 +`) + +func (c *gatewayCache) PutOpenAIReadableShadow(ctx context.Context, principal, task, value string, ttl time.Duration) error { + key, index, err := openAIReadableShadowKeys(principal, task) + if err != nil { + return err + } + if value == "" || len(value) > service.OpenAIReadableShadowMaxBytes || ttl <= 0 || ttl > service.OpenAIReadableShadowTTL { + return errors.New("invalid readable shadow publication") + } + return putOpenAIReadableShadowScript.Run(ctx, c.rdb, []string{key, index}, value, ttl.Milliseconds(), service.OpenAIReadableShadowMaxRecords).Err() +} + +func (c *gatewayCache) GetOpenAIReadableShadow(ctx context.Context, principal, task string) (string, error) { + key, _, err := openAIReadableShadowKeys(principal, task) + if err != nil { + return "", err + } + value, err := c.rdb.Get(ctx, key).Result() + if errors.Is(err, redis.Nil) { + return "", nil + } + return value, err +} + +var invalidateOpenAIReadableShadowScript = redis.NewScript(` +local remaining = redis.call('PTTL', KEYS[1]) +if remaining > 0 then + redis.call('SET', KEYS[1], 'conflict', 'PX', remaining) +end +return 1 +`) + +func (c *gatewayCache) InvalidateOpenAIReadableShadow(ctx context.Context, principal, task string) error { + key, _, err := openAIReadableShadowKeys(principal, task) + if err != nil { + return err + } + return invalidateOpenAIReadableShadowScript.Run(ctx, c.rdb, []string{key}).Err() +} + +var _ service.OpenAIReadableShadowCache = (*gatewayCache)(nil) diff --git a/backend/internal/securityaudit/coordinator.go b/backend/internal/securityaudit/coordinator.go index cb37ecb900fd..ddca0e1c2257 100644 --- a/backend/internal/securityaudit/coordinator.go +++ b/backend/internal/securityaudit/coordinator.go @@ -29,6 +29,9 @@ func NewCoordinator(legacy LegacyEngine, prompt PromptEngine) *Coordinator { } func (c *Coordinator) Check(ctx context.Context, req Request) (decision Decision) { + if req.NoBodyRetention { + ctx = service.WithRecoveredContextPrivacy(ctx) + } if c == nil { return allowDecision(nil, nil) } diff --git a/backend/internal/securityaudit/penalty.go b/backend/internal/securityaudit/penalty.go index 6c8d6a7b0853..a97d5bf643fb 100644 --- a/backend/internal/securityaudit/penalty.go +++ b/backend/internal/securityaudit/penalty.go @@ -41,6 +41,7 @@ func ProvidePenaltyCoordinator(legacy LegacyEngine, prompt PromptEngine, penalti } func penaltyViolation(snapshot PromptSnapshot, source, reason string) service.SecurityPenaltyViolation { + snapshot = snapshot.Redacted() groupID := snapshot.GroupID if snapshot.PenaltyContext.OriginalGroupID != nil { groupID = snapshot.PenaltyContext.OriginalGroupID diff --git a/backend/internal/securityaudit/penalty_integration_test.go b/backend/internal/securityaudit/penalty_integration_test.go index 79c22c015d53..9d5bc1cf34ef 100644 --- a/backend/internal/securityaudit/penalty_integration_test.go +++ b/backend/internal/securityaudit/penalty_integration_test.go @@ -109,7 +109,11 @@ func TestSecurityPenaltyAsyncFindingCommitsWithLeaseFencedEvent(t *testing.T) { require.NoError(t, err) require.True(t, claimed) job.Snapshot.FullPrompt = "SYNTHETIC_ASYNC_PROMPT" - result := &NormalizedResult{Action: ActionBlock, Decision: EventCritical, RiskLevel: RiskCritical, MatchedScanners: []string{"jailbreak"}, ScannerScores: map[string]float64{}, ScannerEvidence: map[string]string{}} + result := &NormalizedResult{ + Action: ActionBlock, Decision: EventCritical, RiskLevel: RiskCritical, Safety: "Unsafe", + Categories: []string{"jailbreak"}, MatchedScanners: []string{"jailbreak"}, + ScannerScores: map[string]float64{"jailbreak": 1}, ScannerEvidence: map[string]string{"jailbreak": "Jailbreak"}, + } _, err = repo.Complete(context.Background(), job, result, false) require.NoError(t, err) _, err = repo.Complete(context.Background(), job, result, false) diff --git a/backend/internal/securityaudit/prompt_guard.go b/backend/internal/securityaudit/prompt_guard.go index 4bab06c10ff5..1f3e24e4d125 100644 --- a/backend/internal/securityaudit/prompt_guard.go +++ b/backend/internal/securityaudit/prompt_guard.go @@ -35,6 +35,12 @@ func newGuardEvaluator(scanner PromptScanner, repo JobRepository, metrics Metric } func (g *GuardEvaluator) Evaluate(ctx context.Context, cfg ActiveConfig, snapshot PromptSnapshot) (*PromptDecision, error) { + return g.evaluate(ctx, cfg, snapshot, true) +} + +// Memory-only async jobs share the scanner bulkheads, but persist through the +// async completion transaction so the configured penalty hook still runs. +func (g *GuardEvaluator) evaluate(ctx context.Context, cfg ActiveConfig, snapshot PromptSnapshot, recordBlocking bool) (*PromptDecision, error) { if g == nil || g.scanner == nil { if g != nil && g.metrics != nil { g.metrics.Observe(DecisionUnavailable, 0) @@ -150,8 +156,9 @@ func (g *GuardEvaluator) Evaluate(ctx context.Context, cfg ActiveConfig, snapsho "latency_ms": aggregated.LatencyMS, "guard_endpoint_id": aggregated.GuardEndpointID, "stage": snapshot.Stage, "status": "completed", })) - if g.repo != nil { - if _, recordErr := g.repo.RecordBlocking(ctx, snapshot.Redacted(), cfg.ConfigVersion, aggregated, cfg.StorePassEvents); recordErr != nil { + if g.repo != nil && recordBlocking { + storedResult := promptResultForRetention(snapshot, aggregated) + if _, recordErr := g.repo.RecordBlocking(ctx, snapshot.Redacted(), cfg.ConfigVersion, storedResult, cfg.StorePassEvents); recordErr != nil { if g.metrics != nil { g.metrics.IncRecordFailed() } @@ -178,6 +185,16 @@ func (g *GuardEvaluator) Evaluate(ctx context.Context, cfg ActiveConfig, snapsho return decision, nil } +func promptResultForRetention(snapshot PromptSnapshot, result *NormalizedResult) *NormalizedResult { + if result == nil || !snapshot.NoBodyRetention { + return result + } + copy := *result + copy.ScannerEvidence = nil + copy.UnknownCategories = nil + return © +} + func logGuardFailure(snapshot PromptSnapshot, cfg ActiveConfig, kind DecisionKind, code, guardEndpointID string, latency time.Duration) { fields := snapshotLogFields(snapshot) fields["config_version"] = cfg.ConfigVersion diff --git a/backend/internal/securityaudit/prompt_recovered_context_test.go b/backend/internal/securityaudit/prompt_recovered_context_test.go new file mode 100644 index 000000000000..dbf3f9e29073 --- /dev/null +++ b/backend/internal/securityaudit/prompt_recovered_context_test.go @@ -0,0 +1,233 @@ +//go:build integration + +package securityaudit + +import ( + "context" + "encoding/json" + "os" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/redis/go-redis/v9" + "github.com/stretchr/testify/require" +) + +const recoveredPromptCanary = "fixture restored private paragraph 734829" + +type recoveredPromptScanner struct { + calls int + block bool + entered chan struct{} + release <-chan struct{} + once sync.Once +} + +func (s *recoveredPromptScanner) Scan(ctx context.Context, _ ActiveEndpoint, text string, _ []string) (*NormalizedResult, error) { + if !strings.Contains(text, recoveredPromptCanary) { + return nil, &GuardError{Code: ErrorCodeInvalidResponse} + } + s.calls++ + if s.entered != nil { + s.once.Do(func() { close(s.entered) }) + } + if s.release != nil { + select { + case <-s.release: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + result := integrationResult(EventPass) + if s.block { + result = integrationResult(EventCritical) + } + result.ScannerEvidence = map[string]string{"fixture": recoveredPromptCanary} + return result, nil +} + +func TestRecoveredContextAsyncEnforcement(t *testing.T) { + for _, scenario := range []string{"admission", "penalty"} { + t.Run(scenario, func(t *testing.T) { + require.NotEmpty(t, os.Getenv(promptAuditPostgresTestEnv)) + require.NotEmpty(t, os.Getenv(promptAuditRedisTestEnv)) + db := openPromptAuditIntegrationDB(t) + client := redis.NewClient(&redis.Options{Addr: os.Getenv(promptAuditRedisTestEnv), DB: 14}) + defer client.Close() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + require.NoError(t, client.FlushDB(ctx).Err()) + defer client.FlushDB(context.Background()) + user, key := insertIdentity(t, db, "users"), insertIdentity(t, db, "api_keys") + penaltyConfig := service.DefaultSecurityPenaltyConfig() + penaltyConfig.Enabled = true + penaltyConfig.ObserveOnly = false + penaltyConfig.Threshold = 1 + encoded, err := json.Marshal(penaltyConfig) + require.NoError(t, err) + _, err = db.Exec("INSERT INTO settings(key,value) VALUES($1,$2),($3,'true')", service.SettingKeySecurityPenalty, string(encoded), service.SettingKeyRiskControlEnabled) + require.NoError(t, err) + penalties := service.NewSecurityPenaltyService(db, postgresPromptAuditSettingRepository{db: db}, nil) + cfg := guardConfig(ActiveEndpoint{ID: "fixture", Enabled: true, TimeoutMS: 5000, InputLimit: 10000}) + cfg.BlockingEnabled = false + cfg.AllGroups = true + cfg.StorePassEvents = true + repo := NewPostgreSQLRepository(db) + svc := NewPromptService(&fakeConfigStore{cfg: cfg, active: true}, repo, NewRedisPayloadStore(client), nil, NewAtomicMetrics()) + svc.background = ctx + scanner := &recoveredPromptScanner{block: true} + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + if scenario == "admission" { + scanner.entered = make(chan struct{}) + scanner.release = release + } + svc.evaluator = NewGuardEvaluator(scanner, repo, NewAtomicMetrics()) + coordinator := ProvidePenaltyCoordinator(nil, svc, penalties) + body, err := json.Marshal(map[string]any{"input": []any{map[string]any{"role": "user", "content": recoveredPromptCanary}}}) + require.NoError(t, err) + req := Request{RequestID: "async-recovered-" + scenario, UserID: user, APIKeyID: key, Protocol: "openai_responses", Model: "fixture", Body: body, + PenaltyContext: PenaltyRequestContext{SessionKey: "fixture-original-session", RequestID: "async-recovered-" + scenario}} + if field := reflect.ValueOf(&req).Elem().FieldByName("NoBodyRetention"); field.IsValid() { + field.SetBool(true) + } + admitted := make(chan Decision, 1) + checkDone := make(chan struct{}) + go func() { defer close(checkDone); admitted <- coordinator.Check(ctx, req) }() + defer func() { unblock(); cancel(); <-checkDone; svc.enqueueWG.Wait() }() + if scenario == "admission" { + select { + case <-scanner.entered: + case <-time.After(2 * time.Second): + t.Fatal("async scanner barrier not reached") + } + payloadKeys, err := client.Keys(ctx, PayloadKeyPrefix+"*").Result() + require.NoError(t, err) + require.Empty(t, payloadKeys, "scanner-held recovered text must not be staged in durable Redis") + select { + case decision := <-admitted: + require.True(t, decision.AllowNextStage, "async risk must preserve request admission semantics") + case <-time.After(time.Second): + t.Fatal("RECOVERED_ASYNC_ADMISSION_BLOCKED: gateway admission waited for an unreleased scanner") + } + unblock() + } else { + select { + case decision := <-admitted: + require.True(t, decision.AllowNextStage) + case <-time.After(2 * time.Second): + t.Fatal("async admission did not finish") + } + } + svc.enqueueWG.Wait() + page, err := penalties.ListEvents(ctx, user, 1, 10) + require.NoError(t, err) + require.EqualValues(t, 1, page.Total, "RECOVERED_ASYNC_PENALTY_MISSING: actual async risk must commit its configured violation") + detail, err := penalties.GetEvent(ctx, user, page.Items[0].ID) + require.NoError(t, err) + detailRaw, err := json.Marshal(detail) + require.NoError(t, err) + require.NotContains(t, string(detailRaw), recoveredPromptCanary) + var session string + require.NoError(t, db.QueryRow("SELECT session_key FROM security_penalty_events WHERE id=$1", detail.ID).Scan(&session)) + require.Equal(t, "fixture-original-session", session, "the penalty must retain its original session scope") + blocked, err := penalties.Admission(ctx, user, session) + require.NoError(t, err) + require.True(t, blocked.Blocked, "async risk must enforce the configured threshold") + other, err := penalties.Admission(ctx, user, "fixture-other-session") + require.NoError(t, err) + require.False(t, other.Blocked, "session policy must not widen to other work") + var jobs, events string + require.NoError(t, db.QueryRow("SELECT string_agg(row_to_json(t)::text,'') FROM prompt_audit_jobs t").Scan(&jobs)) + require.NoError(t, db.QueryRow("SELECT string_agg(row_to_json(t)::text,'') FROM prompt_audit_events t").Scan(&events)) + require.Contains(t, jobs, `"execution_mode":"async_audit"`) + require.Contains(t, jobs, `"status":"done"`) + require.NotContains(t, jobs+events, recoveredPromptCanary) + keys, err := client.Keys(ctx, PayloadKeyPrefix+"*").Result() + require.NoError(t, err) + require.Empty(t, keys) + require.Equal(t, 1, scanner.calls) + // A failed penalty write must roll back the metadata/event too. + _, err = db.Exec(`CREATE FUNCTION fixture_reject_async_penalty() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'fixture penalty unavailable'; END $$`) + require.NoError(t, err) + _, err = db.Exec(`CREATE TRIGGER fixture_reject_async_penalty BEFORE INSERT ON security_penalty_events FOR EACH ROW EXECUTE FUNCTION fixture_reject_async_penalty()`) + require.NoError(t, err) + defer db.Exec(`DROP TRIGGER IF EXISTS fixture_reject_async_penalty ON security_penalty_events; DROP FUNCTION IF EXISTS fixture_reject_async_penalty()`) + req.RequestID += "-rollback" + req.PenaltyContext.RequestID = req.RequestID + req.PenaltyContext.SessionKey = "fixture-rollback-session" + require.True(t, coordinator.Check(ctx, req).AllowNextStage) + svc.enqueueWG.Wait() + var jobCount, eventCount int + require.NoError(t, db.QueryRow("SELECT count(*) FROM prompt_audit_jobs").Scan(&jobCount)) + require.NoError(t, db.QueryRow("SELECT count(*) FROM prompt_audit_events").Scan(&eventCount)) + require.Equal(t, 1, jobCount, "failed penalty cannot leave a successful async job") + require.Equal(t, 1, eventCount, "event and penalty must commit in one transaction") + }) + } +} + +// Uses real PostgreSQL event/job persistence and real Redis payload storage. +// Reflection only lets the unchanged test compile on the pre-provenance RED; +// that baseline actually evaluates/persists the canary and must fail below. +func TestRecoveredContextAuditPersistence(t *testing.T) { + for _, mode := range []string{"blocking_allow", "blocking_risk", "async"} { + t.Run(mode, func(t *testing.T) { + require.NotEmpty(t, os.Getenv(promptAuditPostgresTestEnv), "isolated PostgreSQL is required; cannot skip evidence") + address := os.Getenv(promptAuditRedisTestEnv) + require.NotEmpty(t, address, "isolated Redis is required; cannot skip evidence") + db := openPromptAuditIntegrationDB(t) + client := redis.NewClient(&redis.Options{Addr: address, DB: 14}) + t.Cleanup(func() { _ = client.Close() }) + ctx := context.Background() + require.NoError(t, client.FlushDB(ctx).Err()) + defer client.FlushDB(ctx) + user, key := insertIdentity(t, db, "users"), insertIdentity(t, db, "api_keys") + repo := NewPostgreSQLRepository(db) + cfg := guardConfig(ActiveEndpoint{ID: "fixture", Enabled: true, TimeoutMS: 1000, InputLimit: 10000}) + cfg.AllGroups, cfg.StorePassEvents, cfg.QueueCapacity = true, true, 8 + cfg.BlockingEnabled = mode != "async" + config := &fakeConfigStore{cfg: cfg, active: true} + scanner := &recoveredPromptScanner{block: mode == "blocking_risk"} + svc := NewPromptService(config, repo, NewRedisPayloadStore(client), nil, NewAtomicMetrics()) + svc.evaluator = NewGuardEvaluator(scanner, repo, NewAtomicMetrics()) + svc.background = ctx + body, err := json.Marshal(map[string]any{"input": []any{map[string]any{"role": "user", "content": recoveredPromptCanary}}}) + require.NoError(t, err) + req := Request{RequestID: "recovered-" + mode, UserID: user, APIKeyID: key, Protocol: "openai_responses", Model: "fixture", Body: body} + field := reflect.ValueOf(&req).Elem().FieldByName("NoBodyRetention") + if field.IsValid() { + field.SetBool(true) + } + if mode == "async" { + require.NoError(t, svc.Enqueue(ctx, req)) + svc.enqueueWG.Wait() + } else { + decision, err := svc.Evaluate(ctx, req) + require.NoError(t, err) + require.NotNil(t, decision) + require.Equal(t, mode != "blocking_risk", decision.AllowNextStage, "privacy must not weaken moderation") + } + var jobs, events string + require.NoError(t, db.QueryRow("SELECT COALESCE(string_agg(row_to_json(t)::text, ''), '') FROM prompt_audit_jobs t").Scan(&jobs)) + require.NoError(t, db.QueryRow("SELECT COALESCE(string_agg(row_to_json(t)::text, ''), '') FROM prompt_audit_events t").Scan(&events)) + keys, err := client.Keys(ctx, PayloadKeyPrefix+"*").Result() + require.NoError(t, err) + persisted := jobs + events + for _, key := range keys { + value, err := client.Get(ctx, key).Result() + require.NoError(t, err) + persisted += value + } + require.NotContains(t, persisted, recoveredPromptCanary, "SHADOW_AUDIT_BODY_RETAINED: recovered text must not leave its bounded shadow store") + require.Equal(t, 1, scanner.calls, "recovered text must still be evaluated") + require.NotEmpty(t, events, "metadata decision must remain auditable") + require.Empty(t, keys, "recovered text must never enter the durable asynchronous payload queue") + }) + } +} diff --git a/backend/internal/securityaudit/prompt_repository.go b/backend/internal/securityaudit/prompt_repository.go index 211ca6be4285..f54d1e02595a 100644 --- a/backend/internal/securityaudit/prompt_repository.go +++ b/backend/internal/securityaudit/prompt_repository.go @@ -187,6 +187,56 @@ func (r *PostgreSQLRepository) Complete(ctx context.Context, job *Job, result *N return nil, err } defer func() { _ = tx.Rollback() }() + event, err := completePromptAuditTx(ctx, tx, job, result, storePassEvents, finding) + if err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, err + } + return event, nil +} + +// Recovered text never enters the durable queue or payload store. Its finished +// metadata and penalty are committed together using the same hook and completion +// transaction as Runner.Complete; failed penalty writes roll back the event too. +func (r *PostgreSQLRepository) RecordRecoveredAsync(ctx context.Context, snapshot PromptSnapshot, configVersion int64, result *NormalizedResult, storePassEvents bool) (*Event, error) { + if r == nil || r.db == nil || result == nil || !snapshot.NoBodyRetention { + return nil, errors.New("recovered async completion requires private snapshot and result") + } + result = promptResultForRetention(snapshot, result) + var finding func(*sql.Tx, PromptSnapshot, *NormalizedResult) error + if r.prepareFinding != nil && result.Action == ActionBlock { + var err error + finding, err = r.prepareFinding(ctx) + if err != nil { + return nil, err + } + } + tx, err := r.db.BeginTx(ctx, nil) + if err != nil { + return nil, err + } + defer func() { _ = tx.Rollback() }() + job, err := insertJob(ctx, tx, snapshot.Redacted(), ModeAsync, configVersion, "processing", 1) + if err != nil { + return nil, err + } + job.Snapshot = snapshot.Redacted() + if _, err = tx.ExecContext(ctx, `UPDATE prompt_audit_jobs SET attempts=1, processing_started_at=NOW() WHERE id=$1`, job.ID); err != nil { + return nil, err + } + event, err := completePromptAuditTx(ctx, tx, job, result, storePassEvents, finding) + if err != nil { + return nil, err + } + if err := tx.Commit(); err != nil { + return nil, err + } + return event, nil +} + +func completePromptAuditTx(ctx context.Context, tx *sql.Tx, job *Job, result *NormalizedResult, storePassEvents bool, finding func(*sql.Tx, PromptSnapshot, *NormalizedResult) error) (*Event, error) { updateResult, err := tx.ExecContext(ctx, ` UPDATE prompt_audit_jobs SET status='done', processed_at=NOW(), updated_at=NOW(), last_error_code='', last_error_message='' @@ -206,9 +256,6 @@ func (r *PostgreSQLRepository) Complete(ctx context.Context, job *Job, result *N return nil, err } } - if err := tx.Commit(); err != nil { - return nil, err - } return event, nil } diff --git a/backend/internal/securityaudit/prompt_service.go b/backend/internal/securityaudit/prompt_service.go index 322d3c75e3c4..211df6cdc4a0 100644 --- a/backend/internal/securityaudit/prompt_service.go +++ b/backend/internal/securityaudit/prompt_service.go @@ -23,13 +23,15 @@ type PromptService struct { metrics *AtomicMetrics clock Clock - lifecycleMu sync.Mutex - cancel context.CancelFunc - background context.Context - enqueueWG sync.WaitGroup - enqueueSlots chan struct{} - probeMu sync.RWMutex - probes map[string]ProbeResult + lifecycleMu sync.Mutex + cancel context.CancelFunc + background context.Context + stopping bool + enqueueWG sync.WaitGroup + enqueueSlots chan struct{} + recoveredSlots chan struct{} + probeMu sync.RWMutex + probes map[string]ProbeResult } func NewPromptService( @@ -46,7 +48,7 @@ func NewPromptService( return &PromptService{ config: config, repo: repo, payload: payload, scanner: scanner, metrics: metrics, enqueuer: enqueuer, evaluator: evaluator, runner: runner, clock: realClock{}, - enqueueSlots: make(chan struct{}, 128), probes: map[string]ProbeResult{}, + enqueueSlots: make(chan struct{}, 128), recoveredSlots: make(chan struct{}, 8), probes: map[string]ProbeResult{}, } } @@ -60,6 +62,7 @@ func (s *PromptService) Start(ctx context.Context) error { return nil } background, cancel := context.WithCancel(ctx) + s.stopping = false s.background, s.cancel = background, cancel s.lifecycleMu.Unlock() configErr := s.config.Start(background) @@ -74,6 +77,8 @@ func (s *PromptService) Shutdown(ctx context.Context) error { s.lifecycleMu.Lock() cancel := s.cancel s.cancel = nil + s.stopping = true + s.background = nil s.lifecycleMu.Unlock() if cancel != nil { cancel() @@ -108,10 +113,13 @@ func (s *PromptService) EffectiveMode() Mode { return s.config.EffectiveMode() } -func (s *PromptService) Enqueue(_ context.Context, req Request) error { +func (s *PromptService) Enqueue(ctx context.Context, req Request) error { if s == nil || s.enqueuer == nil || s.EffectiveMode() != ModeAsync { return nil } + if req.NoBodyRetention { + return s.enqueueRecovered(req) + } select { case s.enqueueSlots <- struct{}{}: default: @@ -123,13 +131,14 @@ func (s *PromptService) Enqueue(_ context.Context, req Request) error { } s.lifecycleMu.Lock() background := s.background - s.lifecycleMu.Unlock() - if background == nil { + if background == nil || s.stopping { + s.lifecycleMu.Unlock() <-s.enqueueSlots return errors.New("prompt audit service not started") } - requestCopy := req.Clone() s.enqueueWG.Add(1) + s.lifecycleMu.Unlock() + requestCopy := req.Clone() go func() { defer s.enqueueWG.Done() defer func() { <-s.enqueueSlots }() @@ -140,6 +149,74 @@ func (s *PromptService) Enqueue(_ context.Context, req Request) error { return nil } +func (s *PromptService) enqueueRecovered(req Request) error { + // Eight in-flight jobs, <=128KiB each, no waiting queue, <=30s lifetime. + // Acquire before cloning so an overload never retains unbounded plaintext. + if len(req.Body) > 128*1024 { + return errors.New("recovered audit payload too large") + } + select { + case s.recoveredSlots <- struct{}{}: + default: + if s.metrics != nil { + s.metrics.IncDropped() + } + LogWarn(EventEnqueueDropped, map[string]any{"request_id": req.RequestID, "status": "dropped", "error_code": "recovered_enqueue_busy"}) + return ErrQueueFull + } + s.lifecycleMu.Lock() + background := s.background + if background == nil || s.stopping { + s.lifecycleMu.Unlock() + <-s.recoveredSlots + return errors.New("prompt audit service not started") + } + s.enqueueWG.Add(1) + s.lifecycleMu.Unlock() + copy := req.Clone() + go func() { + defer s.enqueueWG.Done() + defer func() { <-s.recoveredSlots }() + defer func() { + if recover() != nil { + LogError(EventProcessFailed, map[string]any{"request_id": copy.RequestID, "status": "failed", "error_code": "recovered_worker_panic"}) + } + }() + ctx, cancel := context.WithTimeout(background, 30*time.Second) + defer cancel() + if err := s.processRecovered(ctx, copy); err != nil { + if s.metrics != nil { + s.metrics.IncRecordFailed() + } + LogWarn(EventProcessFailed, map[string]any{"request_id": copy.RequestID, "status": "failed", "error_code": "recovered_audit_failed"}) + } + }() + return nil +} + +func (s *PromptService) processRecovered(ctx context.Context, req Request) error { + cfg, ok := s.config.Active() + if !ok || cfg.EffectiveMode() != ModeAsync || !cfg.IncludesGroup(req.GroupID) { + return nil + } + snapshot, err := ExtractPromptSnapshot(req) + if errors.Is(err, ErrNoPromptText) { + return nil + } + if err != nil { + return err + } + decision, err := s.evaluator.evaluate(ctx, cfg, snapshot, false) + if err != nil { + return err + } + if decision == nil || decision.Result == nil { + return errors.New("recovered audit result unavailable") + } + _, err = s.repo.RecordRecoveredAsync(ctx, snapshot, cfg.ConfigVersion, decision.Result, cfg.StorePassEvents) + return err +} + func (s *PromptService) Evaluate(ctx context.Context, req Request) (*PromptDecision, error) { if s == nil || s.config == nil || s.evaluator == nil { return nil, &GuardError{Code: ErrorCodeUnavailable} diff --git a/backend/internal/securityaudit/prompt_snapshot.go b/backend/internal/securityaudit/prompt_snapshot.go index 0013d1422d67..202a33b5f569 100644 --- a/backend/internal/securityaudit/prompt_snapshot.go +++ b/backend/internal/securityaudit/prompt_snapshot.go @@ -67,7 +67,7 @@ func extractPromptSnapshot(req Request, latestTurnOnly bool) (PromptSnapshot, er PromptHash: hex.EncodeToString(digest[:]), RedactedPreview: BuildPromptPreview(metadataText, DefaultPromptPreviewMaxRunes), FullPrompt: BuildFullPrompt(metadataText, DefaultFullPromptMaxRunes), PromptLength: utf8.RuneCountInString(metadataText), MessageCount: len(segments), Stage: stage, - ScanText: scanText, PenaltyContext: req.PenaltyContext, + ScanText: scanText, PenaltyContext: req.PenaltyContext, NoBodyRetention: req.NoBodyRetention, }, nil } diff --git a/backend/internal/securityaudit/prompt_types.go b/backend/internal/securityaudit/prompt_types.go index bcd9de53b9f1..a86ca3099cbf 100644 --- a/backend/internal/securityaudit/prompt_types.go +++ b/backend/internal/securityaudit/prompt_types.go @@ -2,9 +2,9 @@ package securityaudit import ( "context" + "time" "github.com/Wei-Shaw/sub2api/internal/service" - "time" ) const ( @@ -85,6 +85,7 @@ type Request struct { Protocol string Model string Body []byte + NoBodyRetention bool Stage string PenaltyContext PenaltyRequestContext } @@ -118,12 +119,17 @@ type PromptSnapshot struct { MessageCount int `json:"message_count"` Stage string `json:"stage"` - PenaltyContext PenaltyRequestContext `json:"penalty_context,omitempty"` - ScanText string `json:"-"` + PenaltyContext PenaltyRequestContext `json:"penalty_context,omitempty"` + ScanText string `json:"-"` + NoBodyRetention bool `json:"no_body_retention,omitempty"` } func (s PromptSnapshot) Redacted() PromptSnapshot { s.ScanText = "" + if s.NoBodyRetention { + s.FullPrompt = "[Recovered context withheld]" + s.RedactedPreview = "[Recovered context withheld]" + } return s } diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index 676ee5a4a4b0..019753643dc4 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -350,6 +350,7 @@ type ContentModerationCheckInput struct { UpstreamConfig *ContentModerationConfig // Frozen policy for a selected attempt. moderationVersion *int64 riskControlLogOnly bool // Captured at admission and retained by asynchronous tasks. + noBodyRetention bool RequestID string UserID int64 UserEmail string @@ -886,6 +887,7 @@ func (s *ContentModerationService) TestAPIKeys(ctx context.Context, input TestCo } func (s *ContentModerationService) Check(ctx context.Context, input ContentModerationCheckInput) (decision *ContentModerationDecision, err error) { + input.noBodyRetention = HasRecoveredContextPrivacy(ctx) allow := &ContentModerationDecision{Allowed: true, Action: ContentModerationActionAllow} if s == nil || s.settingRepo == nil || s.repo == nil { slog.Info("content_moderation.skip_unavailable", @@ -1019,8 +1021,11 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer } if cfg.Mode == ContentModerationModePreBlock { if (moderationState == nil || !moderationState.KeywordExempt) && cfg.KeywordBlockingMode != ContentModerationKeywordModeAPIOnly && len(cfg.BlockedKeywords) > 0 { - keywordText := extractContentModerationKeywordText(input.Protocol, input.Body) + keywordText := extractContentModerationInput(input.Protocol, input.Body, false, input.noBodyRetention).Text if keyword, hit := runtimeSnapshot.matchBlockedKeyword(keywordText); hit { + if input.noBodyRetention { + keyword = "[Recovered context withheld]" + } metricAction := ContentModerationActionKeywordBlock if input.riskControlLogOnly { metricAction = ContentModerationActionAllow @@ -1062,7 +1067,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer return allow, nil } } - content := ExtractContentModerationInput(input.Protocol, input.Body) + content := extractContentModerationInput(input.Protocol, input.Body, true, input.noBodyRetention) if content.IsEmpty() { slog.Info("content_moderation.skip_empty_input", "user_id", input.UserID, @@ -1170,6 +1175,9 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer } func (s *ContentModerationService) checkSync(ctx context.Context, input ContentModerationCheckInput, cfg *ContentModerationConfig, content ContentModerationInput, hashText string, queueDelay *int, allowBlock bool) *ContentModerationDecision { + if input.noBodyRetention { + ctx = WithRecoveredContextPrivacy(ctx) + } allow := &ContentModerationDecision{Allowed: true, Action: ContentModerationActionAllow} // Observe tasks may wait in the queue while an administrator grants an // exemption. Recheck immediately before sending; never introduce keywords here. @@ -1892,6 +1900,9 @@ func (s *ContentModerationService) callModeration(ctx context.Context, cfg *Cont if trackLoad { s.finishModerationAPIKeyCall(key, latency, false, cfg.Engine) } + if HasRecoveredContextPrivacy(ctx) { + err = errors.New("moderation request failed") + } s.markAPIKeyError(key, err.Error(), latency, httpStatus, cfg.Engine) lastErr = err if httpStatus == http.StatusBadRequest { @@ -2035,6 +2046,12 @@ func (s *ContentModerationService) resolveModerationProxyURL(ctx context.Context } func (s *ContentModerationService) buildLog(input ContentModerationCheckInput, cfg *ContentModerationConfig, action string, flagged bool, highestCategory string, highestScore float64, scores map[string]float64, text string, latency *int, queueDelay *int, errText string) *ContentModerationLog { + if input.noBodyRetention { + text = "[Recovered context withheld]" + if errText != "" { + errText = "moderation request failed" + } + } var userID *int64 if input.UserID > 0 { userID = &input.UserID diff --git a/backend/internal/service/content_moderation_input.go b/backend/internal/service/content_moderation_input.go index b52adfaa21a1..f7dec1077b79 100644 --- a/backend/internal/service/content_moderation_input.go +++ b/backend/internal/service/content_moderation_input.go @@ -14,20 +14,20 @@ func ExtractContentModerationText(protocol string, body []byte) string { } func ExtractContentModerationInput(protocol string, body []byte) ContentModerationInput { - return extractContentModerationInput(protocol, body, true) + return extractContentModerationInput(protocol, body, true, false) } // Keyword checks share semantic moderation's current-user boundaries, but must // inspect client-supplied reminder blocks as ordinary user text. func extractContentModerationKeywordText(protocol string, body []byte) string { - return extractContentModerationInput(protocol, body, false).Text + return extractContentModerationInput(protocol, body, false, false).Text } type moderationTextCollector struct { filterReminders bool } -func extractContentModerationInput(protocol string, body []byte, filterReminders bool) ContentModerationInput { +func extractContentModerationInput(protocol string, body []byte, filterReminders, recovered bool) ContentModerationInput { collector := moderationTextCollector{filterReminders: filterReminders} if len(body) == 0 || !gjson.ValidBytes(body) { return ContentModerationInput{} @@ -40,7 +40,14 @@ func extractContentModerationInput(protocol string, body []byte, filterReminders case ContentModerationProtocolOpenAIChat: collector.collectLastRoleMessage(gjson.GetBytes(body, "messages"), "user", &parts, &images) case ContentModerationProtocolOpenAIResponses: - collector.collectLastResponsesInput(gjson.GetBytes(body, "input"), &parts, &images) + if recovered { + // A rebuilt task can end in a gateway-authored historical user + // marker. Audit its recovered context, not only that final marker. + collector.collectRecoveredResponsesValue(gjson.GetBytes(body, "instructions"), &parts, &images) + collector.collectRecoveredResponsesValue(gjson.GetBytes(body, "input"), &parts, &images) + } else { + collector.collectLastResponsesInput(gjson.GetBytes(body, "input"), &parts, &images) + } case ContentModerationProtocolGemini: collector.collectLastGeminiContent(gjson.GetBytes(body, "contents"), &parts, &images) case ContentModerationProtocolOpenAIImages: @@ -65,6 +72,35 @@ func extractContentModerationInput(protocol string, body []byte, filterReminders return out } +// Only the server-owned recovered-context provenance enables this traversal. +// Read supported plaintext and images without interpreting opaque fields or +// changing the request sent to the provider. Ordinary requests retain their +// current-user boundary. +func (collector moderationTextCollector) collectRecoveredResponsesValue(value gjson.Result, parts *[]string, images *[]string) { + if value.IsArray() { + value.ForEach(func(_, item gjson.Result) bool { + collector.collectRecoveredResponsesValue(item, parts, images) + return true + }) + return + } + if value.IsObject() { + switch value.Get("type").String() { + case "function_call_output", "custom_tool_call_output": + collector.collectRecoveredResponsesValue(value.Get("output"), parts, images) + return + case "output_text", "summary_text": + collector.addModerationText(parts, value.Get("text").String()) + return + } + if content := value.Get("content"); content.Exists() { + collector.collectRecoveredResponsesValue(content, parts, images) + return + } + } + collector.collectContentValue(value, parts, images) +} + // collectSystemOneInput moderates every client-controlled text of a System One // request: question IDs, every question field except the validated type, // unknown top-level extension fields, and the evaluated state. Object keys are diff --git a/backend/internal/service/openai_400_omit_history.go b/backend/internal/service/openai_400_omit_history.go index d1edf77b382a..bc507ce7071f 100644 --- a/backend/internal/service/openai_400_omit_history.go +++ b/backend/internal/service/openai_400_omit_history.go @@ -8,11 +8,6 @@ import ( "github.com/gin-gonic/gin" ) -func openAI400HistoryRecoveryApplied(ctx context.Context) bool { - r := openAIAgentRecoveryFromContext(ctx) - return r != nil && r.omitted400History -} - func (s *SettingService) IsOpenAI400OmitEncryptedHistoryEnabled(ctx context.Context) bool { if s == nil || s.settingRepo == nil || ctx.Err() != nil { return false @@ -62,7 +57,14 @@ func (s *OpenAIGatewayService) prepareOpenAI400HistoryRecovery(ctx context.Conte if r.delivery == nil || len(r.delivery.keys) != 0 || len(r.outputs) != 0 { return refuse("delivery_unconfirmed") } - if r.preservesHistory() && openAIAgentRecoveryInputDigest(body) != r.inputDigest { + expectedInput := r.inputDigest + if r.omittedHistory && r.apiReplayPrepared { + expectedInput = r.apiInputDigest + } + if r.omittedHistory && r.oauthReplayPrepared { + expectedInput = r.oauthInputDigest + } + if r.preservesHistory() && openAIAgentRecoveryInputDigest(body) != expectedInput { return refuse("history_integrity") } if s.checkOpenAIAgentRecoveryRecords(ctx, r, r.delivery.binding) != nil { @@ -85,6 +87,16 @@ func (s *OpenAIGatewayService) prepareOpenAI400HistoryRecovery(ctx context.Conte // remains unchanged. Original keys/known/owner are retained for record and // route checks; omitted inputs must never be published as consumed inputs. next.inputDigest = openAIAgentRecoveryInputDigest(clean) + if next.omittedHistory && next.apiReplayPrepared { + // The retry skips native adaptation, so its final-send expectation must + // include this omission while retaining the frozen controls and route. + next.apiInputDigest = next.inputDigest + } + if next.omittedHistory && next.oauthReplayPrepared { + // This is the already-built native body. Authorize only the explicit + // 400 input transformation; retain the frozen controls and route. + next.oauthInputDigest = next.inputDigest + } next.items = openAIAgentRecoveryItemDigests(clean) d.Applied, d.Decision = true, "same_account_retry_scheduled" c.Set(openAI400HistoryDiagnosticKey, d) diff --git a/backend/internal/service/openai_400_omit_history_test.go b/backend/internal/service/openai_400_omit_history_test.go index 7adcf72c9b5e..ea3de71a69c3 100644 --- a/backend/internal/service/openai_400_omit_history_test.go +++ b/backend/internal/service/openai_400_omit_history_test.go @@ -152,6 +152,7 @@ func TestOpenAI400HistoryNativeForward(t *testing.T) { if tc.after409 { r := openAIAgentRecoveryFromContext(ctx) r.omittedHistory, r.inputDigest = true, openAIAgentRecoveryInputDigest(body) + r.replayControlsDigest = openAI409ControlsDigest(body) } c.Request = c.Request.WithContext(ctx) _, err := svc.Forward(ctx, c, newStreamLineageHTTPAccount(), body) @@ -185,17 +186,25 @@ func TestOpenAI400HistoryNativeForward(t *testing.T) { } func TestOpenAI400HistorySendGuards(t *testing.T) { - for _, mode := range []string{"unchanged", "task", "tool_result", "order", "account", "credential", "url", "budget", "canceled", "output_started", "delivery_pending", "owner_lookup"} { + for _, mode := range []string{"unchanged", "task", "tool_result", "order", "controls", "account", "credential", "url", "budget", "canceled", "output_started", "delivery_pending", "owner_lookup"} { t.Run(mode, func(t *testing.T) { svc := newStreamLineageHTTPService(nil) enableHistory400(svc, true) c, rec := newStreamLineageTestContext("history400-guards") c.Set("api_key", &APIKey{ID: 7, AllowLongContext: true}) - body := history400Body(history400Input, false) + body, err := sjson.SetBytes(history400Body(history400Input, false), "parallel_tool_calls", true) + require.NoError(t, err) ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, body, "history400-guards", "gpt-5.1") original := openAIAgentRecoveryFromContext(ctx) original.omittedHistory, original.inputDigest = true, openAIAgentRecoveryInputDigest(body) + original.replayControlsDigest = openAI409ControlsDigest(body) digest := original.inputDigest + // Exercise the same frozen native API-key adaptation as Forward. + body, err = prepareOpenAI409APIKeyReplay(ctx, body, false) + require.NoError(t, err) + require.True(t, original.apiReplayPrepared) + require.False(t, gjson.GetBytes(body, "parallel_tool_calls").Exists()) + apiInput, apiControls := original.apiInputDigest, original.apiControlsDigest account := newStreamLineageHTTPAccount() request := func(body []byte, url string) *http.Request { req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body)) @@ -230,7 +239,10 @@ func TestOpenAI400HistorySendGuards(t *testing.T) { } require.True(t, changed, "%+v; response=%s", openAI400HistoryDiagnostic(c), rec.Body.String()) require.Equal(t, digest, original.inputDigest, "source snapshot is immutable") + require.Equal(t, apiInput, original.apiInputDigest, "source adapter snapshot is immutable") frozen := openAIAgentRecoveryFromContext(next).inputDigest + require.Equal(t, frozen, openAIAgentRecoveryFromContext(next).apiInputDigest) + require.Equal(t, apiControls, openAIAgentRecoveryFromContext(next).apiControlsDigest, "400 omission must not authorize new controls") switch mode { case "task": clean, err = sjson.SetBytes(clean, "input.4.content", "changed task") @@ -238,6 +250,8 @@ func TestOpenAI400HistorySendGuards(t *testing.T) { clean, err = sjson.SetBytes(clean, "input.3.output", "changed result") case "order": clean, err = sjson.DeleteBytes(clean, "input.2") + case "controls": + clean, err = sjson.SetBytes(clean, "instructions", "unauthorized replacement instructions") case "account": account.ID++ case "credential": diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 126434099d21..4d9773643e40 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -3,10 +3,12 @@ package service import ( "bytes" "context" + "crypto/sha256" "encoding/json" "errors" "strings" "time" + "unicode/utf8" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -27,51 +29,380 @@ func (s *SettingService) IsOpenAI409OmitEncryptedHistoryEnabled(ctx context.Cont return err == nil && strings.TrimSpace(value) == "true" } -// TryOmitOpenAI409History is called only after initial account selection fails, -// before any upstream attempt. It never handles provider responses or retries. +// TryOmitOpenAI409History retains the original pre-send compatibility API. +// HTTP callers use the explicit refusal returned by TryRebuild below. func (s *OpenAIGatewayService) TryOmitOpenAI409History(ctx context.Context, c *gin.Context, body []byte, session, model string, cause error) (context.Context, []byte, bool) { + next, clean, changed, _ := s.TryRebuildOpenAI409History(ctx, c, body, session, model, cause) + return next, clean, changed +} + +func (s *OpenAIGatewayService) TryRebuildOpenAI409History(ctx context.Context, c *gin.Context, body []byte, session, model string, cause error) (context.Context, []byte, bool, error) { var refusal *OpenAIAgentRecoveryError - if !errors.As(cause, &refusal) || (refusal.Reason != "owner_unavailable" && refusal.Reason != "route_changed" && refusal.Reason != "wire_changed") { - return ctx, body, false + if !errors.As(cause, &refusal) { + return ctx, body, false, nil } r := openAIAgentRecoveryFromContext(ctx) - if s == nil || r == nil || r.owner == nil || r.conflict || r.lookupErr != nil || r.disallowLearning || r.omittedHistory || - r.owner.pending != "" || r.owner.failed || r.owner.conflicted || + allowed := refusal.Reason == "owner_unavailable" || refusal.Reason == "route_changed" || refusal.Reason == "wire_changed" || + refusal.Reason == "http_previous_response_unsupported" || (refusal.Reason == "owner_conflict" && r != nil && r.mixedOwners) + if !allowed || s == nil || r == nil || r.disallowLearning || r.omittedHistory || r.delivery != nil || s.settingService == nil || !s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { - return ctx, body, false + return ctx, body, false, nil + } + 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 len(r.items) == 0 && !openAI409HasProviderState(body) { + return ctx, body, false, nil + } + if !openAI409HasReadableIntent(body) { + return ctx, body, false, openAIAgentRecoveryError("readable_intent_missing") } clean, changed := omitOpenAIHistoricalCiphertext(body) - if !changed || ctx.Err() != nil { - return ctx, body, false - } - // Freeze the same narrowly normalized replay metadata that native Responses - // will send. Do this before recording the digest, never after arbitrary - // forwarder transformations. Readable content and call relationships stay - // covered by the original exact-input gate. - clean, err := normalizeOpenAI409ReplayMetadata(clean) + if ctx.Err() != nil { + return ctx, body, false, openAIAgentRecoveryError("store_unavailable") + } + if !changed { + return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") + } + // Build portable readable history before freezing it. Native Responses + // normalization otherwise drops reasoning.content and (with store=false) + // whole plaintext reasoning items after this snapshot, causing a local 409. + // Never rebase the digest on the forwarder's potentially lossy result. + clean, err := prepareOpenAI409ReadableReplay(clean) if err != nil { - return ctx, body, false + return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") } - next := s.WithOpenAIAgentMessageRecovery(ctx, c, clean, session, model) + fresh := context.WithValue(ctx, openAIGuardianParentAffinityContextKey{}, openAIGuardianParentAffinity{}) + next := s.WithOpenAIAgentMessageRecovery(WithOpenAIEncryptedReasoningAffinity(fresh, clean), c, clean, session, model) request := openAIAgentRecoveryFromContext(next) // Preserve the sanitized input at the actual send and reuse the existing // native HTTP delivery fence and no-replay gates. Old owner records stay put. request.omittedHistory = true request.inputDigest = openAIAgentRecoveryInputDigest(clean) - return next, clean, true + request.replayControlsDigest = openAI409ControlsDigest(clean) + request.omittedSource = r + return next, clean, true, nil +} + +// Provider state and mixed completed producers cannot be forwarded as one new +// account's conversation. Rebuild before selection, after all item fences were +// read. A healthy single producer without pointers retains ordinary routing. +func (s *OpenAIGatewayService) PrepareOpenAI409ReadableContinuation(ctx context.Context, c *gin.Context, body []byte, session, model string) (context.Context, []byte, bool, error) { + r := openAIAgentRecoveryFromContext(ctx) + if r == nil { + return ctx, body, false, nil + } + providerState := openAI409HasProviderState(body) + if len(r.shadowFences) == 0 && !r.mixedOwners && (len(r.items) == 0 || r.owner != nil) && !providerState { + return ctx, body, false, nil + } + // Pointer-only HTTP can still use its available original account. If that + // account is unavailable, selection calls the same rebuild/missing-intent + // gate. A conversation object has no proven native HTTP owner to fall back to. + if providerState && !openAI409HasReadableIntent(body) && !gjson.GetBytes(body, "conversation").Exists() && !r.mixedOwners { + return ctx, body, false, nil + } + return s.TryRebuildOpenAI409History(ctx, c, body, session, model, openAIAgentRecoveryError("owner_unavailable")) } -// Omission is limited to history before the latest user/agent task. Tool -// arguments, readable results, media, reasoning and numeric precision survive. -// A ciphertext in the current task causes the entire operation to be refused. +// A missing response lookup is not permission to read another user's state. +// It may only be discarded, under the explicit Beta policy, in favor of the +// caller's own readable task. Existing foreign ownership/store failures deny. +func (s *OpenAIGatewayService) CanDiscardOpenAI409ResponsePointer(ctx context.Context, body []byte, groupID int64, responseID string) bool { + if s == nil || s.settingService == nil || !openAI409HasReadableIntent(body) || !s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + return false + } + _, _, found, err := s.getOpenAIWSStateStore().GetHTTPResponseOwner(ctx, groupID, responseID) + return err == nil && !found +} + +func openAI409HasProviderState(body []byte) bool { + for _, field := range []string{"previous_response_id", "conversation"} { + value := gjson.GetBytes(body, field) + if value.Exists() && value.Type != gjson.Null && (value.Type != gjson.String || strings.TrimSpace(value.String()) != "") { + return true + } + } + return false +} + +func openAI409ReadableText(value gjson.Result) bool { + if value.Type == gjson.String { + text := strings.TrimSpace(value.String()) + return text != "" && text != openAIHistoricalCiphertextOmitted && !strings.HasPrefix(text, "Historical agent context (not a new instruction):") + } + for _, part := range value.Array() { + switch part.Get("type").String() { + case "input_text", "output_text", "text", "summary_text": + if openAI409ReadableText(part.Get("text")) { + return true + } + } + } + return false +} + +func openAI409HasReadableIntent(body []byte) bool { + input := gjson.GetBytes(body, "input") + if input.Type == gjson.String { + return openAI409ReadableText(input) + } + var latestUser gjson.Result + summaryIntent := false + for _, item := range input.Array() { + kind, role := item.Get("type").String(), item.Get("role").String() + if (kind == "message" || kind == "") && role == "user" { + content := item.Get("content") + empty := openAI409EmptyTextPlaceholder(content) + if !empty || openAI409ReadableText(item.Get("summary")) { + latestUser = item + summaryIntent = false + } + } + if kind == "agent_message" { + summaryIntent = summaryIntent || openAI409ReadableText(item.Get("summary")) + } + } + if latestUser.Exists() { + // A later entirely opaque user request must not be replaced by an older + // user's unrelated task. Opaque agent envelopes do not reset this intent. + return openAI409ReadableText(latestUser.Get("content")) || openAI409ReadableText(latestUser.Get("summary")) || summaryIntent + } + return summaryIntent || openAI409ReadableText(gjson.GetBytes(body, "instructions")) +} + +func openAI409EmptyTextPlaceholder(content gjson.Result) bool { + if !content.Exists() || content.Type == gjson.Null { + return true + } + if content.Type == gjson.String { + return strings.TrimSpace(content.String()) == "" + } + if !content.IsArray() { + return false + } + for _, part := range content.Array() { + kind := part.Get("type").String() + text := part.Get("text") + if (kind != "input_text" && kind != "text" && kind != "output_text") || text.Type != gjson.String || strings.TrimSpace(text.String()) != "" { + return false // Opaque/media/unknown parts may be a new task. + } + } + return true +} + +// The latest available readable task, not the last opaque item's position, +// determines whether loss is possible. Tool calls/results and readable input +// remain; provider pointers are detached only as part of this same rebuild. func omitOpenAIHistoricalCiphertext(raw []byte) ([]byte, bool) { - return omitOpenAIHistoricalCiphertextForRecovery(raw, false) + if !utf8.Valid(raw) || !openAIEncryptedJSONUnambiguous(raw) || !openAI409HasReadableIntent(raw) { + return raw, false + } + var source map[string]any + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.UseNumber() + if decoder.Decode(&source) != nil { + return raw, false + } + input, ok := source["input"].([]any) + if text, textInput := source["input"].(string); textInput { + input, ok = []any{map[string]any{"type": "message", "role": "user", "content": text}}, true + source["input"] = input + } + if (source["input"] == nil || (ok && len(input) == 0)) && openAI409ReadableText(gjson.GetBytes(raw, "instructions")) { + // Instructions-only callers also supplied a real task. Carry it in the + // protected input when rebuilding instead of sending an empty task. + input, ok = []any{map[string]any{"type": "message", "role": "user", "content": source["instructions"]}}, true + source["input"] = input + } + if !ok { + return raw, false + } + changed := false + for _, field := range []string{"previous_response_id", "conversation"} { + if _, exists := source[field]; exists { + delete(source, field) + changed = true + } + } + for i, value := range input { + item, _ := value.(map[string]any) + kind, _ := item["type"].(string) + field, textKind := "content", "input_text" + switch kind { + case "item_reference": + input[i] = map[string]any{"type": "message", "role": "assistant", "content": openAIHistoricalCiphertextOmitted} + changed = true + continue + case "compaction", "compaction_summary": + readable, _ := json.Marshal(openAI409ReadableMetadata(map[string]any{"content": item["content"], "summary": item["summary"]})) + input[i] = map[string]any{"type": "message", "role": "assistant", "content": "Historical compaction context (JSON): " + string(readable) + "\n" + openAIHistoricalCiphertextOmitted} + changed = true + continue + case "", "message", "agent_message": + if item["role"] == "assistant" { + textKind = "output_text" + } + case "function_call_output", "custom_tool_call_output": + field = "output" + default: + continue + } + itemChanged := false + if kind == "agent_message" { + if encrypted, exists := item["encrypted_content"]; exists && encrypted != nil && encrypted != "" { + marker := map[string]any{"type": "input_text", "text": openAIHistoricalCiphertextOmitted} + switch content := item["content"].(type) { + case []any: + item["content"] = append(content, marker) + case string: + item["content"] = []any{map[string]any{"type": "input_text", "text": content}, marker} + case nil: + item["content"] = []any{marker} + default: + readable, _ := json.Marshal(openAI409ReadableMetadata(content)) + item["content"] = []any{map[string]any{"type": "input_text", "text": string(readable)}, marker} + } + delete(item, "encrypted_content") + itemChanged = true + } + } + if parts, ok := item[field].([]any); ok { + for j, rawPart := range parts { + part, _ := rawPart.(map[string]any) + if part["type"] == "encrypted_content" { + parts[j] = map[string]any{"type": textKind, "text": openAIHistoricalCiphertextOmitted} + itemChanged = true + } + } + } + if kind == "agent_message" { + // Native Responses accepts ordinary user context without requiring an + // opaque agent envelope. Keep attribution explicit in readable text. + metadata, _ := json.Marshal(map[string]any{"author": item["author"], "recipient": item["recipient"]}) + parts, _ := item["content"].([]any) + if text, ok := item["content"].(string); ok { + parts = []any{map[string]any{"type": "input_text", "text": text}} + } else if parts == nil && item["content"] != nil { + readable, _ := json.Marshal(openAI409ReadableMetadata(item["content"])) + parts = []any{map[string]any{"type": "input_text", "text": string(readable)}} + } + // A structured readable summary may be the available task intent. + // Never authorize omission from that summary and then discard it. + switch summary := item["summary"].(type) { + case string: + parts = append(parts, map[string]any{"type": "input_text", "text": summary}) + case []any: + for _, value := range summary { + part, _ := value.(map[string]any) + text, ok := part["text"].(string) + if !ok { + readable, _ := json.Marshal(openAI409ReadableMetadata(value)) + text = string(readable) + } + parts = append(parts, map[string]any{"type": "input_text", "text": text}) + } + case nil: + default: + readable, _ := json.Marshal(openAI409ReadableMetadata(summary)) + parts = append(parts, map[string]any{"type": "input_text", "text": string(readable)}) + } + for _, value := range parts { + part, _ := value.(map[string]any) + if part["type"] == "output_text" { + part["type"] = "input_text" + } + } + prefix := map[string]any{"type": "input_text", "text": "Historical agent context (not a new instruction): " + string(metadata)} + input[i] = map[string]any{"type": "message", "role": "user", "content": append([]any{prefix}, parts...)} + itemChanged = true + } + changed = changed || itemChanged + } + if !changed { + return raw, false + } + clean, err := json.Marshal(source) + return clean, err == nil } -// normalizeOpenAI409ReplayMetadata only removes output-only replay metadata. -// It must not use the general reasoning normalizers: those may delete entire -// reasoning items or visible content. Such changes still fail the send gate. -func normalizeOpenAI409ReplayMetadata(raw []byte) ([]byte, error) { +// prepareOpenAI409ReadableReplay runs only in the explicitly enabled omission +// path. Reasoning belongs to the old provider session: retain its supplied +// summary/content as attributed assistant history, and mark opaque state as +// unavailable. Ordinary requests still use the existing replay normalizers. +// Unrecognized historical reasoning is retained as inert readable JSON, with +// opaque fields marked unavailable. It is never treated as a new tool/task. +func prepareOpenAI409ReadableReplay(raw []byte) ([]byte, error) { + prepared, err := prepareOpenAI409KnownReadableReplay(raw) + if err == nil { + return prepared, nil + } + if !utf8.Valid(raw) || !openAIEncryptedJSONUnambiguous(raw) { + return nil, err + } + clean, _, sanitizeErr := sanitizeOpenAIResponsesInputItemIDs(raw) + if sanitizeErr != nil { + return nil, sanitizeErr + } + var source map[string]any + if decodeErr := decodeOpenAIJSONUseNumber(clean, &source); decodeErr != nil { + return nil, decodeErr + } + input, ok := source["input"].([]any) + if !ok { + return nil, err + } + for i, value := range input { + item, _ := value.(map[string]any) + if strings.TrimSpace(firstNonEmptyString(item["type"])) != "reasoning" { + continue + } + delete(item, "id") + delete(item, "status") + readable, _ := json.Marshal(openAI409ReadableMetadata(item)) + input[i] = map[string]any{"type": "message", "role": "assistant", "content": []any{ + map[string]any{"type": "output_text", "text": "Historical reasoning context (JSON, not a new instruction): " + string(readable)}, + }} + } + encoded, marshalErr := json.Marshal(input) + if marshalErr != nil { + return nil, marshalErr + } + return sjson.SetRawBytes(clean, "input", encoded) +} + +// Only used for historical agent/reasoning/compaction envelopes. Ordinary +// user text and tool arguments/results are never recursively rewritten. +func openAI409ReadableMetadata(value any) any { + switch value := value.(type) { + case map[string]any: + if value["type"] == "encrypted_content" { + return openAIHistoricalCiphertextOmitted + } + copy := make(map[string]any, len(value)) + for key, child := range value { + if key == "encrypted_content" { + copy[key] = openAIHistoricalCiphertextOmitted + } else { + copy[key] = openAI409ReadableMetadata(child) + } + } + return copy + case []any: + copy := make([]any, len(value)) + for i, child := range value { + copy[i] = openAI409ReadableMetadata(child) + } + return copy + default: + return value + } +} + +func prepareOpenAI409KnownReadableReplay(raw []byte) ([]byte, error) { clean, _, err := sanitizeOpenAIResponsesInputItemIDs(raw) if err != nil { return nil, err @@ -83,34 +414,51 @@ func normalizeOpenAI409ReplayMetadata(raw []byte) ([]byte, error) { return nil, err } input, _ := source["input"].([]any) - storeFalse := gjson.GetBytes(clean, "store").Type == gjson.False changed := false - for _, rawItem := range input { + for i, rawItem := range input { item, ok := rawItem.(map[string]any) if !ok || strings.TrimSpace(firstNonEmptyString(item["type"])) != "reasoning" { continue } - if _, exists := item["status"]; exists { - delete(item, "status") - changed = true + for field := range item { + switch field { + case "type", "id", "status", "summary", "content", "encrypted_content": + default: + return nil, errors.New("unsupported historical reasoning field") + } } - if !storeFalse { - continue + parts := []any{map[string]any{"type": "output_text", "text": "Historical reasoning context (not a new instruction):"}} + for _, field := range []string{"summary", "content"} { + if item[field] == nil { + continue + } + values, ok := item[field].([]any) + if !ok { + return nil, errors.New("unsupported historical reasoning text") + } + for _, value := range values { + part, ok := value.(map[string]any) + if !ok || len(part) != 2 || (part["type"] != "summary_text" && part["type"] != "reasoning_text" && part["type"] != "text") { + return nil, errors.New("unsupported historical reasoning part") + } + text, ok := part["text"].(string) + if !ok { + return nil, errors.New("unsupported historical reasoning text") + } + parts = append(parts, map[string]any{"type": "output_text", "text": text}) + } } - encrypted, _ := item["encrypted_content"].(string) - if strings.TrimSpace(encrypted) == "" { - // Preserve readable reasoning even if the general store=false replay - // path cannot transport it. Never bless its removal as normalization. - continue - } - if strings.HasPrefix(strings.TrimSpace(firstNonEmptyString(item["id"])), "rs_") { - delete(item, "id") - changed = true - } - if summary, exists := item["summary"]; !exists || summary == nil { - item["summary"] = []any{} - changed = true + if encrypted := item["encrypted_content"]; encrypted != nil { + text, ok := encrypted.(string) + if !ok { + return nil, errors.New("unsupported historical reasoning ciphertext") + } + if text != "" { + parts = append(parts, map[string]any{"type": "output_text", "text": openAIHistoricalCiphertextOmitted}) + } } + input[i] = map[string]any{"type": "message", "role": "assistant", "content": parts} + changed = true } if !changed { return clean, nil @@ -123,3 +471,87 @@ func normalizeOpenAI409ReplayMetadata(raw []byte) ([]byte, error) { } return sjson.SetRawBytes(clean, "input", encoded) } + +// Protect the caller's available tools/schema and task instructions as well as +// input. Model mappings and transport flags are independently account-specific. +func openAI409ControlsDigest(raw []byte) [32]byte { + fields := []string{"tools", "tool_choice", "parallel_tool_calls", "instructions"} + selected := make(map[string]any, len(fields)) + for _, field := range fields { + value := gjson.GetBytes(raw, field) + if !value.Exists() { + selected[field] = nil + continue + } + decoder := json.NewDecoder(strings.NewReader(value.Raw)) + decoder.UseNumber() + var decoded any + if decoder.Decode(&decoded) != nil { + return [32]byte{} + } + selected[field] = []any{true, decoded} // Presence is distinct from null. + } + canonical, err := json.Marshal(selected) + if err != nil { + return [32]byte{} + } + return sha256.Sum256(canonical) +} + +func prepareOpenAI409APIKeyReplay(ctx context.Context, body []byte, responsesLite bool) ([]byte, error) { + r := openAIAgentRecoveryFromContext(ctx) + if r == nil || !r.omittedHistory { + return body, nil + } + if openAIAgentRecoveryInputDigest(body) != r.inputDigest || openAI409ControlsDigest(body) != r.replayControlsDigest { + return nil, openAIAgentRecoveryError("wire_changed") + } + prepared, _, err := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite) + if err != nil { + return nil, err + } + r.apiControlsDigest = openAI409ControlsDigest(prepared) + r.apiInputDigest = openAIAgentRecoveryInputDigest(prepared) + r.apiReplayPrepared = true + return prepared, nil +} + +// The one permitted OAuth adaptation starts by verifying the frozen readable +// input and controls. It only promotes system guidance without dropping it, +// flattens native tool declarations, and applies the existing reserved-name +// mapping jointly to declarations/calls. The general input filter is then +// disabled for this already-built replay. Final wire checks remain exact. +func prepareOpenAI409OAuthReplay(ctx context.Context, c *gin.Context, body map[string]any) error { + r := openAIAgentRecoveryFromContext(ctx) + if r == nil || !r.omittedHistory { + return nil + } + before, err := json.Marshal(body) + if err != nil { + return err + } + if openAIAgentRecoveryInputDigest(before) != r.inputDigest || openAI409ControlsDigest(before) != r.replayControlsDigest { + return openAIAgentRecoveryError("wire_changed") + } + if isInstructionsEmpty(body) { + body["instructions"] = defaultCodexSynthInstructions(firstNonEmptyString(body["model"])) + } + extractSystemMessagesFromInput(body, false) + normalizeCodexTools(body) + reverse, _, err := aliasOpenAIOAuthReservedToolNames(body) + if err != nil { + return err + } + setCodexToolNameReverse(c, reverse) + normalizeCodexToolChoice(body) + prepared, err := json.Marshal(body) + if err != nil { + return err + } + // Retain the original snapshot for any allowed pre-send admission retry. + // Only this narrowly derived OAuth expectation is used at its final send. + r.oauthInputDigest = openAIAgentRecoveryInputDigest(prepared) + r.oauthControlsDigest = openAI409ControlsDigest(prepared) + r.oauthReplayPrepared = true + return nil +} diff --git a/backend/internal/service/openai_409_omit_history_test.go b/backend/internal/service/openai_409_omit_history_test.go index 9f49842d944c..b804b26f4ee1 100644 --- a/backend/internal/service/openai_409_omit_history_test.go +++ b/backend/internal/service/openai_409_omit_history_test.go @@ -3,6 +3,7 @@ package service import ( "bytes" "context" + "encoding/json" "net/http" "strings" "testing" @@ -41,17 +42,16 @@ func TestOmitOpenAIHistoricalCiphertextPreservesReadableContext(t *testing.T) { require.Equal(t, clean, again) } -func TestOmitOpenAIHistoricalCiphertextRefusesCurrentTaskAndPointers(t *testing.T) { +func TestOmitOpenAIHistoricalCiphertextRefusesUnreadableTask(t *testing.T) { for name, raw := range map[string]string{ - "new agent": `{"input":[{"type":"agent_message","encrypted_content":"CURRENT","content":"header"}]}`, - "current user": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":[{"type":"encrypted_content","encrypted_content":"CURRENT"}]}]}`, - "current tool result": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"lookup"},{"type":"function_call_output","call_id":"x","output":[{"type":"encrypted_content","encrypted_content":"CURRENT"}]}]}`, - "response pointer": `{"previous_response_id":"resp_x","input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`, - "conversation": `{"conversation":{"id":"conv_x"},"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`, - "reference": `{"input":[{"type":"item_reference","id":"item_x"},{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`, - "compaction": `{"input":[{"type":"compaction","encrypted_content":"STATE"},{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}]}`, - "duplicate keys": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}],"input":[]}`, - "plain history": `{"input":[{"role":"user","content":"keep encrypted_content as literal text"}]}`, + "new agent": `{"input":[{"type":"agent_message","encrypted_content":"CURRENT","content":"header"}]}`, + "current user": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":[{"type":"encrypted_content","encrypted_content":"CURRENT"}]}]}`, + "pointer only": `{"previous_response_id":"resp_x","input":[]}`, + "guidance only": `{"input":[{"role":"system","content":"You are a coding assistant"},{"type":"agent_message","encrypted_content":"CURRENT"}]}`, + "new opaque part": `{"input":[{"role":"user","content":"old task"},{"role":"user","content":[{"type":"encrypted_content","encrypted_content":"NEW"}]}]}`, + "new media part": `{"input":[{"role":"user","content":"old task"},{"role":"user","content":[{"type":"input_image","image_url":"fixture"}]}]}`, + "duplicate keys": `{"input":[{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":"continue"}],"input":[]}`, + "plain history": `{"input":[{"role":"user","content":"keep encrypted_content as literal text"}]}`, } { t.Run(name, func(t *testing.T) { clean, changed := omitOpenAIHistoricalCiphertext([]byte(raw)) @@ -61,6 +61,27 @@ func TestOmitOpenAIHistoricalCiphertextRefusesCurrentTaskAndPointers(t *testing. } } +func TestOmitOpenAIHistoricalCiphertextUsesAvailableIntent(t *testing.T) { + for _, raw := range []string{ + `{"input":[{"role":"user","content":"repair the existing file"},{"type":"agent_message","encrypted_content":"OLD"}]}`, + `{"input":[{"role":"user","content":"repair the existing file"},{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":""}]}`, + `{"input":[{"role":"user","content":"repair the existing file"},{"type":"agent_message","encrypted_content":"OLD"},{"role":"user","content":[{"type":"input_text","text":" \n\t "}]}]}`, + `{"previous_response_id":"resp_x","conversation":{"id":"conv_x"},"input":[{"role":"user","content":"repair the existing file"},{"type":"agent_message","encrypted_content":"OLD"}]}`, + `{"previous_response_id":"resp_x","input":"repair the existing file"}`, + `{"previous_response_id":"resp_x","instructions":"repair the existing file"}`, + `{"input":[{"type":"agent_message","encrypted_content":"OLD","summary":[{"type":"summary_text","text":"repair the existing file"}]}]}`, + `{"input":[{"role":"user","content":[{"type":"encrypted_content","encrypted_content":"OLD"}]},{"type":"agent_message","encrypted_content":"OLD","summary":[{"type":"summary_text","text":"repair the existing file"}]}]}`, + `{"input":[{"type":"item_reference","id":"item_x"},{"type":"compaction","encrypted_content":"OLD"},{"role":"user","content":"repair the existing file"}]}`, + } { + clean, changed := omitOpenAIHistoricalCiphertext([]byte(raw)) + require.True(t, changed, raw) + require.Contains(t, string(clean), "repair the existing file") + require.NotContains(t, string(clean), "OLD") + require.False(t, gjson.GetBytes(clean, "previous_response_id").Exists()) + require.False(t, gjson.GetBytes(clean, "conversation").Exists()) + } +} + func TestOpenAI409OmissionSettingDefaultsOff(t *testing.T) { for _, value := range []string{"", "false", "true", "invalid"} { s := NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: value}}, nil) @@ -96,7 +117,7 @@ func TestOmitOpenAIHistoricalAssistantAgentUsesUserTextParts(t *testing.T) { } func TestOpenAI409ReplayInputTamperingStillFails(t *testing.T) { - for _, mode := range []string{"unchanged", "user_text", "tool_arguments", "tool_result", "call_id", "large_integer", "reasoning_removed", "visible_reasoning_removed", "order", "replay_id_reintroduced"} { + for _, mode := range []string{"unchanged", "user_text", "tool_arguments", "tool_result", "call_id", "large_integer", "reasoning_removed", "visible_reasoning_removed", "order", "replay_id_reintroduced", "tools_removed", "tool_schema", "pointer_reintroduced"} { t.Run(mode, func(t *testing.T) { svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} @@ -105,7 +126,7 @@ func TestOpenAI409ReplayInputTamperingStillFails(t *testing.T) { {"type":"reasoning","id":"rs_fixture_823","status":"completed","encrypted_content":"fixture-reasoning","content":[{"type":"reasoning_text","text":"visible reasoning must survive"}]}, {"type":"function_call","name":"record","call_id":"call_823","arguments":"{\"value\":9007199254740993}"}, {"type":"function_call_output","call_id":"call_823","output":"already recorded exactly once"}, - {"type":"message","role":"user","sequence":9007199254740993,"content":"continue with the result"}],"store":false}` + {"type":"message","role":"user","sequence":9007199254740993,"content":"continue with the result"}],"store":false,"tools":[{"type":"function","name":"record","parameters":{"type":"object"}}]}` c, _ := newTurnStateTestContext(t, 715, "fixture-session") c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(raw), "fixture-session", "gpt-6-astra") @@ -116,7 +137,8 @@ func TestOpenAI409ReplayInputTamperingStillFails(t *testing.T) { require.Equal(t, "9007199254740993", gjson.GetBytes(clean, "input.4.sequence").Raw) require.False(t, gjson.GetBytes(clean, "input.1.id").Exists()) require.False(t, gjson.GetBytes(clean, "input.1.status").Exists()) - require.True(t, gjson.GetBytes(clean, "input.1.summary").IsArray()) + require.Equal(t, "message", gjson.GetBytes(clean, "input.1.type").String()) + require.NotContains(t, string(clean), "fixture-reasoning") originalDigest := openAIAgentRecoveryFromContext(next).inputDigest var err error switch mode { @@ -133,7 +155,7 @@ func TestOpenAI409ReplayInputTamperingStillFails(t *testing.T) { case "reasoning_removed": clean, err = sjson.DeleteBytes(clean, "input.1") case "visible_reasoning_removed": - clean, _, err = normalizeOpenAIResponsesReasoningContentReplay(clean) + clean, err = sjson.DeleteBytes(clean, "input.1.content.1") case "order": items := gjson.GetBytes(clean, "input").Array() clean, err = sjson.SetRawBytes(clean, "input.2", []byte(items[3].Raw)) @@ -141,6 +163,12 @@ func TestOpenAI409ReplayInputTamperingStillFails(t *testing.T) { clean, err = sjson.SetRawBytes(clean, "input.3", []byte(items[2].Raw)) case "replay_id_reintroduced": clean, err = sjson.SetBytes(clean, "input.1.id", "rs_untrusted_replacement") + case "tools_removed": + clean, err = sjson.DeleteBytes(clean, "tools") + case "tool_schema": + clean, err = sjson.SetBytes(clean, "tools.0.parameters.type", "string") + case "pointer_reintroduced": + clean, err = sjson.SetBytes(clean, "previous_response_id", "resp_old_account") } require.NoError(t, err) req, err := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(clean)) @@ -169,7 +197,122 @@ func TestOpenAI409ReplayPreservesOrdinaryAndStoredReasoning(t *testing.T) { ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra") _, clean, changed := svc.TryOmitOpenAI409History(ctx, c, []byte(body), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError("owner_unavailable")) require.True(t, changed) - require.Equal(t, store == "true", gjson.GetBytes(clean, "input.1.id").Exists(), "stored reasoning IDs are not disposable") - require.JSONEq(t, gjson.Get(body, "input.2").Raw, gjson.GetBytes(clean, "input.2").Raw, "readable reasoning without ciphertext must not be discarded") + require.False(t, gjson.GetBytes(clean, "input.1.id").Exists(), "old provider reasoning IDs cannot migrate") + require.NotContains(t, string(clean), "reasoning-cipher") + require.Equal(t, "readable reasoning", gjson.GetBytes(clean, "input.2.content.1.text").String()) + require.Equal(t, "assistant", gjson.GetBytes(clean, "input.2.role").String()) + // Both destructive production normalizers must now leave input intact. + normalized, _, err := normalizeOpenAIAPIKeyStoreFalseReasoningReplay(clean, false) + require.NoError(t, err) + normalized, _, err = normalizeOpenAIResponsesReasoningContentReplay(normalized) + require.NoError(t, err) + require.Equal(t, openAIAgentRecoveryInputDigest(clean), openAIAgentRecoveryInputDigest(normalized)) + } +} + +func TestOpenAI409ReadableReasoningRetainsUnknownShapesAsText(t *testing.T) { + for _, reasoning := range []string{ + `{"type":"reasoning","content":"unrecognized text shape"}`, + `{"type":"reasoning","summary":[{"type":"summary_text","text":"visible","extra":"must not lose"}]}`, + `{"type":"reasoning","content":[{"type":"image","url":"fixture"}]}`, + `{"type":"reasoning","encrypted_content":{"opaque":"unknown"}}`, + `{"type":"reasoning","future_field":"must not lose"}`, + } { + clean, err := prepareOpenAI409ReadableReplay([]byte(`{"input":[` + reasoning + `]}`)) + require.NoError(t, err) + require.Equal(t, "message", gjson.GetBytes(clean, "input.0.type").String()) + require.Contains(t, gjson.GetBytes(clean, "input.0.content.0.text").String(), "Historical reasoning context") + } + clean, err := prepareOpenAI409ReadableReplay([]byte(`{"input":[{"type":"reasoning","content":{"text":"available finding","encrypted_content":"OLD_UNPORTABLE"},"sequence":9007199254740993}]}`)) + require.NoError(t, err) + require.Contains(t, string(clean), "available finding") + require.Contains(t, string(clean), "9007199254740993") + require.NotContains(t, string(clean), "OLD_UNPORTABLE") +} + +func TestOpenAI409RebuildRechecksOriginalDeliveryBeforeSend(t *testing.T) { + for _, fence := range []string{"pending", "failed", "conflict"} { + t.Run(fence, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + issue715LearnRoute(t, svc, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, issue715OpaqueBody) + body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"role":"user","content":"complete the existing task"}]}` + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra") + next, clean, changed, err := svc.TryRebuildOpenAI409History(ctx, c, []byte(body), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError("owner_unavailable")) + require.NoError(t, err) + require.True(t, changed) + key := openAIAgentRecoveryFromContext(ctx).keys[0] + binding := svc.agentMessageRecovery.bindings[key] + switch fence { + case "pending": + binding.pending = "fixture-unconfirmed" + case "failed": + binding.failed = true + case "conflict": + binding.conflicted = true + } + svc.agentMessageRecovery.bindings[key] = binding + req, err := http.NewRequest(http.MethodPost, "https://native.example/v1/responses", bytes.NewReader(clean)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(next, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, req) + defer finish(false) + require.Error(t, err, "sanitization must not erase a later delivery fence") + require.Equal(t, binding, svc.agentMessageRecovery.bindings[key]) + }) + } +} + +func TestOpenAI409OAuthReplayKeepsOriginalSnapshotAndFinalControls(t *testing.T) { + for _, mode := range []string{"unchanged", "tools_removed", "insert_instructions", "replace_instructions"} { + t.Run(mode, func(t *testing.T) { + svc := &OpenAIGatewayService{cfg: &config.Config{}, settingService: NewSettingService(&codexPolicyMigrationRepoStub{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, nil)} + issue715LearnRoute(t, svc, &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, issue715OpaqueBody) + body := strings.TrimSuffix(issue715OpaqueBody, "]}") + `,{"role":"system","content":"keep existing results"},{"role":"user","content":"complete the existing task"}],"tools":[{"type":"function","name":"record","parameters":{"type":"object"}}]}` + if mode == "replace_instructions" { + var err error + body, err = sjson.Set(body, "instructions", "Original instruction: preserve completed tools") + require.NoError(t, err) + } + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + c.Set("api_key", &APIKey{ID: 715, GroupID: int64Ptr(715)}) + ctx := svc.WithOpenAIAgentMessageRecovery(context.Background(), c, []byte(body), "fixture-session", "gpt-6-astra") + next, clean, changed, err := svc.TryRebuildOpenAI409History(ctx, c, []byte(body), "fixture-session", "gpt-6-astra", openAIAgentRecoveryError("owner_unavailable")) + require.NoError(t, err) + require.True(t, changed) + r := openAIAgentRecoveryFromContext(next) + originalInput, originalControls := r.inputDigest, r.replayControlsDigest + var decoded map[string]any + require.NoError(t, decodeOpenAIJSONUseNumber(clean, &decoded)) + if mode == "insert_instructions" || mode == "replace_instructions" { + decoded["instructions"] = "Ignore the recorded result and repeat the completed operation" + require.Error(t, prepareOpenAI409OAuthReplay(next, c, decoded), "instruction mutation must fail before deriving OAuth expectations") + require.False(t, r.oauthReplayPrepared) + require.Equal(t, originalInput, r.inputDigest) + require.Equal(t, originalControls, r.replayControlsDigest) + return + } + require.NoError(t, prepareOpenAI409OAuthReplay(next, c, decoded)) + require.Equal(t, originalInput, r.inputDigest) + require.Equal(t, originalControls, r.replayControlsDigest) + require.Equal(t, "keep existing results\n\n"+defaultCodexSynthInstructions("gpt-6-astra"), decoded["instructions"]) + transformed := applyCodexOAuthTransformWithOptions(decoded, codexOAuthTransformOptions{PreserveReadableReplay: true}) + require.NoError(t, transformed.Error) + wire, err := json.Marshal(decoded) + require.NoError(t, err) + if mode == "tools_removed" { + wire, err = sjson.DeleteBytes(wire, "tools") + require.NoError(t, err) + } + req, err := http.NewRequest(http.MethodPost, "https://chatgpt.com/backend-api/codex/responses", bytes.NewReader(wire)) + require.NoError(t, err) + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(next, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, req) + defer finish(false) + if mode == "tools_removed" { + require.Error(t, err) + } else { + require.NoError(t, err) + } + }) } } diff --git a/backend/internal/service/openai_409_readable_shadow.go b/backend/internal/service/openai_409_readable_shadow.go new file mode 100644 index 000000000000..b8807f2ecbfe --- /dev/null +++ b/backend/internal/service/openai_409_readable_shadow.go @@ -0,0 +1,401 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "strings" + "time" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// Bounded, optional shared data plane. There is deliberately no local fallback. +// The principal budget spans all groups, models, sessions and task identities. +const ( + OpenAIReadableShadowMaxBytes = 64 * 1024 + OpenAIReadableShadowMaxRecords = 8 + OpenAIReadableShadowTTL = 30 * time.Minute +) + +type OpenAIReadableShadowCache interface { + GetOpenAIReadableShadow(ctx context.Context, principal, task string) (string, error) + PutOpenAIReadableShadow(ctx context.Context, principal, task, value string, ttl time.Duration) error + InvalidateOpenAIReadableShadow(ctx context.Context, principal, task string) error +} + +type openAIReadableShadowContextKey struct{} + +type openAIReadableShadowObservation struct { + principal string + task string + raw string + epoch string + fences map[string]string +} + +// This is observed readable context, not provider state or a generation to +// replay. Fences include the specific delivered output and all known sources. +type openAIReadableShadow struct { + Version int `json:"version"` + Scope string `json:"scope"` + Input json.RawMessage `json:"input"` + Instructions json.RawMessage `json:"instructions,omitempty"` + Fences map[string]string `json:"fences"` + Epoch string `json:"epoch"` +} + +func (r *openAIAgentRecoveryRequest) shadowPrincipal() string { + encoded, _ := json.Marshal([]any{1, r.userID, r.keyID}) + digest := sha256.Sum256(encoded) + return hex.EncodeToString(digest[:]) +} + +func (r *openAIAgentRecoveryRequest) shadowTaskKey(item [32]byte) string { + encoded, _ := json.Marshal([]any{1, r.shadowPrincipal(), r.groupID, r.shadowModel, r.session, hex.EncodeToString(item[:])}) + digest := sha256.Sum256(encoded) + return hex.EncodeToString(digest[:]) +} + +func (r *openAIAgentRecoveryRequest) shadowEpochKey(item [32]byte) string { + return r.shadowPrincipal() + ":" + r.shadowTaskKey(item) +} + +// Restore before moderation, image/long-context admission and token reservation. +// 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) { + if s == nil || s.settingService == nil || openAI409HasReadableIntent(body) || + isOpenAIResponsesCompactPath(c) || isOpenAINativeCompactionV2(c) || + !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { + return ctx, body + } + items := openAIAgentRecoveryItemDigests(body) + if len(items) != 1 || !gjson.GetBytes(body, "input").IsArray() || len(gjson.GetBytes(body, "input").Array()) != 1 { + return ctx, body + } + for _, item := range gjson.GetBytes(body, "input").Array() { + if item.Get("type").String() != "agent_message" { + // A media/opaque user request or new tool result can be a distinct + // task. Never replace that unknown intent with an older objective. + return ctx, body + } + } + keyID := getAPIKeyIDFromContext(c) + r := &openAIAgentRecoveryRequest{keyID: keyID, userID: openAIReadableRecoveryUser(c, keyID), + groupID: getOpenAIGroupIDFromContext(c), session: session, shadowModel: gjson.GetBytes(body, "model").String()} + store, ok := s.cache.(OpenAIReadableShadowCache) + if !ok || r.userID <= 0 || r.keyID <= 0 || r.session == "" || r.shadowModel == "" || + !s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + return ctx, body + } + storeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + task := r.shadowTaskKey(items[0]) + epochs, ok := s.cache.(OpenAIAgentRecoveryEpochCache) + if !ok { + return ctx, body + } + var epoch string + for { + var err error + epoch, err = epochs.GetOpenAIAgentRecoveryEpoch(storeCtx, r.shadowPrincipal()+":"+task) + if err != nil { + return ctx, body + } + if !strings.HasPrefix(epoch, "pending:") { + break + } + timer := time.NewTimer(5 * time.Millisecond) + select { + case <-storeCtx.Done(): + timer.Stop() + return ctx, body + case <-timer.C: + } + } + if !strings.HasPrefix(epoch, "ready:pending:") { + return ctx, body + } + raw, err := store.GetOpenAIReadableShadow(storeCtx, r.shadowPrincipal(), task) + if err != nil || raw == "" || len(raw) > OpenAIReadableShadowMaxBytes { + return ctx, body + } + 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() || + s.checkOpenAIReadableShadowFences(storeCtx, record.Fences) != nil { + return ctx, body + } + // Keep the supplied opaque item until the existing lossy builder detaches + // it. Its original owner is still re-read at selection and the final send. + var restored []json.RawMessage + if json.Unmarshal(record.Input, &restored) != nil { + return ctx, body + } + for _, item := range gjson.GetBytes(body, "input").Array() { + restored = append(restored, json.RawMessage(item.Raw)) + } + input, err := json.Marshal(restored) + if err != nil { + return ctx, body + } + clean, err := sjson.SetRawBytes(body, "input", input) + if err == nil && len(record.Instructions) > 0 { + clean, err = sjson.SetRawBytes(clean, "instructions", record.Instructions) + } + if err != nil || !openAI409HasReadableIntent(clean) { + return ctx, body + } + observation := &openAIReadableShadowObservation{principal: r.shadowPrincipal(), task: task, raw: raw, epoch: epoch, fences: record.Fences} + if s.checkOpenAIReadableShadowObservation(storeCtx, observation) != nil { + return ctx, body + } + return context.WithValue(WithRecoveredContextPrivacy(ctx), openAIReadableShadowContextKey{}, observation), clean +} + +func (s *OpenAIGatewayService) checkOpenAIReadableShadowObservation(ctx context.Context, observation *openAIReadableShadowObservation) error { + if observation == nil { + return nil + } + store, ok := s.cache.(OpenAIReadableShadowCache) + epochs, hasEpoch := s.cache.(OpenAIAgentRecoveryEpochCache) + if !ok || !hasEpoch { + return openAIAgentRecoveryError("store_unavailable") + } + 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") + } + epoch, err := epochs.GetOpenAIAgentRecoveryEpoch(ctx, observation.principal+":"+observation.task) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + if raw != observation.raw || epoch != observation.epoch { + return openAIAgentRecoveryError("owner_conflict") + } + return s.checkOpenAIReadableShadowFences(ctx, observation.fences) +} + +func (s *OpenAIGatewayService) checkOpenAIReadableShadowFences(ctx context.Context, fences map[string]string) error { + if len(fences) == 0 { + return nil + } + store, ok := s.cache.(OpenAIAgentRecoveryCache) + if !ok { + return openAIAgentRecoveryError("store_unavailable") + } + 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") + } + actual, err := store.GetOpenAIAgentRecovery(ctx, key) + if err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + if actual != expected { + return openAIAgentRecoveryError("owner_conflict") + } + } + return nil +} + +// Only portable text and already paired tool calls/results are retained. An +// unknown item or an unpaired call/result loses shadow availability; it does +// not reject an otherwise valid original request or resubmit a tool. +func openAIReadableShadowCandidate(body []byte) *openAIReadableShadow { + if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) || !openAI409HasReadableIntent(body) { + return nil + } + clean := body + if input := gjson.GetBytes(clean, "input"); input.Type == gjson.String { + value, _ := json.Marshal([]any{map[string]any{"type": "message", "role": "user", "content": input.String()}}) + clean, _ = sjson.SetRawBytes(clean, "input", value) + } + if omitted, changed := omitOpenAIHistoricalCiphertext(clean); changed { + clean = omitted + } + var err error + clean, err = prepareOpenAI409ReadableReplay(clean) + if err != nil { + return nil + } + input := gjson.GetBytes(clean, "input") + if !input.IsArray() || len(input.Raw) > OpenAIReadableShadowMaxBytes { + return nil + } + calls, outputs := make(map[string]string), make(map[string]string) + for _, item := range input.Array() { + kind, id := item.Get("type").String(), item.Get("call_id").String() + switch kind { + case "", "message": + if !openAIReadableShadowTextOnly(item.Get("content")) { + return nil + } + switch item.Get("role").String() { + case "user", "assistant", "system", "developer": + default: + return nil + } + case "function_call", "custom_tool_call": + if id == "" || calls[id] != "" || (item.Get("status").Exists() && item.Get("status").String() != "completed") { + return nil + } + calls[id] = kind + "_output" + case "function_call_output", "custom_tool_call_output": + if id == "" || outputs[id] != "" || item.Get("output").Type == gjson.Null || !openAIReadableShadowTextOnly(item.Get("output")) || + (item.Get("status").Exists() && item.Get("status").String() != "completed") { + return nil + } + outputs[id] = kind + default: + return nil + } + } + if len(calls) != len(outputs) { + return nil + } + for id, kind := range calls { + if outputs[id] != kind { + return nil + } + } + record := &openAIReadableShadow{Version: 2, Input: json.RawMessage(input.Raw)} + if instructions := gjson.GetBytes(clean, "instructions"); instructions.Exists() { + if instructions.Type != gjson.String && instructions.Type != gjson.Null { + return nil + } + if len(input.Raw)+len(instructions.Raw) > OpenAIReadableShadowMaxBytes { + return nil + } + record.Instructions = json.RawMessage(instructions.Raw) + } + return record +} + +func openAIReadableShadowTextOnly(content gjson.Result) bool { + if content.Type == gjson.String || content.Type == gjson.Null { + return true + } + if !content.IsArray() { + return false + } + for _, part := range content.Array() { + kind := part.Get("type").String() + if (kind != "input_text" && kind != "output_text" && kind != "text" && kind != "summary_text") || part.Get("text").Type != gjson.String { + return false + } + } + return true +} + +func openAIReadableShadowOutputSafe(body []byte, path string) bool { + for _, item := range gjson.GetBytes(body, path).Array() { + switch item.Get("type").String() { + case "agent_message", "message", "reasoning": + default: + return false // In particular, new tool work is not a completed result. + } + } + return true +} + +func (s *OpenAIGatewayService) prepareOpenAIReadableShadow(ctx context.Context, r *openAIAgentRecoveryRequest, body []byte) { + r.shadowCandidate = nil + if r.userID <= 0 || r.shadowModel == "" || !r.shadowReadableIntent || r.disallowLearning || + s.settingService == nil || !s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + return + } + if _, ok := s.cache.(OpenAIReadableShadowCache); ok { + r.shadowCandidate = openAIReadableShadowCandidate(body) + } +} + +// Called inside delivery.once, after owner CAS, and only following a real +// successful downstream terminal write. Errors cannot undo that delivery or +// modify/revoke owners. No body, task, cache value or store error is logged. +func (d *openAIAgentRecoveryDelivery) publishReadableShadow(ctx context.Context) { + r := d.request + if len(r.outputs) == 0 || r.userID <= 0 || r.shadowModel == "" { + return + } + store, ok := d.service.cache.(OpenAIReadableShadowCache) + owners, owns := d.service.cache.(OpenAIAgentRecoveryCache) + if !ok || !owns || d.service.settingService == nil || !d.service.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + return + } + for _, item := range r.outputs { + if r.known[r.itemKey(item)] || r.shadowCandidate == nil || !r.shadowOutputSafe { + // Reusing an opaque identity after more work cannot leave its old + // task snapshot authoritative. Invalidate only an existing shadow; + // never manufacture context for unsafe/unreadable output. + _ = store.InvalidateOpenAIReadableShadow(ctx, r.shadowPrincipal(), r.shadowTaskKey(item)) + } + } + if r.shadowCandidate == nil || !r.shadowOutputSafe { + return + } + fences := make(map[string]string) + for key, route := range r.shadowFences { + fences[key] = route + } + for source := r; source != nil; source = source.omittedSource { + for _, key := range source.keys { + if !source.known[key] { + continue + } + encoded := hex.EncodeToString(key[:]) + raw, err := owners.GetOpenAIAgentRecovery(ctx, encoded) + if err != nil || raw == "" { + return + } + if expected, exists := fences[encoded]; exists && expected != raw { + return + } + fences[encoded] = raw + } + } + if len(fences) >= 64 || d.service.checkOpenAIReadableShadowFences(ctx, fences) != nil { + return + } + route := encodeOpenAIAgentRecoveryBinding(d.binding) + ttl := min(OpenAIReadableShadowTTL, d.service.openAIWSSessionStickyTTL()) + for _, item := range r.outputs { + key := r.itemKey(item) + // Echoed inputs are not new output provenance. + if !d.keys[key] || r.known[key] { + continue + } + encoded := hex.EncodeToString(key[:]) + actual, err := owners.GetOpenAIAgentRecovery(ctx, encoded) + if err != nil || actual != route { + continue + } + record := *r.shadowCandidate + record.Scope = r.shadowTaskKey(item) + if !d.epochs[r.shadowEpochKey(item)] { + continue + } + record.Epoch = d.pending + record.Fences = make(map[string]string, len(fences)+1) + for key, value := range fences { + record.Fences[key] = value + } + record.Fences[encoded] = route + value, err := json.Marshal(record) + if err != nil || len(value) > OpenAIReadableShadowMaxBytes || strings.TrimSpace(string(record.Input)) == "" { + continue + } + _ = store.PutOpenAIReadableShadow(ctx, r.shadowPrincipal(), record.Scope, string(value), ttl) + } +} diff --git a/backend/internal/service/openai_409_ws_ticket_test.go b/backend/internal/service/openai_409_ws_ticket_test.go new file mode 100644 index 000000000000..37f0b50f2781 --- /dev/null +++ b/backend/internal/service/openai_409_ws_ticket_test.go @@ -0,0 +1,203 @@ +package service + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Only replace the fixed OAuth destination. The production dialer still opens +// a real socket through the selected P or Q HTTP proxy with the final headers. +type readableTicketLoopbackDialer struct { + delegate openAIWSClientDialer + p, q string +} + +func (d readableTicketLoopbackDialer) Dial(ctx context.Context, address string, headers http.Header, proxy string) (openAIWSClientConn, int, http.Header, error) { + if address != "wss://chatgpt.com/backend-api/codex/responses" || (proxy != d.p && proxy != d.q) { + return nil, 0, nil, fmt.Errorf("fixture refuses unrecognized destination or proxy") + } + return d.delegate.Dial(ctx, "ws://127.0.0.1:1/v1/responses", headers, proxy) +} + +type readableTicketObservation struct { + proxy string + header http.Header + body []byte +} + +type readableTicketRepo struct{ turnAdmissionRepo } + +func (r *readableTicketRepo) GetByID(context.Context, int64) (*Account, error) { + return r.account, nil +} +func (r *readableTicketRepo) UpdateExtra(context.Context, int64, map[string]any) error { return nil } + +func TestOpenAI409WSTicketBoundEgress(t *testing.T) { + testOpenAI409WSTicketBoundEgress(t, 1) +} + +func TestOpenAI409WSTicketRejectsInvalidConcurrency(t *testing.T) { + testOpenAI409WSTicketBoundEgress(t, 0) +} + +func testOpenAI409WSTicketBoundEgress(t *testing.T, concurrency int) { + t.Helper() + for _, mode := range []string{OpenAIWSIngressModeCtxPool, OpenAIWSIngressModeShared, OpenAIWSIngressModeDedicated} { + t.Run(mode, func(t *testing.T) { + observed := make(chan readableTicketObservation, 4) + var proxyRequests atomic.Int64 + proxyServer := func(label string) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + proxyRequests.Add(1) + conn, err := coderws.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + defer conn.CloseNow() //nolint:errcheck // Fixture transport teardown. + _, body, err := conn.Read(r.Context()) + if err != nil { + t.Error(err) + return + } + observed <- readableTicketObservation{label, r.Header.Clone(), append([]byte(nil), body...)} + if err := conn.Write(r.Context(), coderws.MessageText, []byte(`{"type":"response.completed","response":{"id":"resp_ticket_B","status":"completed","model":"gpt-6-astra","output":[],"usage":{"input_tokens":2,"output_tokens":1}}}`)); err != nil { + t.Error(err) + } + _, _, _ = conn.Read(r.Context()) // consume shutdown/control frames + })) + } + p, q := proxyServer("harvest-P"), proxyServer("ordinary-Q") + defer p.Close() + defer q.Close() + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.OpenAIWS = config.GatewayOpenAIWSConfig{ + Enabled: true, OAuthEnabled: true, ResponsesWebsocketsV2: true, ModeRouterV2Enabled: true, + DialTimeoutSeconds: 3, ReadTimeoutSeconds: 3, WriteTimeoutSeconds: 3, + MaxConnsPerAccount: 1, MaxIdlePerAccount: 1, QueueLimitPerConn: 2, + } + cfg.Gateway.OpenAICodexTicket = config.OpenAICodexTicketConfig{Enabled: true, TargetLength: 292, Models: []string{"gpt-6-astra"}, FailClosed: true} + account := ticketTestAccount(2) + account.Concurrency = concurrency + account.GroupIDs = []int64{9} + account.Extra = map[string]any{"openai_oauth_responses_websockets_v2_enabled": true, "openai_oauth_responses_websockets_v2_mode": mode, "codex_fingerprint_mode": "off"} + decision := NewOpenAIWSProtocolResolver(cfg).Resolve(account) + if concurrency > 0 { + require.Equal(t, OpenAIUpstreamTransportResponsesWebsocketV2, decision.Transport) + } else { + require.Equal(t, OpenAIUpstreamTransportHTTPSSE, decision.Transport) + require.Equal(t, "account_concurrency_invalid", decision.Reason) + } + qURL, err := url.Parse(q.URL) + require.NoError(t, err) + port, err := strconv.Atoi(qURL.Port()) + require.NoError(t, err) + account.Proxy = &Proxy{ID: 9, Protocol: "http", Host: qURL.Hostname(), Port: port, Status: StatusActive} + account.ProxyID = &account.Proxy.ID + pool := newOpenAIWSConnPool(cfg) + pool.setClientDialerForTest(readableTicketLoopbackDialer{newDefaultOpenAIWSClientDialer(), p.URL, q.URL}) + svc := &OpenAIGatewayService{cfg: cfg, accountRepo: &readableTicketRepo{turnAdmissionRepo{account: account}}, + cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg), openaiWSPool: pool, + toolCorrector: NewCodexToolCorrector(), settingService: NewSettingService(&contentModerationTestSettingRepo{values: map[string]string{SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}}, cfg)} + defer svc.CloseOpenAIWSPool() + state := fakeCodexTicketState(292) + require.NoError(t, svc.storeOpenAICodexTicket(context.Background(), account, &openAICodexTicket{ + AccountID: 2, Model: "gpt-6-astra", State: state, Length: 292, Transport: "websocket", + HarvestProxyURL: p.URL, HarvestSessionID: "fixture-ticket-B-session", CapturedAt: time.Now(), ExpiresAt: time.Now().Add(time.Hour), + })) + done := make(chan error, 1) + gateway := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + conn, err := coderws.Accept(w, req, nil) + if err != nil { + done <- err + return + } + defer conn.CloseNow() //nolint:errcheck // Fixture teardown. + _, source, err := conn.Read(req.Context()) + if err != nil { + done <- err + return + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = req + c.Set("api_key", &APIKey{ID: 7, UserID: 8, GroupID: int64Ptr(9)}) + SetOpenAIWSRecoveryPrincipal(c, 8, 7) + // This test isolates the post-unsent-rebuild B transport; the + // handler suite establishes the same-client A disable boundary. + ctx, body, changed, err := svc.RebuildOpenAIWSUnsentTurn(req.Context(), c, source, "fixture-ticket-client", "gpt-6-astra") + if err != nil || !changed { + done <- fmt.Errorf("fixture rebuild failed: changed=%v err=%v", changed, err) + return + } + ctx = ResetOpenAIWSReadableProviderSession(ctx, c) + c.Request = req.WithContext(ctx) + done <- svc.ProxyResponsesWebSocketFromClient(ctx, c, conn, account, "tok", body, nil) + })) + defer gateway.Close() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(gateway.URL, "http"), &coderws.DialOptions{HTTPHeader: http.Header{"Session_id": {"fixture-ticket-client"}, "Conversation_id": {"fixture-old-A"}, "X-Codex-Turn-State": {"fixture-old-A-state"}}}) + require.NoError(t, err) + defer client.CloseNow() //nolint:errcheck // Fixture teardown. + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-6-astra","input":[{"role":"user","content":"Continue the readable coding task without repeating completed work."}]}`))) + _, terminal, err := client.Read(ctx) + if concurrency <= 0 { + require.Error(t, err, "invalid concurrency must close before generation") + require.Empty(t, terminal) + select { + case gatewayErr := <-done: + require.EqualError(t, gatewayErr, "websocket ingress requires ws_v2 transport, got=http_sse") + case <-ctx.Done(): + t.Fatal("rejected ticket fixture gateway did not terminate") + } + require.Zero(t, proxyRequests.Load(), "invalid concurrency must not dial either proxy") + require.Empty(t, observed, "invalid concurrency must not send a B generation") + return + } + if err != nil { + select { + case gatewayErr := <-done: + t.Fatalf("ticket fixture downstream read failed: %v; gateway: %v", err, gatewayErr) + case <-ctx.Done(): + t.Fatalf("ticket fixture downstream read failed: %v; gateway did not finish", err) + } + } + require.NoError(t, err) + require.Equal(t, "response.completed", gjson.GetBytes(terminal, "type").String()) + require.NoError(t, client.Close(coderws.StatusNormalClosure, "done")) + select { + case err := <-done: + require.NoError(t, err) + case <-ctx.Done(): + t.Fatal("fixture gateway did not terminate") + } + select { + case wire := <-observed: + require.Equal(t, "harvest-P", wire.proxy, "WS_RESIDUAL_TICKET_EGRESS_LOST: B ticket must never use ordinary-Q") + require.Equal(t, state, wire.header.Get(openAICodexTurnStateHeader)) + require.Equal(t, "fixture-ticket-B-session", wire.header.Get("session_id")) + require.Empty(t, wire.header.Get("conversation_id")) + require.Contains(t, string(wire.body), "Continue the readable coding task") + require.False(t, gjson.GetBytes(wire.body, "previous_response_id").Exists()) + default: + t.Fatal("missing actual B wire") + } + require.Empty(t, observed, "one B generation only") + }) + } +} diff --git a/backend/internal/service/openai_agent_message_delivery.go b/backend/internal/service/openai_agent_message_delivery.go index 54168231ddbb..cd8123084bed 100644 --- a/backend/internal/service/openai_agent_message_delivery.go +++ b/backend/internal/service/openai_agent_message_delivery.go @@ -21,6 +21,15 @@ type OpenAIAgentRecoveryDeliveryCache interface { FinishOpenAIAgentRecovery(context.Context, string, string, string, bool, time.Duration) error } +// Association epochs are delivery fences, separate from immutable owner +// routes and optional readable payload storage. Reuse revokes the old epoch +// before any output bytes are exposed, including when shadow writes fail. +type OpenAIAgentRecoveryEpochCache interface { + ReserveOpenAIAgentRecoveryEpoch(context.Context, string, string, time.Duration) error + FinishOpenAIAgentRecoveryEpoch(context.Context, string, string, bool, time.Duration) error + GetOpenAIAgentRecoveryEpoch(context.Context, string) (string, error) +} + type openAIAgentRecoveryDelivery struct { service *OpenAIGatewayService ctx context.Context @@ -28,11 +37,12 @@ type openAIAgentRecoveryDelivery struct { binding openAIAgentRecoveryBinding pending string keys map[[32]byte]bool + epochs map[string]bool once sync.Once } 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)} + 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)} } func (s *OpenAIGatewayService) awaitOpenAIAgentRecovery(ctx context.Context, shared OpenAIAgentRecoveryCache, state *openAIAgentRecoveryState, key [32]byte) (openAIAgentRecoveryBinding, bool, error) { @@ -90,6 +100,13 @@ func (d *openAIAgentRecoveryDelivery) reserve(items [][32]byte) error { defer cancel() for _, item := range items { key := d.request.itemKey(item) + epochKey := d.request.shadowEpochKey(item) + if shared, ok := d.service.cache.(OpenAIAgentRecoveryEpochCache); ok && d.request.userID > 0 && !d.epochs[epochKey] { + d.epochs[epochKey] = true + if err := shared.ReserveOpenAIAgentRecoveryEpoch(ctx, epochKey, d.pending, d.service.openAIWSSessionStickyTTL()); err != nil { + return openAIAgentRecoveryError("store_unavailable") + } + } 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. @@ -178,6 +195,22 @@ func (d *openAIAgentRecoveryDelivery) finish(completed bool) { state.mu.Unlock() } } + if completed { + d.publishReadableShadow(ctx) + } + if shared, ok := d.service.cache.(OpenAIAgentRecoveryEpochCache); ok { + eligible := make(map[string]bool) + if completed { + for _, item := range d.request.outputs { + eligible[d.request.shadowEpochKey(item)] = true + } + } + for key := range d.epochs { + // Failed/unknown publication leaves no eligible record matching + // this epoch. An ambiguous CAS cannot restore an older epoch. + _ = shared.FinishOpenAIAgentRecoveryEpoch(ctx, key, d.pending, eligible[key], d.service.openAIWSSessionStickyTTL()) + } + } }) } diff --git a/backend/internal/service/openai_agent_message_recovery.go b/backend/internal/service/openai_agent_message_recovery.go index 06a4fa2d79f5..aa794ad13cc7 100644 --- a/backend/internal/service/openai_agent_message_recovery.go +++ b/backend/internal/service/openai_agent_message_recovery.go @@ -45,28 +45,45 @@ type openAIAgentRecoveryState struct { } type openAIAgentRecoveryRequest struct { - omitted400History bool // one authorized, same-route HTTP 400 history replacement - retry400Route *openAIAgentRecoveryBinding - omittedHistory bool // explicit Beta sanitization; preserve the resulting input and prohibit replay - disableOwnerBinding bool - previousResponseID string - inputDigest [32]byte - keyID int64 - userID int64 - delivery *openAIAgentRecoveryDelivery - outputs [][32]byte - disallowLearning bool - nativeCompaction bool - lookupErr error - toolResult bool - known map[[32]byte]bool - keys [][32]byte - items [][32]byte - owner *openAIAgentRecoveryBinding - conflict bool - groupID int64 - model string - session string + omitted400History bool // one authorized, same-route HTTP 400 history replacement + retry400Route *openAIAgentRecoveryBinding + omittedHistory bool // explicit Beta sanitization; preserve the resulting input and prohibit replay + disableOwnerBinding bool + previousResponseID string + inputDigest [32]byte + replayControlsDigest [32]byte + apiControlsDigest [32]byte + apiInputDigest [32]byte + apiReplayPrepared bool + oauthInputDigest [32]byte + oauthControlsDigest [32]byte + oauthReplayPrepared bool + omittedSource *openAIAgentRecoveryRequest + shadowModel string // original requested model, independent of account/channel projection + shadowReadableIntent bool + shadowCandidate *openAIReadableShadow + shadowOutputSafe bool + shadowUnsafeOutput bool + shadowFences map[string]string + shadowObservation *openAIReadableShadowObservation + keyID int64 + userID int64 + httpResponsePointer bool + delivery *openAIAgentRecoveryDelivery + outputs [][32]byte + disallowLearning bool + nativeCompaction bool + lookupErr error + toolResult bool + known map[[32]byte]bool + keys [][32]byte + items [][32]byte + owner *openAIAgentRecoveryBinding + conflict bool + mixedOwners bool // different completed producers, not a delivery conflict + groupID int64 + model string + session string } // WithOpenAIAgentMessageRecovery observes only opaque item identities. A route @@ -78,12 +95,21 @@ type openAIAgentRecoveryRequest struct { func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Context, c *gin.Context, body []byte, sessionHash, model string) context.Context { request := &openAIAgentRecoveryRequest{groupID: getOpenAIGroupIDFromContext(c), model: model, session: sessionHash} request.disableOwnerBinding = s != nil && s.cfg != nil && s.cfg.Gateway.DisableEncryptedAgentOwnerBinding - if request.disableOwnerBinding { + if request.disableOwnerBinding || (openAI409HasProviderState(body) && s != nil && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx)) || openAIAgentRecoveryHTTPUser(c, getAPIKeyIDFromContext(c)) > 0 { + // An authenticated HTTP response pointer must remain on its actual + // producer even with Beta off and without any encrypted-agent owner. request.previousResponseID = strings.TrimSpace(gjson.GetBytes(body, "previous_response_id").String()) } keyID := getAPIKeyIDFromContext(c) request.keyID = keyID - request.userID = openAIAgentRecoveryHTTPUser(c, keyID) + request.userID = openAIReadableRecoveryUser(c, keyID) + request.httpResponsePointer = openAIAgentRecoveryHTTPUser(c, keyID) > 0 + request.shadowModel = gjson.GetBytes(body, "model").String() + request.shadowReadableIntent = openAI409HasReadableIntent(body) + request.shadowObservation, _ = ctx.Value(openAIReadableShadowContextKey{}).(*openAIReadableShadowObservation) + if request.shadowObservation != nil { + request.shadowFences = request.shadowObservation.fences + } request.nativeCompaction = isOpenAINativeCompactionV2(c) request.disallowLearning = isOpenAIResponsesCompactPath(c) || request.nativeCompaction if s == nil || keyID <= 0 || sessionHash == "" || model == "" { @@ -118,10 +144,15 @@ func (s *OpenAIGatewayService) WithOpenAIAgentMessageRecovery(ctx context.Contex if !found { continue } - if binding.conflicted || (request.ownerBindingRequired() && !sameOpenAIAgentRecoveryRoute(*request.owner, binding)) { + if binding.conflicted { request.conflict = true break } + if request.ownerBindingRequired() && !sameOpenAIAgentRecoveryRoute(*request.owner, binding) { + // Keep scanning: a later item may carry a pending/failed/conflict + // fence. Completed route differences alone may be rebuilt explicitly. + request.mixedOwners = true + } if request.known == nil { request.known = make(map[[32]byte]bool) } @@ -141,7 +172,7 @@ func openAIAgentRecoveryBound(ctx context.Context) bool { request := openAIAgentRecoveryFromContext(ctx) // Evidence still requires native integrity/delivery protection in opt-out // mode. This must not be used to decide whether to pin the producer account. - return request != nil && (request.owner != nil || request.conflict || request.lookupErr != nil || request.preservesHistory() || request.previousResponseID != "") + return request != nil && (request.owner != nil || request.conflict || request.mixedOwners || request.lookupErr != nil || request.preservesHistory() || request.previousResponseID != "") } func (r *openAIAgentRecoveryRequest) ownerBindingRequired() bool { @@ -257,7 +288,7 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryAccount(ctx context.Conte if request.lookupErr != nil { return request.lookupErr } - if request.conflict { + if request.conflict || request.mixedOwners { return openAIAgentRecoveryError("owner_conflict") } // Provider-side response state is never made portable by the agent policy, @@ -267,7 +298,7 @@ func (s *OpenAIGatewayService) checkOpenAIAgentRecoveryAccount(ctx context.Conte if err != nil || owner <= 0 || account == nil || owner != account.ID { return openAIAgentRecoveryError("owner_unavailable") } - if request.userID > 0 && !account.IsOpenAIApiKey() { + if request.httpResponsePointer && !account.IsOpenAIApiKey() { return openAIAgentRecoveryError("http_previous_response_unsupported") } } @@ -330,27 +361,42 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con request.delivery.finish(false) } request.outputs = nil + request.shadowOutputSafe = false + request.shadowUnsafeOutput = false + request.shadowCandidate = nil request.delivery = nil if err := s.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil { return noop, err } + if err := s.checkOpenAIReadableShadowObservation(ctx, request.shadowObservation); err != nil { + return noop, err + } + if request.omittedSource != nil { + // Re-read every original item at the actual send, even though opaque + // bytes were removed. Losing history must not lose a delivery fence. + source := *request.omittedSource + source.disableOwnerBinding = true + if err := s.checkOpenAIAgentRecoveryRecords(ctx, &source, openAIAgentRecoveryBinding{}); err != nil { + return noop, err + } + } // Managed credentials and adapters need their own route ownership contract. if !account.IsOpenAI() || account.HasManagedOpenAIConnections() || account.AuthConnectionID != "" || account.IsOpenAIPassthroughEnabled() || account.IsCopilotSDKEnabled() || account.IsSIWCEnabled() { - if request.owner != nil { + if request.owner != nil || request.preservesHistory() { return noop, openAIAgentRecoveryError("wire_changed") } return noop, nil } if req.GetBody == nil { - if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { + if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") } reader, err := req.GetBody() if err != nil { - if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { + if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") @@ -358,23 +404,37 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con body, err := io.ReadAll(reader) _ = reader.Close() if err != nil { - if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { + if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") } if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { - if len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { + if !request.preservesHistory() && len(request.items) == 0 && request.owner == nil && request.previousResponseID == "" { return noop, nil } return noop, openAIAgentRecoveryError("wire_changed") } - if request.preservesHistory() && openAIAgentRecoveryInputDigest(body) != request.inputDigest { + expectedInput, expectedControls := request.inputDigest, request.replayControlsDigest + if request.omittedHistory && account.IsOpenAIApiKey() && request.apiReplayPrepared { + expectedInput, expectedControls = request.apiInputDigest, request.apiControlsDigest + } + if request.omittedHistory && account.UsesOpenAICodexProtocol() { + if !request.oauthReplayPrepared { + return noop, openAIAgentRecoveryError("wire_changed") + } + expectedInput, expectedControls = request.oauthInputDigest, request.oauthControlsDigest + } + if request.preservesHistory() && openAIAgentRecoveryInputDigest(body) != expectedInput { if request.omittedHistory { logger.FromContext(ctx).Warn("openai.encrypted_history_409_refused", zap.String("stage", "input_integrity")) } return noop, openAIAgentRecoveryError("wire_changed") } + if request.omittedHistory && (gjson.GetBytes(body, "previous_response_id").Exists() || gjson.GetBytes(body, "conversation").Exists() || + openAI409ControlsDigest(body) != expectedControls) { + return noop, openAIAgentRecoveryError("wire_changed") + } if request.previousResponseID != "" && gjson.GetBytes(body, "previous_response_id").String() != request.previousResponseID { return noop, openAIAgentRecoveryError("owner_unavailable") } @@ -404,6 +464,7 @@ func (s *OpenAIGatewayService) prepareOpenAIAgentRecoveryAttempt(ctx context.Con if err := s.checkOpenAIAgentRecoveryRecords(ctx, request, binding); err != nil { return noop, err } + s.prepareOpenAIReadableShadow(ctx, request, body) delivery := newOpenAIAgentRecoveryDelivery(s, ctx, request, binding) request.delivery = delivery return func(completed bool) { @@ -515,9 +576,6 @@ func (r *openAIAgentRecoveryRequest) itemKey(item [32]byte) [32]byte { // output reconstruction and tool/name restoration. The attempt's completion // callback decides whether delivery succeeded; item.done alone grants nothing. func observeOpenAIAgentRecoveryOutput(c *gin.Context, body []byte, nested bool) error { - if !bytes.Contains(body, []byte("agent_message")) && !bytes.Contains(body, []byte(`\u`)) { - return nil - } request := openAIAgentRecoveryFromContext(c.Request.Context()) if request == nil || request.delivery == nil { return nil @@ -529,6 +587,16 @@ func observeOpenAIAgentRecoveryOutput(c *gin.Context, body []byte, nested bool) if nested { path = "response.output" } + if request.shadowCandidate != nil { + request.shadowUnsafeOutput = request.shadowUnsafeOutput || !openAIReadableShadowOutputSafe(body, path) + if nested && gjson.GetBytes(body, "item").IsObject() { + kind := gjson.GetBytes(body, "item.type").String() + 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 + } 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. @@ -537,6 +605,7 @@ func observeOpenAIAgentRecoveryOutput(c *gin.Context, body []byte, nested bool) } if openAIAgentCompletedResponse(body, nested) { request.outputs = openAIAgentRecoveryDigests(body, path) + request.shadowOutputSafe = !request.shadowUnsafeOutput && openAIReadableShadowOutputSafe(body, path) } return request.delivery.reserve(items) } diff --git a/backend/internal/service/openai_agent_message_recovery_error.go b/backend/internal/service/openai_agent_message_recovery_error.go index 04f15add4caf..31192894f23a 100644 --- a/backend/internal/service/openai_agent_message_recovery_error.go +++ b/backend/internal/service/openai_agent_message_recovery_error.go @@ -22,6 +22,8 @@ func (e *OpenAIAgentRecoveryError) ClientCode() string { } func (e *OpenAIAgentRecoveryError) HTTPStatus() int { switch e.Reason { + case "readable_intent_missing", "readable_history_unsupported": + return http.StatusUnprocessableEntity case "owner_rate_limited": return http.StatusTooManyRequests case "owner_overloaded": @@ -43,6 +45,10 @@ func (e *OpenAIAgentRecoveryError) ClientType() string { func (e *OpenAIAgentRecoveryError) ClientMessage() string { var reason, action string switch e.Reason { + case "readable_intent_missing": + return "The current request has no readable task or summary from which a new provider conversation can be built. The opaque contents are unavailable; no generation or tool was replayed." + case "readable_history_unsupported": + return "The supplied history has an unsupported readable representation. No provider state was transferred and no generation or tool was replayed." case "http_previous_response_unsupported": reason = "HTTP previous_response_id continuation is unsupported for this encrypted agent owner." action = "For HTTP continuation, send the complete original history without previous_response_id; current permissions and route compatibility still apply. Waiting alone will not make this request supported. Do not replay tool results while an earlier delivery is uncertain." diff --git a/backend/internal/service/openai_codex_account_identity_test.go b/backend/internal/service/openai_codex_account_identity_test.go index ffceba2d395e..e38eac64c92a 100644 --- a/backend/internal/service/openai_codex_account_identity_test.go +++ b/backend/internal/service/openai_codex_account_identity_test.go @@ -168,6 +168,59 @@ func TestBuildOpenAIWSHeadersNamespacesCodexIdentityByOAuthAccount(t *testing.T) require.Equal(t, httpRequest.Header.Get("session_id"), first.Get("session_id"), "HTTP and WS must derive the same identity from the raw client key") } +func TestBuildUpstreamRequestOAuthHeaderOnlySession(t *testing.T) { + for _, tc := range []struct { + name, underscore, hyphen, cache, seed string + rebuild bool + }{ + {name: "underscore", underscore: "client-session", seed: "client-session", rebuild: true}, + {name: "hyphen", hyphen: "client-session", seed: "client-session", rebuild: true}, + {name: "hyphen_priority", underscore: "other-session", hyphen: "client-session", seed: "client-session", rebuild: true}, + {name: "cache_priority", underscore: "client-session", cache: "explicit-cache", seed: "explicit-cache", rebuild: true}, + {name: "no_client_identity", rebuild: true}, + {name: "ordinary_wire_unchanged", underscore: "client-session"}, + } { + t.Run(tc.name, func(t *testing.T) { + svc := &OpenAIGatewayService{} + body := []byte(`{"model":"gpt-5.1","input":[],"stream":true}`) + build := func(keyID int64, upstream string) http.Header { + t.Helper() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Set("api_key", &APIKey{ID: keyID}) + c.Request.Header.Set("session_id", tc.underscore) + c.Request.Header.Set("session-id", tc.hyphen) + c.Request.Header.Set("conversation_id", "old-provider-state-is-not-a-client-session") + c.Request.Header.Set("thread-id", "unchanged-client-thread") + original := c.Request.Header.Clone() + account := &Account{ID: 11, Platform: PlatformOpenAI, Type: AccountTypeOAuth, + Credentials: map[string]any{"chatgpt_account_id": upstream}, + Extra: map[string]any{"codex_fingerprint_mode": "off"}} + ctx := context.WithValue(context.Background(), openAIAgentRecoveryContextKey{}, &openAIAgentRecoveryRequest{omittedHistory: tc.rebuild}) + req, err := svc.buildUpstreamRequest(ctx, c, account, body, "fixture-token", true, tc.cache, false) + require.NoError(t, err) + require.Equal(t, original, c.Request.Header, "upstream projection must not mutate the client identity") + if tc.seed == "" { + require.Empty(t, req.Header.Get("session_id")) + require.Empty(t, req.Header.Get("conversation_id"), "do not reuse a provider pointer as client intent or identity") + } else { + require.Equal(t, isolateOpenAIUpstreamSessionID(keyID, account, tc.seed), req.Header.Get("session_id")) + require.Equal(t, req.Header.Get("session_id"), req.Header.Get("conversation_id")) + require.NotEqual(t, tc.seed, req.Header.Get("session_id")) + } + return req.Header + } + first := build(77, "fixture-account-A") + require.Equal(t, first, build(77, "fixture-account-A"), "same client/account identity stays stable") + otherAccount, otherKey := build(77, "fixture-account-B"), build(88, "fixture-account-A") + if tc.seed != "" { + require.NotEqual(t, first.Get("session_id"), otherAccount.Get("session_id")) + require.NotEqual(t, first.Get("session_id"), otherKey.Get("session_id")) + } + }) + } +} + func TestBuildUpstreamRequestNamespacesCodexIdentityByOAuthAccount(t *testing.T) { gin.SetMode(gin.TestMode) svc := &OpenAIGatewayService{} diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index f4b33dbab3dc..58e65b58f2dd 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -95,6 +95,7 @@ type codexOAuthTransformOptions struct { SkipDefaultInstructions bool PreserveToolCallIDs bool OmitPromotedSystemMessagesFromInput bool + PreserveReadableReplay bool // explicitly prepared and digest-protected HTTP replay // ResponsesLite selects where an injected hosted tool is declared. ResponsesLite bool } @@ -319,18 +320,20 @@ func applyCodexOAuthTransformWithOptions(reqBody map[string]any, opts codexOAuth // 续链场景保留 item_reference 与 id,避免 call_id 上下文丢失。 if input, ok := reqBody["input"].([]any); ok { - if normalizedInput, modified := normalizeCodexToolRoleMessages(input); modified { - input = normalizedInput - result.Modified = true - } - if normalizedInput, modified := normalizeCodexMessageContentText(input); modified { - input = normalizedInput - result.Modified = true + if !opts.PreserveReadableReplay { + if normalizedInput, modified := normalizeCodexToolRoleMessages(input); modified { + input = normalizedInput + result.Modified = true + } + if normalizedInput, modified := normalizeCodexMessageContentText(input); modified { + input = normalizedInput + result.Modified = true + } + input = filterCodexInputWithOptions(input, codexInputFilterOptions{ + PreserveReferences: needsToolContinuation, + PreserveCallIDs: opts.PreserveToolCallIDs, + }) } - input = filterCodexInputWithOptions(input, codexInputFilterOptions{ - PreserveReferences: needsToolContinuation, - PreserveCallIDs: opts.PreserveToolCallIDs, - }) reqBody["input"] = input result.Modified = true } else if inputStr, ok := reqBody["input"].(string); ok { diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 5233d566d901..9e2e7098f714 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -360,6 +360,13 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } if account.IsOpenAIApiKey() { + if recovery := openAIAgentRecoveryFromContext(ctx); recovery != nil && recovery.omittedHistory { + prepared, prepareErr := prepareOpenAI409APIKeyReplay(ctx, body, responsesLite) + if prepareErr != nil { + return nil, prepareErr + } + body, originalBody = prepared, prepared + } if normalized, changed, normalizeErr := normalizeOpenAIParallelToolCallsWithoutTools(body, responsesLite); normalizeErr != nil { return nil, normalizeErr } else if changed { @@ -584,7 +591,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } instructions := gjson.GetBytes(body, "instructions") instructionsEmpty := !instructions.Exists() || instructions.Type != gjson.String || strings.TrimSpace(instructions.String()) == "" - if instructionsEmpty && account.UsesOpenAICodexProtocol() && !compatMessagesBridge && !nativeCNResponses { + recovery := openAIAgentRecoveryFromContext(ctx) + if instructionsEmpty && account.UsesOpenAICodexProtocol() && !compatMessagesBridge && !nativeCNResponses && (recovery == nil || !recovery.omittedHistory) { markPatchSet("instructions", defaultCodexSynthInstructions(upstreamModel)) } if billingModel != requestedModel { @@ -698,9 +706,17 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if decodeErr != nil { return nil, decodeErr } + readableReplay := false + if recovery := openAIAgentRecoveryFromContext(ctx); recovery != nil && recovery.omittedHistory { + if err := prepareOpenAI409OAuthReplay(ctx, c, decoded); err != nil { + return nil, err + } + readableReplay = true + markDecodedModified() + } // Responses OAuth 与 Chat 兼容入口保持一致:纯文本 system 可以无损提升后删除, // JSON object 模式仍需在 input 中保留 JSON 指令供上游兼容校验。 - omitPromotedSystemMessages := !strings.EqualFold( + omitPromotedSystemMessages := !readableReplay && !strings.EqualFold( strings.TrimSpace(gjson.GetBytes(body, "text.format.type").String()), "json_object", ) @@ -711,6 +727,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco IsCompact: isCompactRequest, SkipDefaultInstructions: true, PreserveToolCallIDs: true, + PreserveReadableReplay: readableReplay, OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages, ResponsesLite: responsesLite, }) @@ -720,6 +737,8 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco codexResult = applyCodexOAuthTransformWithOptions(decoded, codexOAuthTransformOptions{ IsCodexCLI: isCodexCLI, IsCompact: isCompactRequest, + SkipDefaultInstructions: readableReplay, + PreserveReadableReplay: readableReplay, OmitPromotedSystemMessagesFromInput: omitPromotedSystemMessages, ResponsesLite: responsesLite, }) @@ -728,7 +747,11 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{"type": "invalid_request_error", "message": codexResult.Error.Error()}}) return nil, codexResult.Error } - setCodexToolNameReverse(c, codexResult.ToolNameReverse) + if readableReplay { + mergeCodexToolNameReverse(c, codexResult.ToolNameReverse) + } else { + setCodexToolNameReverse(c, codexResult.ToolNameReverse) + } if codexResult.Modified { markDecodedModified() } @@ -1478,7 +1501,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) upstreamCode := extractUpstreamErrorCode(respBody) - if !isControlledExperiment(ctx) && !openAI400HistoryRecoveryApplied(ctx) && !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + if !isControlledExperiment(ctx) && !openAIAgentRecoveryPreservesHistory(ctx) && !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { agentTaskRecoveryTried = true expectedTaskID := account.GetCredential("task_id") if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { @@ -2057,6 +2080,10 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. // 客户端回带的 x-codex-turn-state 若已知由其他账号铸造(failover 换号), // 剥离后再出站——异账号 blob 与本账号的(指纹收敛后)出站身份自相矛盾。 s.guardOpenAICodexTurnStateEcho(c, account, req.Header) + if recovery := openAIAgentRecoveryFromContext(ctx); recovery != nil && recovery.omittedHistory { + req.Header.Del("x-codex-turn-state") + req.Header.Del("conversation_id") + } if err := s.applyOpenAICodexTicket(ctx, account, extractOpenAICodexTicketModel(body), req.Header); err != nil { return nil, err } @@ -2076,6 +2103,14 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. } apiKeyID := getAPIKeyIDFromContext(c) harvestSession := s.harvestPinnedSessionForModel(ctx, account, extractOpenAICodexTicketModel(body)) + sessionSeed := promptCacheKey + if recovery := openAIAgentRecoveryFromContext(ctx); recovery != nil && recovery.omittedHistory && sessionSeed == "" && !isOpenAIResponsesCompactPath(c) { + // An authorized readable rebuild needs a new upstream namespace even + // for header-only clients. Use the ORIGINAL client identity, never an + // old provider pointer. Ordinary requests retain their established + // provider-session behavior. + sessionSeed = extractClientSessionID(c.Request.Header) + } if isOpenAIResponsesCompactPath(c) { req.Header.Set("accept", "application/json") if req.Header.Get("version") == "" { @@ -2090,8 +2125,8 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. } if harvestSession != "" { req.Header.Set("session_id", harvestSession) - } else if promptCacheKey != "" { - isolated := isolateOpenAIUpstreamSessionID(apiKeyID, codexAccountIdentitySource(c, account), promptCacheKey) + } else if sessionSeed != "" { + isolated := isolateOpenAIUpstreamSessionID(apiKeyID, codexAccountIdentitySource(c, account), sessionSeed) req.Header.Set("session_id", isolated) if !compatMessagesBridge || clientConversationID != "" { req.Header.Set("conversation_id", isolated) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 3399d77fd66b..91836fe85293 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -836,6 +836,7 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( if c != nil && c.Request != nil { s.requestTimezoneHeaders(ctx, account, c.Request.Header, req.Header) } + s.detachOpenAIWSReadableProviderHeaders(ctx, req.Header, account) s.pinBoundCodexTicketHarvestIdentity(req, account) if account.IsCopilotSDKEnabled() { diff --git a/backend/internal/service/openai_history_omission.go b/backend/internal/service/openai_history_omission.go index 39c86eefa393..d2953158f5fe 100644 --- a/backend/internal/service/openai_history_omission.go +++ b/backend/internal/service/openai_history_omission.go @@ -10,8 +10,8 @@ import ( "github.com/tidwall/sjson" ) -// Shared pure transformation. HTTP 400 and pre-send 409 have separate admission, -// retry, ownership and opt-in policies; this helper grants no retry permission. +// HTTP 400's stricter history transformation. Pre-send 409 builds portable +// readable context separately; this helper grants no retry permission. func omitOpenAIHistoricalCiphertextForRecovery(raw []byte, omitReasoning bool) ([]byte, bool) { if !utf8.Valid(raw) || !openAIEncryptedJSONUnambiguous(raw) { return raw, false diff --git a/backend/internal/service/openai_ws_agent_recovery.go b/backend/internal/service/openai_ws_agent_recovery.go index 12333b6f26a0..d26560e52b10 100644 --- a/backend/internal/service/openai_ws_agent_recovery.go +++ b/backend/internal/service/openai_ws_agent_recovery.go @@ -3,6 +3,7 @@ package service import ( "bytes" "context" + "encoding/json" "io" "net/http" "net/url" @@ -35,18 +36,22 @@ func OpenAIWSAgentRecoveryBound(ctx context.Context) bool { return openAIAgentRe // One manager per forwarding attempt serializes an immediate next create with // the previous terminal write/commit. Passthrough's AfterTurn runs BEFORE that -// write and must never grant ownership. No plaintext or frame is retained here. +// write and must never grant ownership. The current request's integrity/shadow +// snapshot is bounded by the ingress frame limit; it is not a generation replay buffer. type openAIWSAgentRecovery struct { - mu sync.Mutex - service *OpenAIGatewayService - c *gin.Context - ctx context.Context - session string - request *openAIAgentRecoveryRequest - finish func(bool) - blocked *atomic.Bool - itemDone [][32]byte - known map[[32]byte]bool + mu sync.Mutex + service *OpenAIGatewayService + c *gin.Context + ctx context.Context + session string + request *openAIAgentRecoveryRequest + finish func(bool) + blocked *atomic.Bool + itemDone [][32]byte + known map[[32]byte]bool + readable *openAIAgentRecoveryRequest + readableSource, readableControls [32]byte + bridgeSource []byte // verified pre-builder bytes, bounded by the current frame } func newOpenAIWSAgentRecovery(s *OpenAIGatewayService, ctx context.Context, c *gin.Context) *openAIWSAgentRecovery { @@ -85,6 +90,79 @@ func (r *openAIWSAgentRecovery) preventReplay() { } } +func (r *openAIWSAgentRecovery) readablePrepared() bool { + if r == nil { + return false + } + r.mu.Lock() + defer r.mu.Unlock() + return r.readable != nil +} + +// Prepare before compatibility/OAuth projection and freeze the expected native +// representation. begin validates the original source and actual final bytes; +// it must not mint a new digest from the builder's possibly changed payload. +func (r *openAIWSAgentRecovery) prepareReadable(account *Account, source []byte) ([]byte, error) { + if r == nil { + return source, nil + } + r.mu.Lock() + defer r.mu.Unlock() + r.readable = nil + r.bridgeSource = nil + initial := openAIAgentRecoveryFromContext(r.ctx) + if initial == nil || !initial.omittedHistory { + return source, nil + } + ctx, clean := r.ctx, source + if openAIAgentRecoveryInputDigest(source) != initial.inputDigest || openAI409ControlsDigest(source) != initial.replayControlsDigest { + // The next client turn may still carry the old A opaque history. + // Rebuild that frame independently, preserving every original fence. + var changed bool + var err error + ctx, clean, changed, err = r.service.RebuildOpenAIWSUnsentTurn(r.ctx, r.c, source, r.session, initial.model) + if err != nil { + return nil, err + } + if !changed { + return source, nil + } + } + snapshot := *openAIAgentRecoveryFromContext(ctx) + snapshot.delivery, snapshot.outputs = nil, nil + if snapshot.shadowObservation != nil { + r.c.Request = r.c.Request.WithContext(WithRecoveredContextPrivacy(r.c.Request.Context())) + } + ctx = context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &snapshot) + if account.UsesOpenAICodexProtocol() { + var decoded map[string]any + if err := decodeOpenAIJSONUseNumber(clean, &decoded); err != nil { + return nil, err + } + if err := prepareOpenAI409OAuthReplay(ctx, r.c, decoded); err != nil { + return nil, err + } + var err error + clean, err = json.Marshal(decoded) + if err != nil { + return nil, err + } + } else { + var err error + clean, err = prepareOpenAI409APIKeyReplay(ctx, clean, isOpenAIResponsesLiteWebSocketPayload(clean)) + if err != nil { + return nil, err + } + // Freeze a private copy before any builder sees it. Projection errors + // belong only to an actual HTTP bridge; native WS retains namespaces. + r.bridgeSource = append([]byte(nil), clean...) + } + r.readable = &snapshot + r.readableSource = openAIAgentRecoveryInputDigest(source) + r.readableControls = openAI409ControlsDigest(source) + return clean, nil +} + // Stored native Responses already has a verified response anchor and the // client is resending known intact opaque items. Legacy bridge reconstruction // would append history again (including tasks/tool results) on every turn. @@ -150,6 +228,23 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, model = initial.model } ctx := r.service.WithOpenAIAgentMessageRecovery(r.ctx, r.c, source, r.session, model) + if r.readable != nil { + if openAIAgentRecoveryInputDigest(source) != r.readableSource || openAI409ControlsDigest(source) != r.readableControls { + return openAIAgentRecoveryError("wire_changed") + } + ctx = context.WithValue(ctx, openAIAgentRecoveryContextKey{}, r.readable) + if mode == "http_bridge" && account.IsOpenAIApiKey() { + // Derive the permitted projection exclusively from the verified + // pre-builder snapshot, never from source/payload/request final bytes. + projected, _, err := adaptResponsesClientToolsForFunctionUpstream(r.bridgeSource, "OpenAI WS HTTP bridge") + if err != nil { + return err + } + snapshot := *r.readable + snapshot.apiInputDigest, snapshot.apiControlsDigest = openAIAgentRecoveryInputDigest(projected), openAI409ControlsDigest(projected) + ctx = context.WithValue(ctx, openAIAgentRecoveryContextKey{}, &snapshot) + } + } r.request = openAIAgentRecoveryFromContext(ctx) if r.request.disableOwnerBinding && (openAIAgentRecoveryBound(ctx) || len(r.request.items) > 0) { // Record current-turn replay safety even when a later delivery/pointer @@ -174,7 +269,7 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, return err } previous := gjson.GetBytes(source, "previous_response_id").String() - if (r.request.owner != nil || r.request.disableOwnerBinding) && previous != "" { + if !r.request.omittedHistory && (r.request.owner != nil || r.request.disableOwnerBinding) && previous != "" { owner, err := r.service.getOpenAIWSStateStore().GetResponseAccount(ctx, r.request.groupID, previous) if err != nil || owner != account.ID || gjson.GetBytes(payload, "previous_response_id").String() != previous { return openAIAgentRecoveryError("owner_unavailable") @@ -194,7 +289,11 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte, return err } r.finish = finish - if r.request.owner != nil || len(r.request.items) > 0 { + if r.request.owner != nil || len(r.request.items) > 0 || r.request.omittedHistory || + (r.service.settingService != nil && r.service.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx)) { + // In automatic continuation mode, even a plaintext initial generation + // becomes non-replayable as it crosses the physical write boundary. + // Only a separately proven unsent NEXT frame can change accounts. r.preventReplay() } return nil diff --git a/backend/internal/service/openai_ws_agent_recovery_test.go b/backend/internal/service/openai_ws_agent_recovery_test.go index 325f721a4f2e..664e120afeb3 100644 --- a/backend/internal/service/openai_ws_agent_recovery_test.go +++ b/backend/internal/service/openai_ws_agent_recovery_test.go @@ -15,6 +15,40 @@ import ( "github.com/tidwall/gjson" ) +func TestOpenAI409WSUnsentTurnBoundary(t *testing.T) { + for _, tc := range []struct { + name string + err error + turn int + want bool + }{ + {"disabled_account", denyOpenAITurn("account_ineligible"), 2, true}, + {"route_changed", denyOpenAITurn("account_binding_changed"), 3, true}, + {"initial_warmup", denyOpenAITurn("account_ineligible"), 1, false}, + {"quota", denyOpenAITurn("account_runtime_blocked"), 2, false}, + {"model_policy", denyOpenAITurn("model_not_allowed_in_group"), 2, false}, + {"store_failure", denyOpenAITurn("latest_state_unavailable"), 2, false}, + {"unknown_write", errors.New("upstream write outcome unknown"), 2, false}, + } { + t.Run(tc.name, func(t *testing.T) { + body := []byte(`{"type":"response.create","input":"private-current-task"}`) + err := openAIWSUnsentTurn(tc.err, body, "gpt-5.1", tc.turn) + body[0] = '!' + current, model, turn, ok := OpenAIWSUnsentTurnPayload(err) + require.Equal(t, tc.want, ok) + require.NotContains(t, err.Error(), "private-current-task") + if ok { + require.True(t, gjson.ValidBytes(current), "the rejected current frame must be an independent snapshot") + require.Equal(t, "gpt-5.1", model) + require.Equal(t, tc.turn, turn) + current[0] = '!' + again, _, _, _ := OpenAIWSUnsentTurnPayload(err) + require.True(t, gjson.ValidBytes(again)) + } + }) + } +} + func issue715WSManager(t *testing.T, svc *OpenAIGatewayService, parent context.Context) (*openAIWSAgentRecovery, *gin.Context, *Account) { t.Helper() c, _ := newTurnStateTestContext(t, 715, "fixture-session") diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 157047cba2a2..740a43489077 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -708,6 +708,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( // Neither output absence nor transport failure authorizes account failover. defer func() { if smartStrict && returnErr != nil { + if _, _, _, unsent := OpenAIWSUnsentTurnPayload(returnErr); unsent { + return + } var closeErr *OpenAIWSClientCloseError if !errors.As(returnErr, &closeErr) { returnErr = NewOpenAIWSClientCloseError(coderws.StatusInternalError, "upstream session ended; request was not replayed", nil) @@ -876,6 +879,11 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( parseClientPayload := func(turn int, raw []byte) (openAIWSClientPayload, error) { clientPayloadRaw := append([]byte(nil), raw...) + prepared, prepareErr := agentRecovery.prepareReadable(account, raw) + if prepareErr != nil { + return openAIWSClientPayload{}, openAIWSAgentRecoveryClose(prepareErr) + } + raw = prepared trimmed := bytes.TrimSpace(raw) if len(trimmed) == 0 { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "empty websocket request payload", nil) @@ -935,7 +943,11 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if aliasErr != nil { return openAIWSClientPayload{}, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, aliasErr.Error(), aliasErr) } - updateCodexToolNameReverseForWSFrame(c, normalized, reverse) + if agentRecovery.readablePrepared() { + mergeCodexToolNameReverse(c, reverse) + } else { + updateCodexToolNameReverseForWSFrame(c, normalized, reverse) + } if aliased { normalized = aliasedBody } @@ -1266,6 +1278,12 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } preferredConnID = "" storeDisabled = s.isOpenAIWSStoreDisabledInRequestRaw(payload.payloadRaw, account) + if recovery := openAIAgentRecoveryFromContext(ctx); recovery != nil && recovery.omittedHistory { + // A readable rebuild starts a new provider conversation. Keep the + // original client scope, but never revive A's cached socket/state. + turnState = "" + return + } if useHTTPBridge { // Sticky account affinity may be shared, but an HTTP bridge must not // inherit another connection's native WS turn state or socket binding. @@ -1358,7 +1376,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( account.ID, err, ) - return err + return openAIWSUnsentTurn(err, currentBridgePayload.clientPayloadRaw, currentBridgePayload.originalModel, turn) } } if turnState != "" && c != nil && c.Request != nil { @@ -1843,6 +1861,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( admissionErr, ) lease.MarkBroken() + if latencyGenerationStartedTurn != turn { + admissionErr = openAIWSUnsentTurn(admissionErr, clientPayload, originalModel, turn) + } return nil, admissionErr } turnStart := requesttiming.Now(ctx) @@ -2459,6 +2480,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( account.ID, err, ) + if latencyGenerationStartedTurn != turn { + return openAIWSUnsentTurn(err, currentClientPayload, currentOriginalModel, turn) + } return err } if turn > 1 && !skipBeforeTurn && hooks != nil { @@ -2482,7 +2506,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( account.ID, err, ) - return err + return openAIWSUnsentTurn(err, currentClientPayload, currentOriginalModel, turn) } } if !skipBeforeTurn { @@ -2534,6 +2558,11 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } currentPreviousResponseID := openAIWSPayloadStringFromRaw(currentPayload, "previous_response_id") expectedPrev := strings.TrimSpace(lastTurnResponseID) + if agentRecovery.readablePrepared() { + // Paired completed tools are explicit in the rebuilt input. Never + // reattach a provider pointer that the authorized rebuild removed. + expectedPrev = "" + } if contextWindowBoundary.Changed { // A context-window rollover is a new Responses root. Do not infer a // continuation anchor from the response produced in the old window. @@ -2890,6 +2919,13 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( } if relayErr != nil { lastTurnClean = false + if _, _, _, unsent := OpenAIWSUnsentTurnPayload(relayErr); unsent { + sessionLease.MarkBroken() + if hooks != nil && hooks.AfterTurn != nil { + hooks.AfterTurn(turn, nil, relayErr) + } + return relayErr + } if isOpenAIWSSessionPreempted(ctx) { sessionLease.MarkBroken() return errOpenAIWSSessionPreempted diff --git a/backend/internal/service/openai_ws_forwarder_payload.go b/backend/internal/service/openai_ws_forwarder_payload.go index 30f0a6cb4d95..5e7de39bf2c6 100644 --- a/backend/internal/service/openai_ws_forwarder_payload.go +++ b/backend/internal/service/openai_ws_forwarder_payload.go @@ -78,6 +78,9 @@ func (s *OpenAIGatewayService) buildOpenAIResponsesWSURL(account *Account) (stri return parsed.String(), nil } +// Set only by an authorized unsent readable transition, never by client headers. +type openAIWSReadableProviderKey struct{} + func (s *OpenAIGatewayService) buildOpenAIWSHeaders( ctx context.Context, c *gin.Context, @@ -211,11 +214,30 @@ func (s *OpenAIGatewayService) buildOpenAIWSHeaders( if c != nil && c.Request != nil { s.requestTimezoneHeaders(ctx, account, c.Request.Header, headers) } + s.detachOpenAIWSReadableProviderHeaders(ctx, headers, account) s.restoreBoundCodexTicketHarvestIdentity(ctx, headers, account) return headers, sessionResolution, nil } +// The inbound upgrade identity remains immutable. A valid B-bound ticket is +// independent of the discarded A conversation and must retain its own state. +func (s *OpenAIGatewayService) detachOpenAIWSReadableProviderHeaders(ctx context.Context, headers http.Header, account *Account) { + if detached, _ := ctx.Value(openAIWSReadableProviderKey{}).(bool); detached { + // conversation_id can also be the caller's trusted thread identity. + // Suppress old provider state only on outbound headers, preserving the + // original upgrade headers for later identity checks on this socket. + ticket := s.boundCodexTicketFromHeader(ctx, headers, account) + if ticket == nil { + headers.Del(openAIWSTurnStateHeader) + } + headers.Del("conversation_id") + if account.UsesOpenAICodexProtocol() && harvestTicketSessionID(ticket) == "" && headers.Get("session_id") != "" { + headers.Set("conversation_id", headers.Get("session_id")) + } + } +} + func (s *OpenAIGatewayService) buildOpenAIWSCreatePayload(reqBody map[string]any, account *Account) map[string]any { // OpenAI WS Mode 协议:response.create 字段与 HTTP /responses 基本一致。 // 保留 stream 字段(与 Codex CLI 一致),仅移除 background。 diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index 566d08dc4ba0..85e58e09fe2f 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -31,6 +31,7 @@ const openAIWSHTTPBridgeToolStateContextKey = "openai_ws_http_bridge_tool_state" type openAIWSHTTPBridgeToolState struct { ClientMapping apicompat.ResponsesClientToolMapping + ClientTools json.RawMessage // declarations before lowering; inherited by an omitted-tools turn LoweredTools json.RawMessage } @@ -48,6 +49,7 @@ func setOpenAIWSHTTPBridgeToolState(c *gin.Context, state openAIWSHTTPBridgeTool return } state.LoweredTools = append(json.RawMessage(nil), state.LoweredTools...) + state.ClientTools = append(json.RawMessage(nil), state.ClientTools...) c.Set(openAIWSHTTPBridgeToolStateContextKey, state) } @@ -490,6 +492,10 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( } } inheritedState, _ := openAIWSHTTPBridgeToolStateFromContext(c) + clientTools := inheritedState.ClientTools + if currentTools, present := openAIWSHTTPBridgeRawField(body, "tools"); present { + clientTools = currentTools + } inheritedLoweredTools := decodeOpenAIWSHTTPBridgeLoweredTools(inheritedState.LoweredTools) body, clientToolMapping, err = adaptResponsesClientToolsForFunctionUpstreamWithMapping( body, @@ -514,6 +520,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( } setOpenAIWSHTTPBridgeToolState(c, openAIWSHTTPBridgeToolState{ ClientMapping: clientToolMapping, + ClientTools: clientTools, LoweredTools: loweredTools, }) } @@ -607,6 +614,10 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( account.ID, admissionErr, ) + if forwardStart.IsZero() { + source, _ := ctx.Value(openAIWSAgentSourceKey{}).([]byte) + admissionErr = openAIWSUnsentTurn(admissionErr, source, originalModel, turn) + } return nil, admissionErr } // Freeze the first-send boundary. Rejected-field network attempts remain diff --git a/backend/internal/service/openai_ws_readable_continuation.go b/backend/internal/service/openai_ws_readable_continuation.go new file mode 100644 index 000000000000..97f3e95f9208 --- /dev/null +++ b/backend/internal/service/openai_ws_readable_continuation.go @@ -0,0 +1,177 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "strings" + "sync/atomic" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// 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 +} + +func (e *openAIWSUnsentTurnError) Error() string { + return "websocket current turn not sent: " + e.cause.Error() +} +func (e *openAIWSUnsentTurnError) Unwrap() error { return e.cause } + +func openAIWSUnsentTurn(err error, body []byte, model string, turn int) error { + var denied *OpenAITurnAdmissionError + if turn <= 1 || !errors.As(err, &denied) || !gjson.ValidBytes(body) { + return err + } + switch denied.Reason { + case "account_ineligible", "account_unavailable", "account_binding_changed", "credential_parent_ineligible", "group_membership_changed": + default: + return err // Auth, quota, model policy, store failures and sent work stay terminal. + } + return &openAIWSUnsentTurnError{cause: err, body: append([]byte(nil), body...), model: model, turn: turn} +} + +func OpenAIWSUnsentTurnPayload(err error) ([]byte, string, int, bool) { + var unsent *openAIWSUnsentTurnError + if !errors.As(err, &unsent) { + return nil, "", 0, false + } + return append([]byte(nil), unsent.body...), unsent.model, unsent.turn, true +} + +// ResetOpenAIWSReadableProviderSession drops only the provider-specific smart +// session at an authorized unsent rebuild. Client identity and owner records +// remain untouched. A generation already crossing the write boundary cannot reset it. +func ResetOpenAIWSReadableProviderSession(ctx context.Context, c *gin.Context) context.Context { + r := openAIAgentRecoveryFromContext(ctx) + blocked, _ := ctx.Value(openAIWSAgentRecoveryRetryKey{}).(*atomic.Bool) + if c == nil || r == nil || !r.omittedHistory || r.delivery != nil || blocked == nil || blocked.Load() { + return ctx + } + c.Set(smartProtocolSessionKey, (*openAISmartProtocolSession)(nil)) + return context.WithValue(ctx, openAIWSReadableProviderKey{}, true) +} + +type openAIWSRecoveryPrincipal struct{ userID, keyID int64 } + +// The authenticated handler supplies this identity. It grants shadow scope, +// not HTTP response-pointer authorization or permission to replay a generation. +func SetOpenAIWSRecoveryPrincipal(c *gin.Context, userID, keyID int64) { + c.Set("openai_ws_recovery_principal", openAIWSRecoveryPrincipal{userID, keyID}) +} + +func openAIReadableRecoveryUser(c *gin.Context, keyID int64) int64 { + if c != nil && keyID > 0 { + value, _ := c.Get("openai_ws_recovery_principal") + if principal, ok := value.(openAIWSRecoveryPrincipal); ok && principal.keyID == keyID && principal.userID > 0 { + return principal.userID + } + } + return openAIAgentRecoveryHTTPUser(c, keyID) +} + +// 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 +} + +// 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) { + if s == nil || s.settingService == nil || !s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) { + return ctx, body, false, nil + } + if !utf8.Valid(body) || !openAIEncryptedJSONUnambiguous(body) { + return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") + } + ctx = context.WithValue(ctx, openAIReadableShadowContextKey{}, (*openAIReadableShadowObservation)(nil)) + ctx, body = s.RestoreOpenAIReadableShadow(ctx, c, body, session) + // A missing declaration field inherits the callable tools on this client + // socket. Resolve it BEFORE freezing controls, never from the final wire. + // Explicit empty/null declarations retain their replacement semantics. + if _, present := openAIWSHTTPBridgeRawField(body, "tools"); !present { + if state, ok := openAIWSHTTPBridgeToolStateFromContext(c); ok && len(state.ClientTools) > 0 { + var err error + body, err = sjson.SetRawBytes(body, "tools", state.ClientTools) + if err != nil { + return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") + } + } + } + next := s.WithOpenAIWSAgentRecovery(ctx, c, body, session, model) + if !openAIWSCompletedToolInputs(body) { + return ctx, body, false, openAIAgentRecoveryError("owner_conflict") + } + r := openAIAgentRecoveryFromContext(next) + if len(r.items) == 0 && !openAI409HasProviderState(body) && !r.disallowLearning { + if !openAI409HasReadableIntent(body) { + return ctx, body, false, openAIAgentRecoveryError("readable_intent_missing") + } + input := gjson.GetBytes(body, "input") + if input.Type == gjson.String || !input.Exists() || input.Type == gjson.Null { + text := input.String() + if input.Type != gjson.String { + text = gjson.GetBytes(body, "instructions").String() + } + encoded, _ := json.Marshal([]any{map[string]any{"type": "message", "role": "user", "content": text}}) + var err error + body, err = sjson.SetRawBytes(body, "input", encoded) + if err != nil { + return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") + } + } + clean, err := prepareOpenAI409ReadableReplay(body) + if err != nil { + return ctx, body, false, openAIAgentRecoveryError("readable_history_unsupported") + } + next = context.WithValue(next, openAIGuardianParentAffinityContextKey{}, openAIGuardianParentAffinity{}) + next = WithOpenAIEncryptedReasoningAffinity(next, clean) + r.omittedHistory, r.omittedSource = true, nil + r.inputDigest, r.replayControlsDigest = openAIAgentRecoveryInputDigest(clean), openAI409ControlsDigest(clean) + return next, clean, true, nil + } + next, clean, changed, err := s.TryRebuildOpenAI409History(next, c, body, session, model, openAIAgentRecoveryError("owner_unavailable")) + if changed { + next = context.WithValue(next, openAIWSAgentRecoveryRetryKey{}, &atomic.Bool{}) + } + return next, clean, changed, err +} diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 5b25f8c8d58e..46bc5baf4994 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -748,6 +748,11 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( originalFirstClientMessage := firstClientMessage agentRecovery := openAIWSAgentRecoveryFromContext(ctx) pendingAgentSource := originalFirstClientMessage + if prepared, err := agentRecovery.prepareReadable(account, firstClientMessage); err != nil { + return openAIWSAgentRecoveryClose(err) + } else { + firstClientMessage = prepared + } if next, policyErr := applyOpenAIWSReasoningEffortPolicy(firstClientMessage, hooks, hooks.forcedReasoningEffort()); policyErr != nil { return NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, policyErr.Error(), policyErr) } else { @@ -821,7 +826,11 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if aliasErr != nil { return aliasErr } - updateCodexToolNameReverseForWSFrame(c, firstClientMessage, reverse) + if agentRecovery.readablePrepared() { + mergeCodexToolNameReverse(c, reverse) + } else { + updateCodexToolNameReverseForWSFrame(c, firstClientMessage, reverse) + } if aliased { firstClientMessage = aliasedBody } @@ -1132,6 +1141,11 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } responsesLite := isResponseCreate && isOpenAIResponsesLiteWebSocketPayload(payload) if isResponseCreate { + prepared, err := agentRecovery.prepareReadable(account, payload) + if err != nil { + return payload, nil, openAIWSAgentRecoveryClose(err) + } + payload = prepared if normalized, compatibilityChanged, normalizeErr := normalizeOpenAIResponsesWebSocketCompatibilityBodyWithConfig(s.cfg, payload, account, responsesLite); normalizeErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "invalid websocket request payload", normalizeErr) } else if compatibilityChanged { @@ -1143,7 +1157,11 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if aliasErr != nil { return payload, nil, NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, aliasErr.Error(), aliasErr) } - updateCodexToolNameReverseForWSFrame(c, payload, reverse) + if isResponseCreate && agentRecovery.readablePrepared() { + mergeCodexToolNameReverse(c, reverse) + } else { + updateCodexToolNameReverseForWSFrame(c, payload, reverse) + } if aliased { payload = aliasedBody } @@ -1229,7 +1247,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( account.ID, err, ) - return payload, nil, err + return payload, nil, openAIWSUnsentTurn(err, clientPayload, requestModelForThisFrame, turnNo) } } } @@ -1274,6 +1292,9 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( account.ID, err, ) + if isResponseCreate { + err = openAIWSUnsentTurn(err, clientPayload, requestModelForThisFrame, turnNo) + } return payload, nil, err } } @@ -1442,7 +1463,7 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } if err != nil { s.invalidateOpenAIWSTurnStateAfterAdmissionFailureForRequest(ctx, c, payload, account.ID, err) - return err + return openAIWSUnsentTurn(err, pendingAgentSource, usageMeta.requestModelForFrame(pendingAgentSource), max(2, int(completedTurns.Load())+1)) } if err := s.priorityLatencyBeforeSend(pendingLatencyCtx, account); err != nil { return err @@ -1808,6 +1829,9 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( } func openAIWSPassthroughRelayClientClose(exit openaiwsv2.RelayExit, completedTurns int) (coderws.StatusCode, string, bool) { + if _, _, _, unsent := OpenAIWSUnsentTurnPayload(exit.Err); unsent { + return 0, "", false // Handler owns bounded fresh admission on the same client. + } var closeErr *OpenAIWSClientCloseError if errors.As(exit.Err, &closeErr) { return closeErr.StatusCode(), closeErr.Reason(), true diff --git a/backend/internal/service/recovered_context_privacy.go b/backend/internal/service/recovered_context_privacy.go new file mode 100644 index 000000000000..686c1a77724d --- /dev/null +++ b/backend/internal/service/recovered_context_privacy.go @@ -0,0 +1,16 @@ +package service + +import "context" + +type recoveredContextPrivacyKey struct{} + +// Recovered text is evaluated by normal policies, but cannot be copied to +// audit bodies, excerpts or penalty evidence with a different retention period. +func WithRecoveredContextPrivacy(ctx context.Context) context.Context { + return context.WithValue(ctx, recoveredContextPrivacyKey{}, true) +} + +func HasRecoveredContextPrivacy(ctx context.Context) bool { + value, _ := ctx.Value(recoveredContextPrivacyKey{}).(bool) + return value +} diff --git a/docs/encrypted-agent-owner-policy.md b/docs/encrypted-agent-owner-policy.md index 2f0804a5070b..bb5013edb295 100644 --- a/docs/encrypted-agent-owner-policy.md +++ b/docs/encrypted-agent-owner-policy.md @@ -1,5 +1,7 @@ # 加密 agent 历史账号策略 +后台“409 忽略/历史省略”Beta 开关属于另一个明确有损的路径,见 [HTTP 可读历史续接](encrypted-history-readable-continuation.md)。下述进程配置控制完整密文尝试,不等同于该后台开关。 + 默认仍按已登记的账号和原生 Responses 路线恢复加密 `agent_message`。原账号限流或过载时,保留原等待提示和恢复时间。管理员可显式允许完整历史尝试普通账号池中的其他合格账号: ```yaml diff --git a/docs/encrypted-history-409-beta.md b/docs/encrypted-history-409-beta.md index 739ae7412cde..8e0a6eefb7fd 100644 --- a/docs/encrypted-history-409-beta.md +++ b/docs/encrypted-history-409-beta.md @@ -3,20 +3,22 @@ 入口:系统设置 → 网关设置 → 网关转发行为 → **409 省略加密内容(Beta)**。 默认关闭。管理员保存后,对后续触发条件匹配的请求生效,无需重启。 -HTTP `/v1/responses` 在初次选号、尚未发送上游时,如果已登记的历史加密 agent 账号不可用或路线发生变化,严格模式会返回兼容性 409。开启本功能后,网关尝试省略旧历史中的密文,用明确的“历史加密内容已省略”文本替换,再按正常账号池规则选号一次。支持 JSON 和 SSE 响应。 +HTTP `/v1/responses` 支持 JSON/SSE 有损续接。WebSocket 的 `http_bridge`、`ctx_pool`、`shared`、`dedicated`、`passthrough` 路径可在确认当前轮尚未发送、原账号失去资格时,保持原客户端连接和 session 标识,按正常准入重新选择合格账号。重选受现有账号切换预算限制,无需点击确认、重开会话或重新输入。 -这是有损恢复。模型看不到被省略的内容,不能保证任务结论完整或供应商接受。可读消息、工具调用参数、可读工具结果、工具 ID 及顺序继续保留。已省略的 agent 历史转为带原 author/recipient 说明的普通上下文消息;reasoning 密文保持既有处理。 +这是有损恢复。只要现存最新用户请求、原始指令或可信同任务摘要足够,旧不可读 agent 历史可以省略;不要求恢复完整历史。可读消息、已完成工具的调用参数、结果、ID 和顺序保留。旧 agent/reasoning 内容转换为有明确出处的普通上下文,密文用不可用标记替代。`previous_response_id`、`conversation` 及旧账号会话绑定在重建时一起解除,建立新的上游会话。不能保证缺失历史后的结论完整或供应商接受。 以下条件继续返回原错误: -- 最新用户或 agent 任务及其后的工具结果仍含不可读内容。 -- 请求依赖 `previous_response_id`、`conversation`、`item_reference` 或加密压缩状态,无法从本次请求取得完整历史。 +- 最新请求完全不透明且无可读任务线索,也无匹配的未来 shadow 记录。 +- 只有服务端指针而没有可读当前意图;当前轮工具调用/结果不成对或状态未确认。 - 交付未确认、owner 冲突、共享存储错误、429 限流或 503 过载。 -- WebSocket、压缩端点、已开始返回下游数据或已尝试过上游发送的请求。 +- 压缩端点、当前生成已发送或发送结果不明;已经输出的生成和已完成工具不自动重放。前一轮成功完成不阻止新的未发送轮次恢复。 本功能不针对任意供应商 409 进行删改重试。省略后的实际发送仍检查用户、Key、分组、模型、余额、额度、账号状态和并发;没有可用账号仍会失败。上游拒绝或交付不确定时不自动重新发送。既有 owner 缓存不清空、不改归属;新输出仍通过现有交付屏障登记。 -管理 API 字段:`openai_409_omit_encrypted_history_enabled`,沿用管理员系统设置 GET/PUT。旧客户端不发送该字段时保留已保存值。普通用户不能逐请求启用。只在符合条件的本地拒绝路径读取开关,读取失败按关闭处理;日志仅记录发生了省略与上下文损失,不记录密文、正文或摘要。 +管理 API 字段:`openai_409_omit_encrypted_history_enabled`,沿用管理员系统设置 GET/PUT。旧客户端不发送该字段时保留已保存值。普通用户不能逐请求启用。读取失败按关闭处理;日志仅记录省略与上下文损失,不记录密文、正文或摘要。 + +启用后可为未来请求保存已成功交付、工具关系完整的可读上下文。共享 shadow 按用户/API Key、分组、模型、客户端会话及精确 opaque 任务标识隔离,最长 30 分钟,每个用户/API Key 最多八条、合计 512 KiB。当前首个恢复形态是一个精确 opaque agent 项且没有新意图或未配对工具;已有可读意图优先。原始 owner 不改归属,独立 epoch/CAS 和最终发送前的记录复读防止复用、延迟发布及失效关联。恢复文本仍接受审核,带不保留正文的来源标记。不存在的历史不能回填成 shadow。 关闭后,后续请求恢复严格行为。无需数据库迁移或清 Redis;回退旧二进制会忽略此设置。切换不会取消在途请求,已省略的信息无法由关闭开关恢复。 @@ -30,4 +32,4 @@ HTTP `/v1/responses` 在初次选号、尚未发送上游时,如果已登记 如果后续一般兼容逻辑会删除整个 reasoning 或可读 reasoning.content,仍会拒绝该输入,而不是静默丢弃。此时服务器记录 `openai.encrypted_history_409_refused`、`stage=input_integrity`,不含正文、凭据或密文摘要,客户端错误码保持 `encrypted_agent_recovery_wire_changed`。并非所有历史形态都保证可恢复,未知供应商接受度需另行验证。 -CI 使用真实 handler、隔离 Redis 和 localhost HTTP 假上游,覆盖元数据规范化后的 JSON/SSE 续接、精确一次发送、真实上游拒绝透传及完整性负例;旧 2.21.1 的同一组新增场景必须命名失败。该证据不等于线上六条历史请求已经重放,也不表示修复已发布或部署。 +CI 使用真实 handler、隔离 Redis 和 localhost HTTP/WebSocket 假上游。五适配器回归保留同一客户端,执行 A 工具请求、管理员停用 A、B 复用已完成结果、后续工具验证和正常 terminal;另有关闭开关、无意图、B 不可用、交付未确认及 B 发送后断线的边界。远程 RED/GREEN 必须逐叶核验且不能含编译、panic、race、skip 污染;当前源码本身不代表这些检查已通过。真实供应商验收需要另行授权的隔离环境、两个受控账号和预算,不能用合成 CI 冒充。 diff --git a/docs/encrypted-history-readable-continuation.md b/docs/encrypted-history-readable-continuation.md new file mode 100644 index 000000000000..f3cbb0cfec1f --- /dev/null +++ b/docs/encrypted-history-readable-continuation.md @@ -0,0 +1,44 @@ +# Responses 的自动有损可读续接 + +管理员开启现有 Beta 设置 `openai_409_omit_encrypted_history_enabled` 后,HTTP Responses 可以从可用的最新 user 任务、显式 instructions 或结构化任务摘要自动重建请求,省略不能迁移的旧 opaque 历史,并选择合格账号建立新的 upstream 会话。无需客户端确认、重开会话或重新输入。默认仍为 `false`;它与进程配置 `disable_encrypted_agent_owner_binding` 的完整密文跨账号尝试是两个独立选项。没有新增设置、迁移或公告 ID。 + +本次修复一个发送前仍返回 409 的缺口:历史省略冻结了 input 摘要,但后续 `normalizeOpenAIAPIKeyStoreFalseReasoningReplay` 会删除没有密文的 reasoning,`normalizeOpenAIResponsesReasoningContentReplay` 会删除可读 reasoning.content。最终 `prepareOpenAIAgentRecoveryAttempt` 检测到 input 变化并以 `wire_changed` 拒绝。 + +重建不再把最后一个 agent_message 的位置视为任务可恢复性的依据。现有可读任务在旧 opaque agent 之前也能继续;全部没有可读意图时返回明确的 422 缺失错误,不编造任务或返回假成功。空白 user 占位不覆盖此前任务;仅 system 通用指导和 agent 路由 envelope 不作为任务。较晚的完全 opaque user 任务不能借用此前不相关摘要。 + +旧 agent/reasoning/compaction 的可读内容仍带来源说明,已识别的密文标记为不可用;未知历史 reasoning 结构保留成可读 JSON,而不是作为可执行协议节点发出。工具参数、已完成结果和关联不能因此丢弃。previous_response_id / conversation 同时从 body、映射后的 forwardBody、选号参数和 recovery context 清除。已有异租户 response 归属和 store error 继续拒绝;只有无归属记录的旧指针才可在显式模式下丢弃,且仅使用调用者提供的可读意图。 + +最终发送仍精确校验 input,并新增 tools/schema、tool_choice、parallel_tool_calls 和有效 instructions 的摘要保护。原生 OAuth 在验证原快照后,仅派生 system 指导保留/提升、原生工具声明格式和保留名映射的预期快照;原快照不改写,普通 input 过滤器不能再次丢数据。最终 wire 必须匹配派生预期且无旧 provider pointer。 + +已完成 A/B 记录的账号差异和 pending/failed/conflict 分开处理。所有原 opaque item 都要扫描,重建后保留原 key 引用,在实际发送前再次读取交付屏障,不清除或覆写 A owner。新 B 输出继续先 reserve、成功下游写后 commit;拒绝和未知交付不能触发自动重放。沿用不含正文的 `openai.encrypted_history_409_omitted` 审计标识,不增加阻断客户端的通知。 + +## 当前实现与边界 + +以下描述 PR #834 的最终产品行为;具体提交是否通过动态验证,以该 PR 当前 head 的 Actions 和正文为准,不把测试代码存在或旧 head 成功当作当前验收。 + +| 场景 | 实现与验证边界 | +| --- | --- | +| 原生 API-key / OAuth HTTP JSON、SSE | 可读任务、结构摘要和 provider pointer 联合重建;最终发送检查任务、tools/schema、instructions 与交付屏障 | +| WebSocket HTTP bridge、原生共享/独占池和 passthrough | 只在当前轮尚未发送且原账号不再合格时重建并重新选号;已发送或交付不明的轮次不重放 | +| 后续请求只回带同一 opaque agent item | Beta 开启时可从之前成功交付的同任务 readable shadow 恢复;原始未知历史无可用记录时不编造 | +| 混合 A/B 历史、pending/failed/conflict、旧 owner 消失 | 逐项保留并在发送前复查屏障,旧记录不改写为新账号 | +| 模型/权限/额度/账号/并发、工具副作用 | 重新准入;完整工具调用与已完成结果保留,不自动重做外部工具 | +| 审核 | 恢复的任务和上下文在发送前重新接受提示词及所选上游审核;普通请求仍按既有提取规则。服务端恢复标记禁止正文进入审计持久队列、摘录或处罚证据 | +| 非 Beta 的完整密文 owner-binding opt-out | 独立路径;本 PR 不宣称修复 Issue #842 的普通元数据规范化矩阵 | +| 真实供应商兼容 | 既往维护报告记录了 `afa7dbd6f` 的 API-key HTTP response-pointer A→B 工具循环;不代表当前 head、OAuth、opaque-agent 或 WS 的真实供应商验收 | + +Readable shadow 使用共享 Redis,按用户/API Key、分组、模型、会话和精确任务隔离。每个用户/API Key 总计最多 8 条,每条最多 64 KiB,TTL 最多 30 分钟;不回退到本地存储。它包含可读任务上下文,只有 Beta 开启时发布/恢复,管理员应将其纳入 Redis 的数据保留范围。投递 epoch 和原 owner 独立,失效、冲突、过期或存储不可用时不能借用旧任务。详见 [shadow 约束](future-readable-shadow.md)。 + +没有新增数据库迁移或设置。旧版不能消费新 shadow 的完整恢复语义;回退时关闭 Beta、排空在途请求及旧 WS 后按正常流程切换,不以清空 owner 记录恢复会话。此次源码合并本身不改变线上开关或部署版本。 + +## 远端验证 + +工作流 **Readable continuation 409 RED GREEN**(`readable-continuation-409.yml`)可由 PR 自动触发,也可由监督在发布候选分支后手动触发: + +```bash +gh workflow run readable-continuation-409.yml --repo ranxi2001/sub2api --ref fix/agent409-readable-continuation +``` + +首次新增的 workflow 若尚未被默认分支索引,以 PR 自动触发为准。原 reasoning 工作流仍使用固定生产提交 `dbed7697aa56e76c6eb48c4914fa441496b67bdd` 的 omission 和相应生产调用者,保留候选测试;GREEN 保持干净候选树。两侧执行同一 `TestOpenAI409ReadableContinuationHTTP`,覆盖 18 个 JSON/SSE 场景。新的任务/指针/OAuth 工作流及已取得的旧源码业务 RED 见 [HTTP 重建 TDD](http-readable-task-rebuild-tdd.md)。后续每个候选均须重新取得对应 SHA 的 GREEN;测试存在、编译失败、no-tests、skip、panic/race 或旧版本成功都不算验收。 + +夹具只使用本地虚构 provider、隔离 Redis、虚构身份和内存账本工具。handler 的认证/计费依赖使用现有测试替身,不能据此声称验证了真实权限、余额或供应商协议。GREEN 另运行既有省略、完整性、当前任务、交付和权限保护的定向回归。所有动态执行仅限 Actions;本地仅做静态检查。 diff --git a/docs/future-readable-shadow.md b/docs/future-readable-shadow.md new file mode 100644 index 000000000000..c042c5da5054 --- /dev/null +++ b/docs/future-readable-shadow.md @@ -0,0 +1,49 @@ +# Future readable shadow:提交边界与恢复约束 + +> 历史设计与测试阶段记录:下方“待执行”“尚未实现”“下一片”均描述当时 checkpoint,不代表 PR #834 最终实现。当前能力、Redis 保留边界和未覆盖范围见 [Responses 有损可读续接](encrypted-history-readable-continuation.md#当前实现与边界);动态结果以 PR 当前 head 的 Actions 为准。 + +此增量实现未来 HTTP 请求仅回带同一 opaque agent item 时,恢复之前实际观测并成功交付的同任务上下文。它沿用显式开启的有损续聊 Beta 设置;原始未知历史没有可用线索时不能编造。当前可读意图始终优先,不依赖 shadow 存在。 + +## 第一片范围 + +真实 HTTP JSON/SSE、隔离真实 Redis、两个独立网关 service 实例。A 收到明确任务并返回工具调用,客户端执行一次内存源码补丁,再把真实调用与结果交回 A。A 随后交付 opaque task。管理员停用 A 后,同一客户端/session 只回带该 opaque item,由第二节点恢复已提交上下文并在合格 B 正常完成。provider 必须收到原任务、已完成 call/result 和实际工具 schema;不能重做工具。 + +`TestOpenAI409FutureShadowHTTP` 两个正常场景必须走到真实 B 网络发送与客户端 completed,不能用 cache helper 成功替代。`TestOpenAI409FutureShadowBoundaries` 的 26 个场景覆盖不同 user/key/group/model/session/task、TTL 到期、失败下游写、原 owner pending/failed/conflict、设置关闭和当前可读新任务优先。记录在 actual downstream write 之前不能成为已提交 shadow。过期/跨作用域/未知交付不得产生 B 请求,也不能修改原 owner。 + +实现使用 Redis `openai_readable_shadow:v1:` namespace,scope 含 tenant/user、API key、group、请求 model、session hash、任务关联(完整 opaque item digest)和格式版本;键只含 hash,不能放任务正文。每条最大 64 KiB、TTL 不超过 30 分钟;每个 user/key 跨全部 group/model/session 最多八条,正文总量不超过 512 KiB,原子淘汰旧记录及过期索引。 + +## 生产接入约束 + +1. Capture 只能来自网关实际观测的认证请求中的明确意图和配对的已完成工具结果。绑定到同次已成功交付的具体 opaque output,不能维护按 session 取“最近任务”的泛用 fallback。 +2. 复用原 generation 的 pending/failed/commit 边界:在最后下游写成功之前不发布可读 shadow;发布失败只能让 shadow 不可用,不能改写 producer owner 或授权重发。 +3. Recover 必须重新检查调用者作用域、当前资格、opaque digest/task association、TTL 和全部原 owner delivery fences。先有当前可读任务就用当前请求,不能用旧 shadow 覆盖新意图。不能修改已完成 tool result、恢复为新 tool call 或重放未知副作用。 +4. shared store 在同节点/跨节点均有界。无可用 shared store 时不得改用无期限本机 map,不能通过日志保存正文。记录内容只在服务内受限存储中使用,不加入审计/metrics 错误字符串。 +5. 本片是 HTTP 首测;WS bridge/native/shared/pooled/dedicated 必须分别接入其实际 final payload 与 downstream terminal,不能借 HTTP 测试替代。 + +## 远端证据 + +工作流 **Future readable shadow TDD**(`future-shadow.yml`)现在 PR 自动执行 RED/GREEN。固定 source baseline `84e47f1b57acba77f1cfae08a63e8dd9d32a7991`,disposable worktree 恢复该版本全部生产 Go 文件,保留新回归。RED 必须是两个 leaf 各自的 `FUTURE_SHADOW_B_DISPATCH_MISSING` 与 `encrypted_agent_recovery_readable_intent_missing`,不能接受任意失败、panic/race、skip/no-tests 或编译错误。 + +```bash +gh workflow run future-shadow.yml --repo ranxi2001/sub2api --ref fix/agent409-readable-continuation -f phase=BOTH +``` + +生产实现前已读取远端 run `43455666698` artifact `14054563124`:候选 de22、基线 84e47 的两个具名 leaf 均在预期业务断言失败,无运行污染。新候选 GREEN 必须执行主回归 2、边界 26、资源 18、精确任务关联 2,共 48 个 transport leaf,随后执行 session-last-task 生产变异。候选 SHA、baseline SHA、test/production blobs、原始 JSONL 和 validator 自测记录独立上传。生产候选的 GREEN/变异尚未执行,不能用上述 RED 声称成功。 + +本 checkpoint 另修复既有 Issue805 WS 夹具的基线等待:必须要求整条 owner record 是合法 JSON 数组才视为 A committed;不能仅用 gjson 从 `pending::[...]` 后的数组取到 account ID。原 B pending 屏障、跨节点等待和原记录字节不变断言保持。该修复待远端执行验证,不能声称 WS 有损重建已实现。 + +所有动态执行仅限 Actions;没有受控真实供应商账号/实例,真实 A/B 验收仍是监督负责的 blocker。future shadow 的容量/故障/冲突已有生产实现和 transport 回归,等待远端验证。WS bridge/native/shared/pooled/dedicated 的有损重建与 shadow 接入仍是同 PR 必需后续,不能合并或宣称完整功能验收。 + +## 生产实现与新增反例 + +shadow 恢复在 HTTP 内容审查、image intent、token 预留和选号之前进行,恢复出的任务仍经过当前准入及最终 long-context 检查。它不是绕过准入的授权。当前可读意图优先,不查询旧任务;只有完整 opaque item digest 对应的已提交记录才可提供旧意图,不能使用 session 最近记录。 + +共享存储使用 user/key 的 principal hash 作为 Redis Cluster hash tag;在这个预算内,group/model/session/item 都进入精确任务键。每个 principal 最多八条、每条最大 64 KiB,所有 session/model/group 合计不超过 512 KiB 正文,TTL 最多 30 分钟。索引和记录同 slot 原子写入/淘汰,读和重复发布不续期,相同输出的不同内容失效为 conflict,不能覆盖成新授权。没有共享 store 不启用本机后备。 + +原始请求的可读意图是 capture 前提;实际 native send 的文本及配对 completed call/result 才是保存候选。包含未完成工具或含未知交付的请求不能生成可恢复 shadow。只有真实 downstream terminal 成功后、相应 output owner 提交成功后才发布。记录保留来源的精确 delivery fences,恢复和最后实际发送均再读;缓存失败只损失 future 恢复能力,不改 owner、不重发已交付响应。 + +独审新增 P2 对应 `TestOpenAI409FutureShadowTaskAssociation`:同一个作用域先真实执行 X 的 patch,再执行独立 Y 的 verification,两个不同 opaque output 均已交付并有 committed owner;另一个节点恢复旧 X,B 必须接收 X 的指令与 patch 结果且不能含 Y 指令/verification。原 unknown-item 负例保留。远端 session-last-task 变异必须因任务内容不匹配而失败,不能用缺 owner/缺 store 失败代替。 + +`TestOpenAI409FutureShadowResources` 另覆盖 JSON/SSE × 九项:跨141个任务/session 超出八条正文和128条 epoch预算后旧记录淘汰/最新仍能恢复、仅 shadow 写故障/读故障、超大正文不入库、请求或响应含未完成工具不入库、同一 opaque output 对应两条已交付任务时失效,以及回带旧 opaque 后生成同 identity 时失效。故障通过真实 Redis client 的命令 hook 注入,owner、billing 与真实 HTTP 保留;读故障要求先存在真实 committed record,且必须证明 hook 实际执行。 + +本生产片的 shadow 恢复范围是单个精确 opaque agent item;多条未知 opaque、新 opaque user/media 意图或新未配对工具结果不能借旧快照猜测当前任务。可读请求仍走现有 HTTP 有损重建,不受这个 future-only 范围限制。普通 native HTTP 的共同发送/交付路径可记录上下文。后续独审发现的发布窗口、失效竞态与审计保留已在 [生命周期修复记录](shadow-review-repair-and-ws-tdd.md) 中处理:记录格式升级为2并依赖独立 pending/ready epoch,新增 OAuth shadow 线级回归。新候选全部动态验证、所有 WS 生产入口仍未完成。 diff --git a/docs/http-readable-task-rebuild-tdd.md b/docs/http-readable-task-rebuild-tdd.md new file mode 100644 index 000000000000..bdf881cc619e --- /dev/null +++ b/docs/http-readable-task-rebuild-tdd.md @@ -0,0 +1,58 @@ +# HTTP 可读任务重建:生产候选与远端 TDD + +> 历史设计与测试阶段记录:下方“待执行”“尚未实现”“下一片”均描述当时 checkpoint,不代表 PR #834 最终实现。当前能力、Redis 保留边界和未覆盖范围见 [Responses 有损可读续接](encrypted-history-readable-continuation.md#当前实现与边界);动态结果以 PR 当前 head 的 Actions 为准。 + +测试检查点 `5d8d14b960c2beda3627ee514ee09eead32a771a` 已在 [run 43441932069](https://github.com/ranxi2001/sub2api/actions/runs/43441932069) 取得固定 `96ba36a85edab665ad5a035788fc07a40fd18762` 生产源码的业务 RED:36 个 leaf 均命中 B 未发送的指定断言,30 个 owner_unavailable、6 个 OAuth http_previous_response_unsupported,无运行污染。当前在此 RED 后实现生产候选及独审 oracle 修复;候选 GREEN 和新增 mutation 仍须 Actions 执行,不视为已验收。 + +## 本片目标 + +已授权的有损模式应支持无人值守编码循环:同一客户端把已有可读任务和已完成工具结果继续交给网关,管理员停用 A 后自动选择合格 B。不能要求用户点击确认、换客户端会话、手工重试或重新输入。无法迁移的旧 opaque 历史可以省略;只有没有任何可读意图的请求才不能重建任务。权限、额度、停用状态及未决交付仍独立校验。 + +`TestOpenAI409HTTPTaskRebuild` 有 36 个场景:API-key/OAuth × JSON/SSE × 无指针但最后一个 agent 仍 opaque / previous_response_id / conversation × 完成 / B 拒绝 / 写失败。回归通过真实 localhost HTTP 组合客户端、生产 handler、调度、转发和 provider;使用真实隔离 Redis 与生产 owner Lua。OAuth 的固定 ChatGPT URL 只在最终 HTTPUpstream 发送边界重定向到 localhost,body 和认证头不改写。夹具明确拒绝其他目的地和代理,不能向真实上游外呼。 + +正常路径中,A 返回一次 `apply_patch`,客户端修改一个内存中的 Go 源文件;A 停调度后 B 返回一次 `run_tests`,客户端解析实际修改后的 AST 并计算 `Sum(2,3)`;随后 B 交付最终 completed。所有后续请求只附加实际收到的 output 和实际执行的工具结果,不新增用户指令,不重试,原 session 标识固定。两个工具各执行一次。B 必须收到最新可读任务、system 指导、工具参数和匹配结果;替换请求不含 A 的 provider pointer/ciphertext。第三轮同时包含已交付 A/B opaque 历史,不能再次因混合历史拒绝正常续接。 + +新 B 输出继续接受实际下游写前 pending、写后 commit、写失败 failed 的检查。A owner 不变;上游拒绝不在账号池重放;成功上游用量仍进入 RecordUsage。模拟工具只操作内存数据,不运行外部命令,不代表真实供应商完成了真实仓库编码。 + +`TestOpenAI409HTTPRebuildBoundaries` 有 20 个场景:API-key/OAuth × JSON/SSE × pointer-only 无任务 / opaque-only 无任务 / pending / failed unknown delivery / B 也停用。它们要求明确错误、无完成伪装、无 B generation、owner 及交付屏障保留。该套在 GREEN 阶段执行,不用尚未执行的边界假设充当 RED。 + +provider 现在必须先收到客户端的两个工具声明及完整 schema 才发出任何工具;原生可选 description/strict 默认值可变化,参数 schema 不可丢失或改变。`TestOpenAI409HTTPToolDefinitionOracle` 的 8 个场景在测试专用最终传输层删 tools 或改变 schema,要求真实 provider 返回拒绝且不输出工具、无 B owner/usage grant。 + +`TestOpenAI409HTTPMixedDeliveryFences` 的 48 个场景先产生两个已交付 A item 和一个已交付 B item,再将 A 或 B 的真实 Redis owner record 置为 pending/failed/conflict,测试正反 opaque item 顺序。必须在额外 generation 前拒绝,所有 Redis record 值逐字节不变。反序包含“已完成 B → 已完成 A-extra → fenced A”,专门识别遇 owner 差异就停止扫描的错误。 + +两个远端 disposable source mutant 分别把实际生产扫描缩成最新 key,或在 owner 差异处截断保留 key 列表并 break。它们用不变的真实 HTTP oracle 运行,必须在 `HTTP_REBUILD_FENCE_BYPASSED` 断言失败并证明错误地产生了 `coding-task-complete`;任意其他失败不能算 mutation 被检出。原干净 candidate 不修改。 + +## 远端运行 + +工作流 **HTTP readable task rebuild TDD**(`http-task-rebuild.yml`)现已自动执行 BOTH;监督也可在发布后手动指定阶段: + +```bash +gh workflow run http-task-rebuild.yml --repo ranxi2001/sub2api --ref fix/agent409-readable-continuation -f phase=BOTH +``` + +新增 workflow 如未被默认分支索引,以 PR 自动触发为准。必须取得同一生产候选 SHA 的 GREEN、边界和 mutation 结果,以及独立审查,才能声称 HTTP gate 完成。 + +RED 的固定 source baseline 是 `96ba36a85edab665ad5a035788fc07a40fd18762`:创建 disposable worktree,恢复所有变更的后端生产 Go blobs,保留候选测试与已修 fixture,核对 production diff 为零。原干净 candidate checkout 留给 GREEN。两侧使用同一命令: + +```bash +cd backend +go test -race -json -tags=unit ./internal/handler -run '^TestOpenAI409HTTPTaskRebuild$' -count=1 -timeout=5m +``` + +RED 必须是 36 个命名场景均在 `HTTP_REBUILD_B_DISPATCH_MISSING` 断言失败,且各自输出有明确的旧 owner/HTTP pointer/wire refusal code。构建失败、无测试、skip、panic、race、crash 或任意其他非零退出都不算业务 RED。GREEN 要求 36+20+8+48 个场景全部通过,随后两个独立 source mutant 必须被指定业务断言检出。候选 SHA、source baseline、测试 blob、原始 JSONL、source diff/hash 和验证器自测日志分别记录在 Actions artifact。 + +旧 Issue805 RED 只新增排除此处的后续 Beta fixture,以保持其旧 baseline 下的 helper 依赖相容;原 Issue805 业务测试与断言不变。该排除仅发生于其 disposable RED,其他候选与本 TDD workflow 保留新测试。 + +## 仍需实现和验收 + +本片生产候选已包含:可读任务判定取代最后 agent 位置启发式;body、选号参数和 recovery context 的 provider pointer 一致重建;原生 OAuth 的明确 system/tool 规范化与独立预期摘要;同客户端连续工具回合中已交付 A/B 历史的有损处理;所有原 key 的交付检查和最终发送前重查。原 input 快照不改写,最终校验另覆盖 tools/schema 与有效 instructions。还需当前候选的全部远端 GREEN、mutation 与独立审查,不靠清 owner、任意重置 digest 或假 200 达成。 + +future shadow/安全摘要是后续独立增量。可实现方案是把已观测的明确任务意图与任务关联标识按 tenant/user、API key、group、model、session 和版本隔离,使用有界 TTL 和容量;记录来源与交付状态,内容不进日志。只有可证明与当前 opaque 任务关联的已提交意图才能用于重建,不能把“同 session 上一条任务”无条件套给未知新任务。摘要/意图记录不能覆盖 generation/tool 的 pending 或 unknown 屏障,也不能授权重做副作用。历史从未留下线索时仍准确报告缺失。本 HTTP 检查点不实现该存储。 + +WS HTTP bridge、native/shared/pooled/dedicated、future shadow、真实自有 A/B 上游验证和最终独立 review 都保留为同 PR 必需 gate。HTTP mock 不能替代 WS、真实认证/财务系统或真实供应商验收。 + +## 84e47 独审后的修复候选 + +独审提出一个 P1 和三个 P2,修复候选保留这些执行 gate:未归属 pointer 的 discard waiver 与真实 ownership 分开,任何设置翻转/读取故障导致未完成重建时必须零 upstream send;缺省 instructions 的存在状态也受摘要保护,OAuth 默认指令只能在原快照校验后由受控规则产生;合法嵌套 tool choice 和无工具 parallel 控制使用明确的派生快照;全空白 text-part 数组视为占位,opaque/media/未知 part 仍不能借用旧任务。 + +新增实际 HTTP `TestOpenAI409HTTPUnownedPointerMustDetach` 两场景和 `TestOpenAI409HTTPControlNormalization` 八场景。工作流 `HTTP review counterexamples on 84e47` 在独立旧源码 checkout 对相同测试验证具体错误发送/规范化失败;候选 GREEN 同样执行全套。service integrity 测试另覆盖在 OAuth preparation **之前**插入/替换 instructions 的反例以及确切默认指令正例。新增执行结果仍待当前 head 的 Actions 和独审,不能视为上述 findings 已动态关闭。 diff --git a/docs/shadow-review-repair-and-ws-tdd.md b/docs/shadow-review-repair-and-ws-tdd.md new file mode 100644 index 000000000000..b04d41f04097 --- /dev/null +++ b/docs/shadow-review-repair-and-ws-tdd.md @@ -0,0 +1,40 @@ +# Shadow 生命周期修复与下一 WS 具名 RED + +> 历史设计与测试阶段记录:下方“待执行”“尚未实现”“下一片”均描述当时 checkpoint,不代表 PR #834 最终实现。当前能力、Redis 保留边界和未覆盖范围见 [Responses 有损可读续接](encrypted-history-readable-continuation.md#当前实现与边界);动态结果以 PR 当前 head 的 Actions 为准。 + +本增量优先处理独审 `e593` 的 1 P1 + 3 P2,保留同 PR 未完成的 WS 实现。没有本机动态运行;所有新增回归、RED/GREEN 和变异的执行结果均待远端验证。 + +## 生产修复 + +- Shadow 关联增加独立 epoch fence:输出实际暴露前保留带 token 的 pending,真实终端交付和正文发布尝试结束后 CAS 完成。原 owner 路由字节不变。成功写入的关联冲突只撤销 shadow 可用性,不改变原响应;关联 store 不可用时沿用暴露前的存储拒绝边界。 +- 首次恢复在准入前对 pending 有界等待(最多三秒),避免客户端看到终端后立刻续聊却遇到正常发布窗口。context 保存精确正文版本和 epoch,最终 native send 重读两者及全部源 owner fences。旧版本正文没有新 epoch 不可授权恢复。 +- 复用同一个 opaque identity 会在暴露前切换 epoch;正文写入/失效失败也无法复用旧正文。晚到 publisher 的 token 无法复活已经冲突或更新的关联。正文仍为每个 user/key 八条、64KiB/条、总计512KiB;无正文的 epoch 元数据跨所有 session 最多128条,TTL最多30分钟,两个预算的索引分别原子淘汰且共享各自 principal 的 Redis Cluster slot。 +- 恢复的正文仍经过内容审查。provenance 标记禁止把它保存为 Prompt Audit 正文、预览、扫描器引用、处罚证据或传统 moderation 摘录。异步审计对这类请求使用最多八个并发、每项最多128KiB、最多30秒的内存任务;不等待 scanner 才返回准入,不复制到持久 payload 队列。扫描后通过与 Runner 完成路径相同的事务逻辑提交 async 元数据与配置的处罚 hook,处罚失败则事件一起回滚。正常请求保留原配置行为。 +- HTTP 的授权 response pointer 在 Beta 关闭、没有 encrypted-agent owner 时也绑定原 producer。只有开启 Beta 且有可读意图的显式重建才能清除指针并换号;原 HTTP 用户所有权校验不变。 +- 历史 Issue715 两个 RED 配方移除新 shadow/epoch 依赖;其他已有历史 RED 同步维护,原业务断言与 candidate 测试保留。 + +## 新证据入口 + +`shadow-review-repair.yml` 默认执行固定 `e593` 生产 baseline RED 和 candidate GREEN,保留完全相同的测试。原始 JSONL、SHA/blob 和 validator 自测上传为 `shadow-review-repair-{RED|GREEN}-`。 + +- Publication fences:JSON/SSE × 首发等待、恢复后失效、复用暴露、已有正文时写失败、晚到 publisher,共10条真实跨节点 HTTP/Redis 场景。客户端在 producer 完成前实际读到终端;不能再用等待 handler 返回的串行夹具掩盖窗口。 +- Audit provenance:2条真实 HTTP 恢复后审查输入的 provenance 检查;audit persistence:3条真实 PostgreSQL/Redis 场景,验证 blocking allow/risk 与 async 仍评估合成私有段落,但 jobs/events/async payload 无该正文或 scanner quote。 +- 后续三项 P2 的 async enforcement:2条具名 PostgreSQL/Redis 回归,配置实际 penalty coordinator。`admission` 将 scanner 持续挡在屏障内,证明准入已经返回;`penalty` 证明 async risk 仍有真实处罚、原 session scope 和 async-mode job/event。两条均检查没有持久正文,并注入 SQL 处罚触发器失败验证事务回滚。RED 固定源为 d023;不改原 e593 的正文泄漏 RED。 +- OAuth shadow:12条真实 native final builder → loopback HTTP provider → JSON/SSE client,用固定真实 OAuth URL 构造后仅在 transport 边界重定向;校验 B 身份、账户 session namespace、stream/store 规范、旧 pointer/turn-state 清除与真实 downstream 成败。没有真实供应商网络访问。 +- 无 opaque pointer:8条可读 previous/conversation 成功场景,16条严格模式/无意图/跨用户/B禁用边界。A 的第一响应不含 agent_message,真实 owner Redis 为空,但 HTTP response 用户授权存在。严格 baseline 探测如已通过会如实记录 GREEN,不捏造 RED。 + +新版本必须重跑原48条 shadow及 session-last-task变异;容量夹具扩展为141个任务 identity,独立验证128个 epoch上限和八条正文上限。历史 e593 GREEN/变异成功不等于这些新修复通过。 + +## 下一 WS 生产增量的精确触发 + +`ws-readable-continuation.yml` 暂为测试先行:PR 自动只跑固定 `e593` baseline RED。`TestOpenAI409WSReadableContinuation` 分别走 `http_bridge`、`ctx_pool`、`shared`、`dedicated`、`passthrough` 五个实际配置。真实客户端保持同一连接,A 生成 patch,客户端实际执行一次后管理员停用 A;B 必须接续 verification,再正常 terminal,历史 A owner 不改写、已完成工具不再执行。provider 检查最终任务、工具 schema、call/result、B credential 和旧指针缺失。RED 必须五条各自在 `WS_READABLE_B_DISPATCH_MISSING` 与旧 eligibility refusal 失败,panic/编译/skip/任意 EOF 不能冒充业务 RED。 + +另30条 GREEN 边界准备覆盖 Beta关闭、无可读意图、B禁用、pending/failed owner,以及 B 已实际收帧后断线绝不重放;后者必须实际达到 B 一次,不能以旧 A 拒绝冒充成功。 + +三项 P2 修复后,ambiguous_B 要求 provider 在完整身份/任务/结果/指针检查后记录接受状态、实际注入断线,并在 gateway handler 自然退出后核对 A/B 身份与每种真实 adapter 的精确发送数。普通负例须匹配对应错误码或政策关闭原因,任意 EOF 不可通过。`TestOpenAI409WSAmbiguousOracleMutations` 使用同一 provider/oracle,实际 HTTP 与 socket 各测试 valid、wrong_credential、old_pointer、missing_result、unrelated_eof;十条自验证不依赖尚未实现的 WS 自动换号。远程证据清单要求全部具名叶子。 + +复用暴露场景不再用50ms决定顺序:Y 保持在实际下游写之前,consumer 的真实 Redis GET 结果通过显式屏障交给测试。修复版必须读到 pending 且 B 无发送,随后才放行 Y;旧 e593 若读到旧正文,则先放行该 consumer、仍保持 Y,要求它实际完成以暴露错误 B 发送。所有该场景的失败使用 `SHADOW_REUSED_EXPOSURE_LEAK`,JSON/SSE 均走相同顺序。 + +下一片必须消费具名 RED 并实现实际 per-turn unsent-frame recovery/reselection、每模式最终 payload 与 downstream reserve/commit。跨节点、发送前后竞态、当下权限/quota、WS future-shadow 与 OAuth WS 等剩余门仍需独立补齐。当前并未实现 WS 自动换号,宽泛 Beta 测试匹配到这些先行测试会预期失败;不能删除断言或把测试改为 skip。 + +受控真实自有上游 A/B 尚无批准凭据/隔离实例,仍为监督验收 blocker。loopback provider 只证明实际 transport 与网关行为,不能替代真实供应商验收。 diff --git a/frontend/src/i18n/locales/en/admin/settings.ts b/frontend/src/i18n/locales/en/admin/settings.ts index a1f7ef9af929..72357688aabc 100644 --- a/frontend/src/i18n/locales/en/admin/settings.ts +++ b/frontend/src/i18n/locales/en/admin/settings.ts @@ -575,7 +575,7 @@ export default { }, gatewayForwarding: { omitEncryptedHistory409: 'Omit encrypted content on 409', - omitEncryptedHistory409Hint: 'Off by default. For HTTP Responses rejected before dispatch because the encrypted history owner is unavailable or its route changed, omit historical ciphertext and select an eligible account once. Readable text and tool relationships remain, but omitted context is lost and upstream acceptance is not guaranteed. Excludes current encrypted tasks, server-side conversation pointers, WebSockets, uncertain delivery and store failures. This option does not replay sent requests; a separate 400 Beta controls that recovery.', + omitEncryptedHistory409Hint: 'Off by default. HTTP Responses and WebSocket turns proven unsent can automatically continue on an eligible account from the available readable task and completed tool results, starting a new upstream conversation when needed. Old opaque history may be lost; no confirmation or new client session is required. When enabled, successfully delivered tasks may retain readable context in the internal shared store for up to 30 minutes, limited to eight records and 512 KiB per user/API key, solely for the same task. Context bodies are not logged. Requests with no readable clues, uncertain delivery or store failures remain protected. Already-sent generations and completed tools are not automatically replayed; upstream acceptance is not guaranteed.', omitEncryptedHistory400: 'Lossy encrypted history recovery on 400', omitEncryptedHistory400Hint: 'Off by default. After an explicit encrypted-content HTTP 400 on native Responses, if normal recovery cannot succeed, allow one additional same-account attempt, no later than upstream send 3. Omit ciphertext before the current readable task, preserving readable text and tool relationships. Omitted context is lost and continuation is not guaranteed. Eligible requests following 409 omission are supported. Excludes current encrypted tasks, compaction, server-side pointers, WebSockets, HTTP 200 stream errors, existing output and uncertain delivery.', title: 'Request Forwarding', diff --git a/frontend/src/i18n/locales/zh/admin/settings.ts b/frontend/src/i18n/locales/zh/admin/settings.ts index 1281b74e62af..2052d1a81640 100644 --- a/frontend/src/i18n/locales/zh/admin/settings.ts +++ b/frontend/src/i18n/locales/zh/admin/settings.ts @@ -568,7 +568,7 @@ export default { }, gatewayForwarding: { omitEncryptedHistory409: '409 省略加密内容', - omitEncryptedHistory409Hint: '默认关闭。HTTP Responses 在发送前因原加密历史账号不可用或路线变化返回 409 时,省略旧密文并重新选择合格账号,最多处理一次。保留可读文本和工具调用关系,但被省略的上下文将丢失,不能保证会话完整或上游接受。当前加密任务、服务端会话指针、WebSocket、交付未确认和存储故障不适用;本开关不重放已发送的请求;400 恢复由独立 Beta 控制。', + omitEncryptedHistory409Hint: '默认关闭。HTTP Responses 和已确认当前轮尚未发送的 WebSocket 可基于现存可读任务及已完成工具结果,自动选择合格账号并在需要时建立新的上游会话;旧不可读历史可能丢失,无需确认或重开客户端会话。启用后,成功交付的任务可在内部共享存储保留最多 30 分钟的可读上下文,每个用户/API Key 最多八条、合计 512 KiB,仅供同一任务恢复,不写正文日志。无可读线索、交付未确认和存储故障仍受保护。不会自动重放已发送的生成或已完成工具,不能保证上游接受。', omitEncryptedHistory400: '400 加密历史有损恢复', omitEncryptedHistory400Hint: '默认关闭。原生 HTTP Responses 明确返回加密内容无效的 400、常规恢复未成功时,最多增加一次同账号恢复,且本次恢复不得超过第 3 次上游发送。省略当前可读任务之前的旧密文,保留可读文本和工具关系;被省略的上下文将丢失,不保证续接成功。支持 409 省略后的合格请求。当前加密任务、压缩状态、服务端会话指针、WebSocket、200 流内错误、已有输出和交付不确定不适用。', title: '请求转发行为',