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
5 changes: 3 additions & 2 deletions .github/scripts/ci-ubuntu-mirrors.sh
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#!/usr/bin/env bash
# Ubuntu's authoritative DNS outage can block both Azure and primary mirrors.
# Use MIT's HTTPS Ubuntu mirror in disposable CI; apt retains Ubuntu's signed
# 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.
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' | sudo tee "$mirror_list" >/dev/null
printf '%s\n' 'https://mirrors.mit.edu/ubuntu' 'https://archive.ubuntu.com/ubuntu' | sudo tee "$mirror_list" >/dev/null
fi
done
221 changes: 214 additions & 7 deletions .github/workflows/http2-stream-reset.yml

Large diffs are not rendered by default.

106 changes: 105 additions & 1 deletion backend/internal/handler/http2_peer_reset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,11 @@ func TestHTTP2PeerResetPartialImages(t *testing.T) {
// Keep billing and deferred usage dependencies real even on failed streams;
// a recovered nil-fixture panic is not valid acceptance evidence.
func newHTTP2PeerResetHandler(t *testing.T, upstream service.HTTPUpstream, accounts ...service.Account) *OpenAIGatewayHandler {
t.Helper()
return newHTTP2PeerResetHandlerWithUsage(t, upstream, &openAIWSUsageHandlerUsageLogRepoStub{}, accounts...)
}

func newHTTP2PeerResetHandlerWithUsage(t *testing.T, upstream service.HTTPUpstream, usageRepo service.UsageLogRepository, accounts ...service.Account) *OpenAIGatewayHandler {
t.Helper()
if len(accounts) == 0 {
for i := int64(1); i <= 2; i++ {
Expand All @@ -384,7 +389,7 @@ func newHTTP2PeerResetHandler(t *testing.T, upstream service.HTTPUpstream, accou
cfg := &config.Config{RunMode: config.RunModeSimple}
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
gateway := service.NewOpenAIGatewayService(repo, nil, &openAIWSUsageHandlerUsageLogRepoStub{}, nil, nil, nil, nil, nil, cfg, nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, service.NewDeferredService(repo, nil, time.Minute), nil, nil, nil, nil, nil, nil, nil)
gateway := service.NewOpenAIGatewayService(repo, nil, usageRepo, nil, nil, nil, nil, nil, cfg, nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, service.NewDeferredService(repo, nil, time.Minute), nil, nil, nil, nil, nil, nil, nil)
t.Cleanup(gateway.CloseOpenAIWSPool)
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing, service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg)
h.maxAccountSwitches = 2
Expand Down Expand Up @@ -661,3 +666,102 @@ func TestHTTP2PeerResetWebSocketTurnPersistence(t *testing.T) {
})
}
}

func TestHTTP2CCSemanticFailureOwnershipAndSLA(t *testing.T) {
testHTTP2CCSemanticFailureOwnershipAndSLA(t, false)
}

func TestHTTP2CCDataOnlyMultilineOwnershipAndSLA(t *testing.T) {
testHTTP2CCSemanticFailureOwnershipAndSLA(t, true)
}

func testHTTP2CCSemanticFailureOwnershipAndSLA(t *testing.T, multiline bool) {
t.Helper()
for _, mode := range []string{"responses", "messages"} {
t.Run(mode, func(t *testing.T) {
setupOpsErrorLogTestQueue(t, 8)
var submissions atomic.Int32
upstream := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
submissions.Add(1)
if r.ProtoMajor != 2 || !strings.HasSuffix(r.URL.Path, "/chat/completions") {
t.Error("fixture must use the real HTTP2 CC conversion boundary")
}
w.Header().Set("Content-Type", "text/event-stream")
errorEvent := "event: error\ndata: {\"error\":{\"type\":\"invalid_request_error\",\"code\":\"context_length_exceeded\",\"message\":\"synthetic semantic failure\"}}\n\n"
if multiline {
errorEvent = "data: {\"error\":\ndata: {\"type\":\"invalid_request_error\",\"code\":\"context_length_exceeded\",\"message\":\"synthetic semantic failure\"}\ndata: }\n\n"
}
_, _ = io.WriteString(w, "data: {\"id\":\"synthetic\",\"model\":\"gpt-5.1\",\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"content\":\"partial\"}}],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":1,\"total_tokens\":4}}\n\n"+errorEvent)
w.(http.Flusher).Flush()
panic(http.ErrAbortHandler)
}))
upstream.EnableHTTP2 = true
upstream.StartTLS()
defer upstream.Close()
base, err := url.Parse(upstream.URL)
require.NoError(t, err)
account := service.Account{ID: 1, Name: "synthetic", Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true,
Credentials: map[string]any{"api_key": "synthetic", "base_url": "https://example.invalid"},
Extra: map[string]any{openai_compat.ExtraKeyResponsesMode: string(openai_compat.ResponsesSupportModeForceChatCompletions)}}
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
h := newHTTP2PeerResetHandlerWithUsage(t, &peerResetHTTPUpstream{client: upstream.Client(), base: base}, usageRepo, account)
repo := &ingressRejectOpsRepo{}
ops := service.NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
router := gin.New()
router.Use(OpsErrorLoggerMiddleware(ops))
endpoint := "/v1/" + mode
body := `{"model":"gpt-5.1","stream":true,"input":"synthetic"}`
handler := h.Responses
if mode == "messages" {
handler = h.Messages
body = `{"model":"gpt-5.1","stream":true,"max_tokens":8,"messages":[{"role":"user","content":"synthetic"}]}`
}
router.POST(endpoint, func(c *gin.Context) {
seed, _ := newOpenAIResponsesFailoverTestContext(t, c.Request.Context())
for key, value := range seed.Keys {
c.Set(key, value)
}
key, _ := middleware2.GetAPIKeyFromContext(c)
key.Group.AllowMessagesDispatch = true
handler(c)
})
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(body)))
for len(opsErrorLogQueue) > 0 {
flushOpsErrorLogBatch([]opsErrorLogJob{<-opsErrorLogQueue})
}
require.Equal(t, int32(1), submissions.Load(), "a semantic failure after submission must never replay generation: %s", rec.Body.String())
require.Equal(t, http.StatusOK, rec.Code)
require.Len(t, repo.entries, 1)
entry := repo.entries[0]
if multiline {
require.Equal(t, "client", entry.ErrorOwner, "F4 multiline data-only context rejection must retain client ownership: %s", mode)
} else {
require.Equal(t, "client", entry.ErrorOwner, "F4 complete CC context rejection must retain client ownership after reset: %s", mode)
}
require.True(t, entry.IsBusinessLimited, "F4 context rejection must retain its SLA exclusion after reset")
require.NotEqual(t, "transport_error", entry.ErrorType)
require.Contains(t, entry.ErrorBody, "context_length_exceeded")
require.Equal(t, http.StatusBadRequest, entry.StatusCode)
require.Contains(t, rec.Body.String(), "partial")
require.Contains(t, rec.Body.String(), "context_length_exceeded")
require.NotContains(t, rec.Body.String(), "upstream_http2_stream_error")
require.NotContains(t, rec.Body.String(), "response.completed")
require.NotContains(t, rec.Body.String(), "message_stop")
terminal := "event: response.failed\n"
if mode == "messages" {
terminal = "event: error\n"
}
require.Equal(t, 1, strings.Count(rec.Body.String(), terminal))
require.NotContains(t, rec.Body.String(), "[DONE]")
select {
case usage := <-usageRepo.created:
require.Equal(t, 3, usage.InputTokens, "partial input usage must survive semantic rejection")
require.Equal(t, 1, usage.OutputTokens, "partial output usage must survive semantic rejection")
case <-time.After(2 * time.Second):
t.Fatal("partial usage must reach the real handler usage recorder")
}
})
}
}
11 changes: 11 additions & 0 deletions backend/internal/handler/ops_error_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,17 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc {
logOpsStreamError(c, ops, status)
return
}
// A complete context rejection has already been classified at the
// semantic boundary. The captured terminal's generic message cannot
// discard its request ownership or SLA exclusion.
if marked, ok := service.GetOpsStreamError(c); ok && marked.RequestScoped &&
service.IsOpsContextLimitRejection(marked.IntendedStatus, 0, marked.Code+" "+marked.Message) {
logOpsStreamError(c, ops, status)
if opsStreamErrorsAllRequestScoped(service.GetOpsStreamErrors(c)) {
logOpsRecoveredUpstream(c, ops, status)
}
return
}
body := w.capturedBytes()
parsed := parseOpsErrorResponse(body)
if !parsed.StreamFailure {
Expand Down
6 changes: 3 additions & 3 deletions backend/internal/repository/ai_ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func readAIOpsAccounts(ctx context.Context, tx *sql.Tx, ids []int64) (map[int64]
}

// Final failed provider requests and successes are separate populations. The
// dedup key prevents retries/log duplication becoming fictitious sample size;
// API-key-scoped dedup key prevents retries/log duplication becoming fictitious sample size;
// recovered failover rows, business rejections, 429/529 and client cancels are
// deliberately excluded from automatic fault evidence.
// A final failure wins over a conflicting completed usage trace for the same
Expand All @@ -220,14 +220,14 @@ var aiOpsEvidenceSQL = `WITH success_candidates AS (
AND (NOT u.stream OR t.detail->>'terminal'='completed')
AND COALESCE(u.image_count,0)=0 AND COALESCE(u.image_output_tokens,0)=0 AND COALESCE(u.billing_mode,'token') NOT IN ('image','video')
), failures AS (
SELECT DISTINCT ON (COALESCE(NULLIF(request_id,''),'error:'||id::text))
SELECT DISTINCT ON (api_key_id,COALESCE(NULLIF(request_id,''),'error:'||id::text))
request_id,client_request_id,api_key_id,model FROM ops_error_logs o WHERE account_id=$1 AND created_at>=$2 AND created_at<$3
AND NOT is_count_tokens AND NOT ` + opsBusinessLimitedSQL("o") + ` AND ` + opsEffectiveOwnerSQL("o") + `='provider'
AND NOT ` + opsExplicitRequestRejectionSQL("o", "400, 404, 413, 422, 500, 502, 503", append(append([]string{}, service.OpsContextLimitRejectionNeedles...), service.OpsModelCapabilityRejectionNeedles...)) + `
AND (status_code>=400 OR error_type='transport_error') AND error_type<>'client_canceled'
AND COALESCE(NULLIF(upstream_status_code,0),status_code) NOT IN (429,529)
AND (COALESCE(NULLIF(upstream_status_code,0),status_code)>=500 OR error_phase IN ('connect','transport') OR error_type='transport_error')
ORDER BY COALESCE(NULLIF(request_id,''),'error:'||id::text),created_at DESC,id DESC
ORDER BY api_key_id,COALESCE(NULLIF(request_id,''),'error:'||id::text),created_at DESC,id DESC
), successes AS (
SELECT s.* FROM success_candidates s
WHERE NOT EXISTS (SELECT 1 FROM failures f WHERE f.api_key_id=s.api_key_id AND (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,9 @@ func TestHTTP2AIOpsEvidenceIncludesCommittedTransportFailure(t *testing.T) {

for _, control := range []struct {
name, phase, errorType, owner string
status int
upstream any
business, countTokens bool
status int
upstream any
business, countTokens bool
}{
{name: "recovered_failover", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 200, upstream: 502},
{name: "business", phase: "upstream", errorType: "upstream_error", owner: "provider", status: 503, upstream: 503, business: true},
Expand Down
102 changes: 102 additions & 0 deletions backend/internal/repository/http2_ai_ops_identity_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//go:build integration

package repository

import (
"context"
"encoding/json"
"testing"
"time"

"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)

func TestHTTP2AIOpsFailureIdentityScopedToAPIKey(t *testing.T) {
for _, scenario := range []string{"shared_request", "unknown_model", "conflicting_completed_usage"} {
t.Run(scenario, func(t *testing.T) {
ctx := context.Background()
tx, err := integrationDB.BeginTx(ctx, nil)
require.NoError(t, err)
defer func() { _ = tx.Rollback() }()
suffix := uuid.NewString()
var userID, accountID int64
var keys [3]int64
require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO users(email,password_hash) VALUES($1,'synthetic') RETURNING id`, "http2-identity-"+suffix+"@test.invalid").Scan(&userID))
require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO accounts(name,platform,type,status,schedulable) VALUES($1,'openai','oauth','active',true) RETURNING id`, "http2-identity-"+suffix).Scan(&accountID))
for i := range keys {
require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO api_keys(user_id,key,name) VALUES($1,$2,'synthetic') RETURNING id`, userID, uuid.NewString()).Scan(&keys[i]))
}
now := time.Now().UTC().Truncate(time.Second)
stamp := now.Add(-time.Minute)
model := "gpt-5.4"
requestID := "shared-" + suffix // Ingress accepts a supplied X-Request-ID.
addUsage := func(key int64, id string) {
t.Helper()
var usageID int64
require.NoError(t, tx.QueryRowContext(ctx, `INSERT INTO usage_logs(user_id,api_key_id,account_id,request_id,model,reasoning_effort,input_tokens,output_tokens,stream,created_at) VALUES($1,$2,$3,$4,$5,'high',100,10,true,$6) RETURNING id`, userID, key, accountID, id, model, stamp).Scan(&usageID))
trace, marshalErr := json.Marshal(map[string]any{
"version": 1, "started_at": stamp.Add(-time.Second).Format(time.RFC3339Nano),
"outcome": "success", "status": 200, "body_complete": true,
"canceled": false, "truncated": false, "client_disconnect": false,
"downstream_error": false, "terminal": "completed",
"protocol_decision": map[string]string{"upstream": "http"},
})
require.NoError(t, marshalErr)
_, err = tx.ExecContext(ctx, `INSERT INTO request_timing_details(usage_log_id,trace_id,created_at,detail) VALUES($1,$2::uuid,$3,$4::jsonb)`, usageID, uuid.NewString(), stamp, string(trace))
require.NoError(t, err)
}
addFailure := func(key int64, failureModel string, at time.Time) {
t.Helper()
_, err = tx.ExecContext(ctx, `INSERT INTO ops_error_logs(account_id,api_key_id,request_id,client_request_id,model,error_phase,error_type,error_owner,error_source,severity,status_code,created_at) VALUES($1,$2,$3,$4,$5,'network','transport_error','provider','upstream_transport','error',200,$6)`, accountID, key, requestID, requestID+"-client", failureModel, at)
require.NoError(t, err)
}
capture := func() service.AIOpsEvidenceSnapshot {
t.Helper()
policy := service.DefaultAIOpsPolicy()
policy.ObservationSeconds = 300
evidence, captureErr := captureAIOpsEvidence(ctx, tx, accountID, policy, now, map[int64]aiOpsAccount{accountID: {quotaKnown: true}})
require.NoError(t, captureErr)
return evidence
}
addUsage(keys[0], "local:success-"+suffix)
failureModel := model
if scenario == "unknown_model" {
failureModel = "unknown-model"
}
// Key A is older, so request-only DISTINCT ON incorrectly discards it.
addFailure(keys[0], failureModel, stamp)
addFailure(keys[1], model, stamp.Add(time.Second))
if scenario == "conflicting_completed_usage" {
addUsage(keys[0], "local:"+requestID)
addUsage(keys[1], "client:"+requestID+"-client")
// A key with no failure must retain its matching-ID success.
addUsage(keys[2], "local:"+requestID)
}
assertPopulation := func() {
t.Helper()
evidence := capture()
if scenario == "conflicting_completed_usage" {
require.Equal(t, 4, evidence.Samples, "F3 conflicting completed usage must be excluded only for the same API key")
require.InDelta(t, 0.5, evidence.ErrorRate, 0.000001, "F3 both scoped failures must survive success exclusion")
} else if scenario == "unknown_model" {
require.False(t, evidence.ModelCoverageComplete, "F3 an older different-key unknown-model failure must remain a cohort blocker")
require.Equal(t, 3, evidence.Samples)
require.InDelta(t, 2.0/3.0, evidence.ErrorRate, 0.000001)
} else {
require.Equal(t, 3, evidence.Samples, "F3 one success plus two different-key resets sharing X-Request-ID must be three samples")
require.InDelta(t, 2.0/3.0, evidence.ErrorRate, 0.000001)
}
if scenario != "unknown_model" {
require.True(t, evidence.ModelCoverageComplete)
}
}
assertPopulation()
// Duplicate logs for either key still contribute only one failure.
addFailure(keys[0], failureModel, stamp.Add(2*time.Second))
addFailure(keys[1], model, stamp.Add(3*time.Second))
assertPopulation()
})
}
}
Loading
Loading