Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
ad24431
test: define Anthropic stream integrity regressions and acceptance scope
ranxi2001 Nov 21, 2026
be33d8f
docs: record complete Anthropic integrity acceptance contract
ranxi2001 Nov 21, 2026
f8bed6c
ci: run fixed-source SSE business RED and clean candidate race regres…
ranxi2001 Nov 21, 2026
7f5e6b3
fix: assemble Anthropic SSE frames and validate complete usage before…
ranxi2001 Nov 21, 2026
1913bed
fix: share native SSE integrity and exercise handler billing through …
ranxi2001 Nov 21, 2026
5ce2f62
fix: validate native Messages framing and preserve partial failure bi…
ranxi2001 Nov 21, 2026
6e7003f
fix: remove obsolete native adapter reader imports
ranxi2001 Nov 21, 2026
dbdc03a
fix: report terminal write cancellation and verify bounded reader lif…
ranxi2001 Nov 21, 2026
14fd578
fix: handle SSE carriage returns and bound diagnostics to metadata
ranxi2001 Nov 21, 2026
b418d4b
fix: preserve partial usage when stream writes fail
ranxi2001 Nov 21, 2026
576ae0c
fix: preserve Responses tool restoration and initialize relay timeout…
ranxi2001 Nov 21, 2026
8d8b3c1
fix: initialize relay timer metadata before interval selection
ranxi2001 Nov 21, 2026
41eb020
fix: preserve native cancellation and align full protocol regression …
ranxi2001 Nov 21, 2026
7ca68a3
test: 验证缺少终态时的错误响应与缓存计费
ranxi2001 Nov 21, 2026
a7d17e1
fix: retain native initial output usage and ignore undispatched SSE f…
ranxi2001 Nov 21, 2026
6d324ab
test: exercise official client accumulator and preserve unknown SSE f…
ranxi2001 Nov 21, 2026
e01953b
Merge remote-tracking branch 'origin/production' into HEAD
ranxi2001 Nov 21, 2026
0769756
test: 使用官方 SDK 自带的 HTTP 客户端运行 SSE 回归
ranxi2001 Nov 21, 2026
1f8a84c
fix: honor buffered cancellation and use SDK-owned HTTP transport
ranxi2001 Nov 21, 2026
93687ce
Merge remote-tracking branch 'origin/production' into HEAD
ranxi2001 Nov 21, 2026
2e02684
ci: archive fixed Anthropic RED proof and retain reusable integrity gate
ranxi2001 Nov 21, 2026
e3295d4
fix: propagate buffered response delivery failures with observed usage
ranxi2001 Nov 21, 2026
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
3 changes: 2 additions & 1 deletion .github/ci/scopes.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"deploy/tests/docker-compose-trusted-proxies-env-test.sh",
"deploy/docker-compose*",
".github/ci/go_tests.py",
".github/ci/go-test-weights.json"
".github/ci/go-test-weights.json",
".github/scripts/anthropic_integrity_sdk*"
]
},
"security-scan.yml": {
Expand Down
12 changes: 12 additions & 0 deletions .github/ci/test_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,18 @@ def successful_jobs(self, run_id):
return {'backend'}
self.assertTrue(self.select(head, Evidence())['backend'][0])

def test_official_sdk_fixture_change_selects_backend_integration(self):
actual = json.loads((REPO / '.github/ci/scopes.json').read_text())
self.scopes['backend'] = actual['backend-ci.yml']['integration-test']
for path in ('.github/scripts/anthropic_integrity_sdk.py',
'.github/scripts/anthropic_integrity_sdk_requirements.txt'):
with self.subTest(path=path):
self.write(path, 'changed SDK fixture\n')
head = self.save()
result = self.select(head)
self.assertTrue(result['backend'][0])
self.assertFalse(result['frontend'][0])

def test_other_pr_and_other_repository_results_are_not_candidates(self):
evidence = ci.Evidence('fixture/repo', 'unused')
common = {'head_sha': 'a' * 40, 'head_repository': {'full_name': 'fixture/repo'}, 'pull_requests': [{'number': 7}]}
Expand Down
61 changes: 61 additions & 0 deletions .github/scripts/anthropic_integrity_evidence.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Validate actual business failures/passes, never compilation or skipped tests."""
import json
import pathlib
import re
import sys


def required_tests(mode):
tests = []
for route in ('chat', 'responses'):
tests += [f'TestIssue985Framing/{route}/{case}' for case in ('canonical', 'id', 'comment', 'multidata')]
tests += [f'TestIssue985Failure/{route}/{case}' for case in ('empty', 'terminal_only', 'missing_usage', 'stop_reason_error')]
if mode == 'red':
return tests
for route in ('chat', 'responses', 'native_chat', 'native_responses'):
tests += [f'TestIssue985CanceledBeforeBufferedRead/{route}', f'TestIssue985BufferedFinalWriteFailure/{route}']
for flow in ('stream', 'buffered'):
tests += [f'TestIssue985AdapterBoundaries/{route}/{flow}/{case}' for case in ('crlf', 'cr', 'bom', 'data_only', 'field_order', 'event_without_data', 'compact', 'eof_frame', 'unknown', 'zero', 'missing', 'field_missing', 'stop_reason_only', 'terminal_error', 'malformed', 'mismatch')]
for route in ('native', 'passthrough', 'normal'):
tests += [f'TestIssue985RawPartialUsage/{route}']
tests += [f'TestIssue985NativeRelays/{route}/{case}' for case in ('multidata', 'unknown_multidata', 'empty', 'missing', 'error_after_terminal', 'reasoning')]
tests += ['TestIssue985EveryTransportSplit', 'TestIssue985FrameBoundAndFieldOrder']
tests += [f'TestIssue985FinalWriteFailure/{route}' for route in ('chat_completions', 'responses')]
for flow in ('true', 'false'):
tests += [f'TestIssue985HandlerUsage/{case}/stream={flow}' for case in ('framed', 'missing', 'zero', 'partial_error', 'partial_protocol')]
tests += [f'TestIssue985PostgresBilling/{case}/stream={flow}' for case in ('valid', 'missing', 'explicit_zero', 'partial_protocol', 'partial_error')]
tests += [f'TestIssue985HandlerToolContinuation/stream={flow}']
tests += [f'TestIssue985SDKAccumulator/{case}/stream={flow}' for case in ('text', 'tool', 'zero', 'missing', 'partial_error', 'partial_protocol')]
tests += [f'TestIssue985CancellationResources/cancel={flow}']
return tests


def validate(mode, root):
raw = (root / f'{mode}.jsonl').read_text()
stderr = (root / f'{mode}.stderr').read_text()
try:
events = [json.loads(line) for line in raw.splitlines() if line.strip()]
except ValueError as exc:
raise AssertionError('non-JSON/corrupt Go test output') from exc
output = ''.join(event.get('Output', '') for event in events) + stderr
(root / f'{mode}.log').write_text(output)
assert not re.search(r'WARNING: DATA RACE|build failed|setup failed|no tests to run|panic[: ]|fatal error:|runtime error:|SIGSEGV|test timed out', output), output[-8000:]
assert not any(event.get('Action') == 'skip' for event in events), 'skip contamination'
outcomes = {event['Test']: event['Action'] for event in events if event.get('Test') and event.get('Action') in ('pass', 'fail')}
expected = {test: 'pass' for test in required_tests(mode)}
if mode == 'red':
expected = {test: ('pass' if test.endswith('/canonical') else 'fail') for test in expected}
for test, outcome in expected.items():
assert outcomes.get(test) == outcome, (test, outcome, outcomes.get(test))
rc = int((root / f'{mode}.exitcode').read_text())
assert rc == (1 if mode == 'red' else 0), rc
if mode == 'red':
assert output.count('legal SSE must preserve input 17') == 6, 'RED must fail at business 17/3 oracle'
assert output.count('incomplete or errored stream must fail') == 8, 'RED must demonstrate false success'
else:
assert all(action == 'pass' for action in outcomes.values()), outcomes
print(f'{mode}: validated {len(expected)} required business cases; exit={rc}')


if __name__ == '__main__':
validate(sys.argv[1], pathlib.Path(sys.argv[2]))
54 changes: 54 additions & 0 deletions .github/scripts/anthropic_integrity_evidence_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Negative controls for the strict remote evidence validator (no Go needed)."""
import importlib.util
import json
import pathlib
import tempfile
import unittest

spec = importlib.util.spec_from_file_location('validator', pathlib.Path(__file__).with_name('anthropic_integrity_evidence.py'))
validator = importlib.util.module_from_spec(spec)
spec.loader.exec_module(validator)

class EvidenceControls(unittest.TestCase):
def exercise(self, mutate=None):
events = [{'Test': test, 'Action': 'pass'} for test in validator.required_tests('green')]
if mutate:
mutate(events)
with tempfile.TemporaryDirectory() as d:
root = pathlib.Path(d)
(root / 'green.jsonl').write_text('\n'.join(json.dumps(e) for e in events))
(root / 'green.stderr').write_text('')
(root / 'green.exitcode').write_text('0')
validator.validate('green', root)

def test_complete(self):
self.exercise()

def test_missing(self):
with self.assertRaises(AssertionError):
self.exercise(lambda rows: rows.pop())

def test_pollution(self):
for text in ['panic: injected', 'http: panic serving fixture', 'runtime error: injected', 'SIGSEGV', 'WARNING: DATA RACE', 'build failed', 'fatal error: crash', 'no tests to run', 'test timed out']:
with self.subTest(text=text), self.assertRaises(AssertionError):
self.exercise(lambda rows: rows.append({'Output': text}))

def test_skipped(self):
with self.assertRaises(AssertionError):
self.exercise(lambda rows: rows.append({'Action': 'skip', 'Test': 'extra'}))

def test_corrupt_output(self):
with tempfile.TemporaryDirectory() as d:
root = pathlib.Path(d)
(root / 'green.jsonl').write_text('panic: injected outside JSON\n')
(root / 'green.stderr').write_text('')
(root / 'green.exitcode').write_text('0')
with self.assertRaises(AssertionError):
validator.validate('green', root)

def test_nonzero(self):
with self.assertRaises(AssertionError):
self.exercise(lambda rows: rows.append({'Test': 'extra', 'Action': 'fail'}))

if __name__ == '__main__':
unittest.main()
47 changes: 47 additions & 0 deletions .github/scripts/anthropic_integrity_sdk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""Official client accumulator against an isolated GatewayHandler loopback server."""
import json
import sys
from urllib.parse import urlparse

import openai

endpoint, scenario, stream_flag = sys.argv[1:]
assert urlparse(endpoint).hostname in ('127.0.0.1', 'localhost')
streaming = stream_flag == 'true'
with openai.DefaultHttpx2Client(trust_env=False, timeout=20) as transport:
with openai.OpenAI(api_key='synthetic-fixture', base_url=endpoint + '/v1', max_retries=0, http_client=transport) as client:
messages = [{'role': 'user', 'content': scenario}]
tools = [{'type': 'function', 'function': {'name': 'weather', 'parameters': {
'type': 'object', 'properties': {'city': {'type': 'string'}}, 'required': ['city']}}}]

def complete(history):
if streaming:
with client.chat.completions.stream(model='claude-sonnet-4.5', messages=history, tools=tools) as response:
return response.get_final_completion()
return client.chat.completions.create(model='claude-sonnet-4.5', messages=history, tools=tools)

if scenario in ('missing', 'partial_error', 'partial_protocol'):
try:
complete(messages)
except openai.APIError:
pass
else:
raise AssertionError('official accumulator accepted incomplete stream as success')
else:
response = complete(messages)
assert response.model == 'claude-sonnet-4.5'
assert response.usage is not None
assert response.usage.prompt_tokens == (0 if scenario == 'zero' else 12)
assert response.usage.completion_tokens == (0 if scenario == 'zero' else 7)
if scenario == 'tool':
choice = response.choices[0]
assert choice.finish_reason == 'tool_calls'
call, = choice.message.tool_calls
assert call.id == 'call_fixture' and call.function.name == 'weather'
assert json.loads(call.function.arguments) == {'city': 'Paris'}
messages += [choice.message.model_dump(exclude_none=True),
{'role': 'tool', 'tool_call_id': call.id, 'content': 'sunny'}]
response = complete(messages)
assert response.choices[0].message.content == 'partial'
assert response.choices[0].finish_reason == 'stop'
print(json.dumps({'SDK_PASS': True, 'sdk': openai.__version__, 'scenario': scenario, 'stream': streaming}))
1 change: 1 addition & 0 deletions .github/scripts/anthropic_integrity_sdk_requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
openai==3.57.0
16 changes: 16 additions & 0 deletions .github/workflow-archive/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,19 @@
主 CI 同时移除已合并分支的 `issue854-behavior`、`pelican-round-evidence`、`pr612-regressions`、`pr612-regressions-red` 以及质量模板、用户启用和 Issue854 的条件步骤;VIP 入账工作流也清除旧分支的两段 RED 步骤和 `source-format` job,保留 PostgreSQL GREEN 回归。原定义可从上述归档基线的 `.github/workflows/backend-ci.yml` 查阅。

上述 32 个入口已在 GitHub 登记为停用,历史运行记录保留。需要重跑历史验收时,在任务分支恢复所需文件到 `.github/workflows/`,先核对固定 SHA、分支条件、工具链、runner 和脚本路径,再按任务范围重新启用对应工作流。归档文件保留当时配置,不保证在新代码上直接可运行。常规回归优先并入主 CI;确需专用工作流时按相关路径触发,临时 RED/GREEN、截图或试用构建在任务完成后归档。

## Issue 985 Anthropic SSE integrity

[anthropic-stream-integrity-red-green.yml](anthropic-stream-integrity-red-green.yml)
retains the temporary fixed-production `dfcc6623` RED/GREEN workflow used by
[PR #987](https://github.com/ranxi2001/sub2api/pull/987). The immutable oracle ran
against the original checkout and clean candidates, with raw identity/test logs
in [run 44907259566](https://github.com/ranxi2001/sub2api/actions/runs/44907259566).
That run passed the strict RED/GREEN validator, race, real handlers, official SDK
accumulation, isolated PostgreSQL billing and ordinary server build.

The active `anthropic-stream-integrity.yml` retains the reusable path-triggered
GREEN/race/SDK/PostgreSQL/build gate and validator negative controls. Unit tests
also remain selected by main CI, whose integration job explicitly runs the PG
and official SDK fixtures. Archiving the fixed baseline does not mark PR review
or the current full CI complete; the PR stays Draft pending those gates.
102 changes: 102 additions & 0 deletions .github/workflow-archive/anthropic-stream-integrity-red-green.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
name: Anthropic stream integrity
on:
pull_request:
branches: [production]
paths:
- 'backend/internal/service/*anthropic*'
- 'backend/internal/service/gateway_forward*'
- 'backend/internal/handler/*985*'
- 'backend/internal/pkg/apicompat/**'
- '.github/workflows/anthropic-stream-integrity.yml'
- '.github/scripts/anthropic_integrity*'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: anthropic-integrity-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
jobs:
regression:
runs-on: ubuntu-latest
timeout-minutes: 45
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_USER: fixture
POSTGRES_PASSWORD: fixture
POSTGRES_DB: issue985_fixture
ports: ['15432:5432']
options: >-
--health-cmd "pg_isready -U fixture -d issue985_fixture"
--health-interval 5s --health-timeout 5s --health-retries 10
env:
ISSUE985_TEST_POSTGRES_DSN: 'postgres://fixture:fixture@127.0.0.1:15432/issue985_fixture?sslmode=disable'
CANDIDATE_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
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: Install pinned official SDK for loopback accumulator
run: python3 -m pip install -r .github/scripts/anthropic_integrity_sdk_requirements.txt
- name: Evidence validator negative controls
run: python3 .github/scripts/anthropic_integrity_evidence_test.py
- name: Fixed production business RED, identical oracle
shell: bash
run: |
set -euo pipefail
evidence="$RUNNER_TEMP/anthropic-integrity"
mkdir -p "$evidence"
baseline=dfcc66238b28c8a0392c24d418d81120f95f682f
red_tree="$RUNNER_TEMP/anthropic-red"
git worktree add --detach "$red_tree" "$baseline"
oracle=backend/internal/service/anthropic_stream_integrity_test.go
cp "$oracle" "$red_tree/$oracle"
test "$(git hash-object "$oracle")" = "$(git -C "$red_tree" hash-object "$oracle")"
printf 'candidate=%s\nbaseline=%s\noracle=%s\n' "$CANDIDATE_SHA" "$baseline" "$(git hash-object "$oracle")" > "$evidence/identity.txt"
for path in gateway_forward_compat_stream.go gateway_forward_as_chat_completions.go gateway_forward_as_responses.go; do
p="backend/internal/service/$path"
test "$(git -C "$red_tree" hash-object "$p")" = "$(git rev-parse "$baseline:$p")"
git -C "$red_tree" hash-object "$p" >> "$evidence/identity.txt"
done
cd "$red_tree/backend"
set +e
go test -json -tags=unit ./internal/service -run '^TestIssue985(Framing|Failure)$' -count=1 -timeout=8m > "$evidence/red.jsonl" 2> "$evidence/red.stderr"
rc=$?
set -e
printf '%s\n' "$rc" > "$evidence/red.exitcode"
python3 "$GITHUB_WORKSPACE/.github/scripts/anthropic_integrity_evidence.py" red "$evidence"
- name: Clean candidate GREEN and race
if: ${{ !cancelled() }}
shell: bash
run: |
set -euo pipefail
test "$(git rev-parse HEAD)" = "$CANDIDATE_SHA"
test -z "$(git status --porcelain)"
evidence="$RUNNER_TEMP/anthropic-integrity"
cd backend
set +e
go test -race -json -tags=unit,issue985pg,issue985sdk ./internal/service ./internal/handler -run '^TestIssue985' -count=1 -timeout=10m > "$evidence/green.jsonl" 2> "$evidence/green.stderr"
rc=$?
set -e
printf '%s\n' "$rc" > "$evidence/green.exitcode"
python3 ../.github/scripts/anthropic_integrity_evidence.py green "$evidence"
- name: Ordinary server build
working-directory: backend
env:
CGO_ENABLED: '0'
run: go build -trimpath -o "$RUNNER_TEMP/anthropic-server" ./cmd/server
- uses: actions/upload-artifact@v4
if: always()
with:
name: anthropic-integrity-${{ env.CANDIDATE_SHA }}-${{ github.run_attempt }}
path: ${{ runner.temp }}/anthropic-integrity
if-no-files-found: error
retention-days: 14
Loading
Loading