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
6 changes: 6 additions & 0 deletions .github/scripts/anthropic_integrity_evidence.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ def required_tests(mode):
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}']
for route in ('chat', 'responses', 'native_chat', 'native_responses', 'native_messages', 'passthrough'):
tests += [f'TestIssue985FlushFailure/{route}/{phase}' for phase in ('intermediate', 'final')]
for suite in ('TestIssue985NativeHandlerUsage', 'TestIssue985NativePostgresBilling'):
for route in ('chat', 'responses', 'messages'):
for case in ('unknown', 'explicit_zero', 'input_only', 'output_only', 'cache_only', 'partial_full_error'):
tests += [f'{suite}/{route}/{case}/stream={flow}' for flow in ('true', 'false')]
return tests


Expand Down
181 changes: 181 additions & 0 deletions backend/internal/handler/anthropic_issue985_native_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
//go:build unit

package handler

import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/repository"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)

type issue985NativeCase struct {
name, snapshot string
input, output, cached, created int
streamFailure bool
}

func issue985NativeCases() []issue985NativeCase {
return []issue985NativeCase{
{"unknown", "", 0, 0, 0, 0, true},
{"explicit_zero", `{"input_tokens":0,"output_tokens":0}`, 0, 0, 0, 0, false},
{"input_only", `{"input_tokens":17}`, 17, 0, 0, 0, true},
{"output_only", `{"output_tokens":3}`, 0, 3, 0, 0, true},
{"cache_only", `{"cache_read_input_tokens":7,"cache_creation_input_tokens":5,"cache_creation":{"ephemeral_1h_input_tokens":5}}`, 0, 0, 7, 5, true},
{"partial_full_error", `{"input_tokens":17,"output_tokens":3,"cache_read_input_tokens":7,"cache_creation_input_tokens":5,"cache_creation":{"ephemeral_1h_input_tokens":5}}`, 17, 3, 7, 5, true},
}
}

func (tc issue985NativeCase) wire(bufferedMessages bool) string {
usage := ""
if tc.snapshot != "" {
usage = `,"usage":` + tc.snapshot
}
message := `{"id":"msg_native_fixture","type":"message","role":"assistant","model":"deepseek-v4-flash","content":[{"type":"text","text":"fixture text"}]` + usage + `}`
if bufferedMessages {
return message
}
// Streaming converters consume content_block events, not the buffered JSON
// content array carried on message_start.
message = strings.Replace(message, `"content":[{"type":"text","text":"fixture text"}]`, `"content":[]`, 1)
wire := "event: message_start\ndata: {\"type\":\"message_start\",\"message\":" + message + "}\n\n"
wire += "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n" +
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"fixture text\"}}\n\n" +
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"
if tc.name == "partial_full_error" {
return wire + "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"fixture\"}}\n\n"
}
return wire + "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
}

// Each fixture gateway serves one request. Its in-memory admission balance
// and empty quota snapshot have no backing Redis entries to evict after debit.
type issue985NativeCache struct{ *handlerInflightCache }

func (*issue985NativeCache) InvalidateUserBalance(context.Context, int64) error { return nil }
func (*issue985NativeCache) DeleteUserPlatformQuotaCache(context.Context, int64, string) error {
return nil
}

// Real OpenAI handler, scheduler, native adapter, HTTP transport and RecordUsage.
// No worker pool: the request completion signal follows synchronous billing.
func issue985NativeGateway(t *testing.T, upstreamURL string, billing service.UsageBillingRepository) (*httptest.Server, <-chan struct{}) {
t.Helper()
cfg := &config.Config{Gateway: config.GatewayConfig{StreamDataIntervalTimeout: 2}}
cfg.Default.RateMultiplier = 1
cfg.Security.URLAllowlist.AllowPrivateHosts = true
cfg.Security.URLAllowlist.AllowInsecureHTTP = true
groupID := int64(9400)
group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformDeepseek, Status: service.StatusActive, RateMultiplier: 1}
account := service.Account{ID: 9401, Name: "native-fixture", Platform: service.PlatformDeepseek, Type: service.AccountTypeAPIKey, Status: service.StatusActive, Schedulable: true, Concurrency: 1,
Credentials: map[string]any{"api_key": "fixture", "api_protocol": service.APIProtocolAnthropic, "base_url": upstreamURL}, GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9401, GroupID: groupID}}}
repo := &openAIWSUsageHandlerAccountRepoStub{account: account}
snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{accounts: []*service.Account{&account}}, nil, nil, nil, nil)
cache := service.NewBillingCacheService(&issue985NativeCache{newHandlerInflightCache(100)}, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(cache.Stop)
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 32)}
gw := service.NewOpenAIGatewayService(repo, nil, usageRepo, billing, nil, nil, nil, nil, cfg, snapshot, nil, service.NewBillingService(cfg, nil), service.NewRateLimitService(nil, nil, cfg, nil, nil), cache, repository.NewHTTPUpstream(cfg), &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil)
t.Cleanup(gw.StopOpenAICodexTicketHarvester)
t.Cleanup(gw.CloseOpenAIWSPool)
h := NewOpenAIGatewayHandler(gw, service.NewConcurrencyService(&fakeConcurrencyCache{}), cache, service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg)
h.maxAccountSwitches = 2
done := make(chan struct{}, 32)
router := gin.New()
router.Use(func(c *gin.Context) {
defer func() { done <- struct{}{} }()
c.Set(string(middleware.ContextKeyAPIKey), &service.APIKey{ID: 9402, UserID: 9403, GroupID: &groupID, Group: group, User: &service.User{ID: 9403, Balance: 100, Status: service.StatusActive}})
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9403})
c.Next()
})
router.POST("/v1/chat/completions", h.ChatCompletions)
router.POST("/v1/responses", h.Responses)
router.POST("/v1/messages", h.Messages)
server := httptest.NewServer(router)
t.Cleanup(server.Close)
return server, done
}

func issue985NativeRequest(t *testing.T, tc issue985NativeCase, route string, stream bool, requestID string, billing service.UsageBillingRepository) {
t.Helper()
var calls atomic.Int32
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
if r.URL.Path != "/v1/messages" {
t.Errorf("native adapter bypassed: %s", r.URL.Path)
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("X-Request-Id", requestID)
if route == "messages" && !stream {
w.Header().Set("Content-Type", "application/json")
}
_, _ = io.WriteString(w, tc.wire(route == "messages" && !stream))
}))
defer upstream.Close()
gateway, done := issue985NativeGateway(t, upstream.URL, billing)
path := "/v1/" + route
input := `"messages":[{"role":"user","content":"fixture"}],"max_tokens":32`
if route == "chat" {
path = "/v1/chat/completions"
}
if route == "responses" {
input = `"input":"fixture","max_output_tokens":32`
}
resp, err := gateway.Client().Post(gateway.URL+path, "application/json", strings.NewReader(fmt.Sprintf(`{"model":"deepseek-v4-flash","stream":%t,%s}`, stream, input)))
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
<-done
require.Equal(t, int32(1), calls.Load(), "native generation must never replay")
if tc.streamFailure && (stream || route != "messages") {
require.Contains(t, string(body), `"error"`)
require.NotContains(t, string(body), "[DONE]")
require.NotContains(t, string(body), "response.completed")
require.NotContains(t, string(body), `"finish_reason":"stop"`)
} else {
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Contains(t, string(body), "fixture text")
}
}

func TestIssue985NativeHandlerUsage(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, route := range []string{"chat", "responses", "messages"} {
for _, tc := range issue985NativeCases() {
for _, stream := range []bool{true, false} {
t.Run(fmt.Sprintf("%s/%s/stream=%t", route, tc.name, stream), func(t *testing.T) {
billing := &issue985Billing{}
issue985NativeRequest(t, tc, route, stream, "issue985-native-handler", billing)
events := billing.snapshot()
if tc.name == "unknown" {
require.Empty(t, events, "unknown usage cannot become an ordinary zero quote")
return
}
require.Len(t, events, 1, "all known partial usage is recorded exactly once")
u := events[0].Usage
require.Equal(t, tc.input, u.InputTokens)
require.Equal(t, tc.output, u.OutputTokens)
require.Equal(t, tc.cached, u.CacheReadTokens)
require.Equal(t, tc.created, u.CacheCreationTokens)
require.Equal(t, tc.created, u.CacheCreation1hTokens)
if tc.input+tc.output+tc.cached+tc.created > 0 {
require.Positive(t, u.ActualCost)
} else {
require.Zero(t, u.ActualCost)
}
})
}
}
}
}
75 changes: 73 additions & 2 deletions backend/internal/handler/anthropic_issue985_postgres_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ import (

// Strict CI-only DB fixture: missing infrastructure is failure, never a skip.
// The host, role and database are isolated from every production connection.
func TestIssue985PostgresBilling(t *testing.T) {
func issue985Postgres(t *testing.T) *sql.DB {
t.Helper()
gin.SetMode(gin.TestMode)
dsn := os.Getenv("ISSUE985_TEST_POSTGRES_DSN")
u, err := url.Parse(dsn)
Expand All @@ -38,7 +39,13 @@ func TestIssue985PostgresBilling(t *testing.T) {
ctx := context.Background()
require.NoError(t, db.PingContext(ctx))
require.NoError(t, repository.ApplyMigrations(ctx, db))
_, err = db.ExecContext(ctx, `INSERT INTO groups(id,name,platform) VALUES(9300,'issue985','anthropic');
return db
}

func TestIssue985PostgresBilling(t *testing.T) {
db := issue985Postgres(t)
ctx := context.Background()
_, err := db.ExecContext(ctx, `INSERT INTO groups(id,name,platform) VALUES(9300,'issue985','anthropic');
INSERT INTO users(id,email,password_hash,balance) VALUES(9303,'issue985@example.invalid','fixture',100);
INSERT INTO accounts(id,name,platform,type) VALUES(9301,'issue985','anthropic','apikey');
INSERT INTO api_keys(id,user_id,key,name,group_id) VALUES(9302,9303,'issue985-fixture','issue985',9300);
Expand Down Expand Up @@ -121,3 +128,67 @@ func TestIssue985PostgresBilling(t *testing.T) {
}
}
}

func TestIssue985NativePostgresBilling(t *testing.T) {
db := issue985Postgres(t)
ctx := context.Background()
_, err := db.ExecContext(ctx, `INSERT INTO groups(id,name,platform) VALUES(9400,'issue985-native','deepseek');
INSERT INTO users(id,email,password_hash,balance) VALUES(9403,'issue985-native@example.invalid','fixture',100);
INSERT INTO accounts(id,name,platform,type) VALUES(9401,'issue985-native','deepseek','apikey');
INSERT INTO api_keys(id,user_id,key,name,group_id) VALUES(9402,9403,'issue985-native-fixture','issue985-native',9400);
INSERT INTO account_groups(account_id,group_id) VALUES(9401,9400)`)
require.NoError(t, err)
real := repository.NewUsageBillingRepository(nil, db)
durable, ok := real.(service.DurableUsageBillingRepository)
require.True(t, ok)
for _, route := range []string{"chat", "responses", "messages"} {
for _, tc := range issue985NativeCases() {
for _, stream := range []bool{true, false} {
t.Run(fmt.Sprintf("%s/%s/stream=%t", route, tc.name, stream), func(t *testing.T) {
requestID := fmt.Sprintf("issue985-native-%s-%s-%t", route, tc.name, stream)
billing := &issue985Billing{UsageBillingRepository: real, durable: durable}
issue985NativeRequest(t, tc, route, stream, requestID, billing)
var events, logs, quotes int
require.NoError(t, db.QueryRowContext(ctx, `SELECT (SELECT count(*) FROM usage_billing_events WHERE request_id=$1),(SELECT count(*) FROM usage_logs WHERE request_id=$1),(SELECT count(*) FROM usage_billing_quotes WHERE request_id=$1)`, requestID).Scan(&events, &logs, &quotes))
if tc.name == "unknown" {
require.Empty(t, billing.snapshot())
require.Zero(t, events)
require.Zero(t, logs)
require.Zero(t, quotes, "unknown cannot persist an ordinary zero quote")
return
}
require.Len(t, billing.snapshot(), 1)
require.Equal(t, 1, events)
require.Equal(t, 1, logs)
require.Equal(t, 1, quotes)
var state string
var input, output, cached, created, ttl int
var actual, quoted, canonicalCost float64
var debit sql.NullFloat64
require.NoError(t, db.QueryRowContext(ctx, `SELECT e.state,u.input_tokens,u.output_tokens,u.cache_read_tokens,u.cache_creation_tokens,u.cache_creation_1h_tokens,u.actual_cost,q.quoted_actual_cost,q.canonical_actual_cost,q.wallet_debit FROM usage_billing_events e JOIN usage_logs u USING(request_id,api_key_id) JOIN usage_billing_quotes q USING(request_id,api_key_id) WHERE e.request_id=$1`, requestID).Scan(&state, &input, &output, &cached, &created, &ttl, &actual, &quoted, &canonicalCost, &debit))
require.Equal(t, "complete", state)
require.Equal(t, tc.input, input)
require.Equal(t, tc.output, output)
require.Equal(t, tc.cached, cached)
require.Equal(t, tc.created, created)
require.Equal(t, tc.created, ttl)
if tc.input+tc.output+tc.cached+tc.created > 0 {
require.Positive(t, actual)
require.Positive(t, quoted)
require.Positive(t, canonicalCost)
require.True(t, debit.Valid)
require.InDelta(t, actual, debit.Float64, 1e-8)
} else {
require.Zero(t, actual)
require.Zero(t, quoted)
require.Zero(t, canonicalCost)
require.False(t, debit.Valid)
}
recovered, err := durable.ApplyStagedUsageBilling(ctx, service.UsageBillingEventKey{RequestID: requestID, APIKeyID: 9402})
require.NoError(t, err)
require.False(t, recovered.Result.Applied, "recovery cannot charge known partial usage twice")
})
}
}
}
}
12 changes: 12 additions & 0 deletions backend/internal/server/middleware/request_capture.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (

"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/requestcapture"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)

Expand Down Expand Up @@ -78,4 +79,15 @@ func (w *captureResponseWriter) Write(p []byte) (int, error) {
}
func (w *captureResponseWriter) WriteString(p string) (int, error) { return w.Write([]byte(p)) }

func (w *captureResponseWriter) Flush() { _ = w.FlushError() }

func (w *captureResponseWriter) FlushError() error {
err := service.FlushGatewayResponse(w.ResponseWriter)
if err != nil {
w.session.MarkPartial("client_flush_failed")
w.session.MarkError("client_flush_failed")
}
return err
}

var _ http.Flusher = (*captureResponseWriter)(nil)
70 changes: 70 additions & 0 deletions backend/internal/server/middleware/request_capture_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,73 @@ func TestCaptureSensitiveReadAuditRoutes(t *testing.T) {
require.NotEmpty(t, auditSensitiveReads[route])
}
}

type captureFlushFailureRecorder struct {
*httptest.ResponseRecorder
failAt int
flushes int
}

func (w *captureFlushFailureRecorder) FlushError() error {
w.flushes++
if w.flushes == w.failAt {
return io.ErrClosedPipe
}
w.Flush()
return nil
}

func TestRequestCapturePropagatesFlushFailure(t *testing.T) {
for _, tc := range []struct {
name string
failAt int
wantBody string
}{
{"intermediate", 1, "data: content\n\n"},
{"final", 2, "data: content\n\ndata: [DONE]\n\n"},
} {
t.Run(tc.name, func(t *testing.T) {
store := &captureMiddlewareStore{tasks: map[string]requestcapture.Task{}, records: map[string]requestcapture.Record{}}
manager, err := requestcapture.New(store, t.TempDir(), requestcapture.Config{Enabled: true, QuotaMiB: 10, RetentionDays: 7})
require.NoError(t, err)
defer manager.Close()
_, err = manager.Create(context.Background(), requestcapture.CreateTask{TargetType: "group", TargetID: 7, DurationMinutes: 1}, "fixture")
require.NoError(t, err)
r := gin.New()
r.Use(ClientRequestID(), func(c *gin.Context) {
group := int64(7)
c.Set(string(ContextKeyAPIKey), &service.APIKey{UserID: 1, GroupID: &group})
c.Next()
}, RequestCapture(manager))
var flushErr error
r.GET("/stream", func(c *gin.Context) {
require.IsType(t, &captureResponseWriter{}, c.Writer)
c.Header("Content-Type", "text/event-stream")
for _, frame := range []string{"data: content\n\n", "data: [DONE]\n\n"} {
_, err := c.Writer.WriteString(frame)
require.NoError(t, err)
flushErr = service.FlushGatewayResponse(c.Writer)
if flushErr != nil {
return
}
}
})
writer := &captureFlushFailureRecorder{ResponseRecorder: httptest.NewRecorder(), failAt: tc.failAt}
r.ServeHTTP(writer, httptest.NewRequest(http.MethodGet, "/stream", nil))
require.ErrorIs(t, flushErr, io.ErrClosedPipe)
require.Equal(t, tc.failAt, writer.flushes)
require.Equal(t, tc.wantBody, writer.Body.String())
require.Equal(t, http.StatusOK, writer.Code)
require.Eventually(t, func() bool {
store.mu.Lock()
defer store.mu.Unlock()
for _, record := range store.records {
if record.Partial && record.IsError {
return true
}
}
return false
}, 5*time.Second, 10*time.Millisecond)
})
}
}
Loading
Loading