Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
90 commits
Select commit Hold shift + click to select a range
5e4e386
chore: sync VERSION to 0.2.23 [skip ci]
github-actions[bot] Nov 18, 2026
7892c7a
fix(openai): stop alpha/search tool-level 403s from benching OAuth ac…
Wei-Shaw Nov 20, 2026
1ccf30f
fix(openai): protect rotated oauth credentials from enrichment timeou…
xuemk Nov 11, 2026
9f92e00
feat(gateway): write Claude Code compaction requests at 5m cache TTL
Anankke Nov 14, 2026
11b2467
feat(websearch): add Exa as a web search emulation provider
Anankke Nov 14, 2026
ca0c76b
feat(apicompat): return web_search sources in web_search_tool_result …
Anankke Nov 14, 2026
4f4f15c
fix(apicompat): tolerate non-string action.url and skip unfinished we…
Anankke Nov 14, 2026
a5c8941
fix(apicompat): map ToolSearch to native tool_search for Codex OAuth
Anankke Nov 14, 2026
957d685
fix(apicompat): keep forced tools, result text and reserved names intact
Anankke Nov 14, 2026
6bf8c25
fix: preserve upstream tool search accumulator merge resolution
ranxi2001 Nov 20, 2026
39768f7
fix(openai): keep hosted output items in buffered compat responses
Anankke Nov 14, 2026
564c989
fix(openai): rebuild empty buffered terminal output from done items
Anankke Nov 14, 2026
00c8904
fix(apicompat): keep tool_use input a JSON object in buffered responses
Anankke Nov 14, 2026
e95f908
fix(openai): render custom tool calls only from rebuilt buffered output
Anankke Nov 15, 2026
e59f34c
fix(openai): complete buffered item parts by their own index
Anankke Nov 15, 2026
706f998
fix(openai): follow the streaming path for rebuilt buffered items
Anankke Nov 15, 2026
ff662d8
fix(openai): keep xAI server-side search out of rebuilt buffered tool…
Anankke Nov 16, 2026
3890d8c
perf(scheduler): omit expanded groups from account cache
r266-tech Nov 16, 2026
b3735bd
fix(accounts): refresh Claude and Gemini usage snapshots
wucm667 Nov 16, 2026
448bb3e
ci: rerun checks after allocation guard failure
wucm667 Nov 17, 2026
fae1d7e
fix(i18n): clarify Ultra Fast service tier hints
wucm667 Nov 19, 2026
a2ffac6
fix(composite): adapt thinking to the Claude 5.5 model a route rewrit…
Anankke Nov 16, 2026
5033d18
perf(gateway): skip the cache_control TTL walk when no 1h breakpoint …
lishuangqiang Nov 16, 2026
739da57
fix(grok): bill search calls from xAI usage success counts
Anankke Nov 16, 2026
7b0038e
perf(openai): skip the image-intent body scan when a request cannot d…
lishuangqiang Nov 16, 2026
395aace
perf(openai): reuse an already-validated body when classifying image …
lishuangqiang Nov 16, 2026
c568a7b
perf(openai): apply the image-intent precheck to the declaration scan…
lishuangqiang Nov 16, 2026
ad8da38
perf(service): parse the gateway request body with a single root walk
lishuangqiang Nov 16, 2026
9bb0c44
perf(openai): skip the redundant body validation when parsing respons…
lishuangqiang Nov 16, 2026
e087eae
perf(openai): use the validated parse path for chat completions too
lishuangqiang Nov 16, 2026
98c0ec3
test(gateway): stop ignoring strings.Builder errors in the scan bench…
lishuangqiang Nov 16, 2026
9f3e348
perf(openai): stop copying the whole input array when stripping names…
lishuangqiang Nov 16, 2026
beb6777
style(openai): gofmt the namespace strip equivalence test
lishuangqiang Nov 16, 2026
b27ceb9
perf(openai): stop walking every request body in the tool-schema sani…
lishuangqiang Nov 16, 2026
31764c8
fix(openai): stop pinning large request bodies after the handler
zhx8702 Nov 16, 2026
ce37b72
fix(anthropic): expose metadata-backed long-context models
wucm667 Nov 17, 2026
b0dad12
fix(openai): skip foreign-vendor models on ChatGPT OAuth accounts, pa…
SipengXie2024 Nov 17, 2026
b30320f
fix(accounts): opt in to bulk passthrough model filter changes
r266-tech Nov 17, 2026
b8fca99
feat(accounts): estimate Claude OAuth and setup-token window costs
stevelee477 Nov 17, 2026
0b242fb
feat(frontend): warn on frequent manual token refreshes
Ming-Sir-69 Nov 17, 2026
2371e5a
fix(accounts): omit temperature from account tests for models that re…
Echways Nov 17, 2026
c645329
fix(admin): initialize default platform quotas for new users
XYZ0901 Nov 18, 2026
d6e44a3
fix(gemini): keep trailing parts out of the final tool-result turn
iam1maker Nov 18, 2026
4e36b9c
fix(openai): preserve VS Code IDE context in HTTP Responses
superman2003 Nov 18, 2026
7ce24cb
fix(usage): record per-turn Responses reasoning effort
superman2003 Nov 18, 2026
1918eae
fix(codex): preserve native audio input capabilities
superman2003 Nov 18, 2026
5f2338c
fix(ops): weight average token rate by request duration
TeacherLi07 Nov 18, 2026
915984d
fix(gateway): ensure DeepSeek Anthropic tool-use history carries thin…
alfadb Nov 18, 2026
60c8597
fix(antigravity): preserve upstream Gemini SSE comment frames
r266-tech Nov 18, 2026
01f578d
fix(grok): accept five edit sources and classify input errors
wucm667 Nov 19, 2026
d5823ae
fix(gateway): resolve an issue where 'stop' and Kimi dynamic tool def…
Daiyangcheng Nov 19, 2026
9ccbcac
fix(openai): fail over upstream request timeouts
wucm667 Nov 19, 2026
b2e4cc7
fix(typesafe): apply account model mapping to System One
r266-tech Nov 19, 2026
bc130dc
test(antigravity): a bare 429 on several accounts is request-scoped
william-drakemond Nov 16, 2026
138ad10
fix(antigravity): one request cools at most one account for a bare 429
william-drakemond Nov 16, 2026
44066e4
test(antigravity): a bare 429 after the retry loop cools no second ac…
william-drakemond Nov 19, 2026
c87c4fe
fix(antigravity): a bare 429 after the retry loop cools no account th…
william-drakemond Nov 19, 2026
6cfb6ee
feat(model-plaza): add copy button for model IDs
yan9651688 Nov 20, 2026
02f3b0f
fix(antigravity): query quota from the account's forward endpoint
SipengXie2024 Nov 20, 2026
960af8f
fix(openai): keep relayed image usage on a single SSE data line
SipengXie2024 Nov 17, 2026
01ecca2
fix(gateway): reject request bodies whose duplicate fields disagree
Nov 19, 2026
857a30b
fix(gateway): reject conflicting duplicates in nested objects too
Wei-Shaw Nov 20, 2026
555a675
fix(gateway): close bypasses found in the duplicate-field audit
Wei-Shaw Nov 20, 2026
f46d716
fix(gateway): close second-round audit findings on the duplicate scanner
Wei-Shaw Nov 20, 2026
47f8fe3
fix(gateway): reject multipart parts with an RFC 2231 extended field …
Wei-Shaw Nov 20, 2026
104981c
fix(gateway): satisfy errcheck in duplicate-field scanner
Wei-Shaw Nov 20, 2026
5231793
fix: 对齐上游 v0.2.24 的请求处理、配额依赖与 fork 版本
ranxi2001 Nov 20, 2026
1bc6371
fix: 补齐后台提示、Gemini 读取错误分类与 fork 解析用例
ranxi2001 Nov 20, 2026
4b2d1c4
ci: match v0.2.24 handler fixtures to historical WS baselines
ranxi2001 Nov 20, 2026
915d793
fix: 适配 fork 模型目录、正文读取与网关依赖
ranxi2001 Nov 20, 2026
d5c86a6
ci: assert the retained WS shadow summary regression name
ranxi2001 Nov 20, 2026
71ef9f0
Revert "ci: assert the retained WS shadow summary regression name"
ranxi2001 Nov 20, 2026
8c443eb
Merge commit 'f3ee68d65' into cherry/upstream-024-20261121
ranxi2001 Nov 20, 2026
e7f2096
fix: 对齐 Exa 公告回归与历史模型目录测试接线
ranxi2001 Nov 20, 2026
12d550f
ci: 让 152 固定基线使用同版本的 OAuth 轮换测试
ranxi2001 Nov 20, 2026
b1d08ec
fix: 保留正文读取超时原因并对齐 Gemini 错误归属
ranxi2001 Nov 20, 2026
7d46571
fix: return the persisted OpenAI refresh configuration after concurre…
ranxi2001 Nov 20, 2026
8730f12
fix: align Ultra Fast cutoff text and stabilize the Redis race fixture
ranxi2001 Nov 20, 2026
9eed898
ci: complete PostgreSQL and Redis service definitions for the schedul…
ranxi2001 Nov 20, 2026
7902a81
test: wire the platform quota repository into the lottery integration…
ranxi2001 Nov 20, 2026
9590938
ci: pair historical Grok repository sources with matching OAuth tests
ranxi2001 Nov 20, 2026
305c9f7
Merge production and retain both sets of historical regression fixtures
ranxi2001 Nov 20, 2026
682cddf
test: initialize Pinia when mounting model plaza video pricing
ranxi2001 Nov 20, 2026
0b1ceca
test: use the service quota adapter in the lottery integration fixture
ranxi2001 Nov 21, 2026
9aa8120
test: back Grok media scheduler settings with a readable repository
ranxi2001 Nov 21, 2026
4be3432
test: verify the merged route policy order and isolate stream-only re…
ranxi2001 Nov 21, 2026
669a25d
fix: preserve protocol-specific errors when admission reads an oversi…
ranxi2001 Nov 21, 2026
b8e6874
ci: run the WS ticket regression against the complete pinned service …
ranxi2001 Nov 20, 2026
62e36aa
Merge production 429 regressions and keep historical test inputs cons…
ranxi2001 Nov 21, 2026
c7d077a
test: exercise compatible WS admission, Grok search usage and image e…
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
9 changes: 9 additions & 0 deletions .github/scripts/quality-live-red-compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,12 @@
if 'infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"' not in original:
original = original.replace('import (', 'import (\n\tinfraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"', 1)
target.write_text(original)

# The candidate's metadata resolver also fills an audio capability bit. The
# historical list implementation ignores it; retain storage for that caller.
descriptor = target.with_name('openai_codex_models_service.go')
source = descriptor.read_text()
anchor = 'type codexModelMetadataOverride struct {\n'
if source.count(anchor) != 1:
raise SystemExit('historical descriptor declaration missing or ambiguous')
descriptor.write_text(source.replace(anchor, anchor + '\taudioInput bool\n', 1))
5 changes: 5 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,11 @@ backend/internal/service/ciallo_test.go
backend/internal/service/openai_409_controls_diagnostics_test.go
backend/internal/handler/openai_owner_conflict_diagnostics_test.go

# v0.2.24 model listing and request-body diagnostics depend on newer handler APIs.
backend/internal/handler/gateway_models_test.go
backend/internal/handler/request_body_limit_test.go
backend/internal/handler/request_body_read_log_test.go

# Probe penalty tests use receipt types absent from historical WS sources.
backend/internal/handler/probe_penalty_response_test.go
backend/internal/service/account_probe_penalty_test.go
26 changes: 26 additions & 0 deletions .github/workflows/issue765-image-scheduler.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,29 @@ jobs:
regression:
runs-on: ubuntu-latest
timeout-minutes: 35
services:
postgres:
image: postgres:18.1-alpine3.23
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: sub2api_test
ports:
- 5432:5432
options: >-
--health-cmd "pg_isready -U postgres -d sub2api_test"
--health-interval 5s
--health-timeout 5s
--health-retries 12
redis:
image: redis:8.4-alpine
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 12
env:
CI: 'true'
EXPECTED_HEAD: ${{ github.event.pull_request.head.sha || github.sha }}
Expand Down Expand Up @@ -86,6 +109,9 @@ jobs:
test -z "$(git -C candidate status --porcelain)"
(cd candidate/backend && go test -race -json -tags=unit ./internal/repository ./internal/service -run '^(TestIssue765|TestExtraImageModels)' -count=1 -timeout=10m) > evidence/green-unit.jsonl 2> evidence/green-unit.stderr
- name: GREEN - real Redis publication, memo refresh and revocation
env:
SUB2API_TEST_POSTGRES_DSN: 'postgres://postgres:postgres@127.0.0.1:5432/sub2api_test?sslmode=disable&TimeZone=UTC'
SUB2API_TEST_REDIS_URL: 'redis://127.0.0.1:6379/0'
shell: bash
run: |
set -euo pipefail
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/issue817-grok-persistence.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,10 @@ jobs:
path.write_bytes(historical.replace(anchor, anchor + field, 1))
PY
else
# The pinned repository predates the OpenAI rotation CAS tests.
fixture=backend/internal/repository/account_repo_temp_unsched_test.go
git show "$original:$fixture" > "$fixture"
test "$(git hash-object "$fixture")" = "$(git rev-parse "$original:$fixture")"
# These account repositories predate the compact-routing selector.
# Apply only its import, struct field and constructor initialization.
routing=2c69cefb93828e2bdefc413b4df058f3a342c7e1
Expand Down
2 changes: 1 addition & 1 deletion backend/cmd/server/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

38 changes: 38 additions & 0 deletions backend/internal/handler/gateway_compat_effort_policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"testing"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
Expand All @@ -23,6 +24,43 @@ import (
"github.com/tidwall/gjson"
)

func TestOpenAIResponsesUsageReportsConfigurationUpdateEffort(t *testing.T) {
const input = `[{"role":"user","content":"hello"},{"type":"configuration_update","reasoning":{"effort":"high"}}]`
const body = `{"model":"gpt-6.1-sol","input":` + input + `,"reasoning":{"effort":"medium"}}`
upstream := newAstraProCapturedUpstream(&http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"id":"resp_effort","model":"gpt-6.1-sol","status":"completed","output":[],"usage":{"input_tokens":10,"output_tokens":1}}`)),
})
account := service.Account{
ID: 1, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"api_key": "test-key"},
}
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
cfg := &config.Config{RunMode: config.RunModeSimple}
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
gateway := service.NewOpenAIGatewayService(
&openAIWSUsageHandlerAccountRepoStub{account: account}, nil, usageRepo, nil, nil, nil, nil, nil, cfg,
nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, &service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg)
c, rec := newAstraProFailoverContext(t, body)
h.Responses(c)

require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
_, _, bodies := upstream.snapshot()
require.Len(t, bodies, 1)
require.Equal(t, "medium", gjson.GetBytes(bodies[0], "reasoning.effort").String())
require.JSONEq(t, input, gjson.GetBytes(bodies[0], "input").Raw)
require.Len(t, usageRepo.created, 1)
log := dto.UsageLogFromService(<-usageRepo.created)
require.NotNil(t, log.ReasoningEffort)
require.Equal(t, "high", *log.ReasoningEffort)
}

type compatEffortPolicyUpstream struct {
service.HTTPUpstream
bodies [][]byte
Expand Down
30 changes: 24 additions & 6 deletions backend/internal/handler/gateway_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,11 +150,12 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
if middleware2.RejectRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
status, message := requestBodyReadFailure(reqLog, c.Request, err)
if status == 499 {
c.Status(status)
return
}
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body")
h.errorResponse(c, status, "invalid_request_error", message)
return
}

Expand Down Expand Up @@ -1271,6 +1272,22 @@ func (h *GatewayHandler) Models(c *gin.Context) {

// Get available models from account configurations for the selected group platform.
availableModels := h.gatewayService.GetAvailableModels(c.Request.Context(), groupID, platform)
if platform == service.PlatformAnthropic {
var group *service.Group
if apiKey != nil {
group = apiKey.Group
}
source := availableModels
if group != nil && group.ModelAllowlistEnabled() {
source = service.ModelListingSource(platform, availableModels, service.DefaultModelIDsForPlatform(platform))
} else if len(source) == 0 {
source = service.DefaultModelIDsForPlatform(platform)
}
expanded := h.gatewayService.ExpandAnthropicLongContextModels(c.Request.Context(), group, source)
if len(availableModels) > 0 || len(expanded) > len(source) || (group != nil && group.ModelAllowlistEnabled()) {
availableModels = expanded
}
}
if apiKey != nil && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
source := service.ModelListingSource(platform, availableModels, service.DefaultModelIDsForPlatform(platform))
writeAllowlistedModelsList(c, platform, apiKey.Group.ModelAllowlist.FilterForListing(source))
Expand Down Expand Up @@ -2172,11 +2189,12 @@ func (h *GatewayHandler) CountTokens(c *gin.Context) {
if middleware2.RejectRequestBodyReadError(c, err) {
return
}
if maxErr, ok := extractMaxBytesError(err); ok {
h.errorResponse(c, http.StatusRequestEntityTooLarge, "invalid_request_error", buildBodyTooLargeMessage(maxErr.Limit))
status, message := requestBodyReadFailure(reqLog, c.Request, err)
if status == 499 {
c.Status(status)
return
}
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Failed to read request body")
h.errorResponse(c, status, "invalid_request_error", message)
return
}

Expand Down
4 changes: 3 additions & 1 deletion backend/internal/handler/gateway_handler_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
defer inflightRelease()

// Parse request for session hash
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
bodyRef := service.NewRequestBodyRef(body)
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "chat_completions")
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "chat_completions")
if parsedReq == nil {
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
}
Expand Down
9 changes: 7 additions & 2 deletions backend/internal/handler/gateway_handler_responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
// 里的任何工具声明(含 Codex 被动 image_gen namespace)而关闭。生图意图
// 仅用于能力路由与图片计费;独立图片/视频端点才在利润门范围之外。
requestCtx, pricingAt := service.WithGatewayTokenRequestPricing(requestCtx)
if service.IsImageGenerationIntentForPlatform("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) {
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此走跳过校验的
// 变体,避免对同一份字节再全量校验一次。
if service.IsImageGenerationIntentForPlatformValidated("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) {
requestCtx = service.WithOpenAIImageGenerationIntent(requestCtx)
}
c.Request = c.Request.WithContext(requestCtx)
Expand Down Expand Up @@ -181,8 +184,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
defer inflightRelease()

// Parse request for session hash
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
bodyRef := service.NewRequestBodyRef(body)
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses")
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "responses")
if parsedReq == nil {
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
}
Expand Down
80 changes: 80 additions & 0 deletions backend/internal/handler/gateway_models_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,86 @@ type gatewayModelsAccountRepoStub struct {
byGroup map[int64][]service.Account
}

func TestGatewayModelsAnthropicLongContextVariants(t *testing.T) {
gin.SetMode(gin.TestMode)
const groupID int64 = 8880
for _, test := range []struct {
name string
platform string
mapping map[string]any
metadata map[string]service.UpstreamModelMetadata
allowlist []string
routing map[string][]int64
otherAccounts []service.Account
wantVariants []string
absent []string
}{
{name: "mapped target and threshold", mapping: map[string]any{"public": "upstream", "short": "short", "max-only": "max-only"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 900_000}, "short": {ContextWindow: 899_999}, "max-only": {MaxContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}},
wantVariants: []string{"public[1m]"}, absent: []string{"upstream", "upstream[1m]", "hidden", "hidden[1m]", "short[1m]", "max-only[1m]", claude.DefaultModels[0].ID}},
{name: "wildcard mappings are not concrete variants", mapping: map[string]any{"public*": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public*[1m]"}},
{name: "source metadata cannot override mapped target", mapping: map[string]any{"public": "short"},
metadata: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}, "short": {ContextWindow: 200_000}}, absent: []string{"public[1m]"}},
{name: "no duplicate suffix", mapping: map[string]any{"public": "upstream", "public[1m]": "upstream", "other[1M]": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, wantVariants: []string{"public[1m]", "other[1M]"}, absent: []string{"public[1m][1m]", "other[1M][1m]"}},
{name: "allowlist filters variants", mapping: map[string]any{"public": "upstream", "private": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public"}, absent: []string{"public[1m]", "private", "private[1m]"}},
{name: "allowlist can select variant", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public[1m]"}, wantVariants: []string{"public[1m]"}, absent: []string{"public"}},
{name: "routing excludes metadata account", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"public": {2}}, absent: []string{"public[1m]"}},
{name: "routing includes metadata account", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"pub*": {1}}, wantVariants: []string{"public[1m]"}},
{name: "non-Anthropic listing", platform: service.PlatformOpenAI, mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public[1m]"}},
{name: "unmapped defaults", metadata: map[string]service.UpstreamModelMetadata{claude.DefaultModels[0].ID: {ContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}},
wantVariants: []string{claude.DefaultModels[0].ID + "[1m]"}, absent: []string{"hidden", "hidden[1m]"}},
{name: "other platform account metadata", mapping: map[string]any{"public": "upstream"},
otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformOpenAI, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}},
{name: "unsupported model metadata", mapping: map[string]any{"public": "upstream"},
otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"private": "private"}}, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}},
} {
t.Run(test.name, func(t *testing.T) {
platform := test.platform
if platform == "" {
platform = service.PlatformAnthropic
}
account := service.Account{ID: 1, Platform: platform, Type: service.AccountTypeOAuth, Credentials: map[string]any{"model_mapping": test.mapping}}
account.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: test.metadata})
outsideAccount := service.Account{ID: 3, Platform: service.PlatformAnthropic}
outsideAccount.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}})
h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{
groupID: append([]service.Account{account}, test.otherAccounts...), groupID + 1: {outsideAccount},
}})
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: &service.Group{
ID: groupID, Platform: platform,
ModelAllowlist: service.GroupModelAllowlist{Enabled: test.allowlist != nil, Models: test.allowlist},
ModelRoutingEnabled: test.routing != nil, ModelRouting: test.routing,
}})
h.Models(ctx)
require.Equal(t, http.StatusOK, rec.Code)
var response gatewayModelsResponseForTest
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))
ids := modelIDsForTest(response.Data)
for _, variant := range test.wantVariants {
require.Contains(t, ids, variant)
}
for _, absent := range test.absent {
require.NotContains(t, ids, absent)
}
seen := make(map[string]bool, len(ids))
for _, id := range ids {
require.False(t, seen[id], "duplicate model ID: %s", id)
seen[id] = true
}
})
}
}

type gatewayModelsRouteRepoStub struct {
service.CompositeModelRouteRepository
routes []service.CompositeModelRoute
Expand Down
9 changes: 5 additions & 4 deletions backend/internal/handler/gemini_cached_contents_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,12 @@ func readGeminiCachedContentBody(c *gin.Context) ([]byte, bool) {
if middleware.RejectRequestBodyReadError(c, err) {
return nil, false
}
if maxErr, ok := extractMaxBytesError(err); ok {
googleError(c, http.StatusRequestEntityTooLarge, buildBodyTooLargeMessage(maxErr.Limit))
return nil, false
status, message := requestBodyReadFailure(nil, c.Request, err)
if status == pkghttputil.StatusClientClosedRequest {
c.Status(status)
} else {
googleError(c, status, message)
}
googleError(c, http.StatusBadRequest, "Failed to read request body")
return nil, false
}
if len(body) == 0 {
Expand Down
Loading
Loading