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
60 changes: 60 additions & 0 deletions .github/scripts/issue871-evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
"""Accept only the named diagnosis assertion as the remote behavioral RED."""

import json
import sys
from pathlib import Path

PACKAGE = "github.com/Wei-Shaw/sub2api/internal/service"
ROOT = "TestExcelBPSSearchDiagnosticsThroughForward"
LEAF = ROOT + "/search_403/json"
NODES = {ROOT, LEAF}
MARKER = "issue871_expected_search_diagnosis"
ASSERTION = 'does not contain "phase=search_http; reason=http_rejected"'


def validate(phase, status, raw, stderr=""):
if phase not in {"RED", "GREEN"} or status != (1 if phase == "RED" else 0):
raise ValueError("unexpected phase or test exit status")
combined = (raw + stderr).lower()
for forbidden in (
"panic:", "fatal error", "data race", "build failed", "build-fail",
"setup failed", "no tests to run", "no test files", "--- skip:",
"signal:", "test timed out",
):
if forbidden in combined:
raise ValueError("invalid behavioral evidence: " + forbidden)
events = [json.loads(line) for line in raw.splitlines() if line.strip()]
runs = {name: 0 for name in NODES}
terminals = {name: [] for name in NODES}
packages = []
output = ""
for event in events:
if not isinstance(event, dict) or event.get("Package") != PACKAGE:
raise ValueError("unexpected event/package")
action, test = event.get("Action"), event.get("Test")
if action not in {"start", "run", "pause", "cont", "output", "pass", "fail"}:
raise ValueError("skip/build/unknown event")
if test:
if test not in NODES:
raise ValueError("unexpected test: " + test)
if action == "run":
runs[test] += 1
if action in {"pass", "fail"}:
terminals[test].append(action)
if action == "output" and test == LEAF:
output += event.get("Output", "")
elif action in {"pass", "fail"}:
packages.append(action)
expected = "fail" if phase == "RED" else "pass"
if runs != {name: 1 for name in NODES}:
raise ValueError("missing or repeated named test execution")
if terminals != {name: [expected] for name in NODES} or packages != [expected]:
raise ValueError("unexpected test/package terminal")
if phase == "RED" and (output.count(MARKER) != 1 or ASSERTION not in output):
raise ValueError("RED did not fail at the intended diagnosis assertion")


if __name__ == "__main__":
phase, status, log, stderr = sys.argv[1:]
validate(phase, int(status), Path(log).read_text(), Path(stderr).read_text())
print(phase + " named search diagnosis evidence accepted")
54 changes: 54 additions & 0 deletions .github/scripts/test_issue871_evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import importlib.util
import json
import unittest
from pathlib import Path

spec = importlib.util.spec_from_file_location("gate", Path(__file__).with_name("issue871-evidence.py"))
gate = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gate)


def transcript(phase):
terminal = "fail" if phase == "RED" else "pass"
events = [dict(Action="start", Package=gate.PACKAGE)]
for name in (gate.ROOT, gate.LEAF):
events.append(dict(Action="run", Package=gate.PACKAGE, Test=name))
if phase == "RED":
events.append(dict(Action="output", Package=gate.PACKAGE, Test=gate.LEAF,
Output=gate.MARKER + "\n" + gate.ASSERTION + "\n"))
for name in (gate.LEAF, gate.ROOT):
events.append(dict(Action=terminal, Package=gate.PACKAGE, Test=name))
events.append(dict(Action=terminal, Package=gate.PACKAGE))
return "\n".join(json.dumps(event) for event in events)


class Issue871EvidenceTest(unittest.TestCase):
def test_named_red_and_green(self):
for phase, code in (("RED", 1), ("GREEN", 0)):
gate.validate(phase, code, transcript(phase))

def test_rejects_nonbehavioral_failure_and_missing_test(self):
red = transcript("RED")
for invalid in (
"", red.replace(gate.MARKER, "unrelated_assertion"),
red.replace("phase=search_http; reason=http_rejected", "different assertion"),
red.replace('"Action": "run"', '"Action": "skip"', 1),
red.replace(gate.LEAF, gate.ROOT + "/wrong_case"), red + "\n" + red,
red + "\nnot JSON", red.replace(gate.PACKAGE, "other/package"),
):
with self.subTest(invalid=invalid), self.assertRaises(ValueError):
gate.validate("RED", 1, invalid)

def test_rejects_exit_mismatch_and_runtime_pollution(self):
for phase, code in (("RED", 1), ("GREEN", 0)):
raw = transcript(phase)
with self.assertRaises(ValueError):
gate.validate(phase, 2, raw)
for noise in ("panic: fixture", "build failed", "setup failed", "no tests to run",
"DATA RACE", "--- SKIP: fixture", "test timed out", "fatal error"):
with self.subTest(phase=phase, noise=noise), self.assertRaises(ValueError):
gate.validate(phase, code, raw, noise)


if __name__ == "__main__":
unittest.main()
90 changes: 89 additions & 1 deletion .github/workflows/bps-search.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,121 @@ on:
pull_request:
paths:
- backend/internal/service/basispoints/web_search*
- backend/internal/service/basispoints/upstream_failure.go
- backend/internal/service/openai_excel_bps.go
- backend/internal/service/openai_excel_bps_search*
- backend/internal/service/bps_search_settings_test.go
- frontend/src/components/account/ExcelBPSSearchOptions.vue
- frontend/src/components/account/__tests__/ExcelBPSSearchOptions.spec.ts
- frontend/src/utils/excelBPSDefaults.ts
- .github/scripts/bps-search-preview.mjs
- .github/scripts/issue871-evidence.py
- .github/scripts/test_issue871_evidence.py
- .github/workflows/bps-search.yml
permissions:
contents: read
jobs:
search-protocol:
runs-on: ubuntu-latest
timeout-minutes: 25
timeout-minutes: 40
env:
PYTHONDONTWRITEBYTECODE: '1'
steps:
- uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
- uses: actions/setup-go@v6
with:
go-version-file: backend/go.mod
cache-dependency-path: backend/go.sum
- name: Record exact candidate and baseline source identities
env:
CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }}
shell: bash
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA"
git diff --exit-code HEAD
test -z "$(git status --porcelain)"
evidence_dir="$RUNNER_TEMP/issue871-evidence"
baseline_sha=ff1082fd51038f10dcb3a8ecb1d5a738258b0f66
mkdir -p "$evidence_dir"
git rev-parse HEAD HEAD^{tree} HEAD^ > "$evidence_dir/candidate.txt"
git rev-parse "$baseline_sha" "$baseline_sha^{tree}" > "$evidence_dir/baseline.txt"
git ls-tree -r HEAD -- backend .github/workflows/bps-search.yml .github/scripts/issue871-evidence.py .github/scripts/test_issue871_evidence.py > "$evidence_dir/candidate-blobs.txt"
git ls-tree -r "$baseline_sha" -- backend > "$evidence_dir/baseline-blobs.txt"
cp .github/scripts/issue871-evidence.py .github/scripts/test_issue871_evidence.py "$evidence_dir/"
- name: Validate behavioral evidence gate mutations
run: python3 -m unittest discover -s .github/scripts -p 'test_issue871_evidence.py'
- name: RED isolated production baseline with candidate standalone diagnostics fixture
shell: bash
run: |
set -euo pipefail
evidence_dir="$RUNNER_TEMP/issue871-evidence"
baseline_sha=ff1082fd51038f10dcb3a8ecb1d5a738258b0f66
fixture_path=backend/internal/service/openai_excel_bps_search_diagnostics_test.go
git worktree add --detach "$RUNNER_TEMP/issue871-red" "$baseline_sha"
test "$(git -C "$RUNNER_TEMP/issue871-red" rev-parse HEAD)" = "$baseline_sha"
git show "HEAD:$fixture_path" > "$RUNNER_TEMP/issue871-red/$fixture_path"
git rev-parse "HEAD:$fixture_path" > "$evidence_dir/fixture-blob.txt"
test "$(git hash-object "$RUNNER_TEMP/issue871-red/$fixture_path")" = "$(git rev-parse "HEAD:$fixture_path")"
cp "$RUNNER_TEMP/issue871-red/$fixture_path" "$evidence_dir/standalone-diagnostics_test.go"
git -C "$RUNNER_TEMP/issue871-red" status --short > "$evidence_dir/red-status.txt"
git -C "$RUNNER_TEMP/issue871-red" diff --exit-code HEAD
set +e
(cd "$RUNNER_TEMP/issue871-red/backend" && go test -tags=unit ./internal/service -run '^TestExcelBPSSearchDiagnosticsThroughForward$/^search_403$/^json$' -count=1 -json -timeout=5m) > "$evidence_dir/red.jsonl" 2> "$evidence_dir/red.stderr"
test_status=$?
set -e
printf '%s\n' "$test_status" > "$evidence_dir/red-exit.txt"
python3 .github/scripts/issue871-evidence.py RED "$test_status" "$evidence_dir/red.jsonl" "$evidence_dir/red.stderr"
test "$(git -C "$RUNNER_TEMP/issue871-red" rev-parse HEAD)" = "$baseline_sha"
git -C "$RUNNER_TEMP/issue871-red" diff --exit-code HEAD
- name: GREEN clean exact candidate diagnosis boundary
env:
CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }}
shell: bash
run: |
set -euo pipefail
evidence_dir="$RUNNER_TEMP/issue871-evidence"
test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA"
git diff --exit-code HEAD
test -z "$(git status --porcelain)"
set +e
(cd backend && go test -race -tags=unit ./internal/service -run '^TestExcelBPSSearchDiagnosticsThroughForward$/^search_403$/^json$' -count=1 -json -timeout=5m) > "$evidence_dir/green.jsonl" 2> "$evidence_dir/green.stderr"
test_status=$?
set -e
printf '%s\n' "$test_status" > "$evidence_dir/green-exit.txt"
python3 .github/scripts/issue871-evidence.py GREEN "$test_status" "$evidence_dir/green.jsonl" "$evidence_dir/green.stderr"
test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA"
git diff --exit-code HEAD
test -z "$(git status --porcelain)"
- name: Repeat real Forward repair ownership and provenance with race detection
working-directory: backend
shell: bash
run: |
set -euo pipefail
race_log="$RUNNER_TEMP/issue871-evidence/repair-race-repeat.log"
go test -race -tags=unit ./internal/service -run '^TestExcelBPSSearchRepair(OwnershipRaceThroughForward|ProvenanceThroughForward)$' -count=20 -v -timeout=10m 2>&1 | tee "$race_log"
for repair in transport unknown_target; do
for outcome in success failed; do
for mode in json sse compact_keepalive; do
test "$(grep -Fc -- "--- PASS: TestExcelBPSSearchRepairOwnershipRaceThroughForward/$repair/$outcome/$mode " "$race_log")" -eq 20
done
done
done
- working-directory: backend
run: go test -race ./internal/service/basispoints -run 'Test(WebSearch|AlphaSearch|ToolChoice|CurrentEncrypted|CompactionPolicy)' -count=1 -v
- working-directory: backend
run: go test -race -tags=unit ./internal/service -run 'Test(ExcelBPSAccountSearch|ExcelBPSSearch|BPSSearchDefaults)' -count=1 -v -timeout=10m
- working-directory: backend
run: go test -tags=integration ./internal/repository -run '^TestQuality(BPSSnapshotEqualDefaultsAndManualChanges|EnableBPSRestoreAfterAccountEditorSave|BPSSearchRestorePreservesManualChanges)$' -count=1 -v -timeout=10m
- uses: actions/upload-artifact@v7
if: always()
with:
name: issue871-behavior-${{ github.event.pull_request.head.sha }}
path: ${{ runner.temp }}/issue871-evidence/
retention-days: 30
search-ui:
runs-on: ubuntu-latest
timeout-minutes: 20
Expand Down
39 changes: 39 additions & 0 deletions backend/internal/service/basispoints/WEB_SEARCH.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,45 @@ is invented for it. Any provider-side search cost/entitlement needs separate
operational verification before enabling accounts. No real paid call is part of
CI or local validation.

## Failure diagnostics

`basispoints_search_failed` keeps its existing semantic status 502 and
`server_error` type. It does not imply that the search endpoint returned 502,
or even that a search HTTP request was sent. Failures do not cause replay,
account cooldown, or account disabling based on the diagnostic HTTP status.

Normalized JSON/SSE errors include `error.search_diagnostic` with allowlisted
`phase`, `reason`, and optional `upstream_status`. The same safe summary is
appended to `error.message` and retained in existing Ops error message/detail
fields. An already committed compact keepalive retains the summary in its
failure message; its existing compact error shape is unchanged.

| Phase | Meaning / example reasons |
| --- | --- |
| `search_http` | Search request/transport/rejection: `request_failed`, `transport_failed`, `http_rejected`, `deadline_exceeded`, `canceled` |
| `search_result` | Search body processing: `read_failed`, `parse_failed` |
| `model_initial` | First model stream: `invalid_event`, `unexpected_eof`, `model_did_not_complete`, or fixed stream identity/validation reasons |
| `model_continuation` | Continuation request, HTTP rejection, stream or continuation validation failure |
| `tool_validation` | Tool batch/identity/arguments rejection, including `invalid_tool_response`, `mixed_tool_batch`, `parallel_search_unavailable`, `duplicate_item_id`, `duplicate_call_id` |
| `unknown` | No recognized local failure phase is available |

Unrecognized or missing reasons become `unknown`; missing HTTP evidence is
omitted, never replaced with the semantic status. Search result read/parse
failures can correctly report observed HTTP 200. Model stream failures omit
HTTP status because that bridge boundary has only a response body. Raw model
claims cannot supply search HTTP evidence. Diagnostics contain no error text,
HTTP bodies, query, credential, URL, or identity values. Normal hosted-search
query/source output continues under its existing contract. Client cancellation
retains cancellation handling instead of emitting a search failure.

Raw failure classification, including both tool-correction readers, always
discards claimed search diagnostics. Only the local search bridge and the
gateway parser of its normalized output retain this evidence; correction
errors that bypass ordinary stream normalization still report `unknown`.

These diagnostics address evidence loss only. The cause of the historical
failure in issue #871 and real upstream search recovery remain unverified.

## Management entry points

The account editor, bulk editor, OAuth BPS defaults card and quality-rule BPS
Expand Down
1 change: 1 addition & 0 deletions backend/internal/service/basispoints/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type Bridge struct {
clientStream bool
toolChoice string
selectedTool *tool
searchDiagnostics bool
}

func decode(raw []byte, target any) error {
Expand Down
2 changes: 1 addition & 1 deletion backend/internal/service/basispoints/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ func (b *Bridge) transformWithRepairs(ctx context.Context, reader io.Reader, wri
}
}
terminal = kind == "response.completed" || kind == "response.incomplete" || kind == "response.failed" || kind == "response.cancelled" || kind == "error"
return emit(kind, normalizeFailureEvent(kind, payload))
return emit(kind, b.normalizeFailureEvent(kind, payload))
}
err := readEvents(reader, func(event string, data []byte) error {
if terminal {
Expand Down
43 changes: 38 additions & 5 deletions backend/internal/service/basispoints/upstream_failure.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,51 @@ type UpstreamFailure struct {
Code string
Type string
Message string
Search *SearchFailure
}

func (f *UpstreamFailure) Error() string { return f.Message }

func (f *UpstreamFailure) Details() map[string]any {
return object{"status": f.Status, "code": f.Code, "type": f.Type, "message": f.Message}
detail := object{"status": f.Status, "code": f.Code, "type": f.Type, "message": f.Message}
if f.Search != nil {
detail["search_diagnostic"] = f.Search.details()
}
return detail
}

// ParseUpstreamFailure recognizes failure terminals only. Unknown identifiers
// and free-form upstream messages never enter client responses or diagnostics.
func ParseUpstreamFailure(raw []byte) *UpstreamFailure {
return parseUpstreamFailure(raw, false)
}

// ParseNormalizedUpstreamFailure is for gateway consumption of bridge output,
// never raw model/correction events. Only that boundary may retain locally
// attested search diagnostics that have already passed bridge normalization.
func ParseNormalizedUpstreamFailure(raw []byte) *UpstreamFailure {
return parseUpstreamFailure(raw, true)
}

func parseUpstreamFailure(raw []byte, searchDiagnostics bool) *UpstreamFailure {
if ParseBridgeFailure(raw) != nil {
return nil
}
var payload object
if decode(raw, &payload) != nil {
return nil
}
return classifyUpstreamFailure(text(payload["type"]), payload)
return classifyUpstreamFailureWithSearch(text(payload["type"]), payload, searchDiagnostics)
}

// Raw upstream readers, including both correction readers, cannot attest to
// search HTTP evidence. Keep this default safe even when Details bypasses the
// ordinary bridge normalizer on an error return.
func classifyUpstreamFailure(kind string, payload object) *UpstreamFailure {
return classifyUpstreamFailureWithSearch(kind, payload, false)
}

func classifyUpstreamFailureWithSearch(kind string, payload object, searchDiagnostics bool) *UpstreamFailure {
switch kind {
case "error", "response.failed", "response.cancelled":
default:
Expand Down Expand Up @@ -79,8 +102,18 @@ func classifyUpstreamFailure(kind string, payload object) *UpstreamFailure {
errorType = "invalid_request_error"
}
}
return &UpstreamFailure{Status: status, Code: code, Type: errorType,
failure := &UpstreamFailure{Status: status, Code: code, Type: errorType,
Message: "Excel BPS upstream failure: " + code + "; request was not replayed"}
if code == "basispoints_search_failed" {
failure.Search = NewSearchFailure("unknown", "unknown", 0)
if searchDiagnostics {
failure.Search = parseSearchFailure(detail["search_diagnostic"])
}
// The safe summary also survives compact keepalives and existing Ops
// consumers that retain only the normalized message.
failure.Message += "; " + failure.Search.Error()
}
return failure
}

func failureStatus(value any) int {
Expand Down Expand Up @@ -125,8 +158,8 @@ func failureIdentifierStatus(identifier string) int {

// normalizeFailureEvent preserves response identity/output/usage after the
// bridge has withheld tools, but replaces error details with safe identifiers.
func normalizeFailureEvent(kind string, payload object) object {
failure := classifyUpstreamFailure(kind, payload)
func (b *Bridge) normalizeFailureEvent(kind string, payload object) object {
failure := classifyUpstreamFailureWithSearch(kind, payload, b.searchDiagnostics)
if failure == nil {
return payload
}
Expand Down
Loading
Loading