Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions .github/scripts/assert-issue895-review-red.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"""Require the exact F1 RED failures and every intact/fence/400 control."""

import json
import re
import sys
from collections import Counter
from pathlib import Path


PACKAGE = "github.com/Wei-Shaw/sub2api/internal/service"
PROJECTION = "TestIssue892OpaqueEnvironmentProjectionRefused"
ACTUAL = "TestIssue892ActualSendOpaqueIntegrityAndDelivery"
FENCES = "TestIssue892PreparedUnknownOwnerRechecksFences"
RECOVERY = "TestIssue892ManualTimezone400Recovery"
MARKERS = {
**{f"{PROJECTION}/{kind}/{mode}": "Issue895 F1 projection must refuse a changed opaque envelope"
for kind in ("oauth", "apikey") for mode in ("http", "ws")},
**{f"{ACTUAL}/{mode}/{mutation}": "Issue895 F1 actual send must reject a changed opaque item"
for mode in ("http", "ws") for mutation in ("envelope", "drop")},
}
CONTROLS = (
{f"{ACTUAL}/{mode}/intact" for mode in ("http", "ws")}
| {f"{FENCES}/{mode}/{fence}" for mode in ("http", "ws") for fence in ("pending", "failed")}
| {f"{RECOVERY}/{mode}" for mode in ("enabled", "disabled", "ordinary400", "SSE")}
)


def expected_results():
# Each fixture calls t.Run once with a slash-containing name. Those slash
# prefixes are filters, not separately created intermediate test events.
return {
**dict.fromkeys(CONTROLS, "pass"),
**dict.fromkeys(MARKERS, "fail"),
PROJECTION: "fail",
ACTUAL: "fail",
FENCES: "pass",
RECOVERY: "pass",
None: "fail",
}


def validate(code, raw):
if code != 1:
raise ValueError("expected ordinary go test failure exit 1")
if re.search(r"build failed|build-fail|undefined:|setup failed|no tests to run|"
r"panic:|panic_recovered|fatal error:|runtime error:|WARNING: DATA RACE|"
r"signal:|timed out|timeout|deadline exceeded|--- SKIP:", raw, re.I):
raise ValueError("invalid build/setup/runtime evidence")
events = []
for line in raw.splitlines():
if not line.strip():
continue
try:
event = json.loads(line)
except json.JSONDecodeError as error:
raise ValueError("non-JSON setup or process output") from error
if not isinstance(event, dict) or event.get("Package") != PACKAGE:
raise ValueError("unexpected package or malformed event")
events.append(event)
expected = expected_results()
counts = Counter()
outputs = {}
for event in events:
action, name = event.get("Action"), event.get("Test")
if action not in ("start", "run", "pause", "cont", "output", "pass", "fail"):
raise ValueError("unexpected action, skip or build event")
if name not in expected or (action == "start" and name is not None):
raise ValueError("unselected test or package start")
counts[action, name] += 1
if action in ("pass", "fail") and action != expected[name]:
raise ValueError(f"unexpected result: {name}")
if action == "output":
output = event.get("Output")
if not isinstance(output, str):
raise ValueError("malformed output")
outputs[name] = outputs.get(name, "") + output
if counts["start", None] != 1:
raise ValueError("missing or duplicate package start")
for name, result in expected.items():
if name is not None and counts["run", name] != 1:
raise ValueError(f"missing or duplicate run: {name}")
if counts[result, name] != 1 or counts["pass", name] + counts["fail", name] != 1:
raise ValueError(f"missing or duplicate terminal: {name}")
for name, marker in MARKERS.items():
if marker not in outputs.get(name, ""):
raise ValueError(f"wrong business assertion: {name}")


if __name__ == "__main__":
try:
validate(int(sys.argv[1]), Path(sys.argv[2]).read_text())
except (ValueError, OSError, IndexError) as error:
raise SystemExit(str(error)) from error
print("F1 RED: exactly 8 named failures and 10 passing controls verified")
6 changes: 6 additions & 0 deletions .github/scripts/prepare-ws-owner-red-fixtures.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ if grep -q 'requireCompletedOwners' "$tree/$contract"; then
fi

for target in \
backend/internal/service/openai_400_omit_history.go \
backend/internal/service/openai_409_omit_history.go \
backend/internal/service/openai_lossy_history_restart.go \
backend/internal/service/openai_tool_provenance.go \
Expand Down Expand Up @@ -63,6 +64,11 @@ exclude_new_fixture() {
# New service tests require new private proof/diagnostic types. Their own RED
# uses handler tests; every candidate GREEN retains them and all negative cases.
exclude_new_fixture backend/internal/service/openai_ws_owner_conflict_test.go
# Issue892's later matrix also imports the OAuth dial seam and 400/842 test
# helpers absent from these historical overlays. It is not a selected oracle
# here; its own RED and every clean candidate GREEN retain both exact files.
exclude_new_fixture backend/internal/handler/openai_issue892_timezone_test.go
exclude_new_fixture backend/internal/service/openai_issue892_timezone_test.go
# Very old Issue805 baselines intentionally exclude the later readable harness.
# Only that dependency absence permits removing its new consumer as well.
if ! test -f "$tree/backend/internal/handler/openai_409_ws_rebuild_test.go"; then
Expand Down
153 changes: 153 additions & 0 deletions .github/scripts/test_assert_issue895_review_red.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"""Remote-only verifier tests; synthetic transcripts never count as Go evidence."""

import importlib.util
import json
import unittest
from pathlib import Path


SPEC = importlib.util.spec_from_file_location("issue895_red", Path(__file__).with_name("assert-issue895-review-red.py"))
GATE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(GATE)


# Independent oracle for the actual Go fixture: four roots and eighteen
# direct t.Run children, with no events for slash prefixes inside their names.
EXPECTED = {
"TestIssue892OpaqueEnvironmentProjectionRefused": "fail",
"TestIssue892OpaqueEnvironmentProjectionRefused/apikey/http": "fail",
"TestIssue892OpaqueEnvironmentProjectionRefused/apikey/ws": "fail",
"TestIssue892OpaqueEnvironmentProjectionRefused/oauth/http": "fail",
"TestIssue892OpaqueEnvironmentProjectionRefused/oauth/ws": "fail",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery": "fail",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/http/intact": "pass",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/http/envelope": "fail",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/http/drop": "fail",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws/intact": "pass",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws/envelope": "fail",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws/drop": "fail",
"TestIssue892PreparedUnknownOwnerRechecksFences": "pass",
"TestIssue892PreparedUnknownOwnerRechecksFences/http/pending": "pass",
"TestIssue892PreparedUnknownOwnerRechecksFences/http/failed": "pass",
"TestIssue892PreparedUnknownOwnerRechecksFences/ws/pending": "pass",
"TestIssue892PreparedUnknownOwnerRechecksFences/ws/failed": "pass",
"TestIssue892ManualTimezone400Recovery": "pass",
"TestIssue892ManualTimezone400Recovery/enabled": "pass",
"TestIssue892ManualTimezone400Recovery/disabled": "pass",
"TestIssue892ManualTimezone400Recovery/ordinary400": "pass",
"TestIssue892ManualTimezone400Recovery/SSE": "pass",
None: "fail",
}


def evidence():
events = [{"Action": "start", "Package": GATE.PACKAGE}]
for root, result in EXPECTED.items():
if root is None or "/" in root:
continue
events.append({"Action": "run", "Test": root})
for name, terminal in EXPECTED.items():
if name is None or not name.startswith(root + "/"):
continue
events.append({"Action": "run", "Test": name})
if terminal == "fail":
marker = ("Issue895 F1 projection must refuse a changed opaque envelope"
if root == "TestIssue892OpaqueEnvironmentProjectionRefused"
else "Issue895 F1 actual send must reject a changed opaque item")
events.append({"Action": "output", "Test": name, "Output": marker})
events.append({"Action": terminal, "Test": name})
events.append({"Action": result, "Test": root})
events.append({"Action": "fail"})
for event in events:
event["Package"] = GATE.PACKAGE
return events


def transcript(events):
return "".join(json.dumps(event) + "\n" for event in events)


class Issue895ReviewRedTest(unittest.TestCase):
def test_accepts_exact_expected_failures_and_controls(self):
GATE.validate(1, transcript(evidence()))
self.assertEqual(EXPECTED, GATE.expected_results())
self.assertEqual(8, len(GATE.MARKERS))
self.assertEqual(10, len(GATE.CONTROLS))

def test_accepts_no_intermediate_prefix_events_and_rejects_invented_ones(self):
GATE.validate(1, transcript(evidence()))
for prefix in ("TestIssue892OpaqueEnvironmentProjectionRefused/apikey",
"TestIssue892OpaqueEnvironmentProjectionRefused/oauth",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/http",
"TestIssue892ActualSendOpaqueIntegrityAndDelivery/ws",
"TestIssue892PreparedUnknownOwnerRechecksFences/http",
"TestIssue892PreparedUnknownOwnerRechecksFences/ws"):
self.assertNotIn(prefix, EXPECTED)
extra = [{"Package": GATE.PACKAGE, "Action": action, "Test": prefix}
for action in ("run", "fail")]
with self.assertRaises(ValueError):
GATE.validate(1, transcript(evidence() + extra))

def test_rejects_any_extra_control_failure_including_intact(self):
for name in GATE.CONTROLS:
with self.subTest(name=name):
events = evidence()
for event in events:
if event.get("Test") == name and event["Action"] == "pass":
event["Action"] = "fail"
with self.assertRaises(ValueError):
GATE.validate(1, transcript(events))

def test_rejects_wrong_business_assertion(self):
for name in GATE.MARKERS:
events = evidence()
for event in events:
if event.get("Test") == name and event["Action"] == "output":
event["Output"] = "unrelated assertion failure"
with self.assertRaises(ValueError):
GATE.validate(1, transcript(events))

def test_rejects_missing_runs_leaves_or_terminals_and_duplicates(self):
for name, result in EXPECTED.items():
events = evidence()
terminal = next(event for event in events if event.get("Test") == name and event["Action"] == result)
for bad in ([event for event in events if event is not terminal], events + [terminal]):
with self.assertRaises(ValueError):
GATE.validate(1, transcript(bad))
if name is not None:
with self.assertRaises(ValueError):
GATE.validate(1, transcript([event for event in events if event.get("Test") != name]))
run = next(event for event in events if event.get("Test") == name and event["Action"] == "run")
for bad in ([event for event in events if event is not run], events + [run]):
with self.assertRaises(ValueError):
GATE.validate(1, transcript(bad))

def test_rejects_unselected_failure_and_incorrect_parent_or_package(self):
events = evidence()
with self.assertRaises(ValueError):
GATE.validate(1, transcript(events + [{"Package": GATE.PACKAGE, "Action": "fail", "Test": "TestUnexpected"}]))
for name, result in EXPECTED.items():
bad = evidence()
for event in bad:
if event.get("Test") == name and event["Action"] == result:
event["Action"] = "pass" if result == "fail" else "fail"
with self.assertRaises(ValueError):
GATE.validate(1, transcript(bad))

def test_rejects_compile_setup_skip_panic_timeout_and_abnormal_exit(self):
for message in ("build failed", "undefined: fixture", "setup failed", "no tests to run",
"panic: fixture", "panic_recovered", "fatal error: fixture", "runtime error: fixture",
"WARNING: DATA RACE", "signal: killed", "test timed out", "timeout", "context deadline exceeded", "--- SKIP:"):
for suffix in (message, transcript([{"Package": GATE.PACKAGE, "Action": "output", "Output": message}])):
with self.subTest(message=message), self.assertRaises(ValueError):
GATE.validate(1, transcript(evidence()) + suffix)
for action in ("skip", "build-fail"):
with self.assertRaises(ValueError):
GATE.validate(1, transcript(evidence() + [{"Package": GATE.PACKAGE, "Action": action}]))
for code in (0, 2, 124, 137, -9):
with self.assertRaises(ValueError):
GATE.validate(code, transcript(evidence()))


if __name__ == "__main__":
unittest.main()
16 changes: 15 additions & 1 deletion .github/workflows/issue715-agent-recovery.yml
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ jobs:
# Manager fields and readable-payload methods live together. Restore
# both transport callers with that manager; retain candidate tests and
# standalone admission/principal helpers required by current HTTP.
trap 'git restore --source=HEAD -- "$target" "$caller" "$passthrough" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go; git diff --exit-code' EXIT
trap 'git restore --source=HEAD -- "$target" "$caller" "$passthrough" backend/internal/service/openai_request_timezone_egress.go backend/internal/service/openai_ws_client.go backend/internal/service/openai_issue892_timezone_test.go; git diff --exit-code' EXIT
git restore --source="$original" -- "$target" "$caller" "$passthrough"
expected=$(git rev-parse "$original:$target")
actual=$(git hash-object "$target")
Expand Down Expand Up @@ -442,6 +442,20 @@ jobs:
echo "retained_candidate path=$retained expected_blob=$expected_retained tested_blob=$actual_retained"
test "$expected_retained" = "$actual_retained"
done
# The later timezone proof fixture requires manager.protected, which
# this historical manager does not have. Exclude only this untouched
# non-target fixture; keep the selected wire regression unchanged.
fixture=backend/internal/service/openai_issue892_timezone_test.go
if test -f "$fixture"; then
if git cat-file -e "$original:$fixture" 2>/dev/null; then
echo "refusing to remove a historical fixture" >&2
exit 1
fi
expected_fixture=$(git rev-parse "HEAD:$fixture")
test "$(git hash-object "$fixture")" = "$expected_fixture"
printf 'excluded later fixture path=%s candidate_blob=%s baseline=%s\n' "$fixture" "$expected_fixture" "$original"
rm -- "$fixture"
fi
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
Expand Down
Loading
Loading