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
72 changes: 72 additions & 0 deletions .github/scripts/issue1010_evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""Validate executed, per-leaf Go evidence for the Issue1010 native oracle."""

import json
from pathlib import Path
import sys


PACKAGE = "github.com/Wei-Shaw/sub2api/internal/integration/accountconnectiontiming"
ROOT = "TestGatewayAccountConnectionNativeHTTP"
KINDS = ("new_api", "sub2api")
PROTOCOLS = ("responses", "chat", "anthropic", "gemini")
LEAVES = {f"{ROOT}/{kind}/{protocol}" for kind in KINDS for protocol in PROTOCOLS}
# Each slash-delimited kind/protocol is one t.Run name, not two nested tests.
NODES = LEAVES | {ROOT}
ASSERTION = "gateway probe must reach synthetic upstream exactly once"
GUARD = "GATEWAY_PROTOCOLS_PENDING"
CONTAMINATION = (
"[build failed]", "build-fail", "setup failed", "no tests to run",
"panic:", "fatal error:", "warning: data race", "race detected during execution",
"segmentation fault", "sigsegv", "sigabrt", "sigbus", "test timed out",
"signal: killed", "runtime: out of memory",
)


def validate(raw, mode):
if mode not in ("red", "green"):
raise ValueError(f"unknown evidence mode: {mode}")
if any(marker in raw.lower() for marker in CONTAMINATION):
raise ValueError("build/setup/crash/race/empty-test contamination")
events = [json.loads(line) for line in raw.splitlines() if line.startswith("{")]
if not events:
raise ValueError("missing executed Go test events")
terminal = "fail" if mode == "red" else "pass"
runs = {}
results = {}
output = {}
package_results = []
for event in events:
action = event.get("Action")
if action == "skip":
raise ValueError("skipped oracle")
if event.get("Package") != PACKAGE:
raise ValueError("unexpected package or malformed Go event")
name = event.get("Test")
if name:
if name not in NODES:
raise ValueError(f"unexpected oracle test: {name}")
if action == "run":
runs[name] = runs.get(name, 0) + 1
elif action in ("fail", "pass"):
results.setdefault(name, []).append(action)
elif action == "output":
output[name] = output.get(name, "") + event.get("Output", "")
elif action in ("fail", "pass"):
package_results.append(action)
if runs != dict.fromkeys(NODES, 1):
raise ValueError("missing or duplicate executed oracle tests")
if results != {name: [terminal] for name in NODES}:
raise ValueError("missing, duplicate or unexpected test outcomes")
if package_results != [terminal]:
raise ValueError("missing or unexpected package outcome")
if mode == "red":
for name in sorted(LEAVES):
leaf_output = output.get(name, "")
if ASSERTION not in leaf_output or GUARD not in leaf_output:
raise ValueError(f"{name}: missing its own business assertion or historical guard")


if __name__ == "__main__":
if len(sys.argv) != 3:
raise SystemExit("usage: issue1010_evidence.py red|green oracle.jsonl")
validate(Path(sys.argv[2]).read_text(), sys.argv[1])
70 changes: 70 additions & 0 deletions .github/scripts/test_issue1010_evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Offline evidence-validator regressions; executed only in remote CI."""

import json
import unittest

from issue1010_evidence import ASSERTION, GUARD, LEAVES, NODES, PACKAGE, validate


def oracle_events(mode):
terminal = "fail" if mode == "red" else "pass"
events = [{"Action": "start", "Package": PACKAGE}]
for name in sorted(NODES):
events.append({"Action": "run", "Package": PACKAGE, "Test": name})
if name in LEAVES and mode == "red":
events.append({"Action": "output", "Package": PACKAGE, "Test": name,
"Output": f"{ASSERTION}: {GUARD}\n"})
events.append({"Action": terminal, "Package": PACKAGE, "Test": name})
events.append({"Action": terminal, "Package": PACKAGE})
return events


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


class TestIssue1010RedEvidenceRejectsMixedGuardAndSetupFailures(unittest.TestCase):
def test_all_eight_expected_failures_and_passes(self):
for mode in ("red", "green"):
with self.subTest(mode=mode):
validate(encode(oracle_events(mode)), mode)

def test_each_leaf_requires_its_own_assertion_and_guard(self):
for leaf in sorted(LEAVES):
for replacement in ("unrelated assertion", ASSERTION, GUARD):
with self.subTest(leaf=leaf, replacement=replacement):
events = oracle_events("red")
for event in events:
if event.get("Test") == leaf and event["Action"] == "output":
event["Output"] = replacement
with self.assertRaises(ValueError):
validate(encode(events), "red")

def test_setup_build_skip_crash_race_and_missing_or_unexpected_failures(self):
leaf = sorted(LEAVES)[0]
for mode in ("red", "green"):
for defect in ("setup failed", "[build failed]", "panic: fixture", "WARNING: DATA RACE",
"skip", "missing", "extra-fail", "wrong-outcome", "duplicate"):
with self.subTest(mode=mode, defect=defect):
events = oracle_events(mode)
if defect == "missing":
events = [event for event in events if event.get("Test") != leaf]
elif defect == "skip":
events.append({"Action": "skip", "Package": PACKAGE, "Test": leaf})
elif defect == "extra-fail":
events.append({"Action": "fail", "Package": PACKAGE, "Test": "UnexpectedSetup"})
elif defect == "wrong-outcome":
for event in events:
if event.get("Test") == leaf and event["Action"] in ("pass", "fail"):
event["Action"] = "pass" if mode == "red" else "fail"
elif defect == "duplicate":
events.append({"Action": "run", "Package": PACKAGE, "Test": leaf})
else:
events.append({"Action": "output", "Package": PACKAGE, "Test": leaf,
"Output": defect})
with self.assertRaises(ValueError):
validate(encode(events), mode)


if __name__ == "__main__":
unittest.main()
103 changes: 103 additions & 0 deletions .github/workflows/issue1010-gateway-connection.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
name: Issue1010 gateway connection

on:
workflow_dispatch:
pull_request:
branches: [production]
paths:
- 'backend/internal/service/account*.go'
- 'backend/internal/service/gateway_protocol_admission.go'
- 'backend/internal/handler/admin/account_handler.go'
- 'backend/internal/integration/accountconnectiontiming/**'
- 'backend/internal/repository/http_upstream*.go'
- 'backend/go.mod'
- 'backend/go.sum'
- '.github/workflows/issue1010-gateway-connection.yml'
- '.github/scripts/issue1010_evidence.py'
- '.github/scripts/test_issue1010_evidence.py'

permissions:
contents: read

concurrency:
group: issue1010-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

# Temporary baseline evidence; archive this entry after acceptance.
jobs:
synthetic-upstream:
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
mode: [red, green]
env:
EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }}
BASELINE: 991cd30e2910d5eeb6ab55f6b7fc93e9a494e1a6
MODE: ${{ matrix.mode }}
GOMAXPROCS: '2'
GOFLAGS: '-p=2'
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: Prepare exact source and unchanged HTTP oracle
shell: bash
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD"
mkdir -p evidence "$RUNNER_TEMP/issue1010-baseline"
git rev-parse HEAD > evidence/head.txt
printf '%s\n' "$BASELINE" > evidence/baseline.txt
if [ "$MODE" = red ]; then
git archive "$BASELINE" | tar -x -C "$RUNNER_TEMP/issue1010-baseline"
cp backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go \
"$RUNNER_TEMP/issue1010-baseline/backend/internal/integration/accountconnectiontiming/"
cmp backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go \
"$RUNNER_TEMP/issue1010-baseline/backend/internal/integration/accountconnectiontiming/gateway_account_connection_test.go"
fi
- name: Per-leaf evidence validator regressions
shell: bash
run: |
set -euo pipefail
python3 -m unittest discover -s .github/scripts -p 'test_issue1010_evidence.py' -v
- name: Same native HTTP oracle on baseline and candidate
shell: bash
run: |
set -euo pipefail
source_dir="$GITHUB_WORKSPACE/backend"
if [ "$MODE" = red ]; then source_dir="$RUNNER_TEMP/issue1010-baseline/backend"; fi
set +e
(cd "$source_dir" && go test -race -tags=unit ./internal/integration/accountconnectiontiming \
-run '^TestGatewayAccountConnectionNativeHTTP$' -count=1 -json -timeout=10m) > evidence/oracle.jsonl 2>&1
result=$?
set -e
cat evidence/oracle.jsonl
if [ "$MODE" = red ]; then test "$result" -ne 0; else test "$result" -eq 0; fi
python3 .github/scripts/issue1010_evidence.py "$MODE" evidence/oracle.jsonl
- name: Candidate error cancellation admission and legacy lifecycle regressions
if: matrix.mode == 'green'
working-directory: backend
shell: bash
run: |
set -euo pipefail
go test -race -tags=unit ./internal/integration/accountconnectiontiming \
-run '^Test(GatewayAccountConnection(UpstreamFailureAndEOF|AdmissionNoEgress|ExplicitCompositeRoute|CancellationReleasesReader|NonSchedulableDiagnostic|SuccessSkipsRecoveryAfterKeepaliveCleanup|AdminMultiGroupSelection)|AccountConnectionTiming)' -count=1 -v -timeout=10m \
2>&1 | tee ../evidence/lifecycle.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/lifecycle.log; then exit 1; fi
for name in TestGatewayAccountConnectionUpstreamFailureAndEOF TestGatewayAccountConnectionAdmissionNoEgress TestGatewayAccountConnectionCancellationReleasesReader TestGatewayAccountConnectionNonSchedulableDiagnostic TestGatewayAccountConnectionSuccessSkipsRecoveryAfterKeepaliveCleanup TestGatewayAccountConnectionAdminMultiGroupSelection; do
grep -F -- "--- PASS: $name" ../evidence/lifecycle.log
done
- uses: actions/upload-artifact@v7
if: always()
with:
name: issue1010-${{ matrix.mode }}-${{ env.EXPECTED_HEAD }}-${{ github.run_attempt }}
path: evidence
if-no-files-found: error
19 changes: 16 additions & 3 deletions .github/workflows/issue817-grok-persistence.yml
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ jobs:
git show "$original:$source" > "$source"
test "$(git hash-object "$source")" = "$expected_blob"
if [ "$BEHAVIOR" = red ]; then
# The pinned observer predates Ciallo. Retain its behavior and add
# only the candidate's zero-value field required by ciallo.go.
# Keep the historical observer business code. Add only the
# zero-value struct fields required by current helper callers.
python3 - <<'PY'
from pathlib import Path
import subprocess
Expand All @@ -110,8 +110,21 @@ jobs:
anchor = b'\tmodelTraceAccounts sync.Map\n'
if candidate.count(field) != 1 or field in historical or historical.count(anchor) != 1:
raise SystemExit('unexpected Ciallo compatibility field or historical struct')
path.write_bytes(historical.replace(anchor, anchor + field, 1))
old_options = b'type AccountTestOptions struct {\n\tImageDataURL string\n\tAudioDataURL string\n}\n'
current_options = b'type AccountTestOptions struct {\n\tImageDataURL string\n\tAudioDataURL string\n\tGroupID int64\n\tPlatform string\n}\n'
if historical.count(old_options) != 1 or candidate.count(current_options) != 1:
raise SystemExit('unexpected historical or candidate AccountTestOptions shape')
compatible = historical.replace(anchor, anchor + field, 1).replace(old_options, current_options, 1)
if compatible.replace(field, b'', 1).replace(current_options, old_options, 1) != historical:
raise SystemExit('compatibility overlay changed historical observer business code')
expected = subprocess.check_output(['git', 'hash-object', '--stdin'], input=compatible).strip()
path.write_bytes(compatible)
actual = subprocess.check_output(['git', 'hash-object', str(path)]).strip()
if actual != expected:
raise SystemExit('historical compatibility blob mismatch')
Path('evidence/observer-compile-compatibility-blob.txt').write_bytes(expected + b'\n')
PY
git diff --exit-code HEAD -- '*test.go'
else
# The pinned repository predates the OpenAI rotation CAS tests.
fixture=backend/internal/repository/account_repo_temp_unsched_test.go
Expand Down
12 changes: 12 additions & 0 deletions .github/workflows/issue959-gateway-regression.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ on:
paths:
- 'backend/internal/domain/constants.go'
- 'backend/internal/service/**'
- 'backend/internal/integration/accountconnectiontiming/**'
- 'backend/internal/handler/admin/account*'
- 'backend/internal/handler/dto/account_mapper_redact_test.go'
- 'backend/internal/repository/account_repo.go'
Expand Down Expand Up @@ -118,6 +119,17 @@ jobs:
grep -F -- '--- PASS: TestProcurementSnapshotMixedTargetsThroughUsageWriters' ../evidence/unit-race.log
grep -F -- '--- PASS: TestProcurementSnapshotAdminDTOAndUserPrivacy' ../evidence/unit-race.log
grep -F -- '--- PASS: TestObserverProcurementSnapshotFollowsExistingAccountCostScope' ../evidence/unit-race.log
- name: Gateway connection handler and synthetic upstream
working-directory: backend
shell: bash
run: |
set -euo pipefail
go test -race -tags=unit ./internal/integration/accountconnectiontiming \
-run '^TestGatewayAccountConnection' -count=1 -v -timeout=10m \
2>&1 | tee ../evidence/gateway-connection.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/gateway-connection.log; then exit 1; fi
grep -F -- '--- PASS: TestGatewayAccountConnectionNativeHTTP' ../evidence/gateway-connection.log
grep -F -- '--- PASS: TestGatewayAccountConnectionCancellationReleasesReader' ../evidence/gateway-connection.log
- name: Shared account slots against isolated Redis
working-directory: backend
shell: bash
Expand Down
12 changes: 8 additions & 4 deletions backend/internal/handler/admin/account_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -1420,9 +1420,11 @@ func (h *AccountHandler) Delete(c *gin.Context) {

// TestAccountRequest represents the request body for testing an account
type TestAccountRequest struct {
ModelID string `json:"model_id"`
Prompt string `json:"prompt"`
Mode string `json:"mode"`
ModelID string `json:"model_id"`
Prompt string `json:"prompt"`
Mode string `json:"mode"`
GroupID int64 `json:"group_id"`
Platform string `json:"platform"`
// Optional media for Grok (and future) real generation tests.
// ImageDataURL / AudioDataURL are data:<mime>;base64,... payloads.
ImageDataURL string `json:"image_data_url"`
Expand Down Expand Up @@ -1468,6 +1470,8 @@ func (h *AccountHandler) Test(c *gin.Context) {
opts := service.AccountTestOptions{
ImageDataURL: req.ImageDataURL,
AudioDataURL: req.AudioDataURL,
GroupID: req.GroupID,
Platform: req.Platform,
}

// Use AccountTestService to test the account with SSE streaming
Expand All @@ -1476,7 +1480,7 @@ func (h *AccountHandler) Test(c *gin.Context) {
return
}

if h.rateLimitService != nil {
if h.rateLimitService != nil && !service.IsGatewayAccountTest(c.Request.Context()) {
if _, err := h.rateLimitService.RecoverAccountAfterSuccessfulTest(c.Request.Context(), accountID); err != nil {
_ = c.Error(err)
}
Expand Down
Loading
Loading