diff --git a/.github/scripts/prepare-image-usage-free-fast-red.py b/.github/scripts/prepare-image-usage-free-fast-red.py
index 83991ace77c2..44dce48e5b4a 100644
--- a/.github/scripts/prepare-image-usage-free-fast-red.py
+++ b/.github/scripts/prepare-image-usage-free-fast-red.py
@@ -14,7 +14,12 @@
marker = 'type UsageLog struct {'
# Omit nil just as the pre-snapshot DTO did; persistence RED must reach
# its original missing-snapshot assertion, not a later JSON null mismatch.
- addition = '\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n'
+ addition = ('\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n'
+ '\tProcurementCostSnapshot *ProcurementCostSnapshot `json:"ProcurementCostSnapshot,omitempty"`\n')
+elif phase == 'admin-usage':
+ name = 'backend/internal/handler/dto/types.go'
+ marker = 'type AdminUsageLog struct {'
+ addition = '\n\tProcurementCostSnapshot *service.ProcurementCostSnapshot `json:"procurement_cost_snapshot,omitempty"`\n'
elif phase == 'cache':
name = 'backend/internal/service/customer_cost_details.go'
marker = 'type CustomerCostDetails struct {'
diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt
index 598e6c463cec..a1cde1eec2ec 100644
--- a/.github/scripts/upstream-v0222-red-fixtures.txt
+++ b/.github/scripts/upstream-v0222-red-fixtures.txt
@@ -201,6 +201,13 @@ backend/internal/handler/request_body_read_log_test.go
backend/internal/handler/probe_penalty_response_test.go
backend/internal/service/account_probe_penalty_test.go
+# Native Messages gateway selection requires the request-scoped account and group reader.
+backend/internal/handler/gateway_messages_selection_test.go
+
+# Native Gemini envelope tests share those candidate-only gateway APIs/fixtures.
+# Frozen candidate blob: 2aeba94f1e98e3db91b6d3006ed0d0575775a6e9; full historical RED only.
+backend/internal/handler/gateway_gemini_envelope_test.go
+
# Model plaza display currency tests require the candidate display configuration.
backend/internal/service/model_plaza_currency_test.go
backend/internal/service/model_plaza_currency_update_test.go
diff --git a/.github/workflows/free-fast-customer-cost-details.yml b/.github/workflows/free-fast-customer-cost-details.yml
index f6d94e0edfcb..f23c18e9e7f3 100644
--- a/.github/workflows/free-fast-customer-cost-details.yml
+++ b/.github/workflows/free-fast-customer-cost-details.yml
@@ -95,6 +95,7 @@ jobs:
# The new image receipt reader needs the additive DTO field; retain
# the old Free Fast producer so the selected assertions still fail.
python3 .github/scripts/prepare-image-usage-free-fast-red.py usage "$baseline"
+ python3 .github/scripts/prepare-image-usage-free-fast-red.py admin-usage "$baseline"
# Tests stay byte-for-byte at candidate HEAD. Keep the new additive
# DB column so a missing migration can never qualify as business RED.
set +e
diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml
index 4d605ddd5661..0fce8d978b67 100644
--- a/.github/workflows/issue959-gateway-regression.yml
+++ b/.github/workflows/issue959-gateway-regression.yml
@@ -7,6 +7,23 @@ on:
paths:
- 'backend/internal/domain/constants.go'
- 'backend/internal/service/**'
+ - 'backend/internal/handler/admin/account*'
+ - 'backend/internal/handler/dto/account_mapper_redact_test.go'
+ - 'backend/internal/repository/account_repo.go'
+ - 'backend/internal/repository/group_repo.go'
+ - 'backend/internal/repository/gateway_account*'
+ - 'backend/internal/repository/gateway_request_admission*'
+ - 'backend/internal/repository/gateway_request_candidates*'
+ - 'backend/internal/handler/gateway_messages_selection_test.go'
+ - 'backend/internal/handler/gateway_gemini_envelope_test.go'
+ - 'backend/internal/handler/gemini_v1beta_handler.go'
+ - 'backend/internal/repository/oauth_degradation_group_bindings*'
+ - 'backend/internal/repository/procurement_cost_snapshot*'
+ - 'backend/internal/repository/profit_operations.go'
+ - 'backend/internal/repository/usage_log_repo*'
+ - 'backend/internal/handler/dto/procurement_cost_snapshot*'
+ - 'backend/internal/handler/usage_observer_test.go'
+ - 'backend/migrations/392_usage_procurement_cost_snapshot.sql'
- 'backend/internal/repository/concurrency_cache*'
- 'backend/internal/repository/integration_harness_test.go'
- 'backend/go.mod'
@@ -66,8 +83,8 @@ jobs:
shell: bash
run: |
set -euo pipefail
- go test -race -tags=unit ./internal/service \
- -run '^Test(GatewayIdentity|GatewayUsage|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots)' \
+ go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin ./internal/handler/dto ./internal/repository \
+ -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayProtocol|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \
-count=1 -v -timeout=10m 2>&1 | tee ../evidence/unit-race.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/unit-race.log; then
exit 1
@@ -75,18 +92,62 @@ jobs:
grep -F -- '--- PASS: TestGatewayUsageWritersSnapshotRequestTarget' ../evidence/unit-race.log
grep -F -- '--- PASS: TestNewAPIGatewayCostsFollowRequestTargetWithoutSharedWrites' ../evidence/unit-race.log
grep -F -- '--- PASS: TestUsagePlatformSnapshotsSelectedAccount' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayManagementForwardingRemainsClosed' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolOpenAIAuthoritativeAdmission' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolOpenAIRejectsFinalAuthorityChanges' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolOpenAIResponsesMappedWireModel' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolOpenAILegacyPassthroughKeepsWireModel' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidatesStayRequestScoped' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateSourceRefreshesAfterWarmSnapshot' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateReadFailurePreservesLegacy' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolMessagesHandlerSchedulerToUsage' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolMessagesChannelMappingPreservesBindingModel' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolGeminiFreshAdmissionErrorEnvelope' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolGeminiForwardErrorResponseOwnership' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayManagementUpdateRequiresAtomicCapability' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestGatewayDataImportIdentityValidation' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestAccountGatewayDTORedactsCallingKey' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestProcurementSnapshotMixedTargetsThroughUsageWriters' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestProcurementSnapshotAdminDTOAndUserPrivacy' ../evidence/unit-race.log
+ grep -F -- '--- PASS: TestObserverProcurementSnapshotFollowsExistingAccountCostScope' ../evidence/unit-race.log
- name: Shared account slots against isolated Redis
working-directory: backend
shell: bash
run: |
set -euo pipefail
go test -race -tags=integration ./internal/repository \
- -run '^TestConcurrencyCacheSuite$/^TestGatewayTargetsShareAccountConcurrency$' \
+ -run '^Test((ConcurrencyCacheSuite|AccountRepoSuite)$|GatewayAtomicUpdate)/^(TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion|RequestAdmissionReloadsGroupMembershipAndStatus|RequestCandidatesRequireLiveExplicitAnthropicGroup)|admin|account-service|bulk)$' \
-count=1 -v -timeout=10m 2>&1 | tee ../evidence/concurrency-redis.log
if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/concurrency-redis.log; then
exit 1
fi
grep -F -- '--- PASS: TestConcurrencyCacheSuite/TestGatewayTargetsShareAccountConcurrency' ../evidence/concurrency-redis.log
+ grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayManagementAtomicMembershipAndOAuthExclusion' ../evidence/concurrency-redis.log
+ grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayRequestAdmissionReloadsGroupMembershipAndStatus' ../evidence/concurrency-redis.log
+ grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayRequestCandidatesRequireLiveExplicitAnthropicGroup' ../evidence/concurrency-redis.log
+ grep -F -- '--- PASS: TestGatewayAtomicUpdateOAuthInterleaving' ../evidence/concurrency-redis.log
+ grep -F -- '--- PASS: TestGatewayAtomicUpdateRollbackAfterStagedFields' ../evidence/concurrency-redis.log
+ grep -F -- '--- PASS: TestGatewayAtomicUpdateSuccessfulCommit' ../evidence/concurrency-redis.log
+ grep -F -- '--- PASS: TestGatewayAtomicUpdateCallerTransactionRollback' ../evidence/concurrency-redis.log
+ - name: Procurement snapshots and legacy profit accounting
+ working-directory: backend
+ shell: bash
+ run: |
+ set -euo pipefail
+ go test -race -tags=integration ./internal/repository \
+ -run '^(TestProcurementSnapshot|TestProfitOperationsPersistedProfitIndependentFromAccountDebit|TestProfitOperationsZeroLossUnknownAndCurrentConfiguration)' \
+ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/procurement-cost.log
+ if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/procurement-cost.log; then
+ exit 1
+ fi
+ grep -F -- '--- PASS: TestProcurementSnapshotAllInsertPathsAndImmutability' ../evidence/procurement-cost.log
+ grep -F -- '--- PASS: TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge' ../evidence/procurement-cost.log
+ grep -F -- '--- PASS: TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns' ../evidence/procurement-cost.log
+ grep -F -- '--- PASS: TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched' ../evidence/procurement-cost.log
- uses: actions/upload-artifact@v7
if: always()
with:
diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go
index 760ab31c37aa..49629dbd1565 100644
--- a/backend/internal/domain/constants.go
+++ b/backend/internal/domain/constants.go
@@ -44,6 +44,9 @@ const (
PlatformComposite = "composite"
)
+// AccountPlatformGateway is an account-only identity, never a request or group platform.
+const AccountPlatformGateway = "gateway"
+
// Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。
// 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。
const (
diff --git a/backend/internal/handler/admin/account_data.go b/backend/internal/handler/admin/account_data.go
index 84161ab27039..f2a8f559fef9 100644
--- a/backend/internal/handler/admin/account_data.go
+++ b/backend/internal/handler/admin/account_data.go
@@ -830,6 +830,9 @@ func validateDataProxy(item DataProxy) error {
}
func validateDataAccount(item DataAccount) error {
+ if err := service.ValidateGatewayAccountIdentity(item.Platform, item.Type, item.Credentials); err != nil {
+ return err
+ }
if strings.TrimSpace(item.Name) == "" {
return errors.New("account name is required")
}
@@ -843,7 +846,7 @@ func validateDataAccount(item DataAccount) error {
return errors.New("account credentials is required")
}
switch item.Type {
- case service.AccountTypeOAuth, service.AccountTypeSetupToken, service.AccountTypeAPIKey, service.AccountTypeUpstream:
+ case service.AccountTypeOAuth, service.AccountTypeSetupToken, service.AccountTypeAPIKey, service.AccountTypeUpstream, service.AccountTypeGateway:
default:
return fmt.Errorf("account type is invalid: %s", item.Type)
}
diff --git a/backend/internal/handler/admin/account_gateway_data_test.go b/backend/internal/handler/admin/account_gateway_data_test.go
new file mode 100644
index 000000000000..840a9aa8cd74
--- /dev/null
+++ b/backend/internal/handler/admin/account_gateway_data_test.go
@@ -0,0 +1,24 @@
+package admin
+
+import (
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/gin-gonic/gin/binding"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGatewayDataImportIdentityValidation(t *testing.T) {
+ item := DataAccount{Name: "Gateway import fixture", Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Credentials: map[string]any{"upstream_kind": "sub2api", "base_url": "https://import.example", "api_key": "synthetic-key"}}
+ require.NoError(t, validateDataAccount(item))
+ require.NoError(t, binding.Validator.ValidateStruct(CreateAccountRequest{Name: item.Name, Platform: item.Platform, Type: item.Type, Credentials: item.Credentials}))
+ require.NoError(t, binding.Validator.ValidateStruct(UpdateAccountRequest{Type: item.Type}))
+ item.Platform = service.PlatformOpenAI
+ require.Error(t, validateDataAccount(item))
+ item.Platform = service.PlatformGateway
+ item.Credentials["upstream_kind"] = "unknown"
+ require.Error(t, validateDataAccount(item))
+ item.Type = service.AccountTypeAPIKey
+ require.Error(t, validateDataAccount(item))
+}
diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go
index c9379ff13156..858ed72e44f0 100644
--- a/backend/internal/handler/admin/account_handler.go
+++ b/backend/internal/handler/admin/account_handler.go
@@ -148,7 +148,7 @@ type CreateAccountRequest struct {
Name string `json:"name" binding:"required"`
Notes *string `json:"notes"`
Platform string `json:"platform" binding:"required"`
- Type string `json:"type" binding:"required,oneof=oauth setup-token apikey upstream bedrock service_account"`
+ Type string `json:"type" binding:"required,oneof=oauth setup-token apikey upstream bedrock service_account gateway"`
Credentials map[string]any `json:"credentials" binding:"required"`
Extra map[string]any `json:"extra"`
ProxyID *int64 `json:"proxy_id"`
@@ -170,7 +170,7 @@ type UpdateAccountRequest struct {
Platform string `json:"platform"`
Name string `json:"name"`
Notes *string `json:"notes"`
- Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey upstream bedrock service_account"`
+ Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey upstream bedrock service_account gateway"`
Credentials map[string]any `json:"credentials"`
Extra map[string]any `json:"extra"`
ProxyID *int64 `json:"proxy_id"`
diff --git a/backend/internal/handler/dto/account_mapper_redact_test.go b/backend/internal/handler/dto/account_mapper_redact_test.go
index 44354844eb84..ec897f6431a2 100644
--- a/backend/internal/handler/dto/account_mapper_redact_test.go
+++ b/backend/internal/handler/dto/account_mapper_redact_test.go
@@ -11,6 +11,17 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
)
+func TestAccountGatewayDTORedactsCallingKey(t *testing.T) {
+ account := &service.Account{Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "synthetic-gateway-secret"}}
+ got := AccountFromServiceShallow(account)
+ require.Equal(t, "new_api", got.Credentials["upstream_kind"])
+ require.True(t, got.CredentialsStatus["has_api_key"])
+ raw, err := json.Marshal(got)
+ require.NoError(t, err)
+ require.NotContains(t, string(raw), "synthetic-gateway-secret")
+}
+
func TestAccountFromServiceShallow_RedactsSensitiveCredentials(t *testing.T) {
src := &service.Account{
ID: 42,
diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go
index 99292b7a1c7d..aa4d33ec4d3f 100644
--- a/backend/internal/handler/dto/mappers.go
+++ b/backend/internal/handler/dto/mappers.go
@@ -831,6 +831,7 @@ func UsageLogFromServiceAdmin(l *service.UsageLog) *AdminUsageLog {
BillingTier: l.BillingTier,
AccountRateMultiplier: l.AccountRateMultiplier,
AccountStatsCost: l.AccountStatsCost,
+ ProcurementCostSnapshot: l.ProcurementCostSnapshot,
IPAddress: l.IPAddress,
Account: AccountSummaryFromService(l.Account),
}
diff --git a/backend/internal/handler/dto/procurement_cost_snapshot_test.go b/backend/internal/handler/dto/procurement_cost_snapshot_test.go
new file mode 100644
index 000000000000..e8678bbecee6
--- /dev/null
+++ b/backend/internal/handler/dto/procurement_cost_snapshot_test.go
@@ -0,0 +1,23 @@
+package dto
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/stretchr/testify/require"
+)
+
+func TestProcurementSnapshotAdminDTOAndUserPrivacy(t *testing.T) {
+ factor := .7
+ log := &service.UsageLog{TotalCost: 10, ActualCost: 3, ProcurementCostSnapshot: &service.ProcurementCostSnapshot{
+ Version: 1, AccountType: "gateway", Provider: "new_api", TargetPlatform: "openai", Basis: "total_cost", CostMultiplier: &factor}}
+ admin, err := json.Marshal(UsageLogFromServiceAdmin(log))
+ require.NoError(t, err)
+ require.Contains(t, string(admin), `"procurement_cost_snapshot"`)
+ require.Contains(t, string(admin), `"cost_multiplier":0.7`)
+ user, err := json.Marshal(UsageLogFromService(log))
+ require.NoError(t, err)
+ require.NotContains(t, string(user), "procurement_cost_snapshot")
+ require.Nil(t, UsageLogFromServiceAdmin(&service.UsageLog{}).ProcurementCostSnapshot)
+}
diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go
index e09f36447299..b827f0b3b362 100644
--- a/backend/internal/handler/dto/types.go
+++ b/backend/internal/handler/dto/types.go
@@ -746,6 +746,8 @@ type AdminUsageLog struct {
AccountRateMultiplier *float64 `json:"account_rate_multiplier"`
// AccountStatsCost 自定义定价规则计算的账号统计费用(nil 表示使用默认公式)
AccountStatsCost *float64 `json:"account_stats_cost,omitempty"`
+ // ProcurementCostSnapshot follows existing admin/authorized observer cost scope.
+ ProcurementCostSnapshot *service.ProcurementCostSnapshot `json:"procurement_cost_snapshot,omitempty"`
// IPAddress 用户请求 IP
IPAddress *string `json:"ip_address,omitempty"`
diff --git a/backend/internal/handler/gateway_gemini_envelope_test.go b/backend/internal/handler/gateway_gemini_envelope_test.go
new file mode 100644
index 000000000000..2aeba94f1e98
--- /dev/null
+++ b/backend/internal/handler/gateway_gemini_envelope_test.go
@@ -0,0 +1,306 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "maps"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ middleware "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"
+)
+
+// Only ForwardNative uses this reader. Scheduler hydration uses the separate
+// gatewayMessagesHandlerRepo, so these hooks always run after selection/slots.
+type gatewayGeminiEnvelopeRepo struct {
+ service.AccountRepository
+ source *gatewayMessagesHandlerRepo
+ reads int
+ before func(int) error
+}
+
+func (r *gatewayGeminiEnvelopeRepo) GatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*service.Account, *service.Group, error) {
+ r.reads++
+ if r.before != nil {
+ if err := r.before(r.reads); err != nil {
+ return nil, nil, err
+ }
+ }
+ return r.source.GatewayRequestAccount(ctx, accountID, groupID)
+}
+
+type gatewayGeminiEnvelopeSlots struct {
+ gatewayMessagesSlotCache
+ users int
+ userReleases int
+}
+
+func (s *gatewayGeminiEnvelopeSlots) AcquireUserSlot(context.Context, int64, int, string) (bool, error) {
+ s.users++
+ return true, nil
+}
+
+func (s *gatewayGeminiEnvelopeSlots) ReleaseUserSlot(context.Context, int64, string) error {
+ s.users--
+ s.userReleases++
+ return nil
+}
+
+type gatewayGeminiEnvelopeFixture struct {
+ handler *GatewayHandler
+ account *service.Account
+ repo *gatewayGeminiEnvelopeRepo
+ slots *gatewayGeminiEnvelopeSlots
+ usage *openAIWSUsageHandlerUsageLogRepoStub
+ billing *compatStreamUsageBillingRepo
+ c *gin.Context
+ rec *httptest.ResponseRecorder
+ peerCalls atomic.Int32
+ peerCode int
+ peerBody string
+ cancel context.CancelFunc
+}
+
+func newGatewayGeminiEnvelopeFixture(t *testing.T, stream, batch bool) *gatewayGeminiEnvelopeFixture {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ f := &gatewayGeminiEnvelopeFixture{peerCode: http.StatusOK,
+ peerBody: `{"candidates":[{"content":{"parts":[{"text":"OK"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2}}`}
+ peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ f.peerCalls.Add(1)
+ if r.Header.Get("x-goog-api-key") != "synthetic-gateway-key" {
+ t.Error("native Gemini transport lost its selected credential")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(f.peerCode)
+ _, _ = io.WriteString(w, f.peerBody)
+ }))
+ t.Cleanup(peer.Close)
+ cfg := &config.Config{}
+ cfg.Security.URLAllowlist.AllowPrivateHosts = true
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ cfg.Gateway.Scheduling.LoadBatchEnabled = batch
+ groupID := int64(9711)
+ group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformGemini, Status: service.StatusActive, RateMultiplier: 1}
+ f.account = &service.Account{ID: 9712, Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 3,
+ Credentials: map[string]any{"upstream_kind": "new_api", "api_key": "synthetic-gateway-key", "base_url": peer.URL + "/tenant/v1",
+ "model_mapping": map[string]any{"gemini-2.5-flash": "wire-gemini"}},
+ GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9712, GroupID: groupID}}}
+ schedulerRepo := &gatewayMessagesHandlerRepo{account: f.account, group: group}
+ f.repo = &gatewayGeminiEnvelopeRepo{source: schedulerRepo}
+ f.slots = &gatewayGeminiEnvelopeSlots{}
+ concurrency := service.NewConcurrencyService(f.slots)
+ snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{}, nil, nil, nil, nil)
+ f.usage = &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 2)}
+ f.billing = &compatStreamUsageBillingRepo{}
+ billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
+ t.Cleanup(billingCache.Stop)
+ upstream := repository.NewHTTPUpstream(cfg)
+ gw := service.NewGatewayService(
+ schedulerRepo, &fakeGroupRepo{group: group}, f.usage, f.billing, nil, nil, nil, &stickyWritebackCache{}, cfg,
+ snapshot, concurrency, service.NewBillingService(cfg, nil), nil, nil, nil, upstream,
+ &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ )
+ f.handler = &GatewayHandler{gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitchesGemini: 1,
+ concurrencyHelper: NewConcurrencyHelper(concurrency, SSEPingFormatClaude, 0),
+ geminiCompatService: service.NewGeminiMessagesCompatService(f.repo, nil, nil, nil, nil, nil, upstream, nil, cfg)}
+ action := "generateContent"
+ if stream {
+ action = "streamGenerateContent"
+ }
+ f.rec = httptest.NewRecorder()
+ f.c, _ = gin.CreateTestContext(f.rec)
+ ctx, cancel := context.WithCancel(context.WithValue(context.Background(), ctxkey.Group, group))
+ f.cancel = cancel
+ t.Cleanup(cancel)
+ f.c.Request = httptest.NewRequest(http.MethodPost, "/v1beta/models/gemini-2.5-flash:"+action,
+ strings.NewReader(`{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}`)).WithContext(ctx)
+ f.c.Request.Header.Set("Content-Type", "application/json")
+ f.c.Params = gin.Params{{Key: "modelAction", Value: "/gemini-2.5-flash:" + action}}
+ key := &service.APIKey{ID: 9713, UserID: 9714, GroupID: &groupID, Group: group, Status: service.StatusActive,
+ User: &service.User{ID: 9714, Balance: 100, Concurrency: 1}}
+ f.c.Set(string(middleware.ContextKeyAPIKey), key)
+ f.c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: key.UserID, Concurrency: 1})
+ return f
+}
+
+func (f *gatewayGeminiEnvelopeFixture) assertReleasedWithoutBilling(t *testing.T) {
+ t.Helper()
+ require.Equal(t, f.account.ID, f.slots.id, "request must reach real selection and acquire the shared account slot")
+ require.Zero(t, f.slots.active)
+ require.Equal(t, 1, f.slots.releases)
+ require.Zero(t, f.slots.users)
+ require.Equal(t, 1, f.slots.userReleases)
+ require.Empty(t, f.usage.created)
+ f.billing.mu.Lock()
+ defer f.billing.mu.Unlock()
+ require.Empty(t, f.billing.commands)
+}
+
+func assertGatewayGeminiSafeEnvelope(t *testing.T, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ require.Equal(t, http.StatusBadGateway, rec.Code, rec.Body.String())
+ require.Equal(t, "application/json; charset=utf-8", rec.Header().Get("Content-Type"))
+ require.JSONEq(t, `{"error":{"code":502,"message":"Unable to forward request to upstream","status":"INTERNAL"}}`, rec.Body.String())
+ var envelope map[string]any
+ decoder := json.NewDecoder(strings.NewReader(rec.Body.String()))
+ require.NoError(t, decoder.Decode(&envelope))
+ require.ErrorIs(t, decoder.Decode(&envelope), io.EOF, "only one terminal envelope may be written")
+}
+
+func TestGatewayProtocolGeminiFreshAdmissionErrorEnvelope(t *testing.T) {
+ for _, stream := range []bool{false, true} {
+ for _, batch := range []bool{false, true} {
+ for _, change := range []string{"membership", "key", "status", "mapping-before-send"} {
+ name := change + map[bool]string{false: "/nonstream", true: "/stream"}[stream] + map[bool]string{false: "/fallback", true: "/load-aware"}[batch]
+ t.Run(name, func(t *testing.T) {
+ f := newGatewayGeminiEnvelopeFixture(t, stream, batch)
+ trigger := 1
+ if change == "mapping-before-send" {
+ trigger = 2 // initial ForwardNative admission passed; mapped URL has been built.
+ }
+ f.repo.before = func(read int) error {
+ if read != trigger {
+ return nil
+ }
+ switch change {
+ case "membership":
+ f.account.GroupIDs, f.account.AccountGroups = nil, nil
+ case "key":
+ f.account.Credentials = maps.Clone(f.account.Credentials)
+ f.account.Credentials["api_key"] = "rotated-key-must-not-leak"
+ case "status":
+ f.account.Status = service.StatusDisabled
+ case "mapping-before-send":
+ f.account.Credentials = maps.Clone(f.account.Credentials)
+ f.account.Credentials["model_mapping"] = map[string]any{"gemini-2.5-flash": "changed-wire-model"}
+ }
+ return nil
+ }
+ f.handler.GeminiV1BetaModels(f.c)
+ assertGatewayGeminiSafeEnvelope(t, f.rec)
+ require.Equal(t, trigger, f.repo.reads, "ordinary admission errors must terminate without reselection/replay")
+ require.Zero(t, f.peerCalls.Load())
+ f.assertReleasedWithoutBilling(t)
+ })
+ }
+ }
+ }
+}
+
+// A deterministic body error exercises real native streaming before/after its
+// first write, without relying on socket buffering or transport retry timing.
+type gatewayGeminiEnvelopeReadError struct{}
+
+func (gatewayGeminiEnvelopeReadError) Read([]byte) (int, error) {
+ return 0, errors.New("synthetic internal read failure: credential/config must not leak")
+}
+
+type gatewayGeminiEnvelopeUpstream struct {
+ service.HTTPUpstream
+ body io.Reader
+ calls int
+}
+
+func (u *gatewayGeminiEnvelopeUpstream) Do(*http.Request, string, int64, int) (*http.Response, error) {
+ u.calls++
+ return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(u.body)}, nil
+}
+
+func TestGatewayProtocolGeminiForwardErrorResponseOwnership(t *testing.T) {
+ for _, control := range []string{"alive-uncommitted", "committed-headers-only", "committed-marker", "committed-error", "partial-stream", "cancelled"} {
+ t.Run(control, func(t *testing.T) {
+ f := newGatewayGeminiEnvelopeFixture(t, true, false)
+ var upstream *gatewayGeminiEnvelopeUpstream
+ const partial = "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]}}]}\n\n"
+ switch control {
+ case "alive-uncommitted", "partial-stream":
+ var body io.Reader = gatewayGeminiEnvelopeReadError{}
+ if control == "partial-stream" {
+ body = io.MultiReader(strings.NewReader(partial), body)
+ }
+ upstream = &gatewayGeminiEnvelopeUpstream{body: body}
+ f.handler.geminiCompatService = service.NewGeminiMessagesCompatService(f.repo, nil, nil, nil, nil, nil, upstream, nil, f.handler.cfg)
+ if control == "alive-uncommitted" {
+ f.repo.before = func(int) error {
+ f.c.Header("Content-Length", "999")
+ f.c.Header("Content-Encoding", "gzip")
+ return nil
+ }
+ }
+ case "committed-headers-only", "committed-marker", "cancelled":
+ f.repo.before = func(int) error {
+ if control == "cancelled" {
+ f.cancel()
+ return context.Canceled
+ }
+ if control == "committed-marker" {
+ service.MarkResponseCommitted(f.c)
+ return errors.New("synthetic response already owned by forwarder")
+ }
+ f.c.Header("Content-Type", "text/event-stream")
+ f.c.Status(http.StatusAccepted)
+ f.c.Writer.WriteHeaderNow() // Written=true, Size=0: must not append an envelope.
+ return errors.New("synthetic refusal after header commit")
+ }
+ case "committed-error":
+ f.peerCode = http.StatusBadRequest
+ f.peerBody = `{"error":{"code":400,"status":"INVALID_ARGUMENT","message":"Invalid fixture field"}}`
+ }
+ f.handler.GeminiV1BetaModels(f.c)
+ switch control {
+ case "alive-uncommitted":
+ assertGatewayGeminiSafeEnvelope(t, f.rec)
+ require.Empty(t, f.rec.Header().Get("Cache-Control"))
+ require.Empty(t, f.rec.Header().Get("Connection"))
+ require.Empty(t, f.rec.Header().Get("X-Accel-Buffering"))
+ require.Empty(t, f.rec.Header().Get("Content-Length"))
+ require.Empty(t, f.rec.Header().Get("Content-Encoding"))
+ case "committed-headers-only":
+ require.Equal(t, http.StatusAccepted, f.rec.Code)
+ require.Zero(t, f.rec.Body.Len())
+ require.Equal(t, "text/event-stream", f.rec.Header().Get("Content-Type"))
+ case "committed-marker":
+ require.True(t, service.IsResponseCommitted(f.c))
+ require.False(t, f.c.Writer.Written())
+ require.Zero(t, f.rec.Body.Len())
+ case "committed-error":
+ require.Equal(t, http.StatusBadRequest, f.rec.Code)
+ require.Equal(t, f.peerBody, f.rec.Body.String())
+ require.True(t, service.IsResponseCommitted(f.c))
+ case "partial-stream":
+ require.Equal(t, http.StatusOK, f.rec.Code)
+ require.Equal(t, partial, f.rec.Body.String())
+ require.Equal(t, "text/event-stream", f.rec.Header().Get("Content-Type"))
+ case "cancelled":
+ require.Equal(t, statusClientClosedRequest, f.c.Writer.Status())
+ require.False(t, f.c.Writer.Written())
+ require.Zero(t, f.rec.Body.Len())
+ }
+ if upstream != nil {
+ require.Equal(t, 1, upstream.calls, "a native read failure must never replay")
+ }
+ wantPeers := int32(0)
+ if control == "committed-error" {
+ wantPeers = 1
+ }
+ require.Equal(t, wantPeers, f.peerCalls.Load())
+ f.assertReleasedWithoutBilling(t)
+ })
+ }
+}
diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go
index 9c7ddd4b5100..bbbf8dba1d03 100644
--- a/backend/internal/handler/gateway_handler.go
+++ b/backend/internal/handler/gateway_handler.go
@@ -229,6 +229,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups")
return
}
+ c.Request = c.Request.WithContext(service.WithGatewayMessagesSelection(c.Request.Context(), reqModel))
if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) {
return
}
diff --git a/backend/internal/handler/gateway_messages_selection_test.go b/backend/internal/handler/gateway_messages_selection_test.go
new file mode 100644
index 000000000000..bc9f1507ff1f
--- /dev/null
+++ b/backend/internal/handler/gateway_messages_selection_test.go
@@ -0,0 +1,328 @@
+//go:build unit
+
+package handler
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
+ "github.com/Wei-Shaw/sub2api/internal/repository"
+ middleware "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"
+ "github.com/tidwall/gjson"
+)
+
+type gatewayMessagesHandlerRepo struct {
+ service.AccountRepository
+ account *service.Account
+ group *service.Group
+ queries int
+ reads int
+ afterRead func()
+}
+
+func (r *gatewayMessagesHandlerRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]service.Account, error) {
+ return nil, nil
+}
+
+func (r *gatewayMessagesHandlerRepo) ListGatewayRequestCandidates(context.Context, int64, string) ([]service.Account, *service.Group, error) {
+ r.queries++
+ return []service.Account{*r.account}, r.group, nil
+}
+
+func (r *gatewayMessagesHandlerRepo) GatewayRequestAccount(context.Context, int64, int64) (*service.Account, *service.Group, error) {
+ r.reads++
+ snapshot := *r.account
+ snapshot.AccountGroups = append([]service.AccountGroup(nil), r.account.AccountGroups...)
+ if r.afterRead != nil {
+ r.afterRead()
+ }
+ return &snapshot, r.group, nil
+}
+
+type gatewayMessagesSlotCache struct {
+ fakeConcurrencyCache
+ id int64
+ limit int
+ active int
+ releases int
+ before func()
+}
+
+func (s *gatewayMessagesSlotCache) AcquireAccountSlot(_ context.Context, id int64, limit int, _ string) (bool, error) {
+ s.id, s.limit = id, limit
+ s.active++
+ if s.before != nil {
+ s.before()
+ }
+ return true, nil
+}
+
+func (s *gatewayMessagesSlotCache) ReleaseAccountSlot(context.Context, int64, string) error {
+ s.active--
+ s.releases++
+ return nil
+}
+
+// These are real handler -> scheduler -> slot -> production HTTP adapter ->
+// synthetic peer -> usage sink regressions, not direct Forward helper calls.
+func TestGatewayProtocolMessagesHandlerSchedulerToUsage(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for _, batch := range []bool{false, true} {
+ for _, bound := range []bool{false, true} {
+ for _, revoke := range []bool{false, true} {
+ name := "fallback"
+ if batch {
+ name = "load-aware"
+ }
+ if bound {
+ name += "/sticky"
+ }
+ if revoke {
+ name += "/removed-after-slot"
+ }
+ t.Run(name, func(t *testing.T) {
+ var peerCalls atomic.Int32
+ peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ peerCalls.Add(1)
+ body, err := io.ReadAll(req.Body)
+ require.NoError(t, err)
+ require.Equal(t, "/tenant/v1/messages", req.URL.Path)
+ require.Equal(t, "upstream-claude", gjson.GetBytes(body, "model").String())
+ require.Equal(t, "synthetic-gateway-key", req.Header.Get("x-api-key"))
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"id":"msg_gateway","type":"message","role":"assistant","model":"upstream-claude","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`)
+ }))
+ defer peer.Close()
+ cfg := &config.Config{}
+ cfg.Security.URLAllowlist.AllowPrivateHosts = true
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ cfg.Gateway.Scheduling.LoadBatchEnabled = batch
+ groupID := int64(9591)
+ group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1}
+ account := &service.Account{ID: 9592, Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 3,
+ Credentials: map[string]any{"upstream_kind": "new_api", "api_key": "synthetic-gateway-key", "base_url": peer.URL + "/tenant/v1",
+ "model_mapping": map[string]any{"claude-sonnet-4.5": "upstream-claude"}},
+ GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9592, GroupID: groupID}}}
+ repo := &gatewayMessagesHandlerRepo{account: account, group: group}
+ slots := &gatewayMessagesSlotCache{}
+ if revoke {
+ slots.before = func() { account.GroupIDs, account.AccountGroups = nil, nil }
+ }
+ concurrency := service.NewConcurrencyService(slots)
+ cache := &stickyWritebackCache{}
+ if bound {
+ cache.accountID = account.ID
+ }
+ // Warm shared snapshot is empty: no gateway platform view is cached.
+ snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{}, nil, nil, nil, nil)
+ usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 2)}
+ billing := &compatStreamUsageBillingRepo{}
+ billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
+ t.Cleanup(billingCache.Stop)
+ gw := service.NewGatewayService(
+ repo, &fakeGroupRepo{group: group}, usage, billing, nil, nil, nil, cache, cfg,
+ snapshot, concurrency, service.NewBillingService(cfg, nil), nil, nil, nil, repository.NewHTTPUpstream(cfg),
+ &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
+ )
+ h := &GatewayHandler{gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
+ concurrencyHelper: NewConcurrencyHelper(concurrency, SSEPingFormatClaude, 0)}
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"claude-sonnet-4.5","max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`))
+ c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, group))
+ c.Request.Header.Set("Content-Type", "application/json")
+ key := &service.APIKey{ID: 9593, UserID: 9594, GroupID: &groupID, Group: group, User: &service.User{ID: 9594, Balance: 100}}
+ c.Set(string(middleware.ContextKeyAPIKey), key)
+ c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9594})
+ h.Messages(c)
+ require.Equal(t, account.ID, slots.id)
+ require.Equal(t, account.Concurrency, slots.limit)
+ require.Zero(t, slots.active)
+ require.Positive(t, slots.releases)
+ require.Positive(t, repo.reads)
+ if revoke {
+ require.Zero(t, peerCalls.Load())
+ require.Empty(t, usage.created)
+ return
+ }
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.Equal(t, int32(1), peerCalls.Load())
+ select {
+ case log := <-usage.created:
+ require.Equal(t, account.ID, log.AccountID)
+ require.Equal(t, service.PlatformAnthropic, log.Platform)
+ require.Equal(t, 12, log.InputTokens)
+ require.NotNil(t, log.ProcurementCostSnapshot)
+ require.Equal(t, service.PlatformAnthropic, log.ProcurementCostSnapshot.TargetPlatform)
+ case <-time.After(3 * time.Second):
+ t.Fatal("handler did not deliver usage to its sink")
+ }
+ require.False(t, account.IsSchedulable())
+ })
+ }
+ }
+ }
+}
+
+type gatewayMessagesChannelRepo struct {
+ service.ChannelRepository
+ channel service.Channel
+ groupID int64
+}
+
+func (r *gatewayMessagesChannelRepo) ListAll(context.Context) ([]service.Channel, error) {
+ return []service.Channel{r.channel}, nil
+}
+
+func (r *gatewayMessagesChannelRepo) GetGroupPlatforms(context.Context, []int64) (map[int64]string, error) {
+ return map[int64]string{r.groupID: service.PlatformAnthropic}, nil
+}
+
+func TestGatewayProtocolMessagesChannelMappingPreservesBindingModel(t *testing.T) {
+ for _, batch := range []bool{false, true} {
+ for _, scenario := range []string{"channel", "channel-account-mapping", "revoke-selection-model", "no-mapping", "legacy-channel", "legacy-no-mapping"} {
+ name := "fallback/" + scenario
+ if batch {
+ name = "load-aware/" + scenario
+ }
+ t.Run(name, func(t *testing.T) {
+ const publicModel = "claude-sonnet-4.5"
+ mapped := scenario != "no-mapping" && scenario != "legacy-no-mapping"
+ legacy := strings.HasPrefix(scenario, "legacy-")
+ wantWire := publicModel
+ if mapped {
+ wantWire = "relay-sonnet"
+ }
+ if scenario == "channel-account-mapping" {
+ wantWire = "account-relay-sonnet"
+ }
+ var peerCalls atomic.Int32
+ peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ peerCalls.Add(1)
+ body, err := io.ReadAll(req.Body)
+ require.NoError(t, err)
+ require.Equal(t, "/tenant/v1/messages", req.URL.Path)
+ require.Equal(t, wantWire, gjson.GetBytes(body, "model").String())
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"id":"msg_mapping","type":"message","role":"assistant","model":"`+wantWire+`","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`)
+ }))
+ defer peer.Close()
+ cfg := &config.Config{}
+ cfg.Security.URLAllowlist.AllowPrivateHosts = true
+ cfg.Security.URLAllowlist.AllowInsecureHTTP = true
+ cfg.Gateway.Scheduling.LoadBatchEnabled = batch
+ groupID := int64(9595)
+ group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1,
+ ModelAllowlist: service.GroupModelAllowlist{Enabled: true, Models: []string{publicModel}}}
+ if scenario == "revoke-selection-model" {
+ // Isolate the binding guard: a separate public allowlist must not
+ // mask a final admission that incorrectly accepts the wire alias.
+ group.ModelAllowlist = service.GroupModelAllowlist{}
+ }
+ account := &service.Account{ID: 9596, Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Status: service.StatusActive, Schedulable: true, Concurrency: 2,
+ Credentials: map[string]any{"upstream_kind": "new_api", "api_key": "synthetic-only", "base_url": peer.URL + "/tenant/v1"},
+ GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9596, GroupID: groupID, AllowedModels: []string{publicModel}}}}
+ if scenario == "channel-account-mapping" {
+ // Selection checks source keys; forwarding maps the channel result,
+ // exactly as the existing handler and legacy account contract do.
+ account.Credentials["model_mapping"] = map[string]any{publicModel: "selection-target-not-wire", "relay-sonnet": wantWire}
+ }
+ sharedCache := &fakeSchedulerCache{}
+ if legacy {
+ account.Platform, account.Type = service.PlatformAnthropic, service.AccountTypeAPIKey
+ account.Credentials["base_url"] = peer.URL + "/tenant"
+ account.Extra = map[string]any{"anthropic_passthrough": true}
+ sharedCache.accounts = []*service.Account{account}
+ }
+ repo := &gatewayMessagesHandlerRepo{account: account, group: group}
+ slots := &gatewayMessagesSlotCache{}
+ revokedAtRead := 0
+ if scenario == "revoke-selection-model" {
+ repo.afterRead = func() {
+ if slots.active > 0 && revokedAtRead == 0 {
+ // The returned hydration snapshot still permits selection.
+ // The next authority read sees only the wire alias permitted.
+ revokedAtRead = repo.reads
+ account.AccountGroups = []service.AccountGroup{{AccountID: account.ID, GroupID: groupID, AllowedModels: []string{"relay-sonnet"}}}
+ }
+ }
+ }
+ channelRepo := &gatewayMessagesChannelRepo{groupID: groupID, channel: service.Channel{ID: 9597, Status: service.StatusActive,
+ GroupIDs: []int64{groupID}, BillingModelSource: service.BillingModelSourceRequested}}
+ if mapped {
+ channelRepo.channel.ModelMapping = map[string]map[string]string{service.PlatformAnthropic: {publicModel: "relay-sonnet"}}
+ }
+ channels := service.NewChannelService(channelRepo, nil, nil, nil, nil)
+ concurrency := service.NewConcurrencyService(slots)
+ usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 2)}
+ billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil)
+ t.Cleanup(billingCache.Stop)
+ gw := service.NewGatewayService(
+ repo, &fakeGroupRepo{group: group}, usage, &compatStreamUsageBillingRepo{}, nil, nil, nil, nil, cfg,
+ service.NewSchedulerSnapshotService(sharedCache, nil, nil, nil, nil), concurrency, service.NewBillingService(cfg, nil), nil, nil, nil, repository.NewHTTPUpstream(cfg),
+ &service.DeferredService{}, nil, nil, nil, nil, nil, nil, channels, nil, nil, nil, nil,
+ )
+ h := &GatewayHandler{gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1,
+ concurrencyHelper: NewConcurrencyHelper(concurrency, SSEPingFormatClaude, 0)}
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"`+publicModel+`","max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`))
+ c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, group))
+ c.Request.Header.Set("Content-Type", "application/json")
+ key := &service.APIKey{ID: 9598, UserID: 9599, GroupID: &groupID, Group: group, User: &service.User{ID: 9599, Balance: 100}}
+ c.Set(string(middleware.ContextKeyAPIKey), key)
+ c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9599})
+ h.Messages(c)
+ require.Equal(t, account.ID, slots.id)
+ require.Equal(t, 2, slots.limit)
+ require.Zero(t, slots.active)
+ require.Positive(t, slots.releases)
+ if scenario == "revoke-selection-model" {
+ require.Positive(t, revokedAtRead)
+ require.Greater(t, repo.reads, revokedAtRead, "final admission must read the changed binding after hydration")
+ require.Zero(t, peerCalls.Load())
+ require.Empty(t, usage.created)
+ return
+ }
+ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
+ require.Equal(t, int32(1), peerCalls.Load())
+ select {
+ case log := <-usage.created:
+ require.Equal(t, account.ID, log.AccountID)
+ require.Equal(t, publicModel, log.RequestedModel)
+ channelModel := publicModel
+ if mapped {
+ channelModel = "relay-sonnet"
+ }
+ require.Equal(t, channelModel, log.Model, "retain the existing Forward model; RequestedModel records the public name")
+ require.NotNil(t, log.UpstreamModel)
+ require.Equal(t, wantWire, *log.UpstreamModel)
+ require.Equal(t, 12, log.InputTokens)
+ if mapped {
+ chain := publicModel + "→relay-sonnet"
+ if scenario == "channel-account-mapping" {
+ chain += "→" + wantWire
+ }
+ require.NotNil(t, log.ModelMappingChain)
+ require.Equal(t, chain, *log.ModelMappingChain)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("handler did not deliver mapped usage")
+ }
+ })
+ }
+ }
+}
diff --git a/backend/internal/handler/gemini_v1beta_handler.go b/backend/internal/handler/gemini_v1beta_handler.go
index 72d1f24d30e6..bc80e1e1071d 100644
--- a/backend/internal/handler/gemini_v1beta_handler.go
+++ b/backend/internal/handler/gemini_v1beta_handler.go
@@ -392,6 +392,7 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
return
}
+ c.Request = c.Request.WithContext(service.WithGatewayGeminiSelection(c.Request.Context(), modelName))
stream := action == gemini.ActionStreamGenerateContent
reqLog = reqLog.With(zap.String("model", modelName), zap.String("action", action), zap.Bool("stream", stream))
@@ -817,8 +818,15 @@ func (h *GatewayHandler) GeminiV1BetaModels(c *gin.Context) {
return
}
}
- // 转发层已写出错误响应;客户端断开时转发层不写,响应未提交则标记 499。
- failoverClientGone(c)
+ // Fresh admission can fail before the forwarder writes a response.
+ // Preserve committed responses and client cancellation; never replay an ordinary error.
+ if !failoverClientGone(c) && !c.Writer.Written() && !service.IsResponseCommitted(c) {
+ // A stream read failure may leave headers staged before its first byte.
+ for _, header := range []string{"Content-Type", "Content-Length", "Content-Encoding", "Cache-Control", "Connection", "X-Accel-Buffering"} {
+ c.Writer.Header().Del(header)
+ }
+ googleError(c, http.StatusBadGateway, "Unable to forward request to upstream")
+ }
reqLog.Error("gemini.forward_failed", zap.Int64("account_id", account.ID), zap.Error(err))
return
}
diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go
index 4188456abcca..ee4615784929 100644
--- a/backend/internal/handler/openai_chat_completions.go
+++ b/backend/internal/handler/openai_chat_completions.go
@@ -126,6 +126,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
// 解析渠道级模型映射
channelMapping, _ := h.gatewayService.ResolveChannelMappingAndRestrict(c.Request.Context(), apiKey.GroupID, reqModel)
forwardModel := openAIChannelForwardModel(channelMapping, reqModel)
+ c.Request = c.Request.WithContext(service.WithGatewayOpenAISelection(c.Request.Context(), reqModel, reqModel))
c.Request = c.Request.WithContext(service.WithOpenAIForwardModel(c.Request.Context(), forwardModel, false))
if h.errorPassthroughService != nil {
diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go
index d62f3a719510..89978538a81d 100644
--- a/backend/internal/handler/openai_gateway_handler.go
+++ b/backend/internal/handler/openai_gateway_handler.go
@@ -925,6 +925,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) {
forwardBody := openAIModelMappedBody(body, channelMapping.Mapped, channelMapping.MappedModel, h.gatewayService.ReplaceModelInBody)
seedOpenAIForwardImageIntentHint(c, channelMapping.Mapped, imageIntent)
forwardModel := openAIChannelForwardModel(channelMapping, reqModel)
+ c.Request = c.Request.WithContext(service.WithGatewayOpenAISelection(c.Request.Context(), reqModel, reqModel))
c.Request = c.Request.WithContext(service.WithOpenAIForwardModel(
c.Request.Context(),
forwardModel,
@@ -1812,6 +1813,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
currentRoutingModel = effectiveMappedModel
}
reqLog.Debug("openai_messages.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs)))
+ c.Request = c.Request.WithContext(service.WithGatewayOpenAISelection(c.Request.Context(), reqModel, currentRoutingModel))
c.Request = c.Request.WithContext(service.WithOpenAIForwardModel(c.Request.Context(), currentRoutingModel, false))
selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability(
c.Request.Context(),
diff --git a/backend/internal/handler/usage_observer_test.go b/backend/internal/handler/usage_observer_test.go
index 82c90ba49008..abe9602590dd 100644
--- a/backend/internal/handler/usage_observer_test.go
+++ b/backend/internal/handler/usage_observer_test.go
@@ -55,6 +55,7 @@ func observerUsageRouter(r *observerUsageRepo, role string) *gin.Engine {
router.GET("/usage/dashboard/snapshot-v2", h.DashboardSnapshotV2)
router.GET("/usage/filter-options", h.ObserverFilterOptions)
router.GET("/usage/:id/timing", h.ObserverTiming)
+ router.GET("/usage/:id", h.GetByID)
return router
}
func usageGET(router *gin.Engine, path string) *httptest.ResponseRecorder {
@@ -104,6 +105,49 @@ func TestObserverUsageScopeAndProjection(t *testing.T) {
}
}
+func TestObserverProcurementSnapshotFollowsExistingAccountCostScope(t *testing.T) {
+ accountRate, accountCost := 2.0, 9.0
+ for _, role := range []string{service.RoleObserver, service.RoleUser} {
+ t.Run(role, func(t *testing.T) {
+ row := service.UsageLog{ID: 1, UserID: 42, AccountRateMultiplier: &accountRate,
+ Account: &service.Account{ID: 7, Credentials: map[string]any{"api_key": "synthetic-must-not-leak"}}}
+ // Historical WS regressions compile this test package against older UsageLog types.
+ // The observer response below must expose the decoded snapshot on the candidate.
+ require.NoError(t, json.Unmarshal([]byte(`{"ProcurementCostSnapshot":{
+ "version":1,"account_type":"gateway","provider":"new_api","target_platform":"openai",
+ "basis":"total_cost","cost_multiplier":0.7}}`), &row))
+ r := &observerUsageRepo{record: &row, userUsageRepoCapture: userUsageRepoCapture{
+ listRows: []service.UsageLog{row}, stats: &usagestats.UsageStats{TotalAccountCost: &accountCost}}}
+ router := observerUsageRouter(r, role)
+ for _, path := range []string{"/usage?user_id=999", "/usage/1"} {
+ w := usageGET(router, path)
+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())
+ require.NotContains(t, w.Body.String(), "synthetic-must-not-leak")
+ if role == service.RoleObserver {
+ require.Contains(t, w.Body.String(), `"account_rate_multiplier":2`)
+ require.Contains(t, w.Body.String(), `"procurement_cost_snapshot"`)
+ require.Contains(t, w.Body.String(), `"cost_multiplier":0.7`)
+ } else {
+ require.NotContains(t, w.Body.String(), "account_rate_multiplier")
+ require.NotContains(t, w.Body.String(), "procurement_cost_snapshot")
+ }
+ }
+ require.Equal(t, int64(42), r.listFilters.UserID, "query user_id cannot expand existing ownership scope")
+ w := usageGET(router, "/usage/stats?user_id=999")
+ require.Equal(t, http.StatusOK, w.Code, w.Body.String())
+ if role == service.RoleObserver {
+ require.Contains(t, w.Body.String(), `"total_account_cost":9`)
+ } else {
+ require.NotContains(t, w.Body.String(), `"total_account_cost":9`)
+ }
+ r.record.UserID = 999
+ w = usageGET(router, "/usage/1")
+ require.Equal(t, http.StatusForbidden, w.Code)
+ require.NotContains(t, w.Body.String(), "procurement_cost_snapshot", "a foreign record remains forbidden")
+ })
+ }
+}
+
func TestObserverOwnUsageFiltersAndTiming(t *testing.T) {
r := &observerUsageRepo{record: &service.UsageLog{ID: 1, UserID: 999}}
router := observerUsageRouter(r, service.RoleObserver)
diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go
index 56efdf73b74c..2e1c04f73959 100644
--- a/backend/internal/repository/account_repo.go
+++ b/backend/internal/repository/account_repo.go
@@ -181,6 +181,12 @@ func createAccountRecord(ctx context.Context, client *dbent.Client, account *ser
if account == nil {
return service.ErrAccountNilInput
}
+ if err := service.ValidateGatewayAccountIdentity(account.Platform, account.Type, account.Credentials); err != nil {
+ return err
+ }
+ if account.IsGateway() {
+ account.Schedulable = false
+ }
account.Extra = copyJSONMap(account.Extra)
delete(account.Extra, service.OAuthDegradationActionExtraKey)
@@ -346,6 +352,9 @@ func (r *accountRepository) CreateWithAccountGroups(ctx context.Context, account
return err
}
+ if err := validateGatewayGroupBindings(ctx, txClient, account, groupIDs); err != nil {
+ return err
+ }
if err := createAccountRecord(ctx, txClient, account); err != nil {
return err
}
@@ -658,6 +667,9 @@ func (r *accountRepository) updateLockedAccount(
explicitRateSyncEnabled *bool,
explicitRateMultiplier *float64,
) (*dbent.Account, error) {
+ if err := service.ValidateGatewayAccountIdentity(account.Platform, account.Type, account.Credentials); err != nil {
+ return nil, err
+ }
extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, explicitProbeEnabled, explicitRateSyncEnabled)
if err != nil {
return nil, err
@@ -697,6 +709,9 @@ func (r *accountRepository) updateLockedAccount(
if !preserveOAuthErrorScheduling && (!accounttimer.PreserveSchedulable(ctx) || account.Status == service.StatusError) {
builder.SetSchedulable(schedulable)
}
+ if account.IsGateway() {
+ builder.SetSchedulable(false)
+ }
if explicitRateMultiplier != nil {
builder.SetRateMultiplier(*explicitRateMultiplier)
@@ -2503,6 +2518,9 @@ func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, gro
// SetGroupAllowedModels 覆盖账号在各个已绑定分组内的模型限制:allowed 里没有的分组恢复为不限制,
// 账号未绑定的分组被忽略。有变化时通知调度器刷新该账号的缓存。
func (r *accountRepository) SetGroupAllowedModels(ctx context.Context, accountID int64, allowed map[int64][]string) error {
+ if scoped := r.accountTransactionScope(ctx); scoped != r {
+ return scoped.SetGroupAllowedModels(ctx, accountID, allowed)
+ }
tx, err := r.client.Tx(ctx)
if err != nil && !errors.Is(err, dbent.ErrTxStarted) {
return err
@@ -2625,6 +2643,8 @@ func (r *accountRepository) schedulableAccountsQuery(now time.Time) *dbent.Accou
Where(
dbaccount.StatusEQ(service.StatusActive),
dbaccount.SchedulableEQ(true),
+ dbaccount.TypeNEQ(service.AccountTypeGateway),
+ dbaccount.PlatformNEQ(service.PlatformGateway),
tempUnschedulablePredicate(),
notExpiredPredicate(now),
dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)),
@@ -2683,6 +2703,7 @@ func (r *accountRepository) ListSchedulableCapacityByGroupIDs(ctx context.Contex
AND a.deleted_at IS NULL
AND a.status = $2
AND a.schedulable = TRUE
+ AND a.type <> 'gateway' AND a.platform <> 'gateway'
AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= $3)
AND (a.expires_at IS NULL OR a.expires_at > $3 OR a.auto_pause_on_expired = FALSE)
AND (a.overload_until IS NULL OR a.overload_until <= $3)
@@ -2731,6 +2752,8 @@ func (r *accountRepository) ListSchedulableByPlatform(ctx context.Context, platf
dbaccount.PlatformEQ(platform),
dbaccount.StatusEQ(service.StatusActive),
dbaccount.SchedulableEQ(true),
+ dbaccount.TypeNEQ(service.AccountTypeGateway),
+ dbaccount.PlatformNEQ(service.PlatformGateway),
tempUnschedulablePredicate(),
notExpiredPredicate(now),
dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)),
@@ -2765,6 +2788,8 @@ func (r *accountRepository) ListSchedulableByPlatforms(ctx context.Context, plat
dbaccount.PlatformIn(platforms...),
dbaccount.StatusEQ(service.StatusActive),
dbaccount.SchedulableEQ(true),
+ dbaccount.TypeNEQ(service.AccountTypeGateway),
+ dbaccount.PlatformNEQ(service.PlatformGateway),
tempUnschedulablePredicate(),
notExpiredPredicate(now),
dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)),
@@ -2785,6 +2810,8 @@ func (r *accountRepository) ListSchedulableUngroupedByPlatform(ctx context.Conte
dbaccount.PlatformEQ(platform),
dbaccount.StatusEQ(service.StatusActive),
dbaccount.SchedulableEQ(true),
+ dbaccount.TypeNEQ(service.AccountTypeGateway),
+ dbaccount.PlatformNEQ(service.PlatformGateway),
dbaccount.Not(dbaccount.HasAccountGroups()),
tempUnschedulablePredicate(),
notExpiredPredicate(now),
@@ -2809,6 +2836,8 @@ func (r *accountRepository) ListSchedulableUngroupedByPlatforms(ctx context.Cont
dbaccount.PlatformIn(platforms...),
dbaccount.StatusEQ(service.StatusActive),
dbaccount.SchedulableEQ(true),
+ dbaccount.TypeNEQ(service.AccountTypeGateway),
+ dbaccount.PlatformNEQ(service.PlatformGateway),
dbaccount.Not(dbaccount.HasAccountGroups()),
tempUnschedulablePredicate(),
notExpiredPredicate(now),
@@ -2860,6 +2889,8 @@ func (r *accountRepository) ListModelAvailabilityCandidates(
preds := []dbpredicate.Account{
dbaccount.StatusEQ(service.StatusActive),
dbaccount.SchedulableEQ(true),
+ dbaccount.TypeNEQ(service.AccountTypeGateway),
+ dbaccount.PlatformNEQ(service.PlatformGateway),
dbaccount.PlatformIn(platforms...),
}
if !includeGrouped {
@@ -4079,7 +4110,7 @@ func (r *accountRepository) queryAccountsByGroup(ctx context.Context, groupID in
preds = append(preds, dbaccount.PlatformIn(opts.platforms...))
}
if opts.schedulable {
- preds = append(preds, dbaccount.SchedulableEQ(true))
+ preds = append(preds, dbaccount.SchedulableEQ(true), dbaccount.TypeNEQ(service.AccountTypeGateway), dbaccount.PlatformNEQ(service.PlatformGateway))
if !opts.ignoreTransientState {
now := time.Now()
preds = append(preds,
@@ -4532,7 +4563,7 @@ func (r *accountRepository) ListDueUpstreamBillingProbeAccounts(ctx context.Cont
FROM accounts
WHERE deleted_at IS NULL
AND status = 'active'
- AND type = 'apikey'
+ AND (type = 'apikey' OR (type = 'gateway' AND platform = 'gateway'))
AND extra @> '{"upstream_billing_probe_enabled": true}'::jsonb
), parsed AS MATERIALIZED (
SELECT
diff --git a/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go b/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go
index 113725063664..a13678034453 100644
--- a/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go
+++ b/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go
@@ -28,9 +28,7 @@ func TestAccountRepositoryListDueUpstreamBillingProbeAccountsBoundsQuery(t *test
normalized := normalizeSQLWhitespace(capturedSQL)
require.Contains(t, normalized, "deleted_at IS NULL")
require.Contains(t, normalized, "status = 'active'")
- // 探测资格已放宽到全部 API-key 平台:候选 SQL 不得再按 platform 过滤。
- require.NotContains(t, normalized, "platform")
- require.Contains(t, normalized, "type = 'apikey'")
+ require.Contains(t, normalized, "(type = 'apikey' OR (type = 'gateway' AND platform = 'gateway'))")
require.Contains(t, normalized, `extra @> '{"upstream_billing_probe_enabled": true}'::jsonb`)
require.Contains(t, normalized, "jsonb_path_query_first_tz")
require.Contains(t, normalized, `'(\.[0-9]{6})[0-9]+(Z|[+-][0-9]{2}:[0-9]{2})$'`)
diff --git a/backend/internal/repository/gateway_account_atomic_integration_test.go b/backend/internal/repository/gateway_account_atomic_integration_test.go
new file mode 100644
index 000000000000..82a5ceeeef3b
--- /dev/null
+++ b/backend/internal/repository/gateway_account_atomic_integration_test.go
@@ -0,0 +1,282 @@
+//go:build integration
+
+package repository
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ dbent "github.com/Wei-Shaw/sub2api/ent"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/stretchr/testify/require"
+)
+
+// The barriers are outside the production implementation. They exercise real
+// service calls and independent PostgreSQL transactions without timing sleeps.
+type gatewayAtomicBarrierRepo struct {
+ service.AdminAccountRepository
+ atomic service.GatewayAccountTransactionRepository
+ beforeLock bool
+ failBinding bool
+ entered chan struct{}
+ release chan struct{}
+ once sync.Once
+ staged *service.Account
+}
+
+func (r *gatewayAtomicBarrierRepo) wait(ctx context.Context) error {
+ r.once.Do(func() { close(r.entered) })
+ select {
+ case <-r.release:
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+func (r *gatewayAtomicBarrierRepo) WithinGatewayAccountTransaction(ctx context.Context, id int64, groups []int64, run func(context.Context) error) error {
+ if r.beforeLock {
+ if err := r.wait(ctx); err != nil {
+ return err
+ }
+ }
+ return r.atomic.WithinGatewayAccountTransaction(ctx, id, groups, run)
+}
+
+func (r *gatewayAtomicBarrierRepo) BindGroups(ctx context.Context, id int64, groups []int64) error {
+ if r.failBinding {
+ var err error
+ r.staged, err = r.AdminAccountRepository.GetByID(ctx, id)
+ if err != nil {
+ return err
+ }
+ if err := r.wait(ctx); err != nil {
+ return err
+ }
+ return service.ErrGatewayAccountGroup
+ }
+ return r.AdminAccountRepository.BindGroups(ctx, id, groups)
+}
+
+type gatewayAtomicResult struct {
+ err error
+ bulk *service.BulkUpdateAccountsResult
+}
+
+func gatewayAtomicFixture(t *testing.T) (service.AdminAccountRepository, service.AdminGroupRepository, *service.Account, int64) {
+ t.Helper()
+ ctx := t.Context()
+ repo := NewAdminAccountRepository(integrationEntClient, integrationDB, nil)
+ groups := NewAdminGroupRepository(integrationEntClient, integrationDB)
+ stamp := time.Now().UnixNano()
+ oldGroup, err := integrationEntClient.Group.Create().SetName(fmt.Sprintf("gateway-atomic-old-%d", stamp)).SetPlatform(service.PlatformOpenAI).Save(ctx)
+ require.NoError(t, err)
+ target, err := integrationEntClient.Group.Create().SetName(fmt.Sprintf("gateway-atomic-target-%d", stamp)).SetPlatform(service.PlatformAnthropic).Save(ctx)
+ require.NoError(t, err)
+ a := &service.Account{Name: fmt.Sprintf("gateway-atomic-%d", stamp), Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Status: service.StatusActive, Concurrency: 2, Priority: 10,
+ Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "original-synthetic-key"},
+ Extra: map[string]any{service.AccountCostMultiplierExtraKey: 0.3, "quota_used": 12.0}}
+ require.NoError(t, repo.CreateWithAccountGroups(ctx, a, []service.AccountGroup{{GroupID: oldGroup.ID, Priority: 37, AllowedModels: []string{"fixture-model"}}}))
+ t.Cleanup(func() {
+ _, _ = integrationDB.Exec(`DELETE FROM scheduler_outbox WHERE account_id=$1 OR group_id IN ($2,$3)`, a.ID, oldGroup.ID, target.ID)
+ _, _ = integrationDB.Exec(`DELETE FROM account_groups WHERE account_id=$1`, a.ID)
+ _, _ = integrationDB.Exec(`DELETE FROM accounts WHERE id=$1`, a.ID)
+ _, _ = integrationDB.Exec(`DELETE FROM groups WHERE id IN ($1,$2)`, oldGroup.ID, target.ID)
+ })
+ return repo, groups, a, target.ID
+}
+
+func gatewayAtomicWrite(ctx context.Context, route string, repo service.AdminAccountRepository, groups service.AdminGroupRepository, id, target int64) gatewayAtomicResult {
+ ids := []int64{target}
+ credentials := map[string]any{"api_key": "replacement-synthetic-key"}
+ name := "gateway-atomic-edited"
+ if route == "account-service" {
+ _, err := service.NewAccountService(repo, groups).Update(ctx, id, service.UpdateAccountRequest{Name: &name, Credentials: &credentials, GroupIDs: &ids})
+ return gatewayAtomicResult{err: err}
+ }
+ admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, integrationEntClient, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ if route == "bulk" {
+ result, err := admin.BulkUpdateAccounts(ctx, &service.BulkUpdateAccountsInput{AccountIDs: []int64{id}, Name: name, Credentials: credentials, GroupIDs: &ids, SkipMixedChannelCheck: true})
+ return gatewayAtomicResult{err: err, bulk: result}
+ }
+ // Platform is intentionally omitted: this was the reviewed partial-write path.
+ _, err := admin.UpdateAccount(ctx, id, &service.UpdateAccountInput{Name: name, Credentials: credentials, GroupIDs: &ids, SkipMixedChannelCheck: true})
+ return gatewayAtomicResult{err: err}
+}
+
+func gatewayAtomicAssertUnchanged(t *testing.T, repo service.AccountRepository, before *service.Account) {
+ t.Helper()
+ after, err := repo.GetByID(t.Context(), before.ID)
+ require.NoError(t, err)
+ require.Equal(t, before.Name, after.Name)
+ require.Equal(t, before.Credentials, after.Credentials)
+ require.Equal(t, before.RateMultiplier, after.RateMultiplier)
+ require.Equal(t, before.Extra, after.Extra)
+ require.Equal(t, before.Status, after.Status)
+ require.Equal(t, before.Schedulable, after.Schedulable)
+ require.Equal(t, before.GroupIDs, after.GroupIDs)
+ for i := range before.AccountGroups {
+ require.Equal(t, before.AccountGroups[i].Priority, after.AccountGroups[i].Priority)
+ require.Equal(t, before.AccountGroups[i].AllowedModels, after.AccountGroups[i].AllowedModels)
+ }
+}
+
+func TestGatewayAtomicUpdateOAuthInterleaving(t *testing.T) {
+ for _, route := range []string{"admin", "account-service", "bulk"} {
+ t.Run(route, func(t *testing.T) {
+ repo, groups, a, target := gatewayAtomicFixture(t)
+ barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), beforeLock: true,
+ entered: make(chan struct{}), release: make(chan struct{})}
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
+ defer cancel()
+ done := make(chan gatewayAtomicResult, 1)
+ go func() { done <- gatewayAtomicWrite(ctx, route, barrier, groups, a.ID, target) }()
+ select {
+ case <-barrier.entered:
+ case <-ctx.Done():
+ t.Fatal("update did not reach the post-precheck transaction barrier")
+ }
+ group, err := groups.GetByID(ctx, target)
+ require.NoError(t, err)
+ group.RequireOAuthOnly = true
+ require.NoError(t, groups.Update(ctx, group), "independent group transaction wins after the service precheck")
+ _, err = integrationDB.ExecContext(ctx, `UPDATE accounts SET rate_multiplier=2.5,extra=extra||'{"quota_used":19,"cost_multiplier":0.7}'::jsonb WHERE id=$1`, a.ID)
+ require.NoError(t, err)
+ before, err := repo.GetByID(ctx, a.ID)
+ require.NoError(t, err)
+ close(barrier.release)
+ select {
+ case result := <-done:
+ if route == "bulk" {
+ require.NoError(t, result.err)
+ require.NotNil(t, result.bulk)
+ require.Equal(t, []int64{a.ID}, result.bulk.FailedIDs)
+ require.Empty(t, result.bulk.SuccessIDs)
+ } else {
+ require.ErrorIs(t, result.err, service.ErrGatewayAccountGroup)
+ }
+ case <-ctx.Done():
+ t.Fatal("update did not finish")
+ }
+ gatewayAtomicAssertUnchanged(t, repo, before)
+ })
+ }
+}
+
+func TestGatewayAtomicUpdateRollbackAfterStagedFields(t *testing.T) {
+ for _, route := range []string{"admin", "account-service", "bulk"} {
+ t.Run(route, func(t *testing.T) {
+ repo, groups, a, target := gatewayAtomicFixture(t)
+ before, err := repo.GetByID(t.Context(), a.ID)
+ require.NoError(t, err)
+ var events int
+ require.NoError(t, integrationDB.QueryRow(`SELECT count(*) FROM scheduler_outbox WHERE account_id=$1`, a.ID).Scan(&events))
+ barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), failBinding: true,
+ entered: make(chan struct{}), release: make(chan struct{})}
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
+ defer cancel()
+ done := make(chan gatewayAtomicResult, 1)
+ go func() { done <- gatewayAtomicWrite(ctx, route, barrier, groups, a.ID, target) }()
+ select {
+ case <-barrier.entered:
+ case <-ctx.Done():
+ t.Fatal("update did not reach binding after staging fields")
+ }
+ require.Equal(t, "gateway-atomic-edited", barrier.staged.Name)
+ require.Equal(t, "replacement-synthetic-key", barrier.staged.Credentials["api_key"])
+ gatewayAtomicAssertUnchanged(t, repo, before) // independent connection cannot see staged writes
+ close(barrier.release)
+ select {
+ case result := <-done:
+ if route == "bulk" {
+ require.NoError(t, result.err)
+ require.NotNil(t, result.bulk)
+ require.Equal(t, []int64{a.ID}, result.bulk.FailedIDs)
+ } else {
+ require.ErrorIs(t, result.err, service.ErrGatewayAccountGroup)
+ }
+ case <-ctx.Done():
+ t.Fatal("rollback did not finish")
+ }
+ gatewayAtomicAssertUnchanged(t, repo, before)
+ var afterEvents int
+ require.NoError(t, integrationDB.QueryRow(`SELECT count(*) FROM scheduler_outbox WHERE account_id=$1`, a.ID).Scan(&afterEvents))
+ require.Equal(t, events, afterEvents, "failed writes must not publish outbox events")
+ })
+ }
+}
+
+func TestGatewayAtomicUpdateSuccessfulCommit(t *testing.T) {
+ for _, route := range []string{"admin", "account-service", "bulk"} {
+ t.Run(route, func(t *testing.T) {
+ repo, groups, a, target := gatewayAtomicFixture(t)
+ barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), beforeLock: true,
+ entered: make(chan struct{}), release: make(chan struct{})}
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
+ defer cancel()
+ done := make(chan gatewayAtomicResult, 1)
+ go func() { done <- gatewayAtomicWrite(ctx, route, barrier, groups, a.ID, target) }()
+ select {
+ case <-barrier.entered:
+ case <-ctx.Done():
+ t.Fatal("update did not reach the pre-lock billing-state barrier")
+ }
+ _, err := integrationDB.ExecContext(ctx, `UPDATE accounts SET rate_multiplier=2.5,extra=extra||'{"quota_used":19,"cost_multiplier":0.7}'::jsonb WHERE id=$1`, a.ID)
+ require.NoError(t, err)
+ close(barrier.release)
+ var result gatewayAtomicResult
+ select {
+ case result = <-done:
+ case <-ctx.Done():
+ t.Fatal("atomic commit did not finish")
+ }
+ require.NoError(t, result.err)
+ if route == "bulk" {
+ require.NotNil(t, result.bulk)
+ require.Equal(t, []int64{a.ID}, result.bulk.SuccessIDs)
+ }
+ after, err := repo.GetByID(t.Context(), a.ID)
+ require.NoError(t, err)
+ require.Equal(t, "gateway-atomic-edited", after.Name)
+ require.Equal(t, "replacement-synthetic-key", after.Credentials["api_key"])
+ require.Equal(t, []int64{target}, after.GroupIDs)
+ require.NotNil(t, after.RateMultiplier)
+ require.Equal(t, 2.5, *after.RateMultiplier, "omitted request rate must retain the latest committed value")
+ require.Equal(t, 19.0, after.Extra["quota_used"])
+ require.Equal(t, 0.7, after.CostMultiplier())
+ require.False(t, after.IsSchedulable())
+ })
+ }
+}
+
+func TestGatewayAtomicUpdateCallerTransactionRollback(t *testing.T) {
+ for _, route := range []string{"admin", "account-service", "bulk"} {
+ t.Run(route, func(t *testing.T) {
+ repo, groups, a, target := gatewayAtomicFixture(t)
+ before, err := repo.GetByID(t.Context(), a.ID)
+ require.NoError(t, err)
+ barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), failBinding: true,
+ entered: make(chan struct{}), release: make(chan struct{})}
+ close(barrier.release)
+ tx, err := integrationEntClient.Tx(t.Context())
+ require.NoError(t, err)
+ defer func() { _ = tx.Rollback() }()
+ result := gatewayAtomicWrite(dbent.NewTxContext(t.Context(), tx), route, barrier, groups, a.ID, target)
+ if route == "bulk" {
+ require.NoError(t, result.err)
+ require.NotNil(t, result.bulk)
+ require.Equal(t, []int64{a.ID}, result.bulk.FailedIDs)
+ } else {
+ require.ErrorIs(t, result.err, service.ErrGatewayAccountGroup)
+ }
+ // A caller can commit other successful work without committing this
+ // failed item's fields or outbox. The savepoint owns item rollback.
+ require.NoError(t, tx.Commit())
+ gatewayAtomicAssertUnchanged(t, repo, before)
+ })
+ }
+}
diff --git a/backend/internal/repository/gateway_account_group_bindings_test.go b/backend/internal/repository/gateway_account_group_bindings_test.go
new file mode 100644
index 000000000000..98786948ea0d
--- /dev/null
+++ b/backend/internal/repository/gateway_account_group_bindings_test.go
@@ -0,0 +1,40 @@
+package repository
+
+import (
+ "context"
+ "testing"
+
+ "github.com/DATA-DOG/go-sqlmock"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/stretchr/testify/require"
+)
+
+func TestGatewayManagementRepositoryBindingGuard(t *testing.T) {
+ for _, policy := range []string{"explicit-mixed", "oauth-only", "missing", "invalid-platform"} {
+ t.Run(policy, func(t *testing.T) {
+ db, mock, err := sqlmock.New()
+ require.NoError(t, err)
+ defer func() { _ = db.Close() }()
+ mock.ExpectQuery(`SELECT COALESCE\(extra,.*FROM accounts.*FOR NO KEY UPDATE`).WithArgs(int64(959)).
+ WillReturnRows(sqlmock.NewRows([]string{"extra", "platform", "type"}).AddRow(`{}`, service.PlatformGateway, service.AccountTypeGateway))
+ rows := sqlmock.NewRows([]string{"id", "platform", "require_oauth_only"}).AddRow(1, service.PlatformOpenAI, false)
+ switch policy {
+ case "explicit-mixed":
+ rows.AddRow(2, service.PlatformAnthropic, false)
+ case "oauth-only":
+ rows.AddRow(2, service.PlatformComposite, true)
+ case "invalid-platform":
+ rows.AddRow(2, service.PlatformGateway, false)
+ }
+ mock.ExpectQuery(`SELECT id,platform,require_oauth_only FROM groups`).WithArgs("[1,2]").WillReturnRows(rows)
+ ids, err := lockOAuthDegradationGroupBindings(context.Background(), db, 959, []int64{1, 2})
+ if policy == "explicit-mixed" {
+ require.NoError(t, err)
+ require.Equal(t, []int64{1, 2}, ids)
+ } else {
+ require.ErrorIs(t, err, service.ErrGatewayAccountGroup)
+ }
+ require.NoError(t, mock.ExpectationsWereMet())
+ })
+ }
+}
diff --git a/backend/internal/repository/gateway_account_management_integration_test.go b/backend/internal/repository/gateway_account_management_integration_test.go
new file mode 100644
index 000000000000..c445714c8c96
--- /dev/null
+++ b/backend/internal/repository/gateway_account_management_integration_test.go
@@ -0,0 +1,57 @@
+//go:build integration
+
+package repository
+
+import "github.com/Wei-Shaw/sub2api/internal/service"
+
+func (s *AccountRepoSuite) TestGatewayManagementAtomicMembershipAndOAuthExclusion() {
+ openai, err := s.client.Group.Create().SetName("gateway-openai").SetPlatform(service.PlatformOpenAI).Save(s.ctx)
+ s.Require().NoError(err)
+ anthropic, err := s.client.Group.Create().SetName("gateway-anthropic").SetPlatform(service.PlatformAnthropic).Save(s.ctx)
+ s.Require().NoError(err)
+ composite, err := s.client.Group.Create().SetName("gateway-composite").SetPlatform(service.PlatformComposite).Save(s.ctx)
+ s.Require().NoError(err)
+ oauth, err := s.client.Group.Create().SetName("gateway-oauth-only").SetPlatform(service.PlatformComposite).SetRequireOauthOnly(true).Save(s.ctx)
+ s.Require().NoError(err)
+ a := &service.Account{Name: "gateway-account", Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Status: service.StatusActive, Schedulable: true, Concurrency: 2,
+ Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "synthetic-key"}}
+ s.Require().NoError(s.repo.CreateWithAccountGroups(s.ctx, a, []service.AccountGroup{
+ {GroupID: openai.ID, Priority: 1}, {GroupID: anthropic.ID, Priority: 2}, {GroupID: composite.ID, Priority: 3},
+ }))
+ stored, err := s.repo.GetByID(s.ctx, a.ID)
+ s.Require().NoError(err)
+ s.False(stored.Schedulable)
+ s.Equal("new_api", stored.Credentials["upstream_kind"])
+ s.ElementsMatch([]int64{openai.ID, anthropic.ID, composite.ID}, stored.GroupIDs)
+ // A manual/stale flag cannot leak this incomplete type into any eligible pool.
+ s.Require().NoError(s.repo.SetSchedulable(s.ctx, a.ID, true))
+ candidates, err := s.repo.ListSchedulableByGroupID(s.ctx, openai.ID)
+ s.Require().NoError(err)
+ s.Empty(candidates)
+ candidates, err = s.repo.ListSchedulable(s.ctx)
+ s.Require().NoError(err)
+ for _, candidate := range candidates {
+ s.NotEqual(a.ID, candidate.ID)
+ }
+ s.Error(s.repo.BindGroups(s.ctx, a.ID, []int64{openai.ID, oauth.ID}))
+ s.Error(s.repo.AddToGroup(s.ctx, a.ID, oauth.ID, 1))
+ groups := newGroupRepositoryWithSQL(s.client, s.repo.sql)
+ s.Error(groups.BindAccountsToGroup(s.ctx, oauth.ID, []int64{a.ID}))
+ rejected := *a
+ rejected.ID = 0
+ rejected.Name = "rejected-gateway"
+ s.Error(s.repo.CreateWithAccountGroups(s.ctx, &rejected, []service.AccountGroup{{GroupID: oauth.ID, Priority: 1}}))
+ s.Zero(rejected.ID, "rejected group policy is checked before inserting the account")
+ stored, err = s.repo.GetByID(s.ctx, a.ID)
+ s.Require().NoError(err)
+ s.ElementsMatch([]int64{openai.ID, anthropic.ID, composite.ID}, stored.GroupIDs, "rejection preserves prior explicit memberships")
+ s.Require().NoError(s.repo.BindGroups(s.ctx, a.ID, []int64{anthropic.ID}))
+ stored, err = s.repo.GetByID(s.ctx, a.ID)
+ s.Require().NoError(err)
+ s.Equal([]int64{anthropic.ID}, stored.GroupIDs, "removal does not infer other platform memberships")
+ group, err := groups.GetByID(s.ctx, anthropic.ID)
+ s.Require().NoError(err)
+ group.RequireOAuthOnly = true
+ s.ErrorIs(groups.Update(s.ctx, group), service.ErrGatewayAccountGroup, "group edits cannot strand a gateway in an OAuth-only group")
+}
diff --git a/backend/internal/repository/gateway_account_transaction.go b/backend/internal/repository/gateway_account_transaction.go
new file mode 100644
index 000000000000..00189db32cf6
--- /dev/null
+++ b/backend/internal/repository/gateway_account_transaction.go
@@ -0,0 +1,78 @@
+package repository
+
+import (
+ "context"
+ "errors"
+ "time"
+
+ dbent "github.com/Wei-Shaw/sub2api/ent"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+)
+
+var _ service.GatewayAccountTransactionRepository = (*accountRepository)(nil)
+
+// WithinGatewayAccountTransaction reuses the established repository tx scope:
+// billing settings still use updateLockedAccount and its managed-state fences,
+// bulk still uses its existing SQL merge, and bindings retain their live checks.
+func (r *accountRepository) WithinGatewayAccountTransaction(ctx context.Context, id int64, groups []int64, run func(context.Context) error) (writeErr error) {
+ tx := dbent.TxFromContext(ctx)
+ owned := tx == nil
+ if owned {
+ var err error
+ tx, err = r.client.Tx(ctx)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+ } else {
+ // Bulk callers may keep their outer transaction after a failed item.
+ // Roll back this item's staged fields even in that caller-owned scope.
+ if _, err := tx.Client().ExecContext(ctx, "SAVEPOINT gateway_account_update"); err != nil {
+ return err
+ }
+ defer func() {
+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
+ defer cancel()
+ if writeErr != nil {
+ _, err := tx.Client().ExecContext(cleanupCtx, "ROLLBACK TO SAVEPOINT gateway_account_update")
+ writeErr = errors.Join(writeErr, err)
+ if err != nil {
+ _ = tx.Rollback()
+ return
+ }
+ }
+ _, err := tx.Client().ExecContext(cleanupCtx, "RELEASE SAVEPOINT gateway_account_update")
+ writeErr = errors.Join(writeErr, err)
+ if err != nil {
+ _ = tx.Rollback()
+ }
+ }()
+ }
+ txctx := dbent.NewTxContext(ctx, tx)
+ // Match the existing binding lock order: group policies, then account row.
+ if err := lockLiveGroups(txctx, tx.Client(), groups); err != nil {
+ return err
+ }
+ if _, err := lockOAuthDegradationGroupBindings(txctx, tx.Client(), id, groups); err != nil {
+ return err
+ }
+ account, err := r.GetByID(txctx, id)
+ if err != nil {
+ return err
+ }
+ if !account.IsGateway() || account.Platform != service.PlatformGateway {
+ return service.ErrGatewayAccountIdentity
+ }
+ if err := run(txctx); err != nil {
+ return err
+ }
+ // Context-scoped repositories suppress precommit cache publication. Reuse
+ // the existing commit hook for caller-owned transactions as well as ours.
+ service.AfterAccountCommit(txctx, func(committed context.Context) {
+ r.syncSchedulerAccountSnapshot(committed, id)
+ })
+ if owned {
+ return tx.Commit()
+ }
+ return nil
+}
diff --git a/backend/internal/repository/gateway_request_admission.go b/backend/internal/repository/gateway_request_admission.go
new file mode 100644
index 000000000000..3394320a9038
--- /dev/null
+++ b/backend/internal/repository/gateway_request_admission.go
@@ -0,0 +1,65 @@
+package repository
+
+import (
+ "context"
+ "database/sql"
+
+ dbent "github.com/Wei-Shaw/sub2api/ent"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+)
+
+var _ service.GatewayRequestAccountReader = (*accountRepository)(nil)
+
+func (r *accountRepository) GatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*service.Account, *service.Group, error) {
+ return withGatewayReadSnapshot(ctx, r, func(ctx context.Context, reader *accountRepository) (*service.Account, *service.Group, error) {
+ return reader.gatewayRequestAccount(ctx, accountID, groupID)
+ })
+}
+
+// Reuse the caller's transaction when present. Otherwise keep the account,
+// bindings and group policy in one repeatable-read snapshot.
+func withGatewayReadSnapshot[T any](ctx context.Context, r *accountRepository, read func(context.Context, *accountRepository) (T, *service.Group, error)) (T, *service.Group, error) {
+ tx := dbent.TxFromContext(ctx)
+ if tx == nil {
+ tx, _ = r.sql.(*dbent.Tx)
+ }
+ if tx != nil {
+ ctx = dbent.NewTxContext(ctx, tx)
+ return read(ctx, r.accountTransactionScope(ctx))
+ }
+ var zero T
+ tx, err := r.client.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead})
+ if err != nil {
+ return zero, nil, err
+ }
+ defer func() { _ = tx.Rollback() }()
+ ctx = dbent.NewTxContext(ctx, tx)
+ value, group, err := read(ctx, r.accountTransactionScope(ctx))
+ if err != nil {
+ return zero, nil, err
+ }
+ if err := tx.Commit(); err != nil {
+ return zero, nil, err
+ }
+ return value, group, nil
+}
+
+func (r *accountRepository) gatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*service.Account, *service.Group, error) {
+ account, err := r.GetByID(ctx, accountID)
+ if err != nil {
+ return nil, nil, err
+ }
+ paused, err := performancePaused(ctx, clientFromContext(ctx, r.client), []int64{accountID})
+ if err != nil {
+ return nil, nil, err
+ }
+ account.PerformancePaused = paused[accountID]
+ group, err := clientFromContext(ctx, r.client).Group.Get(ctx, groupID)
+ if err != nil {
+ return nil, nil, translatePersistenceError(err, service.ErrGroupNotFound, nil)
+ }
+ if group.DeletedAt != nil {
+ return nil, nil, service.ErrGroupNotFound
+ }
+ return account, groupEntityToService(group), nil
+}
diff --git a/backend/internal/repository/gateway_request_admission_integration_test.go b/backend/internal/repository/gateway_request_admission_integration_test.go
new file mode 100644
index 000000000000..d472eae5996f
--- /dev/null
+++ b/backend/internal/repository/gateway_request_admission_integration_test.go
@@ -0,0 +1,30 @@
+//go:build integration
+
+package repository
+
+import "github.com/Wei-Shaw/sub2api/internal/service"
+
+func (s *AccountRepoSuite) TestGatewayRequestAdmissionReloadsGroupMembershipAndStatus() {
+ group, err := s.client.Group.Create().SetName("gateway-request-admission").SetPlatform(service.PlatformComposite).Save(s.ctx)
+ s.Require().NoError(err)
+ a := &service.Account{Name: "gateway-admission", Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Status: service.StatusActive, Concurrency: 2,
+ Credentials: map[string]any{"upstream_kind": "sub2api", "base_url": "https://gateway.example", "api_key": "synthetic-only"}}
+ s.Require().NoError(s.repo.CreateWithAccountGroups(s.ctx, a, []service.AccountGroup{{GroupID: group.ID, Priority: 1}}))
+ current, liveGroup, err := s.repo.GatewayRequestAccount(s.ctx, a.ID, group.ID)
+ s.Require().NoError(err)
+ s.Equal([]int64{group.ID}, current.GroupIDs)
+ s.False(liveGroup.RequireOAuthOnly)
+ s.Require().NoError(s.repo.BindGroups(s.ctx, a.ID, nil))
+ _, err = s.client.Group.UpdateOneID(group.ID).SetRequireOauthOnly(true).Save(s.ctx)
+ s.Require().NoError(err)
+ current, liveGroup, err = s.repo.GatewayRequestAccount(s.ctx, a.ID, group.ID)
+ s.Require().NoError(err)
+ s.Empty(current.GroupIDs, "reader cannot reuse the pre-removal membership snapshot")
+ s.True(liveGroup.RequireOAuthOnly, "terminal admission sees the current group policy")
+ _, err = s.client.Account.UpdateOneID(a.ID).SetStatus(service.StatusError).Save(s.ctx)
+ s.Require().NoError(err)
+ current, _, err = s.repo.GatewayRequestAccount(s.ctx, a.ID, group.ID)
+ s.Require().NoError(err)
+ s.Equal(service.StatusError, current.Status)
+}
diff --git a/backend/internal/repository/gateway_request_candidates.go b/backend/internal/repository/gateway_request_candidates.go
new file mode 100644
index 000000000000..ff49c323554e
--- /dev/null
+++ b/backend/internal/repository/gateway_request_candidates.go
@@ -0,0 +1,52 @@
+package repository
+
+import (
+ "context"
+
+ dbent "github.com/Wei-Shaw/sub2api/ent"
+ dbaccount "github.com/Wei-Shaw/sub2api/ent/account"
+ dbaccountgroup "github.com/Wei-Shaw/sub2api/ent/accountgroup"
+ "github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/Wei-Shaw/sub2api/internal/service"
+)
+
+var _ service.GatewayRequestCandidateReader = (*accountRepository)(nil)
+
+// This request-only SELECT never expands the platform bucket queries. It reads
+// policy, explicit membership, credentials and runtime state in one SQL snapshot.
+func (r *accountRepository) ListGatewayRequestCandidates(ctx context.Context, groupID int64, target string) ([]service.Account, *service.Group, error) {
+ if groupID <= 0 || !domain.IsConcretePlatform(target) {
+ return nil, nil, nil
+ }
+ return withGatewayReadSnapshot(ctx, r, func(ctx context.Context, reader *accountRepository) ([]service.Account, *service.Group, error) {
+ return reader.gatewayRequestCandidates(ctx, groupID, target)
+ })
+}
+
+func (r *accountRepository) gatewayRequestCandidates(ctx context.Context, groupID int64, target string) ([]service.Account, *service.Group, error) {
+ g, err := r.client.Group.Get(ctx, groupID)
+ if err != nil {
+ return nil, nil, translatePersistenceError(err, service.ErrGroupNotFound, nil)
+ }
+ group := groupEntityToService(g)
+ if g.DeletedAt != nil || !group.IsActive() || (group.Platform != target && group.Platform != service.PlatformComposite) || group.RequireOAuthOnly {
+ return nil, group, nil
+ }
+ ids, err := observerAccountQuery(ctx, r.client.Account.Query()).Where(
+ dbaccount.PlatformEQ(service.PlatformGateway), dbaccount.TypeEQ(service.AccountTypeGateway),
+ dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true),
+ dbaccount.HasAccountGroupsWith(dbaccountgroup.GroupIDEQ(groupID)),
+ ).Order(dbent.Asc(dbaccount.FieldPriority), dbent.Asc(dbaccount.FieldID)).IDs(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ accounts := make([]service.Account, 0, len(ids))
+ for _, id := range ids {
+ account, _, err := r.gatewayRequestAccount(ctx, id, groupID)
+ if err != nil {
+ return nil, nil, err
+ }
+ accounts = append(accounts, *account)
+ }
+ return accounts, group, nil
+}
diff --git a/backend/internal/repository/gateway_request_candidates_integration_test.go b/backend/internal/repository/gateway_request_candidates_integration_test.go
new file mode 100644
index 000000000000..58da481e379d
--- /dev/null
+++ b/backend/internal/repository/gateway_request_candidates_integration_test.go
@@ -0,0 +1,42 @@
+//go:build integration
+
+package repository
+
+import "github.com/Wei-Shaw/sub2api/internal/service"
+
+func (s *AccountRepoSuite) TestGatewayRequestCandidatesRequireLiveExplicitAnthropicGroup() {
+ group, err := s.client.Group.Create().SetName("gateway-candidates").SetPlatform(service.PlatformAnthropic).Save(s.ctx)
+ s.Require().NoError(err)
+ a := &service.Account{Name: "gateway-candidate", Platform: service.PlatformGateway, Type: service.AccountTypeGateway,
+ Status: service.StatusActive, Concurrency: 2,
+ Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "synthetic-only"}}
+ s.Require().NoError(s.repo.CreateWithAccountGroups(s.ctx, a, []service.AccountGroup{{GroupID: group.ID}}))
+ _, err = s.client.Account.UpdateOneID(a.ID).SetSchedulable(true).Save(s.ctx)
+ s.Require().NoError(err)
+ accounts, live, err := s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, service.PlatformAnthropic)
+ s.Require().NoError(err)
+ s.Require().Len(accounts, 1)
+ s.Equal(a.ID, accounts[0].ID)
+ s.Equal(service.PlatformGateway, accounts[0].Platform)
+ s.Equal([]int64{group.ID}, accounts[0].GroupIDs)
+ s.False(accounts[0].IsSchedulable(), "SELECT returns a neutral account, never a globally eligible view")
+ s.Equal(service.PlatformAnthropic, live.Platform)
+ legacyBucket, err := s.repo.ListSchedulableByGroupIDAndPlatform(s.ctx, group.ID, service.PlatformAnthropic)
+ s.Require().NoError(err)
+ s.Empty(legacyBucket, "shared snapshot queries still exclude gateway")
+ for _, target := range []string{service.PlatformOpenAI, service.PlatformGemini, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformComposite} {
+ accounts, _, err = s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, target)
+ s.Require().NoError(err)
+ s.Empty(accounts)
+ }
+ s.Require().NoError(s.repo.BindGroups(s.ctx, a.ID, nil))
+ accounts, _, err = s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, service.PlatformAnthropic)
+ s.Require().NoError(err)
+ s.Empty(accounts, "warm prior reads cannot retain removed membership")
+ _, err = s.client.Group.UpdateOneID(group.ID).SetRequireOauthOnly(true).Save(s.ctx)
+ s.Require().NoError(err)
+ accounts, live, err = s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, service.PlatformAnthropic)
+ s.Require().NoError(err)
+ s.Empty(accounts)
+ s.True(live.RequireOAuthOnly)
+}
diff --git a/backend/internal/repository/group_repo.go b/backend/internal/repository/group_repo.go
index 64a73c4d5f9e..17008625b5db 100644
--- a/backend/internal/repository/group_repo.go
+++ b/backend/internal/repository/group_repo.go
@@ -237,7 +237,7 @@ func (r *groupRepository) CreateFromSource(ctx context.Context, groupIn *service
JOIN accounts a ON a.id = ag.account_id
WHERE ag.group_id = $1
AND a.deleted_at IS NULL
- AND (NOT $3 OR a.type <> $4)
+ AND (NOT $3 OR (a.type <> $4 AND a.type <> 'gateway' AND a.platform <> 'gateway'))
ON CONFLICT (account_id, group_id) DO NOTHING`,
sourceGroupID,
groupIn.ID,
@@ -289,11 +289,53 @@ func (r *groupRepository) GetByIDLite(ctx context.Context, id int64) (*service.G
}
func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) error {
+ client := r.client
+ var gatewayTx *dbent.Tx
+ if groupIn.RequireOAuthOnly {
+ var err error
+ gatewayTx, err = client.Tx(ctx)
+ if err != nil && !errors.Is(err, dbent.ErrTxStarted) {
+ return err
+ }
+ if gatewayTx != nil {
+ defer func() { _ = gatewayTx.Rollback() }()
+ client = gatewayTx.Client()
+ }
+ // Membership writers hold FOR SHARE on this group. Serialize an OAuth
+ // restriction edit with them so neither side can bypass the new policy.
+ rows, err := client.QueryContext(ctx, `SELECT id FROM groups WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, groupIn.ID)
+ if err != nil {
+ return err
+ }
+ found := rows.Next()
+ rowErr := rows.Err()
+ _ = rows.Close()
+ if rowErr != nil {
+ return rowErr
+ }
+ if !found {
+ return service.ErrGroupNotFound
+ }
+ rows, err = client.QueryContext(ctx, `SELECT 1 FROM account_groups ag JOIN accounts a ON a.id=ag.account_id
+ WHERE ag.group_id=$1 AND a.deleted_at IS NULL AND (a.type='gateway' OR a.platform='gateway') LIMIT 1`, groupIn.ID)
+ if err != nil {
+ return err
+ }
+ hasGateway := rows.Next()
+ rowErr = rows.Err()
+ _ = rows.Close()
+ if rowErr != nil {
+ return rowErr
+ }
+ if hasGateway {
+ return service.ErrGatewayAccountGroup
+ }
+ }
modelPricing, err := json.Marshal(groupIn.ModelPricing)
if err != nil {
return fmt.Errorf("marshal group model pricing: %w", err)
}
- builder := r.client.Group.UpdateOneID(groupIn.ID).
+ builder := client.Group.UpdateOneID(groupIn.ID).
SetName(groupIn.Name).
SetDescription(groupIn.Description).
SetPlatform(groupIn.Platform).
@@ -459,6 +501,12 @@ func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) er
return translatePersistenceError(err, service.ErrGroupNotFound, service.ErrGroupExists)
}
groupIn.UpdatedAt = updated.UpdatedAt
+ if gatewayTx != nil {
+ if err := enqueueSchedulerOutbox(ctx, client, service.SchedulerOutboxEventGroupChanged, nil, &groupIn.ID, nil); err != nil {
+ return err
+ }
+ return gatewayTx.Commit()
+ }
if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventGroupChanged, nil, &groupIn.ID, nil); err != nil {
logger.LegacyPrintf("repository.group", "[SchedulerOutbox] enqueue group update failed: group=%d err=%v", groupIn.ID, err)
}
diff --git a/backend/internal/repository/oauth_degradation_group_bindings.go b/backend/internal/repository/oauth_degradation_group_bindings.go
index ee8d39e26cca..a20a8f742458 100644
--- a/backend/internal/repository/oauth_degradation_group_bindings.go
+++ b/backend/internal/repository/oauth_degradation_group_bindings.go
@@ -2,6 +2,7 @@ package repository
import (
"context"
+ "encoding/json"
"github.com/Wei-Shaw/sub2api/internal/service"
)
@@ -10,7 +11,7 @@ import (
// Degradation removes native bindings once; later administrator edits may restore
// them. The historical action must never filter an ordinary binding save.
func lockOAuthDegradationGroupBindings(ctx context.Context, exec sqlExecutor, accountID int64, proposed []int64) ([]int64, error) {
- rows, err := exec.QueryContext(ctx, `SELECT COALESCE(extra,'{}'::jsonb) FROM accounts WHERE id=$1 AND deleted_at IS NULL FOR NO KEY UPDATE`, accountID)
+ rows, err := exec.QueryContext(ctx, `SELECT COALESCE(extra,'{}'::jsonb), platform, type FROM accounts WHERE id=$1 AND deleted_at IS NULL FOR NO KEY UPDATE`, accountID)
if err != nil {
return nil, err
}
@@ -22,8 +23,54 @@ func lockOAuthDegradationGroupBindings(ctx context.Context, exec sqlExecutor, ac
return nil, service.ErrAccountNotFound
}
var raw []byte
- if err := rows.Scan(&raw); err != nil {
+ var platform, kind string
+ if err := rows.Scan(&raw, &platform, &kind); err != nil {
return nil, err
}
- return proposed, rows.Err()
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ if err := rows.Close(); err != nil {
+ return nil, err
+ }
+ return proposed, validateGatewayGroupBindings(ctx, exec, &service.Account{Platform: platform, Type: kind}, proposed)
+}
+
+// Recheck live policy under a shared group lock, including indirect writers
+// (scoped admin, quality and AI moves) that do not call the usual binding API.
+func validateGatewayGroupBindings(ctx context.Context, exec sqlExecutor, a *service.Account, ids []int64) error {
+ if a == nil || (!a.IsGateway() && a.Platform != service.PlatformGateway) || len(ids) == 0 {
+ return nil
+ }
+ encoded, err := json.Marshal(ids)
+ if err != nil {
+ return err
+ }
+ rows, err := exec.QueryContext(ctx, `SELECT id,platform,require_oauth_only FROM groups
+ WHERE id IN (SELECT value::bigint FROM jsonb_array_elements_text($1::jsonb)) AND deleted_at IS NULL
+ ORDER BY id FOR SHARE`, string(encoded))
+ if err != nil {
+ return err
+ }
+ defer func() { _ = rows.Close() }()
+ seen := make(map[int64]bool, len(ids))
+ for rows.Next() {
+ var group service.Group
+ if err := rows.Scan(&group.ID, &group.Platform, &group.RequireOAuthOnly); err != nil {
+ return err
+ }
+ if err := service.ValidateGatewayAccountGroup(a, &group); err != nil {
+ return err
+ }
+ seen[group.ID] = true
+ }
+ if err := rows.Err(); err != nil {
+ return err
+ }
+ for _, id := range ids {
+ if !seen[id] {
+ return service.ErrGatewayAccountGroup
+ }
+ }
+ return nil
}
diff --git a/backend/internal/repository/oauth_degradation_group_bindings_test.go b/backend/internal/repository/oauth_degradation_group_bindings_test.go
index 3f6dc4114f33..836eb4aa6ca2 100644
--- a/backend/internal/repository/oauth_degradation_group_bindings_test.go
+++ b/backend/internal/repository/oauth_degradation_group_bindings_test.go
@@ -10,7 +10,7 @@ import (
func expectOAuthDegradationGroupBindingsAccount(mock sqlmock.Sqlmock, id int64, extra string) {
mock.ExpectQuery(`SELECT COALESCE\(extra,.*FROM accounts.*FOR NO KEY UPDATE`).WithArgs(id).
- WillReturnRows(sqlmock.NewRows([]string{"extra"}).AddRow(extra))
+ WillReturnRows(sqlmock.NewRows([]string{"extra", "platform", "type"}).AddRow(extra, "", ""))
}
func TestOAuthDegradationAuditDoesNotBlockQualityGroupRestore(t *testing.T) {
diff --git a/backend/internal/repository/procurement_cost_snapshot_integration_test.go b/backend/internal/repository/procurement_cost_snapshot_integration_test.go
new file mode 100644
index 000000000000..fe7db81d7ac6
--- /dev/null
+++ b/backend/internal/repository/procurement_cost_snapshot_integration_test.go
@@ -0,0 +1,149 @@
+//go:build integration
+
+package repository
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/service"
+ "github.com/Wei-Shaw/sub2api/migrations"
+ "github.com/stretchr/testify/require"
+)
+
+func procurementFixtureSnapshot(platform string, factor *float64) *service.ProcurementCostSnapshot {
+ return &service.ProcurementCostSnapshot{Version: 1, AccountType: "gateway", Provider: "new_api", TargetPlatform: platform, Basis: "total_cost", CostMultiplier: factor}
+}
+
+func TestProcurementSnapshotAllInsertPathsAndImmutability(t *testing.T) {
+ f := newChannelOperationsFixture(t)
+ repo := newUsageLogRepositoryWithSQL(integrationEntClient, integrationDB)
+ for _, mode := range []string{"single", "batch", "best-effort-single", "best-effort-batch", "legacy"} {
+ t.Run(mode, func(t *testing.T) {
+ factor := .7
+ log := &service.UsageLog{UserID: f.user, APIKeyID: f.key, AccountID: f.account, RequestID: fmt.Sprintf("procurement-%d-%s", f.account, mode),
+ Platform: "openai", Model: "fixture-model", TotalCost: 10, ActualCost: 3, CreatedAt: time.Now().UTC()}
+ if mode != "legacy" {
+ log.ProcurementCostSnapshot = procurementFixtureSnapshot("openai", &factor)
+ }
+ prepared := prepareUsageLogInsert(log)
+ var err error
+ switch mode {
+ case "single", "legacy":
+ _, err = repo.createSingle(t.Context(), integrationDB, log)
+ case "batch":
+ key := usageLogBatchKey(log.RequestID, log.APIKeyID)
+ _, _, _, err = repo.batchInsertUsageLogs(integrationDB, []string{key}, map[string]usageLogInsertPrepared{key: prepared})
+ case "best-effort-single":
+ err = execUsageLogInsertNoResult(t.Context(), integrationDB, prepared)
+ case "best-effort-batch":
+ query, args := buildUsageLogBestEffortInsertQuery([]usageLogInsertPrepared{prepared})
+ _, err = integrationDB.ExecContext(t.Context(), query, args...)
+ }
+ require.NoError(t, err)
+ stored, err := scanUsageLog(integrationDB.QueryRowContext(t.Context(), "SELECT "+usageLogSelectColumns+" FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", log.RequestID, f.key))
+ require.NoError(t, err)
+ require.Equal(t, log.ProcurementCostSnapshot, stored.ProcurementCostSnapshot)
+ require.Equal(t, 10.0, stored.TotalCost)
+ require.Equal(t, 3.0, stored.ActualCost)
+ if mode != "legacy" {
+ log.ProcurementCostSnapshot = procurementFixtureSnapshot("openai", nil)
+ _, err = repo.createSingle(t.Context(), integrationDB, log)
+ require.NoError(t, err)
+ var saved float64
+ require.NoError(t, integrationDB.QueryRow(`SELECT (procurement_cost_snapshot->>'cost_multiplier')::numeric FROM usage_logs WHERE id=$1`, stored.ID).Scan(&saved))
+ require.Equal(t, .7, saved, "dedup must retain the first snapshot")
+ _, err = integrationDB.Exec(`UPDATE usage_logs SET procurement_cost_snapshot=NULL WHERE id=$1`, stored.ID)
+ require.ErrorContains(t, err, "immutable")
+ }
+ })
+ }
+}
+
+func TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge(t *testing.T) {
+ repo, cmd, usage, _ := durableBillingFixture(t)
+ factor := .7
+ usage.Platform, usage.TotalCost, usage.ActualCost = "openai", 10, 3
+ cmd.BalanceCost, cmd.APIKeyQuotaCost = 3, 3
+ usage.ProcurementCostSnapshot = procurementFixtureSnapshot("openai", &factor)
+ require.NoError(t, repo.StageUsageBilling(t.Context(), &cmd, &usage))
+ usage.ProcurementCostSnapshot = procurementFixtureSnapshot("kimi", nil)
+ require.NoError(t, repo.StageUsageBilling(t.Context(), &cmd, &usage))
+ key := service.UsageBillingEventKey{RequestID: cmd.RequestID, APIKeyID: cmd.APIKeyID}
+ for i := 0; i < 2; i++ {
+ _, err := repo.ApplyStagedUsageBilling(t.Context(), key)
+ require.NoError(t, err)
+ }
+ stored, err := scanUsageLog(repo.db.QueryRowContext(t.Context(), "SELECT "+usageLogSelectColumns+" FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", cmd.RequestID, cmd.APIKeyID))
+ require.NoError(t, err)
+ require.Equal(t, "openai", stored.ProcurementCostSnapshot.TargetPlatform)
+ require.Equal(t, .7, *stored.ProcurementCostSnapshot.CostMultiplier)
+ var balance, quota float64
+ require.NoError(t, repo.db.QueryRow(`SELECT balance FROM users WHERE id=$1`, cmd.UserID).Scan(&balance))
+ require.NoError(t, repo.db.QueryRow(`SELECT quota_used FROM api_keys WHERE id=$1`, cmd.APIKeyID).Scan("a))
+ require.Equal(t, 97.0, balance, "user charge is actual_cost=3, never procurement 7")
+ require.Equal(t, 3.0, quota, "replay cannot double-charge")
+}
+
+func TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns(t *testing.T) {
+ f := newChannelOperationsFixture(t)
+ now := time.Now().UTC()
+ _, err := integrationDB.Exec(`UPDATE accounts SET type='gateway',platform='gateway',credentials='{"upstream_kind":"new_api","base_url":"https://gateway.example/tenant","api_key":"synthetic-only"}',extra='{"cost_multiplier":99}',rate_multiplier=77 WHERE id=$1`, f.account)
+ require.NoError(t, err)
+ repo := newUsageLogRepositoryWithSQL(integrationEntClient, integrationDB)
+ for i, target := range []string{"openai", "kimi"} {
+ factor := []float64{.7, .1}[i]
+ _, err = repo.createSingle(t.Context(), integrationDB, &service.UsageLog{UserID: f.user, APIKeyID: f.key, AccountID: f.account,
+ RequestID: fmt.Sprintf("procurement-mixed-%d-%d", f.account, i), Platform: target, Model: "fixture-model", TotalCost: 10, ActualCost: 3,
+ CreatedAt: now.Add(-time.Hour), ProcurementCostSnapshot: procurementFixtureSnapshot(target, &factor)})
+ require.NoError(t, err)
+ }
+ filter := service.UpstreamOperationsFilter{From: now.Add(-24 * time.Hour), Until: now, AccountID: f.account, Dimension: "account", ModelScope: "public", Sort: "requests", Direction: "desc", Page: 1, PageSize: 20}
+ read := func() map[string]any {
+ out, err := f.repo.ReadProfitOperations(t.Context(), filter)
+ require.NoError(t, err)
+ var data map[string]any
+ require.NoError(t, json.Unmarshal(out.Usage, &data))
+ return data["summary"].(map[string]any)
+ }
+ summary := read()
+ require.Equal(t, 8.0, summary["estimated_cost"], "10*.7 + 10*.1 exactly once; never account debit 77 or current cost 99")
+ require.Equal(t, 6.0, summary["request_income"])
+ require.Equal(t, -2.0, summary["estimated_profit"])
+ _, err = integrationDB.Exec(`UPDATE accounts SET extra='{"cost_multiplier":0.01}',rate_multiplier=1 WHERE id=$1`, f.account)
+ require.NoError(t, err)
+ require.Equal(t, summary["estimated_cost"], read()["estimated_cost"], "account edits cannot reprice captured requests")
+ factor := .7
+ future := procurementFixtureSnapshot("openai", &factor)
+ future.Version = 99
+ for i, snapshot := range []*service.ProcurementCostSnapshot{nil, procurementFixtureSnapshot("openai", nil), future, procurementFixtureSnapshot("kimi", &factor)} {
+ _, err = repo.createSingle(t.Context(), integrationDB, &service.UsageLog{UserID: f.user, APIKeyID: f.key, AccountID: f.account,
+ RequestID: fmt.Sprintf("procurement-unknown-%d-%d", f.account, i), Platform: "openai", Model: "fixture-model", TotalCost: 10, ActualCost: 3,
+ CreatedAt: now.Add(-time.Hour), ProcurementCostSnapshot: snapshot})
+ require.NoError(t, err)
+ }
+ summary = read()
+ require.Nil(t, summary["estimated_cost"])
+ require.Equal(t, 4.0, summary["unknown_cost_requests"], "missing, captured unknown, unsupported version and mismatched target all stay unknown")
+ require.Equal(t, 8.0, summary["covered_estimated_cost"])
+}
+
+func TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched(t *testing.T) {
+ tx, err := integrationDB.BeginTx(context.Background(), nil)
+ require.NoError(t, err)
+ defer func() { _ = tx.Rollback() }()
+ _, err = tx.Exec(`CREATE TEMP TABLE usage_logs(id bigint,total_cost numeric,actual_cost numeric) ON COMMIT DROP; INSERT INTO usage_logs VALUES(1,10,3)`)
+ require.NoError(t, err)
+ sql, err := migrations.FS.ReadFile("392_usage_procurement_cost_snapshot.sql")
+ require.NoError(t, err)
+ for i := 0; i < 2; i++ {
+ _, err = tx.Exec(string(sql))
+ require.NoError(t, err)
+ }
+ var unchanged bool
+ require.NoError(t, tx.QueryRow(`SELECT procurement_cost_snapshot IS NULL AND total_cost=10 AND actual_cost=3 FROM usage_logs WHERE id=1`).Scan(&unchanged))
+ require.True(t, unchanged)
+}
diff --git a/backend/internal/repository/profit_operations.go b/backend/internal/repository/profit_operations.go
index 648f4643265a..537ec80b3a97 100644
--- a/backend/internal/repository/profit_operations.go
+++ b/backend/internal/repository/profit_operations.go
@@ -21,6 +21,7 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea
var accounts []struct {
operationsAccount
Multiplier *float64 `json:"multiplier"`
+ AccountType string `json:"account_type"`
CostBasis string `json:"cost_basis"`
URLKey string `json:"url_key"`
URLAttribution string `json:"url_attribution"`
@@ -37,16 +38,18 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea
if err = json.Unmarshal(raw, &accounts); err != nil {
return nil, err
}
- rows, err := tx.QueryContext(ctx, `SELECT id,extra->'cost_multiplier' FROM accounts WHERE id IN (SELECT id FROM jsonb_to_recordset($1::jsonb) c(id bigint))`, string(raw))
+ rows, err := tx.QueryContext(ctx, `SELECT id,type,extra->'cost_multiplier' FROM accounts WHERE id IN (SELECT id FROM jsonb_to_recordset($1::jsonb) c(id bigint))`, string(raw))
if err != nil {
return nil, err
}
defer func() { _ = rows.Close() }()
costs := map[int64]any{}
+ accountTypes := map[int64]string{}
for rows.Next() {
var id int64
var value []byte
- if err = rows.Scan(&id, &value); err != nil {
+ var accountType string
+ if err = rows.Scan(&id, &accountType, &value); err != nil {
return nil, err
}
var cost any
@@ -56,6 +59,7 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea
}
}
costs[id] = cost
+ accountTypes[id] = accountType
}
if err = rows.Err(); err != nil {
return nil, err
@@ -66,6 +70,11 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea
v, basis := service.OperationsCostMultiplier(&service.Account{Extra: map[string]any{"cost_multiplier": costs[id]}})
a.Multiplier = v
a.CostBasis = basis
+ a.AccountType = accountTypes[id]
+ if a.AccountType == service.AccountTypeGateway {
+ a.Multiplier = nil
+ a.CostBasis = "request_procurement_unknown"
+ }
}
if err = rows.Close(); err != nil {
return nil, err
@@ -178,11 +187,25 @@ func profitOAuthChannels(ctx context.Context, tx *sql.Tx, raw string) (map[int64
}
const profitOperationsCohort = `accounts_config AS (
- SELECT * FROM jsonb_to_recordset($3::jsonb) AS c(id bigint,name text,key text,attribution text,updated_at timestamptz,deleted boolean,multiplier numeric,cost_basis text,schedulable boolean,concurrency integer,status text,url_key text,url_attribution text,url_channel_id bigint,url_origin_hash text,channel_id bigint,channel_name text,channel_code text,channel_remark text,channel_revision bigint,assignment text,oauth_channel_id bigint)
+ SELECT * FROM jsonb_to_recordset($3::jsonb) AS c(id bigint,name text,key text,attribution text,updated_at timestamptz,deleted boolean,multiplier numeric,cost_basis text,schedulable boolean,concurrency integer,status text,url_key text,url_attribution text,url_channel_id bigint,url_origin_hash text,channel_id bigint,channel_name text,channel_code text,channel_remark text,channel_revision bigint,assignment text,oauth_channel_id bigint,account_type text)
), cohort AS (
SELECT * FROM accounts_config WHERE ($4='' OR key=$4) AND ($5::bigint=0 OR id=$5) AND ($11::bigint=0 OR channel_id=$11)
)`
+// A captured unknown/unsupported snapshot never falls back to today's account
+// settings. The multiplier already includes New API's request-target x1/x7.
+const profitRequestCostMultiplierSQL = `CASE WHEN u.procurement_cost_snapshot IS NOT NULL THEN
+ CASE WHEN u.procurement_cost_snapshot->>'version'='1'
+ AND u.procurement_cost_snapshot->>'basis'='total_cost'
+ AND u.procurement_cost_snapshot->>'account_type'='gateway'
+ AND u.procurement_cost_snapshot->>'provider' IN ('new_api','sub2api')
+ AND u.procurement_cost_snapshot->>'target_platform'=u.platform
+ AND u.platform<>'' AND u.platform<>'composite'
+ AND jsonb_typeof(u.procurement_cost_snapshot->'cost_multiplier')='number'
+ THEN CASE WHEN (u.procurement_cost_snapshot->>'cost_multiplier')::numeric BETWEEN 0 AND 1000000
+ THEN (u.procurement_cost_snapshot->>'cost_multiplier')::numeric END END
+ WHEN c.account_type='gateway' THEN NULL ELSE c.multiplier END`
+
// Join the complete projection before applying the selected cohort. Joining only
// cohort would turn every configured account outside it into account_missing.
const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS (
@@ -190,7 +213,9 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS
u.account_stats_cost,u.input_tokens,u.output_tokens,u.cache_read_tokens,u.cache_creation_tokens,u.duration_ms,u.billing_type,u.created_at,u.queue_timing,u.queue_wait_ms,
COALESCE('channel:'||owner.channel_id::text,c.url_key,'unknown:account_missing') AS upstream_key,
CASE WHEN e.channel_id IS NOT NULL OR h.channel_id IS NOT NULL THEN 'historical_channel' WHEN legacy.channel_id IS NOT NULL THEN 'legacy_channel_estimate' WHEN owner.channel_id IS NOT NULL THEN 'provider_url' ELSE COALESCE(c.url_attribution,'account_missing') END AS attribution,
- c.name AS account_name,c.updated_at AS config_updated_at,c.deleted,c.multiplier,owner.channel_id AS explicit_channel_id,ch.name AS channel_name,ch.code AS channel_code,ch.remark AS channel_remark,ch.revision AS channel_revision,p.id AS provider_id,p.site_type AS provider_site_type,
+ c.name AS account_name,c.updated_at AS config_updated_at,c.deleted,` + profitRequestCostMultiplierSQL + ` AS multiplier,
+ u.procurement_cost_snapshot IS NOT NULL AS has_procurement_snapshot,
+ owner.channel_id AS explicit_channel_id,ch.name AS channel_name,ch.code AS channel_code,ch.remark AS channel_remark,ch.revision AS channel_revision,p.id AS provider_id,p.site_type AS provider_site_type,
CASE WHEN snap.amount IS NOT NULL THEN snap.amount
WHEN $18::bool AND jsonb_typeof(p.metrics->'today_spend')='number' AND p.observed_at>=$12::timestamptz AND p.observed_at<$13::timestamptz THEN (p.metrics->>'today_spend')::numeric END AS wallet_spend,
CASE WHEN snap.amount IS NOT NULL AND snap.currency IN ('USD','CNY','quota_units') THEN snap.currency
@@ -203,7 +228,8 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS
CASE WHEN h.assignment='manual_unlinked' AND owner.channel_id IS NOT NULL THEN CASE WHEN c.url_key='unknown:oauth_dynamic_endpoint' THEN 'provider_import' ELSE 'provider_url' END END,
h.assignment,
CASE WHEN legacy.channel_id IS NOT NULL THEN 'explicit' WHEN owner.channel_id IS NOT NULL AND c.url_key='unknown:oauth_dynamic_endpoint' THEN 'provider_import' WHEN owner.channel_id IS NOT NULL THEN 'provider_url' WHEN c.url_key IS NULL OR c.url_key LIKE 'unknown:%' THEN 'unbound_unknown' ELSE 'unbound_url' END) AS assignment,
- e.amount AS upstream_reported,e.settled_amount AS upstream_debit,COALESCE(c.cost_basis,'account_missing') AS cost_basis,
+ e.amount AS upstream_reported,e.settled_amount AS upstream_debit,
+ CASE WHEN u.procurement_cost_snapshot IS NOT NULL THEN 'request_procurement_snapshot' ELSE COALESCE(c.cost_basis,'account_missing') END AS cost_basis,
COALESCE(NULLIF(u.requested_model,''),u.model) AS public_model,
u.total_cost AS cost_base
FROM usage_logs u LEFT JOIN accounts_config c ON c.id=u.account_id
@@ -399,9 +425,9 @@ func (r *channelRepository) ReadProfitOperations(ctx context.Context, f service.
'catalog',COALESCE((SELECT jsonb_agg(to_jsonb(g)) FROM (SELECT key AS key,COALESCE(NULLIF(max(channel_name),''),key) AS name,max(channel_id) AS channel_id,max(channel_code) AS channel_code,max(channel_remark) AS channel_remark,max(channel_revision) AS channel_revision,max(assignment) AS assignment,count(*) AS accounts FROM cohort c WHERE NOT deleted AND ($6::bigint=0 OR EXISTS(SELECT 1 FROM account_groups ag WHERE ag.account_id=c.id AND ag.group_id=$6)) GROUP BY key ORDER BY key LIMIT $9 OFFSET $10)g),'[]'::jsonb),
'capacity',(SELECT jsonb_build_object('accounts',count(*),'schedulable',count(*) FILTER(WHERE schedulable AND status='active'),'configured_concurrency',COALESCE(sum(concurrency),0)) FROM cohort c WHERE NOT deleted AND ($6::bigint=0 OR EXISTS(SELECT 1 FROM account_groups ag WHERE ag.account_id=c.id AND ag.group_id=$6))),
'catalog_total',(SELECT count(DISTINCT key) FROM cohort c WHERE NOT deleted AND ($6::bigint=0 OR EXISTS(SELECT 1 FROM account_groups ag WHERE ag.account_id=c.id AND ag.group_id=$6))),
- 'account_details_limit',100,'historical_upstream_snapshot_requests',(SELECT count(*) FROM priced WHERE attribution='historical_channel'),'historical_cost_multiplier_snapshot_requests',0,
+ 'account_details_limit',100,'historical_upstream_snapshot_requests',(SELECT count(*) FROM priced WHERE attribution='historical_channel'),'historical_cost_multiplier_snapshot_requests',(SELECT count(*) FROM priced WHERE has_procurement_snapshot AND multiplier IS NOT NULL),
'wallet_synced_at',(SELECT to_jsonb(max(observed_at)) FROM provider_spend_snapshots WHERE window_from=$1 AND window_until=$2 AND amount IS NOT NULL),
- 'cost_formula','bound channel: provider_spend_snapshots for this exact window (today also falls back to channel-operations today_spend); wallet total is not split by account or model; unbound channel: usage_logs.total_cost * current extra.cost_multiplier (default 0.1)',
+ 'cost_formula','request procurement estimate: persisted usage_logs.total_cost * captured procurement multiplier once; unknown gateway snapshots stay unknown; legacy estimate: total_cost * current extra.cost_multiplier (default 0.1); bound channel wallet accounting is unchanged and never split across requests',
'income_source','persisted usage_logs.actual_cost; subscription usage valuation, not cash receipts; no guarantee of debit in simple mode',
'standard_source','persisted usage_logs.total_cost; historical model/cache/per-request pricing is not recalculated',
'account_rate_multiplier_used',false,'error_rate',NULL)`
diff --git a/backend/internal/repository/usage_billing_admission_recovery_integration_test.go b/backend/internal/repository/usage_billing_admission_recovery_integration_test.go
index 88d89226cf8c..6ebecbe88f77 100644
--- a/backend/internal/repository/usage_billing_admission_recovery_integration_test.go
+++ b/backend/internal/repository/usage_billing_admission_recovery_integration_test.go
@@ -79,8 +79,8 @@ func requireBillingOwnerRefs(t *testing.T, repo *usageBillingRepository, user in
type admissionRecoverySnapshot struct {
State, Failure, Payload, Result, Balance, Quota string
- Attempts, Logs, Claims int
- NextAttempt, StagedAt time.Time
+ Attempts, Logs, Claims int
+ NextAttempt, StagedAt time.Time
}
func readAdmissionRecoverySnapshot(t *testing.T, repo *usageBillingRepository, cmd service.UsageBillingCommand) admissionRecoverySnapshot {
diff --git a/backend/internal/repository/usage_log_repo_insert.go b/backend/internal/repository/usage_log_repo_insert.go
index 3029981b3c3c..1ffc75ac92e8 100644
--- a/backend/internal/repository/usage_log_repo_insert.go
+++ b/backend/internal/repository/usage_log_repo_insert.go
@@ -92,6 +92,7 @@ var usageLogInsertArgTypes = [...]string{
"jsonb", // queue_timing
"text", // platform
"jsonb", // customer_cost_details
+ "jsonb", // procurement_cost_snapshot
}
const (
@@ -298,14 +299,15 @@ func (r *usageLogRepository) createSingle(ctx context.Context, sqlq sqlExecutor,
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9,
$10, $11,
$12, $13, $14, $15,
$16, $17, $18, $19,
$20, $21, $22, $23, $24, $25,
- $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68
+ $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68, $69
)
ON CONFLICT (request_id, api_key_id) DO NOTHING
RETURNING id, created_at
@@ -764,7 +766,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
) AS (VALUES `)
// Each batch row prepends the synthetic input_index before the 61
@@ -865,7 +868,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
)
SELECT
user_id,
@@ -935,7 +939,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
FROM input
ON CONFLICT (request_id, api_key_id) DO NOTHING
RETURNING request_id, api_key_id, id, created_at
@@ -1045,7 +1050,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) (
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
) AS (VALUES `)
args := make([]any, 0, len(preparedList)*60)
@@ -1141,7 +1147,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) (
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
)
SELECT
user_id,
@@ -1211,7 +1218,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) (
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
FROM input
ON CONFLICT (request_id, api_key_id) DO NOTHING
`)
@@ -1289,14 +1297,15 @@ func execUsageLogInsertNoResult(ctx context.Context, sqlq sqlExecutor, prepared
created_at,
queue_timing,
platform,
- customer_cost_details
+ customer_cost_details,
+ procurement_cost_snapshot
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9,
$10, $11,
$12, $13, $14, $15,
$16, $17, $18, $19,
$20, $21, $22, $23, $24, $25,
- $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68
+ $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68, $69
)
ON CONFLICT (request_id, api_key_id) DO NOTHING
`, prepared.args...)
@@ -1321,6 +1330,12 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared {
duration := nullInt(log.DurationMs)
firstToken := nullInt(log.FirstTokenMs)
queueWait := nullInt(log.QueueWaitMs)
+ var procurementCostSnapshot any
+ if log.ProcurementCostSnapshot != nil {
+ if raw, err := json.Marshal(log.ProcurementCostSnapshot); err == nil {
+ procurementCostSnapshot = string(raw)
+ }
+ }
var customerCostDetails any
if log.CustomerCostDetails != nil {
if raw, err := json.Marshal(log.CustomerCostDetails); err == nil {
@@ -1439,6 +1454,7 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared {
queueTiming,
nullString(&log.Platform),
customerCostDetails,
+ procurementCostSnapshot,
},
}
}
diff --git a/backend/internal/repository/usage_log_repo_query.go b/backend/internal/repository/usage_log_repo_query.go
index ad7d1b83640f..fbae0551cdf5 100644
--- a/backend/internal/repository/usage_log_repo_query.go
+++ b/backend/internal/repository/usage_log_repo_query.go
@@ -19,7 +19,7 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
)
-const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, queue_wait_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, cache_creation_30m_tokens, cache_creation_12h_tokens, created_at, queue_timing, platform, customer_cost_details"
+const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, queue_wait_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, cache_creation_30m_tokens, cache_creation_12h_tokens, created_at, queue_timing, platform, customer_cost_details, procurement_cost_snapshot"
func (r *usageLogRepository) GetByID(ctx context.Context, id int64) (log *service.UsageLog, err error) {
query := "SELECT " + usageLogSelectColumns + " FROM usage_logs WHERE id = $1"
@@ -507,6 +507,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e
cacheCreation30m int
cacheCreation12h int
createdAt time.Time
+ procurementCostSnapshot sql.NullString
customerCostDetails sql.NullString
queueTiming sql.NullString
platform sql.NullString
@@ -582,6 +583,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e
&queueTiming,
&platform,
&customerCostDetails,
+ &procurementCostSnapshot,
); err != nil {
return nil, err
}
@@ -623,6 +625,13 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e
LongContextBillingApplied: longContextBillingApplied,
CreatedAt: createdAt,
}
+ if procurementCostSnapshot.Valid {
+ var snapshot service.ProcurementCostSnapshot
+ if err := json.Unmarshal([]byte(procurementCostSnapshot.String), &snapshot); err != nil {
+ return nil, err
+ }
+ log.ProcurementCostSnapshot = &snapshot
+ }
if customerCostDetails.Valid {
var detail service.CustomerCostDetails
if json.Unmarshal([]byte(customerCostDetails.String), &detail) == nil {
diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go
index 8024f90190b3..35e4298d2161 100644
--- a/backend/internal/repository/usage_log_repo_request_type_test.go
+++ b/backend/internal/repository/usage_log_repo_request_type_test.go
@@ -109,6 +109,7 @@ func TestUsageLogRepositoryCreateSyncRequestTypeAndLegacyFields(t *testing.T) {
sqlmock.AnyArg(), // queue_timing
sql.NullString{}, // platform
nil, // customer_cost_details
+ nil, // procurement_cost_snapshot
).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(99), createdAt))
@@ -210,6 +211,7 @@ func TestUsageLogRepositoryCreate_PersistsServiceTier(t *testing.T) {
sqlmock.AnyArg(), // queue_timing
sql.NullString{}, // platform
nil, // customer_cost_details
+ nil, // procurement_cost_snapshot
).
WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(100), createdAt))
@@ -290,8 +292,8 @@ func TestPrepareUsageLogInsert_PersistsNativeCompactionV2WithoutChangingRequestT
prepared := prepareUsageLogInsert(log)
require.Len(t, prepared.args, len(usageLogInsertArgTypes))
- require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-7])
- require.Equal(t, true, prepared.args[len(prepared.args)-7])
+ require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-8])
+ require.Equal(t, true, prepared.args[len(prepared.args)-8])
require.Equal(t, int16(service.RequestTypeStream), prepared.args[30])
require.Equal(t, service.RequestTypeStream, log.RequestType)
require.True(t, log.Stream)
@@ -979,6 +981,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // queue_timing
sql.NullString{}, // platform
sql.NullString{}, // customer_cost_details
+ sql.NullString{}, // procurement_cost_snapshot
}})
require.NoError(t, err)
require.Equal(t, 2, log.ImageCount)
@@ -1065,6 +1068,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // queue_timing
sql.NullString{}, // platform
sql.NullString{}, // customer_cost_details
+ sql.NullString{}, // procurement_cost_snapshot
}})
require.NoError(t, err)
require.NotNil(t, log.ServiceTier)
@@ -1134,6 +1138,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // queue_timing
sql.NullString{}, // platform
sql.NullString{}, // customer_cost_details
+ sql.NullString{}, // procurement_cost_snapshot
}})
require.NoError(t, err)
require.NotNil(t, log.ServiceTier)
@@ -1204,6 +1209,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) {
sql.NullString{}, // queue_timing
sql.NullString{}, // platform
sql.NullString{}, // customer_cost_details
+ sql.NullString{}, // procurement_cost_snapshot
}})
require.NoError(t, err)
require.NotNil(t, log.ServiceTier)
diff --git a/backend/internal/repository/usage_log_session_id_unit_test.go b/backend/internal/repository/usage_log_session_id_unit_test.go
index 8c8649598493..6263ebd63c7a 100644
--- a/backend/internal/repository/usage_log_session_id_unit_test.go
+++ b/backend/internal/repository/usage_log_session_id_unit_test.go
@@ -30,7 +30,7 @@ func newSessionIDUsageLog(sessionID *string) *service.UsageLog {
// TestPrepareUsageLogInsert_SessionIDArgWiring pins the session_id column to the
// arg slice / arg-type table so the five INSERT column lists stay in sync. session_id
-// is immediately before native_compaction_v2; created_at, queue_timing, platform and customer_cost_details follow.
+// is immediately before native_compaction_v2; created_at, queue_timing, platform, customer_cost_details and procurement_cost_snapshot follow.
func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) {
sessionID := "sess-persisted-123"
prepared := prepareUsageLogInsert(newSessionIDUsageLog(&sessionID))
@@ -38,16 +38,16 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) {
require.Len(t, prepared.args, len(usageLogInsertArgTypes),
"prepared args must match the arg-type table length")
- // session_id precedes native_compaction_v2, both TTL counters, created_at, queue_timing, platform and customer_cost_details.
- sessionArg := prepared.args[len(prepared.args)-8]
+ // session_id precedes native_compaction_v2, both TTL counters, created_at, queue_timing, platform, customer_cost_details and procurement_cost_snapshot.
+ sessionArg := prepared.args[len(prepared.args)-9]
ns, ok := sessionArg.(sql.NullString)
require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg)
require.True(t, ns.Valid)
require.Equal(t, sessionID, ns.String)
- require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-8],
+ require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-9],
"session_id arg type must be text")
- require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-7],
+ require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-8],
"native_compaction_v2 arg type must be boolean")
}
@@ -55,14 +55,14 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) {
// persisted as SQL NULL rather than an empty string.
func TestPrepareUsageLogInsert_SessionIDNullWhenAbsent(t *testing.T) {
prepared := prepareUsageLogInsert(newSessionIDUsageLog(nil))
- sessionArg := prepared.args[len(prepared.args)-8]
+ sessionArg := prepared.args[len(prepared.args)-9]
ns, ok := sessionArg.(sql.NullString)
require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg)
require.False(t, ns.Valid, "absent session id must be NULL, not empty string")
empty := ""
preparedEmpty := prepareUsageLogInsert(newSessionIDUsageLog(&empty))
- nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-8].(sql.NullString)
+ nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-9].(sql.NullString)
require.False(t, nsEmpty.Valid, "empty session id must also be NULL")
}
diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go
index d25a19a8dc49..91d12f52f39c 100644
--- a/backend/internal/service/account.go
+++ b/backend/internal/service/account.go
@@ -79,6 +79,14 @@ type Account struct {
GroupIDs []int64
Groups []*Group
+ // Request-local transport binding only; never persisted or exported. Final
+ // admission compares the neutral gateway identity before rebuilding a view.
+ gatewayProtocolSource *Account
+ gatewayProtocolModel string
+ gatewayBindingModel string
+ gatewayMessagesView *Account
+ gatewaySelectionTarget string
+
// model_mapping 热路径缓存(非持久化字段)
modelMappingCache map[string]string
modelMappingCacheReady bool
@@ -276,6 +284,11 @@ func accountLoadPreferenceRate(account *Account, loadRate int) int {
}
func (a *Account) IsSchedulable() bool {
+ // Fail closed until the four gateway protocols and their final admission
+ // checks are implemented together. Manual switches cannot bypass this gate.
+ if a.IsGateway() || a.Platform == PlatformGateway {
+ return false
+ }
if !a.IsActive() || !a.Schedulable || a.PerformancePaused {
return false
}
diff --git a/backend/internal/service/account_group.go b/backend/internal/service/account_group.go
index 5b27d18bda65..e6eaeab1fbc3 100644
--- a/backend/internal/service/account_group.go
+++ b/backend/internal/service/account_group.go
@@ -98,6 +98,9 @@ func (a *Account) IsModelAllowedInGroup(groupID *int64, requestedModel string) b
if a == nil || groupID == nil {
return true
}
+ if a.gatewayBindingModel != "" {
+ requestedModel = a.gatewayBindingModel
+ }
allowed := a.GroupAllowedModels(*groupID)
if len(allowed) == 0 {
return true
diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go
index db9ce856fe8f..9c386fc0a4e8 100644
--- a/backend/internal/service/account_service.go
+++ b/backend/internal/service/account_service.go
@@ -149,6 +149,13 @@ type AccountDuplicateRepository interface {
CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error
}
+// GatewayAccountTransactionRepository keeps the new gateway's settings, exact
+// memberships and outbox writes in one transaction. Legacy accounts retain
+// their existing write paths. The callback receives the repository's tx context.
+type GatewayAccountTransactionRepository interface {
+ WithinGatewayAccountTransaction(ctx context.Context, accountID int64, groupIDs []int64, run func(context.Context) error) error
+}
+
// AccountBillingSettingsRepository applies an admin edit without overwriting a
// rate_multiplier that a successful upstream probe synchronized after the edit
// form was loaded. A nil rateMultiplier means the request did not edit it.
@@ -243,6 +250,12 @@ func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository)
// Create 创建账号
func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (*Account, error) {
+ if err := ValidateGatewayAccountIdentity(req.Platform, req.Type, req.Credentials); err != nil {
+ return nil, err
+ }
+ if err := validateGatewayAccountGroups(ctx, &Account{Platform: req.Platform, Type: req.Type}, s.groupRepo, req.GroupIDs); err != nil {
+ return nil, err
+ }
if err := ValidateModelMappingMode(req.Credentials); err != nil {
return nil, err
}
@@ -276,6 +289,18 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (
account.AutoPauseOnExpired = true
}
+ if account.IsGateway() {
+ if creator, ok := s.accountRepo.(AccountDuplicateRepository); ok {
+ groups := make([]AccountGroup, 0, len(req.GroupIDs))
+ for i, id := range req.GroupIDs {
+ groups = append(groups, AccountGroup{GroupID: id, Priority: i + 1})
+ }
+ if err := creator.CreateWithAccountGroups(ctx, account, groups); err != nil {
+ return nil, err
+ }
+ return account, nil
+ }
+ }
if err := s.accountRepo.Create(ctx, account); err != nil {
return nil, fmt.Errorf("create account: %w", err)
}
@@ -353,6 +378,35 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount
}
// 更新字段
+ if account.IsGateway() || account.Platform == PlatformGateway {
+ credentials := account.Credentials
+ if req.Credentials != nil {
+ credentials = mergeGatewayCredentials(account.Credentials, *req.Credentials)
+ req.Credentials = &credentials
+ }
+ if err := ValidateGatewayAccountIdentity(account.Platform, account.Type, credentials); err != nil {
+ return nil, err
+ }
+ ids := account.GroupIDs
+ if req.GroupIDs != nil {
+ ids = *req.GroupIDs
+ }
+ if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, ids); err != nil {
+ return nil, err
+ }
+ if !gatewayAccountTransactionActive(ctx) {
+ var updated *Account
+ err := withinGatewayAccountTransaction(ctx, s.accountRepo, id, ids, func(txctx context.Context) error {
+ var err error
+ updated, err = s.Update(txctx, id, req)
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+ return updated, err
+ }
+ }
if req.Name != nil {
account.Name = *req.Name
}
diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go
index e025b5d1f6a0..f178cb697fe3 100644
--- a/backend/internal/service/account_test_service.go
+++ b/backend/internal/service/account_test_service.go
@@ -409,6 +409,9 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int
}
}
bindAccountTestPlatform(c, account)
+ if account.gatewayProtocolsPending() {
+ return s.sendErrorAndEnd(c, ErrGatewayProtocolsPending.Error())
+ }
recordQualityBatchRoute(c, account, modelID, account.Platform+":"+account.GetAPIProtocol())
if expected, ok := ctx.Value(modelTraceContextKey{}).(modelTraceEnvironment); ok {
actual, err := modelTraceEnvironmentForAccount(account, modelID)
diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go
index 33735d87592f..36ef7aa78760 100644
--- a/backend/internal/service/admin_account.go
+++ b/backend/internal/service/admin_account.go
@@ -432,6 +432,9 @@ func normalizeOpenAILongContextBillingUpdateExtra(account *Account, input *Updat
// Grok media eligibility helpers live in account_grok_media_eligibility.go.
func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) {
+ if err := ValidateGatewayAccountIdentity(input.Platform, input.Type, input.Credentials); err != nil {
+ return nil, err
+ }
if err := ValidateAccountProbePenaltyExtra(accountExtra); err != nil {
return nil, err
}
@@ -471,7 +474,7 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an
Concurrency: normalizeAccountConcurrency(input.Platform, input.Type, input.Concurrency),
Priority: input.Priority,
Status: StatusActive,
- Schedulable: input.InitialAdmissionPlan == nil,
+ Schedulable: input.InitialAdmissionPlan == nil && input.Type != AccountTypeGateway,
}
if input.ProbeEnabled != nil && *input.ProbeEnabled {
if !isUpstreamBillingProbeAccount(account) {
@@ -521,6 +524,15 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an
}
func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error) {
+ if input == nil {
+ return nil, ErrAccountNilInput
+ }
+ if err := ValidateGatewayAccountIdentity(input.Platform, input.Type, input.Credentials); err != nil {
+ return nil, err
+ }
+ if err := validateGatewayAccountGroups(ctx, &Account{Platform: input.Platform, Type: input.Type}, s.groupRepo, input.GroupIDs); err != nil {
+ return nil, err
+ }
if err := ValidateAccountCostMultiplierExtra(input.Extra); err != nil {
return nil, err
}
@@ -555,7 +567,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
// 绑定分组
groupIDs := input.GroupIDs
// 如果没有指定分组,自动绑定对应平台的默认分组
- if len(groupIDs) == 0 && !input.SkipDefaultGroupBind {
+ if len(groupIDs) == 0 && !input.SkipDefaultGroupBind && input.Type != AccountTypeGateway {
defaultGroupName := input.Platform + "-default"
groups, err := s.groupRepo.ListActiveByPlatform(ctx, input.Platform)
if err == nil {
@@ -602,14 +614,18 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil {
return nil, err
}
- if (account.InitialAdmissionPlan != nil || account.InitialAPIKeyDisposition != nil) && s.accountDuplicateRepo != nil {
+ atomicCreator := s.accountDuplicateRepo
+ if account.IsGateway() && atomicCreator == nil {
+ atomicCreator, _ = s.accountRepo.(AccountDuplicateRepository)
+ }
+ if (account.IsGateway() || account.InitialAdmissionPlan != nil || account.InitialAPIKeyDisposition != nil) && atomicCreator != nil {
// Publish the initially blocked account, its groups and both background
// plans atomically; the worker cannot race a partially bound import.
groups := make([]AccountGroup, 0, len(groupIDs))
for _, id := range groupIDs {
groups = append(groups, AccountGroup{GroupID: id, Priority: 50})
}
- if err := s.accountDuplicateRepo.CreateWithAccountGroups(ctx, account, groups); err != nil {
+ if err := atomicCreator.CreateWithAccountGroups(ctx, account, groups); err != nil {
return nil, err
}
} else {
@@ -655,7 +671,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou
}
func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *UpdateAccountInput) (*Account, error) {
- if input.Platform != "" && s.entClient != nil && dbent.TxFromContext(ctx) == nil {
+ if input.Platform != "" && input.Platform != PlatformGateway && s.entClient != nil && dbent.TxFromContext(ctx) == nil {
return s.scopedAdminTransaction(ctx, id, false, func(txctx context.Context) (*Account, error) {
return s.UpdateAccount(txctx, id, input)
})
@@ -681,6 +697,28 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
if err != nil {
return nil, err
}
+ if err := validateGatewayAccountUpdate(account, input); err != nil {
+ return nil, err
+ }
+ gatewayGroupIDs := account.GroupIDs
+ if input.GroupIDs != nil {
+ gatewayGroupIDs = *input.GroupIDs
+ }
+ if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, gatewayGroupIDs); err != nil {
+ return nil, err
+ }
+ if account.IsGateway() && !gatewayAccountTransactionActive(ctx) {
+ var updated *Account
+ err := withinGatewayAccountTransaction(ctx, s.accountRepo, id, gatewayGroupIDs, func(txctx context.Context) error {
+ var err error
+ updated, err = s.UpdateAccount(txctx, id, input)
+ return err
+ })
+ if err != nil {
+ return nil, err
+ }
+ return updated, err
+ }
if err := prepareVertexAuthModeUpdate(account, input); err != nil {
return nil, err
}
@@ -767,7 +805,11 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U
} else if len(input.Credentials) > 0 {
// 敏感子键采用"incoming 没提供就保留"的合并语义:前端响应已脱敏,
// 全对象 PUT 编辑时不会再带回 token,避免覆盖时清空已有凭证。
- account.Credentials = MergePreservingSensitiveCreds(account.Credentials, input.Credentials)
+ if account.IsGateway() {
+ account.Credentials = mergeGatewayCredentials(account.Credentials, input.Credentials)
+ } else {
+ account.Credentials = MergePreservingSensitiveCreds(account.Credentials, input.Credentials)
+ }
if err := validateQwenCacheCredentials(account.Credentials); err != nil {
return nil, err
}
@@ -1245,13 +1287,26 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。
var cachedTargets []*Account
- if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || hasExcelBPSProxyUpdates(input.Extra) {
+ if len(input.Credentials) > 0 || input.ProxyID != nil || input.GroupIDs != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || hasExcelBPSProxyUpdates(input.Extra) {
loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs)
if err != nil {
return nil, err
}
cachedTargets = loaded
}
+ for _, account := range cachedTargets {
+ if account == nil || (!account.IsGateway() && account.Platform != PlatformGateway) {
+ continue
+ }
+ if err := ValidateGatewayAccountIdentity(account.Platform, account.Type, mergeGatewayCredentials(account.Credentials, input.Credentials)); err != nil {
+ return nil, err
+ }
+ if input.GroupIDs != nil {
+ if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, *input.GroupIDs); err != nil {
+ return nil, err
+ }
+ }
+ }
targetsByID := make(map[int64]*Account, len(cachedTargets))
for _, account := range cachedTargets {
if account != nil {
@@ -1485,10 +1540,25 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
if s.excelOAuthReauth != nil && bpsChanged {
repoUpdates.ExcelBPSAuthorizationPending = pendingByAccount
}
- if _, err := s.accountRepo.BulkUpdate(ctx, input.AccountIDs, repoUpdates); err != nil {
- return nil, err
+ // A failed gateway binding must roll back its metadata too. Keep legacy
+ // accounts on the existing batch path; each gateway with a membership edit
+ // commits its own fields+groups atomically and reports its own result.
+ legacyIDs := make([]int64, 0, len(input.AccountIDs))
+ gatewayIDs := make(map[int64]bool)
+ for _, id := range input.AccountIDs {
+ if input.GroupIDs != nil && targetsByID[id] != nil && targetsByID[id].IsGateway() {
+ gatewayIDs[id] = true
+ } else {
+ legacyIDs = append(legacyIDs, id)
+ }
+ }
+ if len(legacyIDs) > 0 {
+ if _, err := s.accountRepo.BulkUpdate(ctx, legacyIDs, repoUpdates); err != nil {
+ return nil, err
+ }
}
+ gatewayWriteCtx := ctx
ctx = accounttimer.WithoutManualIntent(ctx)
// 将 proxy 变更传播到每个目标账号的 spark 影子账号
@@ -1497,7 +1567,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
if *repoUpdates.ProxyID != 0 {
effectiveProxyID = repoUpdates.ProxyID
}
- for _, accountID := range input.AccountIDs {
+ for _, accountID := range legacyIDs {
if err := s.propagateProxyToShadows(ctx, accountID, effectiveProxyID); err != nil {
return nil, err
}
@@ -1508,15 +1578,24 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
for _, accountID := range input.AccountIDs {
entry := BulkUpdateAccountResult{AccountID: accountID}
- if input.GroupIDs != nil {
- if err := s.accountRepo.BindGroups(ctx, accountID, *input.GroupIDs); err != nil {
- entry.Success = false
- entry.Error = err.Error()
- result.Failed++
- result.FailedIDs = append(result.FailedIDs, accountID)
- result.Results = append(result.Results, entry)
- continue
- }
+ var bindingErr error
+ if gatewayIDs[accountID] {
+ bindingErr = withinGatewayAccountTransaction(gatewayWriteCtx, s.accountRepo, accountID, *input.GroupIDs, func(txctx context.Context) error {
+ if _, err := s.accountRepo.BulkUpdate(txctx, []int64{accountID}, repoUpdates); err != nil {
+ return err
+ }
+ return s.accountRepo.BindGroups(accounttimer.WithoutManualIntent(txctx), accountID, *input.GroupIDs)
+ })
+ } else if input.GroupIDs != nil {
+ bindingErr = s.accountRepo.BindGroups(ctx, accountID, *input.GroupIDs)
+ }
+ if bindingErr != nil {
+ entry.Success = false
+ entry.Error = bindingErr.Error()
+ result.Failed++
+ result.FailedIDs = append(result.FailedIDs, accountID)
+ result.Results = append(result.Results, entry)
+ continue
}
entry.Success = true
@@ -1529,7 +1608,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
}
func updatesUpstreamBillingProbeIdentity(credentials map[string]any) bool {
- for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
+ for _, key := range []string{"api_key", "base_url", GatewayUpstreamKindCredentialKey, credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
if _, ok := credentials[key]; ok {
return true
}
@@ -1545,7 +1624,7 @@ func upstreamBillingProbeIdentity(account *Account) map[string]any {
if account.ProxyID != nil {
identity["proxy_id"] = *account.ProxyID
}
- for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
+ for _, key := range []string{"api_key", "base_url", GatewayUpstreamKindCredentialKey, credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
if value, ok := account.Credentials[key]; ok {
identity[key] = value
}
diff --git a/backend/internal/service/antigravity_gateway_claude.go b/backend/internal/service/antigravity_gateway_claude.go
index 7e81156da05f..b0a30fc3d84f 100644
--- a/backend/internal/service/antigravity_gateway_claude.go
+++ b/backend/internal/service/antigravity_gateway_claude.go
@@ -28,6 +28,9 @@ import (
// ├─ 成功 → 正常返回
// └─ 失败 → 设置模型限流 + 清除粘性绑定 → 切换账号
func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte, isStickySession bool) (*ForwardResult, error) {
+ if account.gatewayProtocolsPending() {
+ return s.forwardGatewayMessages(ctx, c, account, body)
+ }
if err := CheckUpstreamModeration(ctx, c, account); err != nil {
return nil, err
}
diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go
index 01d6aa55bfc0..684049c3872d 100644
--- a/backend/internal/service/antigravity_gateway_gemini.go
+++ b/backend/internal/service/antigravity_gateway_gemini.go
@@ -42,6 +42,9 @@ func WithForwardGeminiSession(groupID int64, sessionHash string) ForwardGeminiOp
}
func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte, isStickySession bool, options ...ForwardGeminiOption) (*ForwardResult, error) {
+ if account.gatewayProtocolsPending() {
+ return s.forwardGatewayGemini(ctx, c, account, originalModel, action, stream, body)
+ }
if err := CheckUpstreamModeration(ctx, c, account); err != nil {
return nil, err
}
diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go
index 7a8f7a2c0fd5..d83d4ad46c82 100644
--- a/backend/internal/service/antigravity_gateway_upstream.go
+++ b/backend/internal/service/antigravity_gateway_upstream.go
@@ -19,6 +19,9 @@ import (
// ForwardUpstream 使用 base_url + /v1/messages + 双 header 认证透传上游 Claude 请求
func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) {
+ if account.gatewayProtocolsPending() {
+ return s.forwardGatewayMessages(ctx, c, account, body)
+ }
if err := CheckUpstreamModeration(ctx, c, account); err != nil {
return nil, err
}
diff --git a/backend/internal/service/gateway_account.go b/backend/internal/service/gateway_account.go
index 5ae169381165..f5b5dd6d514c 100644
--- a/backend/internal/service/gateway_account.go
+++ b/backend/internal/service/gateway_account.go
@@ -2,16 +2,134 @@ package service
import (
"context"
+ "maps"
+ "net/url"
+ "strings"
"github.com/Wei-Shaw/sub2api/internal/domain"
+ infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
)
+// PlatformGateway is reserved for account storage and is excluded from the catalog.
+const PlatformGateway = domain.AccountPlatformGateway
+const GatewayUpstreamKindCredentialKey = "upstream_kind"
+
+var ErrGatewayAccountIdentity = infraerrors.BadRequest("INVALID_GATEWAY_ACCOUNT", "gateway accounts require platform/type gateway, upstream_kind new_api or sub2api, a site URL and an API key")
+var ErrGatewayAccountGroup = infraerrors.BadRequest("INVALID_GATEWAY_GROUP", "gateway accounts require an existing concrete or composite group that does not require OAuth")
+var ErrGatewayProtocolsPending = infraerrors.BadRequest("GATEWAY_PROTOCOLS_PENDING", "gateway scheduling and forwarding are not available yet")
+var ErrGatewayAtomicUpdateRequired = infraerrors.BadRequest("GATEWAY_ATOMIC_UPDATE_REQUIRED", "gateway updates require transactional account and group writes")
+
+type gatewayAccountTransactionKey struct{}
+
+func gatewayAccountTransactionActive(ctx context.Context) bool {
+ active, _ := ctx.Value(gatewayAccountTransactionKey{}).(bool)
+ return active
+}
+
+func withinGatewayAccountTransaction(ctx context.Context, repo AccountRepository, id int64, groups []int64, run func(context.Context) error) error {
+ writer, ok := repo.(GatewayAccountTransactionRepository)
+ if !ok {
+ return ErrGatewayAtomicUpdateRequired
+ }
+ return writer.WithinGatewayAccountTransaction(ctx, id, groups, func(txctx context.Context) error {
+ return run(context.WithValue(txctx, gatewayAccountTransactionKey{}, true))
+ })
+}
+
+// ValidateGatewayAccountIdentity reserves an account-only identity. Legacy
+// records are neither reclassified nor subjected to new credential validation.
+func ValidateGatewayAccountIdentity(platform, accountType string, credentials map[string]any) error {
+ if platform != PlatformGateway && accountType != AccountTypeGateway {
+ return nil
+ }
+ if platform != PlatformGateway || accountType != AccountTypeGateway {
+ return ErrGatewayAccountIdentity
+ }
+ kind, _ := credentials[GatewayUpstreamKindCredentialKey].(string)
+ key, _ := credentials["api_key"].(string)
+ base, _ := credentials["base_url"].(string)
+ u, err := url.Parse(base)
+ if (kind != "new_api" && kind != "sub2api") || strings.TrimSpace(key) == "" || strings.ContainsAny(key, "\r\n") ||
+ err != nil || u == nil || (u.Scheme != "https" && u.Scheme != "http") || u.Hostname() == "" ||
+ u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.TrimSpace(base) != base {
+ return ErrGatewayAccountIdentity
+ }
+ return nil
+}
+
+// ValidateGatewayAccountGroup adds only the new type's binding policy. Existing
+// account rules remain with their existing callers. No implicit membership is
+// created by this check; group IDs must be supplied by the administrator.
+func ValidateGatewayAccountGroup(a *Account, group *Group) error {
+ if a == nil || (!a.IsGateway() && a.Platform != PlatformGateway) {
+ return nil
+ }
+ if !a.IsGateway() || a.Platform != PlatformGateway || group == nil || group.ID <= 0 ||
+ !domain.IsGroupPlatform(group.Platform) || group.RequireOAuthOnly {
+ return ErrGatewayAccountGroup
+ }
+ return nil
+}
+
+func validateGatewayAccountGroups(ctx context.Context, a *Account, repo GroupRepository, ids []int64) error {
+ if a == nil || (!a.IsGateway() && a.Platform != PlatformGateway) || len(ids) == 0 {
+ return nil
+ }
+ if repo == nil {
+ return ErrGatewayAccountGroup
+ }
+ for _, id := range ids {
+ if id <= 0 {
+ return ErrGatewayAccountGroup
+ }
+ group, err := repo.GetByID(ctx, id)
+ if err != nil {
+ return err
+ }
+ if err := ValidateGatewayAccountGroup(a, group); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func validateGatewayAccountUpdate(a *Account, input *UpdateAccountInput) error {
+ platform, kind := a.Platform, a.Type
+ if input.Platform != "" {
+ platform = input.Platform
+ }
+ if input.Type != "" {
+ kind = input.Type
+ }
+ if a.IsGateway() || a.Platform == PlatformGateway || platform == PlatformGateway || kind == AccountTypeGateway {
+ // Conversion needs a new account, not a platform edit that loses bindings
+ // or reuses credentials with different ownership/protocol semantics.
+ if platform != a.Platform || kind != a.Type {
+ return ErrGatewayAccountIdentity
+ }
+ credentials := mergeGatewayCredentials(a.Credentials, input.Credentials)
+ return ValidateGatewayAccountIdentity(platform, kind, credentials)
+ }
+ return nil
+}
+
+func mergeGatewayCredentials(existing, incoming map[string]any) map[string]any {
+ out := make(map[string]any, len(existing)+len(incoming))
+ maps.Copy(out, existing)
+ maps.Copy(out, incoming)
+ return out
+}
+
// IsGateway identifies the dedicated cross-platform account type. Existing
// apikey/upstream credentials and probe settings never opt an account into it.
func (a *Account) IsGateway() bool {
return a != nil && a.Type == AccountTypeGateway
}
+func (a *Account) gatewayProtocolsPending() bool {
+ return a != nil && (a.IsGateway() || a.Platform == PlatformGateway)
+}
+
// usagePlatformForRequest preserves the selected account's platform for legacy
// accounts. A gateway has no single provider: use the handler's request snapshot
// (also available after async handoff), then the resolved request/group platform.
diff --git a/backend/internal/service/gateway_account_management_test.go b/backend/internal/service/gateway_account_management_test.go
new file mode 100644
index 000000000000..0420cee59e62
--- /dev/null
+++ b/backend/internal/service/gateway_account_management_test.go
@@ -0,0 +1,244 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/stretchr/testify/require"
+)
+
+func gatewayManagementFixture() *Account {
+ return &Account{ID: 959, Name: "Gateway fixture", Platform: PlatformGateway, Type: AccountTypeGateway,
+ Status: StatusActive, Schedulable: true, Concurrency: 2,
+ Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example/tenant", "api_key": "synthetic-key"}}
+}
+
+type gatewayManagementAtomicRepo struct {
+ *accountRepoStubForBulkUpdate
+ transactions int
+ transactionErr error
+}
+
+func (r *gatewayManagementAtomicRepo) WithinGatewayAccountTransaction(ctx context.Context, _ int64, _ []int64, run func(context.Context) error) error {
+ r.transactions++
+ if r.transactionErr != nil {
+ return r.transactionErr
+ }
+ return run(ctx)
+}
+
+func TestGatewayManagementIdentityIsAccountOnly(t *testing.T) {
+ a := gatewayManagementFixture()
+ require.NoError(t, ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials))
+ require.False(t, domain.IsConcretePlatform(PlatformGateway))
+ require.False(t, domain.IsGroupPlatform(PlatformGateway))
+ for _, kind := range []string{"new_api", "sub2api"} {
+ a.Credentials["upstream_kind"] = kind
+ require.NoError(t, ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials))
+ }
+ for _, platform := range []string{PlatformOpenAI, PlatformComposite, ""} {
+ require.Error(t, ValidateGatewayAccountIdentity(platform, AccountTypeGateway, a.Credentials))
+ }
+ for _, kind := range []string{AccountTypeAPIKey, AccountTypeUpstream, AccountTypeOAuth} {
+ require.Error(t, ValidateGatewayAccountIdentity(PlatformGateway, kind, a.Credentials))
+ require.NoError(t, ValidateGatewayAccountIdentity(PlatformOpenAI, kind, nil), "legacy validation is unchanged")
+ }
+ for _, field := range []string{"upstream_kind", "base_url", "api_key"} {
+ a = gatewayManagementFixture()
+ delete(a.Credentials, field)
+ require.Error(t, ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials), field)
+ }
+ for _, address := range []string{"relative/path", "ftp://gateway.example", "https://user:secret@gateway.example", "https://gateway.example?api_key=secret", "https://gateway.example/#secret"} {
+ a = gatewayManagementFixture()
+ a.Credentials["base_url"] = address
+ err := ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials)
+ require.Error(t, err)
+ require.NotContains(t, err.Error(), "secret", "invalid configuration must not echo credentials")
+ }
+}
+
+func TestGatewayManagementGroupsAcceptConcreteAndCompositeRejectOAuthOnly(t *testing.T) {
+ a := gatewayManagementFixture()
+ for _, platform := range append(domain.ConcretePlatformIDs(), PlatformComposite) {
+ g := &Group{ID: 1, Platform: platform}
+ require.NoError(t, ValidateGatewayAccountGroup(a, g), platform)
+ g.RequireOAuthOnly = true
+ require.Error(t, ValidateGatewayAccountGroup(a, g), platform)
+ }
+ require.Error(t, ValidateGatewayAccountGroup(a, &Group{ID: 1, Platform: PlatformGateway}))
+ require.Error(t, ValidateGatewayAccountGroup(a, nil))
+ require.NoError(t, ValidateGatewayAccountGroup(&Account{Type: AccountTypeAPIKey}, nil), "do not change legacy policy")
+ // A stored/manual schedulable=true cannot bypass the incomplete protocol gate.
+ require.False(t, a.IsSchedulable())
+}
+
+func TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups(t *testing.T) {
+ for _, oauthOnly := range []bool{false, true} {
+ repo := &accountRepoStubForBulkUpdate{createID: 959}
+ groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{
+ 1: {ID: 1, Platform: PlatformOpenAI}, 2: {ID: 2, Platform: PlatformAnthropic, RequireOAuthOnly: oauthOnly},
+ 3: {ID: 3, Platform: PlatformComposite},
+ }}
+ svc := &adminServiceImpl{accountRepo: repo, groupRepo: groups}
+ a := gatewayManagementFixture()
+ created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{Name: a.Name, Platform: a.Platform, Type: a.Type,
+ Credentials: a.Credentials, Concurrency: 2, GroupIDs: []int64{1, 2, 3}})
+ if oauthOnly {
+ require.Error(t, err)
+ require.Nil(t, repo.createAccount)
+ require.Empty(t, repo.bindGroupsCalls)
+ } else {
+ require.NoError(t, err)
+ require.Equal(t, []int64{1, 2, 3}, repo.bindGroupsByAccount[created.ID])
+ require.False(t, created.Schedulable)
+ }
+ }
+ // No implicit default lookup even when no group repository was configured.
+ repo := &accountRepoStubForBulkUpdate{createID: 959}
+ a := gatewayManagementFixture()
+ created, err := (&adminServiceImpl{accountRepo: repo}).CreateAccount(context.Background(), &CreateAccountInput{
+ Name: a.Name, Platform: a.Platform, Type: a.Type, Credentials: a.Credentials})
+ require.NoError(t, err)
+ require.Empty(t, created.GroupIDs)
+ require.Empty(t, repo.bindGroupsCalls)
+}
+
+func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *testing.T) {
+ a := gatewayManagementFixture()
+ repo := &gatewayManagementAtomicRepo{accountRepoStubForBulkUpdate: &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{959: a}}}
+ svc := &adminServiceImpl{accountRepo: repo}
+ updated, err := svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{
+ Name: "Edited gateway", Credentials: map[string]any{"base_url": "https://edited.example"}})
+ require.NoError(t, err)
+ require.Equal(t, 1, repo.transactions)
+ require.Equal(t, "synthetic-key", updated.Credentials["api_key"])
+ require.Equal(t, "new_api", updated.Credentials["upstream_kind"])
+ for _, input := range []*UpdateAccountInput{{Platform: PlatformOpenAI}, {Type: AccountTypeAPIKey}, {Credentials: map[string]any{"upstream_kind": "unknown"}}} {
+ repo.updatedAccounts = nil
+ _, err := svc.UpdateAccount(context.Background(), 959, input)
+ require.Error(t, err)
+ require.Empty(t, repo.updatedAccounts)
+ }
+ legacy, legacyRepo := newPlatformEditService()
+ _, err = legacy.UpdateAccount(context.Background(), 7, &UpdateAccountInput{Platform: PlatformGateway, Type: AccountTypeGateway, Credentials: a.Credentials})
+ require.Error(t, err)
+ require.Empty(t, legacyRepo.updatedAccounts)
+}
+
+func TestGatewayManagementUpdateRequiresAtomicCapability(t *testing.T) {
+ for _, route := range []string{"admin", "account-service", "bulk"} {
+ t.Run(route, func(t *testing.T) {
+ a := gatewayManagementFixture()
+ repo := &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{a.ID: a}, getByIDsAccounts: []*Account{a}}
+ groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformOpenAI}}}
+ ids := []int64{1}
+ admin := &adminServiceImpl{accountRepo: repo, groupRepo: groups}
+ switch route {
+ case "admin":
+ _, err := admin.UpdateAccount(context.Background(), a.ID, &UpdateAccountInput{GroupIDs: &ids, Name: "must not save"})
+ require.ErrorIs(t, err, ErrGatewayAtomicUpdateRequired)
+ case "account-service":
+ _, err := NewAccountService(repo, groups).Update(context.Background(), a.ID, UpdateAccountRequest{GroupIDs: &ids})
+ require.ErrorIs(t, err, ErrGatewayAtomicUpdateRequired)
+ case "bulk":
+ result, err := admin.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{AccountIDs: []int64{a.ID}, GroupIDs: &ids, Name: "must not save", SkipMixedChannelCheck: true})
+ require.NoError(t, err)
+ require.Equal(t, []int64{a.ID}, result.FailedIDs)
+ }
+ require.Empty(t, repo.updatedAccounts)
+ require.Zero(t, repo.bulkUpdateCalls)
+ require.Empty(t, repo.bindGroupsCalls)
+ })
+ }
+}
+
+func TestGatewayManagementMixedBulkRetainsLegacyWritePath(t *testing.T) {
+ gateway := gatewayManagementFixture()
+ legacy := &Account{ID: 7, Platform: PlatformOpenAI, Type: AccountTypeAPIKey}
+ repo := &gatewayManagementAtomicRepo{accountRepoStubForBulkUpdate: &accountRepoStubForBulkUpdate{getByIDsAccounts: []*Account{legacy, gateway}}, transactionErr: ErrGatewayAccountGroup}
+ groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformOpenAI}}}
+ ids := []int64{1}
+ result, err := (&adminServiceImpl{accountRepo: repo, groupRepo: groups}).BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{
+ AccountIDs: []int64{legacy.ID, gateway.ID}, GroupIDs: &ids, Name: "fixture edit", SkipMixedChannelCheck: true})
+ require.NoError(t, err)
+ require.Equal(t, []int64{legacy.ID}, repo.bulkUpdateIDs, "gateway fields must never enter the legacy batch before membership validation")
+ require.Equal(t, []int64{legacy.ID}, repo.bindGroupsCalls)
+ require.Equal(t, []int64{legacy.ID}, result.SuccessIDs)
+ require.Equal(t, []int64{gateway.ID}, result.FailedIDs)
+ require.Equal(t, 1, repo.transactions)
+}
+
+func TestGatewayManagementAccountServiceRejectsOAuthGroupsBeforeCreate(t *testing.T) {
+ repo := &accountRepoStubForBulkUpdate{createID: 959}
+ groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformComposite, RequireOAuthOnly: true}}}
+ a := gatewayManagementFixture()
+ _, err := NewAccountService(repo, groups).Create(context.Background(), CreateAccountRequest{
+ Name: a.Name, Platform: a.Platform, Type: a.Type, Credentials: a.Credentials, GroupIDs: []int64{1}})
+ require.Error(t, err)
+ require.Nil(t, repo.createAccount)
+}
+
+func TestGatewayManagementForwardingRemainsClosed(t *testing.T) {
+ a := gatewayManagementFixture()
+ ctx := context.Background()
+ // Nil services/contexts are deliberate: the guard must run before transport,
+ // policy evaluation, model parsing, OAuth replay or any other side effects.
+ _, err := (*GatewayService)(nil).Forward(ctx, nil, a, nil)
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*OpenAIGatewayService)(nil).Forward(ctx, nil, a, nil)
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*OpenAIGatewayService)(nil).ForwardAsAnthropic(ctx, nil, a, nil, "", "")
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*OpenAIGatewayService)(nil).ForwardAsChatCompletions(ctx, nil, a, nil, "", "")
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*GeminiMessagesCompatService)(nil).Forward(ctx, nil, a, nil)
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*GeminiMessagesCompatService)(nil).ForwardNative(ctx, nil, a, "fixture", "generateContent", false, nil)
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*AntigravityGatewayService)(nil).Forward(ctx, nil, a, nil, false)
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*AntigravityGatewayService)(nil).ForwardGemini(ctx, nil, a, "fixture", "generateContent", false, nil, false)
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ _, err = (*AntigravityGatewayService)(nil).ForwardUpstream(ctx, nil, a, nil)
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending)
+ require.ErrorIs(t, (*OpenAIGatewayService)(nil).ForwardCountTokensAsAnthropic(ctx, nil, a, nil, ""), ErrGatewayProtocolsPending)
+ require.ErrorIs(t, (*OpenAIGatewayService)(nil).ForwardResponsesInputTokens(ctx, nil, a, nil), ErrGatewayProtocolsPending)
+}
+
+func TestGatewayManagementUpdateAndBulkRejectOAuthBindingsBeforeWrites(t *testing.T) {
+ for _, path := range []string{"admin", "account-service", "bulk"} {
+ t.Run(path, func(t *testing.T) {
+ a := gatewayManagementFixture()
+ repo := &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{a.ID: a}, getByIDsAccounts: []*Account{a}}
+ groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformOpenAI, RequireOAuthOnly: true}}}
+ ids := []int64{1}
+ var err error
+ switch path {
+ case "admin":
+ _, err = (&adminServiceImpl{accountRepo: repo, groupRepo: groups}).UpdateAccount(context.Background(), a.ID, &UpdateAccountInput{GroupIDs: &ids, Name: "must not save"})
+ case "account-service":
+ _, err = NewAccountService(repo, groups).Update(context.Background(), a.ID, UpdateAccountRequest{GroupIDs: &ids})
+ case "bulk":
+ _, err = (&adminServiceImpl{accountRepo: repo, groupRepo: groups}).BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{
+ AccountIDs: []int64{a.ID}, GroupIDs: &ids, SkipMixedChannelCheck: true, Name: "must not save"})
+ }
+ require.Error(t, err)
+ require.Empty(t, repo.updatedAccounts)
+ require.Zero(t, repo.bulkUpdateCalls)
+ require.Empty(t, repo.bindGroupsCalls)
+ })
+ }
+}
+
+func TestGatewayManagementBulkRejectsInvalidCredentialMerge(t *testing.T) {
+ a := gatewayManagementFixture()
+ repo := &accountRepoStubForBulkUpdate{getByIDsAccounts: []*Account{a}}
+ _, err := (&adminServiceImpl{accountRepo: repo}).BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{
+ AccountIDs: []int64{a.ID}, Credentials: map[string]any{"upstream_kind": "unknown"}})
+ require.ErrorIs(t, err, ErrGatewayAccountIdentity)
+ require.Zero(t, repo.bulkUpdateCalls)
+ require.Equal(t, "new_api", a.Credentials["upstream_kind"])
+}
diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go
index 5ef43a3ef008..eceeb56b1c08 100644
--- a/backend/internal/service/gateway_anthropic_passthrough.go
+++ b/backend/internal/service/gateway_anthropic_passthrough.go
@@ -96,6 +96,24 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput(
var resp *http.Response
retryStart := time.Now()
for attempt := 1; attempt <= maxRetryAttempts; attempt++ {
+ if account.gatewayProtocolSource != nil {
+ latest, err := s.gatewayProtocolAccount(ctx, account.gatewayProtocolSource, "anthropic", account.gatewayProtocolModel)
+ if err != nil {
+ return nil, err
+ }
+ if openAITurnRouteFingerprint(latest) != openAITurnRouteFingerprint(account) {
+ return nil, ErrGatewayAccountIdentity
+ }
+ account = latest
+ token, _, err = s.GetAccessToken(ctx, account)
+ if err != nil {
+ return nil, err
+ }
+ proxyURL = ""
+ if account.ProxyID != nil && account.Proxy != nil {
+ proxyURL = account.Proxy.URL()
+ }
+ }
upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, input.RequestStream)
upstreamReq, wireBody, err := s.buildUpstreamRequestAnthropicAPIKeyPassthrough(upstreamCtx, c, account, input.Body, token)
releaseUpstreamCtx()
diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go
index 9175be4086d9..88023d961541 100644
--- a/backend/internal/service/gateway_forward.go
+++ b/backend/internal/service/gateway_forward.go
@@ -13,6 +13,7 @@ import (
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/tidwall/gjson"
@@ -120,6 +121,18 @@ func sleepWithContext(ctx context.Context, d time.Duration) error {
// Forward 转发请求到Claude API
func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, parsed *ParsedRequest) (result *ForwardResult, err error) {
+ if account.gatewayProtocolsPending() {
+ if parsed != nil && parsed.GroupID != nil {
+ if group, ok := ctx.Value(ctxkey.Group).(*Group); !ok || group == nil || group.ID != *parsed.GroupID {
+ return nil, ErrGatewayAccountGroup
+ }
+ }
+ view, err := s.gatewayProtocolAccount(ctx, account, "anthropic", gatewayProtocolParsedModel(parsed))
+ if err != nil {
+ return nil, err
+ }
+ account = view
+ }
if err := CheckUpstreamModeration(ctx, c, account); err != nil {
return nil, err
}
diff --git a/backend/internal/service/gateway_messages_selection.go b/backend/internal/service/gateway_messages_selection.go
new file mode 100644
index 000000000000..94463585dbc4
--- /dev/null
+++ b/backend/internal/service/gateway_messages_selection.go
@@ -0,0 +1,179 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
+)
+
+type gatewaySelectionKey struct{}
+
+type gatewaySelection struct {
+ groupID int64
+ model string
+ publicModel string
+ family domain.PlatformGateway
+ target string
+}
+
+func withGatewaySelection(ctx context.Context, publicModel, model string, family domain.PlatformGateway) context.Context {
+ group, _ := ctx.Value(ctxkey.Group).(*Group)
+ if group == nil {
+ return ctx
+ }
+ target := group.Platform
+ if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok {
+ target = resolved
+ }
+ if forced, _ := ctx.Value(ctxkey.ForcePlatform).(string); forced != "" {
+ if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok && resolved != forced {
+ return ctx
+ }
+ target = forced
+ }
+ return context.WithValue(ctx, gatewaySelectionKey{}, gatewaySelection{groupID: group.ID, publicModel: publicModel, model: model, family: family, target: target})
+}
+
+func WithGatewayMessagesSelection(ctx context.Context, model string) context.Context {
+ family := domain.PlatformGatewayAnthropic
+ group, _ := ctx.Value(ctxkey.Group).(*Group)
+ target, _ := ResolvedTargetPlatformFromContext(ctx)
+ if (group != nil && group.Platform == PlatformGemini) || target == PlatformGemini {
+ family = domain.PlatformGatewayGemini
+ }
+ return withGatewaySelection(ctx, model, model, family)
+}
+
+func WithGatewayOpenAISelection(ctx context.Context, publicModel, model string) context.Context {
+ return withGatewaySelection(ctx, publicModel, model, domain.PlatformGatewayOpenAI)
+}
+
+func WithGatewayGeminiSelection(ctx context.Context, model string) context.Context {
+ return withGatewaySelection(ctx, model, model, domain.PlatformGatewayGemini)
+}
+
+// GatewayRequestCandidateReader is deliberately separate from shared snapshot
+// queries: a neutral account must never enter a platform bucket or group zero.
+// Membership and group policy must come from the same primary SQL snapshot.
+type GatewayRequestCandidateReader interface {
+ ListGatewayRequestCandidates(context.Context, int64, string) ([]Account, *Group, error)
+}
+
+func requestGatewaySelection(ctx context.Context, groupID *int64, platform string) (gatewaySelection, bool) {
+ selection, ok := ctx.Value(gatewaySelectionKey{}).(gatewaySelection)
+ group, _ := ctx.Value(ctxkey.Group).(*Group)
+ if !ok || selection.model == "" || groupID == nil || *groupID <= 0 || group == nil || group.ID != *groupID || selection.groupID != *groupID ||
+ !group.IsActive() || group.RequireOAuthOnly || selection.target != platform ||
+ (group.Platform != platform && group.Platform != PlatformComposite) {
+ return gatewaySelection{}, false
+ }
+ if target, ok := ResolvedTargetPlatformFromContext(ctx); ok && target != platform {
+ return gatewaySelection{}, false
+ }
+ if forced, _ := ctx.Value(ctxkey.ForcePlatform).(string); forced != "" && forced != platform {
+ return gatewaySelection{}, false
+ }
+ spec, concrete := domain.LookupPlatform(platform)
+ nativeAntigravity := platform == PlatformAntigravity && (selection.family == domain.PlatformGatewayAnthropic || selection.family == domain.PlatformGatewayGemini)
+ return selection, concrete && (spec.Gateway == selection.family || nativeAntigravity)
+}
+
+func (s *GatewayService) appendGatewayMessagesCandidates(ctx context.Context, groupID *int64, platform string, accounts []Account) ([]Account, error) {
+ return appendGatewayCandidates(ctx, s.accountRepo, s.schedulerSnapshot, groupID, platform, accounts), nil
+}
+
+func appendGatewayCandidates(ctx context.Context, repo AccountRepository, snapshot *SchedulerSnapshotService, groupID *int64, platform string, accounts []Account) []Account {
+ selection, enabled := requestGatewaySelection(ctx, groupID, platform)
+ if !enabled {
+ return accounts
+ }
+ reader, _ := repo.(GatewayRequestCandidateReader)
+ if snapshot != nil && snapshot.localSnapshotReader != nil {
+ reader, _ = snapshot.localSnapshotReader.(GatewayRequestCandidateReader)
+ }
+ if reader == nil {
+ return accounts
+ }
+ ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
+ defer cancel()
+ candidates, group, err := reader.ListGatewayRequestCandidates(ctx, *groupID, platform)
+ if err != nil {
+ slog.Warn("gateway candidate read unavailable", "group_id", *groupID, "error", err)
+ return accounts
+ }
+ // An invalidated group contributes no gateway candidates. Legacy candidates
+ // retain their existing scheduler policy, independent of this capability.
+ if group == nil || (group.Platform != platform && group.Platform != PlatformComposite) {
+ return accounts
+ }
+ seen := make(map[int64]bool, len(accounts))
+ accounts = append([]Account(nil), accounts...)
+ for i := range accounts {
+ seen[accounts[i].ID] = true
+ }
+ for i := range candidates {
+ candidate := candidates[i]
+ view, err := gatewayProtocolAccountFromSnapshot(ctx, &candidate, &candidate, group, selection.family, selection.model)
+ if err != nil || seen[candidate.ID] {
+ continue
+ }
+ if selection.family == domain.PlatformGatewayOpenAI {
+ // Run the normal provider-specific scheduler predicates on a local
+ // projection; the handler receives the neutral account for accounting.
+ view.Platform = platform
+ accounts = append(accounts, *view)
+ seen[candidate.ID] = true
+ continue
+ }
+ candidate.gatewaySelectionTarget = platform
+ candidate.gatewayMessagesView = view
+ accounts = append(accounts, candidate)
+ seen[candidate.ID] = true
+ }
+ return accounts
+}
+
+func (s *GatewayService) refreshGatewayMessagesSelection(ctx context.Context, account *Account) (*Account, error) {
+ group, _ := ctx.Value(ctxkey.Group).(*Group)
+ if group == nil {
+ return nil, ErrGatewayProtocolsPending
+ }
+ scope, _ := ctx.Value(gatewaySelectionKey{}).(gatewaySelection)
+ selection, enabled := requestGatewaySelection(ctx, &group.ID, scope.target)
+ if !enabled {
+ return nil, ErrGatewayProtocolsPending
+ }
+ view, err := s.gatewayProtocolAccount(ctx, account, selection.family, selection.model)
+ if err != nil {
+ return nil, err
+ }
+ neutral := *view.gatewayProtocolSource
+ neutral.gatewaySelectionTarget = selection.target
+ neutral.gatewayMessagesView = view
+ return &neutral, nil
+}
+
+// Rebuild the scheduling projection from current membership and credentials.
+// Only HTTP text entry points put this capability in their request context.
+func (s *OpenAIGatewayService) openAIGatewaySelectionView(ctx context.Context, account *Account) (*Account, error) {
+ if account == nil || (!account.IsGateway() && account.gatewayProtocolSource == nil) {
+ return account, nil
+ }
+ if account.gatewayProtocolSource != nil {
+ account = account.gatewayProtocolSource
+ }
+ scope, _ := ctx.Value(gatewaySelectionKey{}).(gatewaySelection)
+ selection, ok := requestGatewaySelection(ctx, &scope.groupID, scope.target)
+ if !ok || selection.family != domain.PlatformGatewayOpenAI {
+ return nil, ErrGatewayProtocolsPending
+ }
+ view, err := s.gatewayProtocolAccount(ctx, account, selection.family, selection.model)
+ if err != nil {
+ return nil, err
+ }
+ view.Platform = selection.target
+ return view, nil
+}
diff --git a/backend/internal/service/gateway_messages_selection_test.go b/backend/internal/service/gateway_messages_selection_test.go
new file mode 100644
index 000000000000..ef19bcb6db69
--- /dev/null
+++ b/backend/internal/service/gateway_messages_selection_test.go
@@ -0,0 +1,230 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
+ "github.com/stretchr/testify/require"
+)
+
+type gatewayMessagesCandidateRepo struct {
+ *gatewayProtocolAdmissionRepo
+ queries int
+ err error
+}
+
+func (r *gatewayMessagesCandidateRepo) ListGatewayRequestCandidates(context.Context, int64, string) ([]Account, *Group, error) {
+ r.queries++
+ return []Account{*r.account}, r.group, r.err
+}
+
+func TestGatewayProtocolMessagesCandidatesStayRequestScoped(t *testing.T) {
+ for _, scenario := range []string{"eligible", "unbound", "oauth-only", "other-target", "composite", "disabled", "paused", "cooling", "429", "401", "low-balance", "wrong-model", "unscoped"} {
+ t.Run(scenario, func(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformAnthropic)
+ repo := &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base}
+ ctx = WithGatewayMessagesSelection(ctx, "public-model")
+ switch scenario {
+ case "unbound":
+ repo.account.GroupIDs, repo.account.AccountGroups = nil, nil
+ case "oauth-only":
+ repo.group.RequireOAuthOnly = true
+ case "other-target":
+ ctx = WithResolvedTargetPlatform(ctx, PlatformGemini)
+ case "composite":
+ repo.group.Platform = PlatformComposite
+ ctx = WithResolvedTargetPlatform(ctx, PlatformAnthropic)
+ case "disabled":
+ repo.account.Status = StatusDisabled
+ case "paused":
+ repo.account.PerformancePaused = true
+ case "cooling":
+ until := time.Now().Add(time.Hour)
+ repo.account.TempUnschedulableUntil = &until
+ case "429":
+ until := time.Now().Add(time.Hour)
+ repo.account.RateLimitResetAt = &until
+ case "401", "low-balance":
+ repo.account.Status = StatusError
+ case "wrong-model":
+ repo.account.Credentials["model_mapping"] = map[string]any{"other": "other"}
+ case "unscoped":
+ ctx = context.WithValue(context.Background(), ctxkey.Group, repo.group)
+ }
+ svc := &GatewayService{accountRepo: repo}
+ accounts, err := svc.appendGatewayMessagesCandidates(ctx, &repo.group.ID, PlatformAnthropic, nil)
+ require.NoError(t, err)
+ if scenario != "eligible" && scenario != "composite" {
+ require.Empty(t, accounts)
+ return
+ }
+ require.Len(t, accounts, 1)
+ require.Equal(t, repo.account.ID, accounts[0].ID)
+ require.True(t, svc.isAccountSchedulableForSelection(&accounts[0]))
+ require.True(t, svc.isAccountAllowedForPlatform(&accounts[0], PlatformAnthropic, true))
+ require.False(t, accounts[0].IsSchedulable(), "neutral identity never becomes globally schedulable")
+ require.Nil(t, repo.account.gatewayMessagesView, "shared repository snapshot stays untouched")
+ repo.account.Status = StatusDisabled
+ _, err = svc.hydrateSelectedAccount(ctx, &accounts[0])
+ require.Error(t, err, "post-selection hydration must consult fresh authority")
+ })
+ }
+}
+
+func TestGatewayProtocolMessagesCandidateReadFailurePreservesLegacy(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformAnthropic)
+ repo := &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base, err: errors.New("primary unavailable")}
+ ctx = WithGatewayMessagesSelection(ctx, "public-model")
+ legacy := Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true}
+ svc := &GatewayService{accountRepo: repo}
+ accounts, err := svc.appendGatewayMessagesCandidates(ctx, &repo.group.ID, PlatformAnthropic, []Account{legacy})
+ require.NoError(t, err)
+ require.Equal(t, []Account{legacy}, accounts)
+ require.Equal(t, 1, repo.queries)
+}
+
+func TestGatewayProtocolMessagesCandidateSourceRefreshesAfterWarmSnapshot(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformAnthropic)
+ repo := &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base}
+ ctx = WithGatewayMessagesSelection(ctx, "public-model")
+ snapshot := NewSchedulerSnapshotService(&snapshotReaderCache{hit: true}, nil, nil, nil, nil)
+ svc := &GatewayService{accountRepo: repo, schedulerSnapshot: snapshot}
+ first, _, err := svc.listSchedulableAccounts(ctx, &repo.group.ID, PlatformAnthropic, false)
+ require.NoError(t, err)
+ require.Len(t, first, 1)
+ repo.account.GroupIDs, repo.account.AccountGroups = nil, nil
+ second, _, err := svc.listSchedulableAccounts(ctx, &repo.group.ID, PlatformAnthropic, false)
+ require.NoError(t, err)
+ require.Empty(t, second, "outbox lag cannot retain a revoked candidate")
+ require.Equal(t, 2, repo.queries)
+}
+
+func TestGatewayProtocolCandidatesByGroupAndProtocol(t *testing.T) {
+ for _, target := range []string{PlatformOpenAI, PlatformKimi, PlatformGrok, PlatformGemini, PlatformAntigravity} {
+ for _, composite := range []bool{false, true} {
+ t.Run(target+map[bool]string{false: "/concrete", true: "/composite"}[composite], func(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(target)
+ repo := &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base}
+ if composite {
+ base.group.Platform = PlatformComposite
+ ctx = WithResolvedTargetPlatform(ctx, target)
+ }
+ if target == PlatformGemini || target == PlatformAntigravity {
+ ctx = WithGatewayGeminiSelection(ctx, "public-model")
+ } else {
+ ctx = WithGatewayOpenAISelection(ctx, "public-model", "public-model")
+ }
+ accounts := appendGatewayCandidates(ctx, repo, nil, &base.group.ID, target, nil)
+ require.Len(t, accounts, 1)
+ require.Equal(t, base.account.ID, accounts[0].ID)
+ require.Equal(t, base.account.Concurrency, accounts[0].Concurrency)
+ require.Empty(t, appendGatewayCandidates(ctx, repo, nil, nil, target, nil))
+ if accounts[0].IsGateway() {
+ svc := &GatewayService{accountRepo: repo}
+ require.True(t, svc.isAccountAllowedForPlatform(&accounts[0], target, false))
+ _, err := svc.hydrateSelectedAccount(ctx, &accounts[0])
+ require.NoError(t, err)
+ } else {
+ require.Equal(t, target, accounts[0].Platform)
+ svc := &OpenAIGatewayService{accountRepo: repo}
+ fresh, err := svc.openAIGatewaySelectionView(ctx, &accounts[0])
+ require.NoError(t, err)
+ require.True(t, fresh.gatewayProtocolSource.IsGateway())
+ base.account.GroupIDs, base.account.AccountGroups = nil, nil
+ _, err = svc.openAIGatewaySelectionView(ctx, &accounts[0])
+ require.Error(t, err)
+ }
+ })
+ }
+ }
+}
+
+func TestGatewayProtocolRegionalAssignmentAndRemoval(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ base.account.ID = 1
+ ctx = WithGatewayOpenAISelection(ctx, "public-model", "public-model")
+ bucket := SchedulerBucket{GroupID: base.group.ID, Platform: PlatformOpenAI, Mode: SchedulerModeSingle}
+ doc := RegionalSchedulerDocument{Version: 1, Groups: []*Group{base.group},
+ Buckets: []RegionalSchedulerBucket{{Bucket: bucket, Accounts: []*Account{base.account}}}}
+ payload, err := json.Marshal(doc)
+ require.NoError(t, err)
+ require.Error(t, RegionalSchedulerValidator([]int64{2})(payload))
+ replica := regionalTestReplica(t, filepath.Join(t.TempDir(), "state"), true)
+ require.NoError(t, replica.PublishNext(ctx, "test", time.Minute, payload))
+ reader, err := NewRegionalSchedulerReader(replica)
+ require.NoError(t, err)
+ snapshot := NewSchedulerSnapshotService(nil, nil, nil, nil, nil)
+ snapshot.SetLocalSnapshotReader(reader)
+ accounts := appendGatewayCandidates(ctx, nil, snapshot, &base.group.ID, PlatformOpenAI, nil)
+ require.Len(t, accounts, 1)
+ require.Equal(t, int64(1), accounts[0].ID)
+ ordinary, _, err := reader.GetLocalSnapshot(ctx, bucket)
+ require.NoError(t, err)
+ require.Empty(t, ordinary)
+ doc.Buckets[0].Accounts = []*Account{}
+ payload, err = json.Marshal(doc)
+ require.NoError(t, err)
+ require.NoError(t, replica.PublishNext(ctx, "test", time.Minute, payload))
+ _, err = (&OpenAIGatewayService{schedulerSnapshot: snapshot}).openAIGatewaySelectionView(ctx, &accounts[0])
+ require.Error(t, err)
+}
+
+func (r *gatewayMessagesCandidateRepo) ListSchedulableByGroupID(context.Context, int64) ([]Account, error) {
+ return nil, nil
+}
+
+func TestGatewayProtocolCatalogFollowsLiveBindings(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ base.account.Credentials["model_mapping"] = map[string]any{"public-alias": "upstream", "other": "hidden"}
+ base.account.AccountGroups[0].AllowedModels = []string{"public-alias"}
+ svc := &GatewayService{accountRepo: &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base}}
+ want := []string{"public-alias"}
+ require.Equal(t, want, svc.GetAvailableModels(ctx, &base.group.ID, PlatformOpenAI))
+ models, err := svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI)
+ require.NoError(t, err)
+ require.Equal(t, want, models)
+ base.account.GroupIDs, base.account.AccountGroups = nil, nil
+ require.Empty(t, svc.GetAvailableModels(ctx, &base.group.ID, PlatformOpenAI))
+}
+
+func TestGatewayProtocolOpenAIChannelModelKeepsBinding(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ ctx = WithGatewayOpenAISelection(ctx, "public", "public")
+ base.account.AccountGroups[0].AllowedModels = []string{"public"}
+ base.account.Credentials["model_mapping"] = map[string]any{"public": "mapped"}
+ view, err := prepareGatewayProtocolAccount(ctx, base.account, base, "openai", "channel-model")
+ require.NoError(t, err)
+ require.True(t, view.IsModelAllowedInGroup(&base.group.ID, "channel-model"))
+ require.True(t, supportsOpenAIRequestModel(view, "channel-model", false))
+ base.account.AccountGroups[0].AllowedModels = []string{"channel-model"}
+ _, err = prepareGatewayProtocolAccount(ctx, base.account, base, "openai", "channel-model")
+ require.Error(t, err)
+}
+
+func TestGatewayProtocolCatalogCompositePublicAlias(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformComposite)
+ base.group.ModelAllowlist = GroupModelAllowlist{Enabled: true, Models: []string{"public"}}
+ base.account.AccountGroups[0].AllowedModels = []string{"upstream"}
+ base.account.Credentials["model_mapping"] = map[string]any{"upstream": "wire"}
+ svc := &GatewayService{accountRepo: &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base},
+ compositeResolver: NewCompositeRouteResolver(compositeRouteRepoStub{routes: []CompositeModelRoute{
+ {GroupID: base.group.ID, PublicModel: "public", UpstreamModel: "upstream", TargetPlatform: PlatformOpenAI,
+ Endpoint: CompositeRouteEndpointAny, MatchType: CompositeRouteMatchExact, Enabled: true},
+ }})}
+ models, err := svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformComposite)
+ require.NoError(t, err)
+ require.Equal(t, []string{"public"}, models)
+ base.account.Credentials["model_mapping"] = map[string]any{"public": "wire"}
+ base.account.AccountGroups[0].AllowedModels = []string{"public"}
+ models, err = svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformComposite)
+ require.NoError(t, err)
+ require.Empty(t, models, "an explicit route must authorize its actual upstream model")
+
+}
diff --git a/backend/internal/service/gateway_model_catalog.go b/backend/internal/service/gateway_model_catalog.go
index e41352a972d4..02da6b61fa9a 100644
--- a/backend/internal/service/gateway_model_catalog.go
+++ b/backend/internal/service/gateway_model_catalog.go
@@ -3,12 +3,100 @@ package service
import (
"context"
"fmt"
+ "slices"
"sort"
"strings"
"github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
)
+type gatewayModelCatalog struct {
+ ctx context.Context
+ family domain.PlatformGateway
+ group *Group
+ accounts []Account
+}
+
+func (catalog gatewayModelCatalog) allows(public, upstream string) bool {
+ if catalog.group == nil || public == "" || upstream == "" {
+ return false
+ }
+ ctx := withGatewaySelection(catalog.ctx, public, upstream, catalog.family)
+ for i := range catalog.accounts {
+ account := &catalog.accounts[i]
+ if _, err := gatewayProtocolAccountFromSnapshot(ctx, account, account, catalog.group, catalog.family, upstream); err == nil {
+ return true
+ }
+ }
+ return false
+}
+
+func (s *GatewayService) readGatewayModelCatalog(ctx context.Context, groupID *int64, target string) (gatewayModelCatalog, error) {
+ spec, concrete := domain.LookupPlatform(target)
+ reader, _ := s.accountRepo.(GatewayRequestCandidateReader)
+ if groupID == nil || *groupID <= 0 || !concrete {
+ return gatewayModelCatalog{}, nil
+ }
+ family := spec.Gateway
+ if target == PlatformAntigravity {
+ family = domain.PlatformGatewayAnthropic
+ }
+ if snap := s.schedulerSnapshot; snap != nil && snap.localSnapshotReader != nil {
+ reader, _ = snap.localSnapshotReader.(GatewayRequestCandidateReader)
+ group, err := snap.GetGroupByIDLite(ctx, *groupID)
+ if err != nil {
+ return gatewayModelCatalog{}, err
+ }
+ ctx = context.WithValue(ctx, ctxkey.Group, group)
+ ctx = WithResolvedTargetPlatform(ctx, target)
+ ctx = withGatewaySelection(ctx, "catalog", "catalog", family)
+ }
+ if reader == nil {
+ return gatewayModelCatalog{}, nil
+ }
+ candidates, group, err := reader.ListGatewayRequestCandidates(ctx, *groupID, target)
+ if err != nil || len(candidates) == 0 || group == nil || group.ID != *groupID {
+ return gatewayModelCatalog{}, err
+ }
+ ctx = context.WithValue(ctx, ctxkey.Group, group)
+ ctx = WithResolvedTargetPlatform(ctx, target)
+ return gatewayModelCatalog{ctx: ctx, family: family, group: group, accounts: candidates}, nil
+}
+
+func (catalog gatewayModelCatalog) directModels(target string) []string {
+ if catalog.group == nil {
+ return nil
+ }
+ groupID := &catalog.group.ID
+ group := catalog.group
+ var result []string
+ for i := range catalog.accounts {
+ account := &catalog.accounts[i]
+ models := groupAllowedConcreteModels(account, groupID)
+ for name := range account.GetModelMapping() {
+ models = append(models, name)
+ }
+ if len(models) == 0 {
+ models = append(models, group.ModelAllowlist.Models...)
+ if !IsMultiProtocolAPIKeyProvider(target) {
+ models = append(models, DefaultModelIDsForPlatform(target)...)
+ }
+ }
+ for _, model := range models {
+ if model == "" || strings.Contains(model, "*") {
+ continue
+ }
+ modelCtx := withGatewaySelection(catalog.ctx, model, model, catalog.family)
+ if _, err := gatewayProtocolAccountFromSnapshot(modelCtx, account, account, group, catalog.family, model); err == nil {
+ result = append(result, model)
+ }
+ }
+ }
+ slices.Sort(result)
+ return slices.Compact(result)
+}
+
// GetGroupModelCatalog is the fail-closed source for multi-group discovery.
// Unlike the legacy listing API, an error or missing accounts never means
// "advertise defaults". One repository snapshot supplies every concrete platform.
@@ -25,7 +113,23 @@ func (s *GatewayService) GetGroupModelCatalog(ctx context.Context, groupID int64
platforms = domain.CompositePrecedencePlatformIDs()
}
seen := make(map[string]struct{})
+ var routes []CompositeModelRoute
+ if platform == PlatformComposite && s.compositeResolver != nil && s.compositeResolver.repo != nil {
+ routes, err = s.compositeResolver.repo.ListByGroup(ctx, groupID, false)
+ if err != nil {
+ return nil, err
+ }
+ }
+ gatewayCatalogs := make(map[string]gatewayModelCatalog)
for _, concrete := range platforms {
+ catalog, err := s.readGatewayModelCatalog(ctx, &groupID, concrete)
+ if err != nil {
+ return nil, err
+ }
+ gatewayCatalogs[concrete] = catalog
+ for _, model := range catalog.directModels(concrete) {
+ seen[model] = struct{}{}
+ }
var visible []Account
for _, account := range accounts {
if account.Platform == concrete || mixedListingAccountAllowed(concrete, &account) {
@@ -66,11 +170,7 @@ func (s *GatewayService) GetGroupModelCatalog(ctx context.Context, groupID int64
}
}
}
- if platform == PlatformComposite && s.compositeResolver != nil && s.compositeResolver.repo != nil {
- routes, err := s.compositeResolver.repo.ListByGroup(ctx, groupID, false)
- if err != nil {
- return nil, err
- }
+ if len(routes) > 0 {
activeRoutes := make([]CompositeModelRoute, 0, len(routes))
candidates := make(map[string]struct{}, len(seen)+len(routes))
for model := range seen {
@@ -107,6 +207,10 @@ func (s *GatewayService) GetGroupModelCatalog(ctx context.Context, groupID int64
if upstream == "" {
upstream = model
}
+ if gatewayCatalogs[route.TargetPlatform].allows(model, upstream) {
+ available[model] = struct{}{}
+ break
+ }
for _, account := range accounts {
if account.Platform == route.TargetPlatform && account.IsModelAllowedInGroup(&groupID, upstream) && account.IsModelSupported(upstream) {
available[model] = struct{}{}
diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go
new file mode 100644
index 000000000000..1988429963ef
--- /dev/null
+++ b/backend/internal/service/gateway_protocol_admission.go
@@ -0,0 +1,239 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "maps"
+ "strings"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
+ "github.com/gin-gonic/gin"
+)
+
+func gatewayProtocolParsedModel(parsed *ParsedRequest) string {
+ if parsed == nil {
+ return ""
+ }
+ return parsed.Model
+}
+
+func gatewayProtocolBodyModel(body []byte) string {
+ var request struct {
+ Model string `json:"model"`
+ }
+ _ = json.Unmarshal(body, &request)
+ return request.Model
+}
+
+func (s *GatewayService) gatewayProtocolAccount(ctx context.Context, account *Account, family domain.PlatformGateway, model string) (*Account, error) {
+ if s == nil {
+ return nil, ErrGatewayProtocolsPending
+ }
+ return prepareGatewayProtocolAccount(ctx, account, gatewayAccountReader(s.accountRepo, s.schedulerSnapshot), family, model)
+}
+
+func (s *OpenAIGatewayService) gatewayProtocolAccount(ctx context.Context, account *Account, family domain.PlatformGateway, model string) (*Account, error) {
+ if s == nil {
+ return nil, ErrGatewayProtocolsPending
+ }
+ return prepareGatewayProtocolAccount(ctx, account, gatewayAccountReader(s.accountRepo, s.schedulerSnapshot), family, model)
+}
+
+func (s *GeminiMessagesCompatService) gatewayProtocolAccount(ctx context.Context, account *Account, family domain.PlatformGateway, model string) (*Account, error) {
+ if s == nil {
+ return nil, ErrGatewayProtocolsPending
+ }
+ return prepareGatewayProtocolAccount(ctx, account, gatewayAccountReader(s.accountRepo, s.schedulerSnapshot), family, model)
+}
+
+// Relay accounts on Antigravity URLs use native protocols, never the official
+// cloudcode OAuth envelope or its default model aliases.
+func (s *AntigravityGatewayService) forwardGatewayMessages(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) {
+ if s == nil {
+ return nil, ErrGatewayProtocolsPending
+ }
+ cfg := &config.Config{}
+ if s.settingService != nil && s.settingService.cfg != nil {
+ cfg = s.settingService.cfg
+ }
+ parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic)
+ if err != nil {
+ return nil, err
+ }
+ relay := &GatewayService{cfg: cfg, httpUpstream: s.httpUpstream, accountRepo: s.accountRepo, schedulerSnapshot: s.schedulerSnapshot,
+ rateLimitService: s.rateLimitService, settingService: s.settingService,
+ responseHeaderFilter: compileResponseHeaderFilter(cfg), deferredService: &DeferredService{}}
+ return relay.Forward(ctx, c, account, parsed)
+}
+
+func (s *AntigravityGatewayService) forwardGatewayGemini(ctx context.Context, c *gin.Context, account *Account, model, action string, stream bool, body []byte) (*ForwardResult, error) {
+ if s == nil {
+ return nil, ErrGatewayProtocolsPending
+ }
+ cfg := &config.Config{}
+ if s.settingService != nil && s.settingService.cfg != nil {
+ cfg = s.settingService.cfg
+ }
+ relay := &GeminiMessagesCompatService{cfg: cfg, httpUpstream: s.httpUpstream, accountRepo: s.accountRepo, schedulerSnapshot: s.schedulerSnapshot,
+ rateLimitService: s.rateLimitService}
+ return relay.ForwardNative(ctx, c, account, model, action, stream, body)
+}
+
+// GatewayRequestAccountReader reloads the account and its requested group at
+// final admission. It never infers membership from an account platform or URL.
+type GatewayRequestAccountReader interface {
+ GatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*Account, *Group, error)
+}
+
+func gatewayAccountReader(repo AccountRepository, snapshot *SchedulerSnapshotService) GatewayRequestAccountReader {
+ if snapshot != nil && snapshot.localSnapshotReader != nil {
+ reader, _ := snapshot.localSnapshotReader.(GatewayRequestAccountReader)
+ return reader
+ }
+ reader, _ := repo.(GatewayRequestAccountReader)
+ return reader
+}
+
+// prepareGatewayProtocolAccount makes an isolated API-key transport view. The
+// caller retains the original gateway for usage/procurement bookkeeping. ID,
+// concurrency, proxy and runtime state remain those of the one shared account.
+func prepareGatewayProtocolAccount(ctx context.Context, selected *Account, reader GatewayRequestAccountReader, family domain.PlatformGateway, model string) (*Account, error) {
+ group, _ := ctx.Value(ctxkey.Group).(*Group)
+ if selected == nil || !selected.IsGateway() || group == nil || group.ID <= 0 {
+ return nil, ErrGatewayProtocolsPending
+ }
+ if model == "" {
+ return nil, ErrGatewayProtocolsPending
+ }
+ if reader == nil {
+ return nil, ErrGatewayProtocolsPending
+ }
+ current, liveGroup, err := reader.GatewayRequestAccount(ctx, selected.ID, group.ID)
+ if err != nil {
+ return nil, err
+ }
+ return gatewayProtocolAccountFromSnapshot(ctx, selected, current, liveGroup, family, model)
+}
+
+func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current *Account, liveGroup *Group, family domain.PlatformGateway, model string) (*Account, error) {
+ group, _ := ctx.Value(ctxkey.Group).(*Group)
+ if selected == nil || group == nil || model == "" {
+ return nil, ErrGatewayProtocolsPending
+ }
+ if current == nil || !current.IsGateway() || current.Platform != PlatformGateway || current.ID != selected.ID || liveGroup == nil || liveGroup.ID != group.ID ||
+ !liveGroup.IsActive() || ValidateGatewayAccountGroup(current, liveGroup) != nil {
+ return nil, ErrGatewayAccountGroup
+ }
+ if err := ValidateGatewayAccountIdentity(current.Platform, current.Type, current.Credentials); err != nil {
+ return nil, err
+ }
+ if current.ParentAccountID != nil || current.AuthConnectionID != "" {
+ return nil, ErrGatewayAccountIdentity
+ }
+ // A credential/proxy edit after selection requires a fresh selection, rather
+ // than forwarding with one identity and logging another identity's snapshot.
+ for _, key := range []string{"api_key", "base_url", GatewayUpstreamKindCredentialKey} {
+ if selected.GetCredential(key) != current.GetCredential(key) {
+ return nil, ErrGatewayAccountIdentity
+ }
+ }
+ if (selected.ProxyID == nil) != (current.ProxyID == nil) ||
+ (selected.ProxyID != nil && *selected.ProxyID != *current.ProxyID) {
+ return nil, ErrGatewayAccountIdentity
+ }
+ member := false
+ for _, id := range current.GroupIDs {
+ member = member || id == liveGroup.ID
+ }
+ for _, binding := range current.AccountGroups {
+ member = member || binding.GroupID == liveGroup.ID
+ }
+ if !member {
+ return nil, ErrGatewayAccountGroup
+ }
+ target := liveGroup.Platform
+ if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok {
+ target = resolved
+ }
+ if forced, _ := ctx.Value(ctxkey.ForcePlatform).(string); forced != "" {
+ if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok && resolved != forced {
+ return nil, ErrGatewayAccountGroup
+ }
+ target = forced
+ }
+ spec, concrete := domain.LookupPlatform(target)
+ if !concrete || (liveGroup.Platform != PlatformComposite && liveGroup.Platform != target) {
+ return nil, ErrGatewayAccountGroup
+ }
+ nativeAntigravity := target == PlatformAntigravity && (family == domain.PlatformGatewayAnthropic || family == domain.PlatformGatewayGemini)
+ if spec.Gateway != family && !nativeAntigravity {
+ return nil, ErrGatewayProtocolsPending
+ }
+ // Validate model scope while the account still has its neutral identity: no
+ // official provider defaults or passthrough options can bypass a whitelist.
+ scope := *current
+ scope.Credentials = maps.Clone(current.Credentials)
+ scope.modelMappingCacheReady = false
+ id := liveGroup.ID
+ selectionModel := model
+ publicModel := model
+ if selection, enabled := requestGatewaySelection(ctx, &id, target); enabled && selection.family == family {
+ selectionModel = selection.model
+ publicModel = selection.publicModel
+ if scheduling, _ := ctx.Value(gatewaySchedulingModelContextKey{}).(string); scheduling != "" {
+ selectionModel = scheduling
+ }
+ }
+ if original, ok := RequestedPublicModelFromContext(ctx); ok {
+ publicModel = original
+ }
+ // Account source-key scope and binding eligibility follow selection, before
+ // channel rewriting. Forward retains model as the channel input and applies
+ // the existing account mapping to it; a wire alias grants no binding rights.
+ if !liveGroup.ModelAllowlist.Allows(publicModel) || !scope.isModelMappingSupported(selectionModel) || !scope.IsModelAllowedInGroup(&id, selectionModel) {
+ return nil, ErrGatewayAccountGroup
+ }
+ view := scope
+ view.gatewayProtocolSource = &scope
+ view.gatewayProtocolModel = model
+ view.gatewayBindingModel = selectionModel
+ view.Type = AccountTypeAPIKey
+ view.Platform = string(family)
+ // Provider-specific alternate credentials/endpoints are not gateway inputs.
+ // Keep only the one upstream key/site and portable mapping/header settings.
+ view.Credentials = make(map[string]any)
+ for _, key := range []string{"api_key", "base_url", "model_mapping", "compact_model_mapping", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
+ if value, ok := scope.Credentials[key]; ok {
+ view.Credentials[key] = value
+ }
+ }
+ // Only normalize a terminal protocol version. Tenant prefixes stay intact;
+ // native builders append the protocol's own /v1 or /v1beta exactly once.
+ base := strings.TrimSuffix(strings.TrimRight(view.GetCredential("base_url"), "/"), "/v1beta")
+ if family == domain.PlatformGatewayGemini || family == domain.PlatformGatewayAnthropic {
+ base = strings.TrimSuffix(base, "/v1")
+ }
+ view.Credentials["base_url"] = base
+ delete(view.Credentials, "api_base_urls")
+ view.Extra = maps.Clone(current.Extra)
+ if view.Extra == nil {
+ view.Extra = make(map[string]any)
+ }
+ for _, key := range []string{"openai_connections_managed", "openai_copilot_sdk", "openai_prism_browser", "custom_base_url_enabled"} {
+ delete(view.Extra, key)
+ }
+ view.modelMappingCacheReady = false
+ if !view.IsSchedulableForModelWithContext(ctx, selectionModel) || !view.IsSchedulableForModelWithContext(ctx, model) {
+ return nil, ErrGatewayProtocolsPending
+ }
+ if family == domain.PlatformGatewayAnthropic {
+ view.Extra["anthropic_passthrough"] = true
+ }
+ if family == domain.PlatformGatewayOpenAI {
+ view.Extra["openai_passthrough"] = true
+ view.Extra["openai_passthrough_model_filter"] = true
+ }
+ return &view, nil
+}
diff --git a/backend/internal/service/gateway_protocol_admission_test.go b/backend/internal/service/gateway_protocol_admission_test.go
new file mode 100644
index 000000000000..c3e55f7f758a
--- /dev/null
+++ b/backend/internal/service/gateway_protocol_admission_test.go
@@ -0,0 +1,175 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
+ "github.com/stretchr/testify/require"
+)
+
+type gatewayProtocolAdmissionRepo struct {
+ AccountRepository
+ account *Account
+ group *Group
+ calls int
+}
+
+func (r *gatewayProtocolAdmissionRepo) GatewayRequestAccount(_ context.Context, _, _ int64) (*Account, *Group, error) {
+ r.calls++
+ return r.account, r.group, nil
+}
+
+func gatewayProtocolFixture(target string) (*gatewayProtocolAdmissionRepo, context.Context) {
+ a := &Account{ID: 959, Platform: PlatformGateway, Type: AccountTypeGateway, Status: StatusActive, Schedulable: true,
+ Concurrency: 2, Priority: 7, GroupIDs: []int64{1}, AccountGroups: []AccountGroup{{GroupID: 1}},
+ Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example/tenant/v1", "api_key": "synthetic-only"}}
+ g := &Group{ID: 1, Platform: target, Status: StatusActive, Hydrated: true}
+ return &gatewayProtocolAdmissionRepo{account: a, group: g}, context.WithValue(context.Background(), ctxkey.Group, g)
+}
+
+func TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity(t *testing.T) {
+ for _, spec := range domain.Platforms() {
+ for _, composite := range []bool{false, true} {
+ t.Run(spec.ID+map[bool]string{false: "/concrete", true: "/composite"}[composite], func(t *testing.T) {
+ repo, ctx := gatewayProtocolFixture(spec.ID)
+ if composite {
+ repo.group.Platform = PlatformComposite
+ ctx = WithResolvedTargetPlatform(ctx, spec.ID)
+ }
+ family := spec.Gateway
+ if family == domain.PlatformGatewayAntigravity {
+ family = domain.PlatformGatewayAnthropic
+ }
+ view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, family, "public-model")
+ require.NoError(t, err)
+ require.Equal(t, repo.account.ID, view.ID)
+ require.Equal(t, 2, view.Concurrency)
+ require.Equal(t, 7, view.Priority)
+ require.Equal(t, AccountTypeAPIKey, view.Type)
+ require.Equal(t, "synthetic-only", view.GetCredential("api_key"))
+ wantBase := "https://gateway.example/tenant/v1"
+ if family == domain.PlatformGatewayGemini || family == domain.PlatformGatewayAnthropic {
+ wantBase = "https://gateway.example/tenant"
+ }
+ require.Equal(t, wantBase, view.GetCredential("base_url"))
+ require.Equal(t, "public-model", view.GetMappedModel("public-model"), "default model names pass through")
+ require.Equal(t, PlatformGateway, repo.account.Platform)
+ require.Equal(t, AccountTypeGateway, repo.account.Type)
+ view.Credentials["api_key"] = "changed-view-only"
+ require.Equal(t, "synthetic-only", repo.account.GetCredential("api_key"))
+ })
+ }
+ }
+}
+
+func TestGatewayProtocolAdmissionRejectsUnboundWrongTargetAndOAuth(t *testing.T) {
+ for _, scenario := range []string{"no-context", "unbound", "wrong-target", "oauth-only", "disabled-group", "disabled-account", "unschedulable", "unresolved-composite", "invalid-url", "model-group", "model-account", "wrong-protocol", "legacy-replacement"} {
+ t.Run(scenario, func(t *testing.T) {
+ repo, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ family := domain.PlatformGatewayOpenAI
+ switch scenario {
+ case "no-context":
+ ctx = context.Background()
+ case "unbound":
+ repo.account.GroupIDs, repo.account.AccountGroups = nil, nil
+ case "wrong-target":
+ ctx = WithResolvedTargetPlatform(ctx, PlatformKimi)
+ case "oauth-only":
+ repo.group.RequireOAuthOnly = true
+ case "disabled-group":
+ repo.group.Status = StatusDisabled
+ case "disabled-account":
+ repo.account.Status = StatusDisabled
+ case "unschedulable":
+ repo.account.Schedulable = false
+ case "unresolved-composite":
+ repo.group.Platform = PlatformComposite
+ case "invalid-url":
+ repo.account.Credentials["base_url"] = "https://gateway.example?key=secret"
+ case "model-group":
+ repo.account.AccountGroups[0].AllowedModels = []string{"other"}
+ case "model-account":
+ repo.account.Credentials["model_mapping"] = map[string]any{"other": "other"}
+ case "wrong-protocol":
+ family = domain.PlatformGatewayGemini
+ case "legacy-replacement":
+ repo.account.Type, repo.account.Platform = AccountTypeAPIKey, PlatformOpenAI
+ }
+ _, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, family, "public-model")
+ require.Error(t, err)
+ })
+ }
+}
+
+func TestGatewayProtocolAdmissionBaseVersionAndModelScopes(t *testing.T) {
+ for _, suffix := range []string{"", "/v1", "/v1beta", "/v1/"} {
+ repo, ctx := gatewayProtocolFixture(PlatformGemini)
+ repo.account.Credentials["base_url"] = "https://gateway.example/tenant" + suffix
+ view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayGemini, "public-model")
+ require.NoError(t, err)
+ require.Equal(t, "https://gateway.example/tenant", view.GetCredential("base_url"))
+ require.Equal(t, "https://gateway.example/tenant"+suffix, repo.account.GetCredential("base_url"), "URL normalization is request-local")
+ }
+ repo, ctx := gatewayProtocolFixture(PlatformComposite)
+ ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{Matched: true, PublicModel: "public-alias", UpstreamModel: "resolved-model", TargetPlatform: PlatformOpenAI})
+ repo.group.ModelAllowlist = GroupModelAllowlist{Enabled: true, Models: []string{"public-alias"}}
+ repo.account.AccountGroups[0].AllowedModels = []string{"resolved-model"}
+ repo.account.Credentials["model_mapping"] = map[string]any{"resolved-model": "upstream-model"}
+ view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "resolved-model")
+ require.NoError(t, err)
+ require.Equal(t, "upstream-model", view.GetMappedModel("resolved-model"))
+ repo.account.Credentials["api_base_urls"] = map[string]any{"responses": "https://alternate.invalid"}
+ repo.account.Extra = map[string]any{"openai_copilot_sdk": true, "openai_connections_managed": true}
+ view, err = prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "resolved-model")
+ require.NoError(t, err)
+ require.NotContains(t, view.Credentials, "api_base_urls")
+ require.False(t, view.IsCopilotSDKEnabled())
+ require.False(t, view.HasManagedOpenAIConnections())
+}
+
+func TestGatewayProtocolAdmissionAntigravityAcceptsBothNativeProtocols(t *testing.T) {
+ repo, ctx := gatewayProtocolFixture(PlatformAntigravity)
+ for _, family := range []domain.PlatformGateway{domain.PlatformGatewayAnthropic, domain.PlatformGatewayGemini} {
+ view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, family, "custom-model")
+ require.NoError(t, err)
+ require.Equal(t, "custom-model", view.GetMappedModel("custom-model"), "do not inject official Antigravity mappings into a relay")
+ }
+ ctx = context.WithValue(ctx, ctxkey.ForcePlatform, PlatformGemini)
+ _, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayGemini, "custom-model")
+ require.Error(t, err, "forced URL must not bypass concrete group target")
+}
+
+func TestGatewayProtocolAdmissionSharedStateAndSelectionIdentity(t *testing.T) {
+ repo, ctx := gatewayProtocolFixture(PlatformComposite)
+ selected := *repo.account
+ selected.Credentials = map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example/tenant/v1", "api_key": "synthetic-only"}
+ repo.account.Credentials["api_key"] = "rotated-after-selection"
+ _, err := prepareGatewayProtocolAccount(WithResolvedTargetPlatform(ctx, PlatformOpenAI), &selected, repo, domain.PlatformGatewayOpenAI, "public-model")
+ require.ErrorIs(t, err, ErrGatewayAccountIdentity)
+ repo.account.Credentials["api_key"] = "synthetic-only"
+ repo.account.Status = StatusError
+ for _, target := range []string{PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity} {
+ family := domain.PlatformGateway(target)
+ if target == PlatformAntigravity {
+ family = domain.PlatformGatewayAnthropic
+ }
+ _, err := prepareGatewayProtocolAccount(WithResolvedTargetPlatform(ctx, target), &selected, repo, family, "public-model")
+ require.Error(t, err, "one shared account error blocks all target protocols")
+ }
+}
+
+func TestGatewayProtocolAdmissionPreservesModelCooldown(t *testing.T) {
+ repo, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ repo.account.Extra = map[string]any{modelRateLimitsKey: map[string]any{
+ "public-model": map[string]any{"rate_limit_reset_at": time.Now().Add(time.Hour).Format(time.RFC3339)},
+ }}
+ _, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "public-model")
+ require.ErrorIs(t, err, ErrGatewayProtocolsPending, "transport view must retain existing per-model cooldown admission")
+ _, err = prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "another-model")
+ require.NoError(t, err, "a model cooldown does not erase other model capacity")
+}
diff --git a/backend/internal/service/gateway_protocol_forward_test.go b/backend/internal/service/gateway_protocol_forward_test.go
new file mode 100644
index 000000000000..d60c06ba4655
--- /dev/null
+++ b/backend/internal/service/gateway_protocol_forward_test.go
@@ -0,0 +1,170 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+)
+
+type gatewayProtocolTransport struct {
+ anthropicHTTPUpstreamRecorder
+ accountID int64
+ concurrency int
+ proxyURL string
+}
+
+func (u *gatewayProtocolTransport) Do(req *http.Request, proxy string, id int64, concurrency int) (*http.Response, error) {
+ u.accountID, u.concurrency = id, concurrency
+ u.proxyURL = proxy
+ return u.anthropicHTTPUpstreamRecorder.Do(req, proxy, id, concurrency)
+}
+
+func (u *gatewayProtocolTransport) DoWithTLS(req *http.Request, proxy string, id int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) {
+ return u.Do(req, proxy, id, concurrency)
+}
+
+func TestGatewayProtocolAnthropicBaseVersionsReachNativeBuilder(t *testing.T) {
+ for _, target := range []string{PlatformAnthropic, PlatformAntigravity} {
+ for _, prefix := range []string{"", "/tenant"} {
+ for _, suffix := range []string{"", "/v1", "/v1/", "/v1beta"} {
+ t.Run(target+prefix+suffix, func(t *testing.T) {
+ repo, ctx := gatewayProtocolFixture(target)
+ base := "https://gateway.example" + prefix + suffix
+ repo.account.Credentials["base_url"] = base
+ view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayAnthropic, "public-model")
+ require.NoError(t, err)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
+ svc := &GatewayService{cfg: rawChatCompletionsTestConfig()}
+ req, _, err := svc.buildUpstreamRequestAnthropicAPIKeyPassthrough(ctx, c, view, []byte(`{"model":"public-model","messages":[]}`), "synthetic-only")
+ require.NoError(t, err)
+ require.Equal(t, prefix+"/v1/messages", req.URL.Path)
+ require.Equal(t, "gateway.example", req.URL.Host)
+ require.Equal(t, base, repo.account.GetCredential("base_url"), "stored site and tenant prefix stay intact")
+ })
+ }
+ }
+ }
+}
+
+func TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity(t *testing.T) {
+ for _, route := range []string{"anthropic", "openai", "gemini", "antigravity-messages", "antigravity-gemini"} {
+ t.Run(route, func(t *testing.T) {
+ target := route
+ if strings.HasPrefix(route, "antigravity-") {
+ target = PlatformAntigravity
+ }
+ repo, ctx := gatewayProtocolFixture(target)
+ repo.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"}
+ body := []byte(`{"model":"public-model","messages":[{"role":"user","content":"hello"}],"max_tokens":16,"stream":false}`)
+ path, content := "/v1/messages", `{"id":"fixture","type":"message","model":"upstream-model","content":[{"type":"text","text":"OK"}],"usage":{"input_tokens":10,"output_tokens":2}}`
+ if route == "openai" {
+ path = "/v1/responses"
+ body = []byte(`{"model":"public-model","input":"hello","stream":false}`)
+ content = `{"id":"resp_fixture","object":"response","status":"completed","model":"upstream-model","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":10,"output_tokens":2,"total_tokens":12}}`
+ }
+ if route == "gemini" || route == "antigravity-gemini" {
+ path = "/v1beta/models/public-model:generateContent"
+ body = []byte(`{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}`)
+ content = `{"candidates":[{"content":{"parts":[{"text":"OK"}],"role":"model"},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2,"totalTokenCount":12}}`
+ }
+ if strings.HasPrefix(route, "antigravity-") {
+ path = "/antigravity" + path
+ }
+ upstream := &gatewayProtocolTransport{anthropicHTTPUpstreamRecorder: anthropicHTTPUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"fixture-id"}}, Body: io.NopCloser(strings.NewReader(content))}}}
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)).WithContext(ctx)
+ c.Request.Host = "inbound-only.invalid"
+ c.Request.Header.Set("Authorization", "Bearer inbound-must-not-leak")
+ cfg := &config.Config{}
+ var err error
+ switch route {
+ case "anthropic":
+ svc := &GatewayService{cfg: cfg, accountRepo: repo, httpUpstream: upstream,
+ responseHeaderFilter: compileResponseHeaderFilter(cfg), rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}}
+ _, err = svc.Forward(ctx, c, repo.account, &ParsedRequest{Body: NewRequestBodyRef(body), Model: "public-model"})
+ case "openai":
+ svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), accountRepo: &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: repo}, httpUpstream: upstream, requireLatestTurnAdmission: true,
+ rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}, responseHeaderFilter: compileResponseHeaderFilter(cfg)}
+ _, err = svc.Forward(ctx, c, repo.account, body)
+ case "gemini":
+ svc := &GeminiMessagesCompatService{cfg: cfg, accountRepo: repo, httpUpstream: upstream, rateLimitService: &RateLimitService{}}
+ _, err = svc.ForwardNative(ctx, c, repo.account, "public-model", "generateContent", false, body)
+ case "antigravity-messages":
+ svc := &AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream, rateLimitService: &RateLimitService{}, settingService: &SettingService{cfg: cfg}}
+ _, err = svc.Forward(ctx, c, repo.account, body, false)
+ case "antigravity-gemini":
+ svc := &AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream, rateLimitService: &RateLimitService{}, settingService: &SettingService{cfg: cfg}}
+ _, err = svc.ForwardGemini(ctx, c, repo.account, "public-model", "generateContent", false, body, false)
+ }
+ require.NoError(t, err)
+ require.NotNil(t, upstream.lastReq, "real service entry must reach its existing native upstream builder")
+ require.Equal(t, "gateway.example", upstream.lastReq.URL.Host)
+ if route == "gemini" || route == "antigravity-gemini" {
+ require.Equal(t, "/tenant/v1beta/models/upstream-model:generateContent", upstream.lastReq.URL.Path)
+ require.Equal(t, "synthetic-only", upstream.lastReq.Header.Get("x-goog-api-key"))
+ } else {
+ want := "/tenant/v1/messages"
+ if route == "openai" {
+ want = "/tenant/v1/responses"
+ }
+ require.Equal(t, want, upstream.lastReq.URL.Path)
+ require.Contains(t, string(upstream.lastBody), "upstream-model")
+ require.NotContains(t, upstream.lastReq.Header.Get("Authorization"), "inbound-must-not-leak")
+ }
+ require.Equal(t, AccountTypeGateway, repo.account.Type)
+ require.Equal(t, PlatformGateway, repo.account.Platform)
+ require.Equal(t, int64(959), repo.account.ID)
+ require.Equal(t, int64(959), upstream.accountID, "all native transports share one account key and connection budget")
+ require.Equal(t, 2, upstream.concurrency)
+ require.NotEmpty(t, recorder.Body.String())
+ })
+ }
+}
+
+func TestGatewayProtocolForwardRejectsRemovedMembershipBeforeTransport(t *testing.T) {
+ for _, route := range []string{"anthropic", "openai", "gemini", "antigravity-messages", "antigravity-gemini"} {
+ t.Run(route, func(t *testing.T) {
+ target := route
+ if strings.HasPrefix(route, "antigravity-") {
+ target = PlatformAntigravity
+ }
+ repo, ctx := gatewayProtocolFixture(target)
+ selected := *repo.account
+ repo.account = &Account{ID: selected.ID, Platform: PlatformGateway, Type: AccountTypeGateway,
+ Status: StatusActive, Schedulable: true, Credentials: selected.Credentials}
+ upstream := &gatewayProtocolTransport{}
+ body := []byte(`{"model":"public-model","messages":[{"role":"user","content":"hello"}]}`)
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)).WithContext(ctx)
+ var err error
+ switch route {
+ case "anthropic":
+ _, err = (&GatewayService{accountRepo: repo, httpUpstream: upstream}).Forward(ctx, c, &selected, &ParsedRequest{Model: "public-model", Body: NewRequestBodyRef(body)})
+ case "openai":
+ _, err = (&OpenAIGatewayService{accountRepo: repo, httpUpstream: upstream}).Forward(ctx, c, &selected, body)
+ case "gemini":
+ _, err = (&GeminiMessagesCompatService{accountRepo: repo, httpUpstream: upstream}).ForwardNative(ctx, c, &selected, "public-model", "generateContent", false, body)
+ case "antigravity-messages":
+ _, err = (&AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream}).Forward(ctx, c, &selected, body, false)
+ case "antigravity-gemini":
+ _, err = (&AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream}).ForwardGemini(ctx, c, &selected, "public-model", "generateContent", false, body, false)
+ }
+ require.ErrorIs(t, err, ErrGatewayAccountGroup)
+ require.Nil(t, upstream.lastReq, "stale selection cannot leak a key after membership removal")
+ })
+ }
+}
diff --git a/backend/internal/service/gateway_protocol_openai_admission_test.go b/backend/internal/service/gateway_protocol_openai_admission_test.go
new file mode 100644
index 000000000000..cc3634d023b2
--- /dev/null
+++ b/backend/internal/service/gateway_protocol_openai_admission_test.go
@@ -0,0 +1,200 @@
+//go:build unit
+
+package service
+
+import (
+ "bytes"
+ "context"
+ "io"
+ "maps"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/require"
+ "github.com/tidwall/gjson"
+)
+
+// Both production reader capabilities are required; a supplied-account-only
+// fixture cannot exercise the final authoritative OpenAI send boundary.
+type gatewayProtocolOpenAIRepo struct {
+ *gatewayProtocolAdmissionRepo
+ turnReads int
+ changeAt int
+ change func(*Account)
+}
+
+func (r *gatewayProtocolOpenAIRepo) GetOpenAITurnAdmission(context.Context, int64) (*Account, *Account, error) {
+ r.turnReads++
+ a := *r.account
+ a.Credentials = maps.Clone(a.Credentials)
+ if r.change != nil && r.turnReads >= r.changeAt {
+ r.change(&a)
+ }
+ return &a, nil, nil
+}
+
+func gatewayProtocolOpenAIForward(t *testing.T, route string, stream bool, repo *gatewayProtocolOpenAIRepo, ctx context.Context) (*OpenAIForwardResult, *gatewayProtocolTransport, *httptest.ResponseRecorder, error) {
+ t.Helper()
+ path := "/v1/responses"
+ body := []byte(`{"model":"public-model","input":"hello","stream":false}`)
+ if stream {
+ body = []byte(`{"model":"public-model","input":"hello","stream":true}`)
+ }
+ if route == "compact" {
+ path += "/compact"
+ }
+ if route == "chat" || route == "messages" {
+ path = "/v1/chat/completions"
+ body = []byte(`{"model":"public-model","messages":[{"role":"user","content":"hello"}],"max_tokens":16,"stream":false}`)
+ if route == "messages" {
+ path = "/v1/messages"
+ }
+ }
+ content := `{"id":"resp_fixture","object":"response","status":"completed","model":"upstream-model","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":10,"output_tokens":2,"total_tokens":12}}`
+ contentType := "application/json"
+ // Chat/Messages bridges always request upstream Responses SSE, including
+ // buffered downstream clients. Their fixture must supply a terminal event.
+ if stream || route == "chat" || route == "messages" {
+ contentType = "text/event-stream"
+ content = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"OK\"}\n\ndata: {\"type\":\"response.completed\",\"response\":" + content + "}\n\ndata: [DONE]\n\n"
+ }
+ if route == "compact" {
+ if mapped, ok := repo.account.ResolveCompactMappedModel("public-model"); ok {
+ content = strings.ReplaceAll(content, "upstream-model", mapped)
+ }
+ }
+ upstream := &gatewayProtocolTransport{anthropicHTTPUpstreamRecorder: anthropicHTTPUpstreamRecorder{resp: &http.Response{
+ StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(content))}}}
+ recorder := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(recorder)
+ c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)).WithContext(ctx)
+ groupID := repo.group.ID
+ c.Set("api_key", &APIKey{GroupID: &groupID})
+ cfg := rawChatCompletionsTestConfig()
+ svc := &OpenAIGatewayService{cfg: cfg, accountRepo: repo, httpUpstream: upstream,
+ requireLatestTurnAdmission: true, rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}, responseHeaderFilter: compileResponseHeaderFilter(cfg)}
+ var result *OpenAIForwardResult
+ var err error
+ switch route {
+ case "chat":
+ result, err = svc.ForwardAsChatCompletions(ctx, c, repo.account, body, "", "")
+ case "messages":
+ result, err = svc.ForwardAsAnthropic(ctx, c, repo.account, body, "", "")
+ default:
+ result, err = svc.Forward(ctx, c, repo.account, body)
+ }
+ return result, upstream, recorder, err
+}
+
+func TestGatewayProtocolOpenAIAuthoritativeAdmission(t *testing.T) {
+ for _, route := range []string{"responses", "chat", "messages"} {
+ t.Run(route, func(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ base.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"}
+ base.account.AccountGroups[0].AllowedModels = []string{"public-model"}
+ proxyID := int64(95)
+ base.account.ProxyID = &proxyID
+ base.account.Proxy = &Proxy{ID: proxyID, Protocol: "http", Host: "proxy.invalid", Port: 8080}
+ repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base}
+ result, upstream, _, err := gatewayProtocolOpenAIForward(t, route, false, repo, ctx)
+ require.NoError(t, err)
+ require.NotNil(t, result)
+ require.GreaterOrEqual(t, repo.turnReads, 2, "initial and actual-send admission must both read authority")
+ require.NotNil(t, upstream.lastReq)
+ require.Equal(t, "upstream-model", gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Equal(t, route != "responses", gjson.GetBytes(upstream.lastBody, "stream").Bool())
+ require.False(t, result.Stream, "buffered downstream stays buffered while bridges consume upstream SSE")
+ require.Equal(t, "public-model", result.Model)
+ require.Equal(t, "upstream-model", result.UpstreamModel)
+ require.Equal(t, 10, result.Usage.InputTokens)
+ require.Equal(t, int64(959), upstream.accountID)
+ require.Equal(t, 2, upstream.concurrency)
+ require.Equal(t, "http://proxy.invalid:8080", upstream.proxyURL)
+ require.Equal(t, PlatformGateway, repo.account.Platform)
+ require.False(t, repo.account.IsSchedulable(), "the scheduler stays fail closed")
+ })
+ }
+}
+
+func TestGatewayProtocolOpenAIRejectsFinalAuthorityChanges(t *testing.T) {
+ for _, route := range []string{"responses", "chat", "messages"} {
+ for _, change := range []string{"membership", "disabled", "credential", "platform", "cooldown", "disabled-group", "oauth-only"} {
+ t.Run(route+"/"+change, func(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base, changeAt: 2, change: func(a *Account) {
+ switch change {
+ case "membership":
+ a.GroupIDs, a.AccountGroups = nil, nil
+ case "disabled":
+ a.Status = StatusDisabled
+ case "credential":
+ a.Credentials["api_key"] = "rotated-synthetic-only"
+ case "platform":
+ a.Platform, a.Type = PlatformOpenAI, AccountTypeAPIKey
+ case "cooldown":
+ a.Schedulable = false
+ case "disabled-group":
+ base.group.Status = StatusDisabled
+ case "oauth-only":
+ base.group.RequireOAuthOnly = true
+ }
+ }}
+ _, upstream, _, err := gatewayProtocolOpenAIForward(t, route, false, repo, ctx)
+ require.Error(t, err)
+ require.GreaterOrEqual(t, repo.turnReads, 2)
+ require.Nil(t, upstream.lastReq, "a later authoritative rejection must precede transport")
+ })
+ }
+ }
+}
+
+func TestGatewayProtocolOpenAILegacyPassthroughKeepsWireModel(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ base.account.Platform, base.account.Type = PlatformOpenAI, AccountTypeAPIKey
+ base.account.Extra = map[string]any{"openai_passthrough": true}
+ base.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"}
+ repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base}
+ result, upstream, _, err := gatewayProtocolOpenAIForward(t, "responses", false, repo, ctx)
+ require.NoError(t, err)
+ require.Equal(t, "public-model", gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Equal(t, "public-model", result.Model)
+ require.Empty(t, result.UpstreamModel)
+}
+
+func TestGatewayProtocolOpenAIResponsesMappedWireModel(t *testing.T) {
+ for _, scenario := range []struct {
+ name, route string
+ stream bool
+ }{
+ {"nonstream", "responses", false}, {"stream", "responses", true}, {"compact", "compact", false}, {"compact-override", "compact", false},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ base, ctx := gatewayProtocolFixture(PlatformOpenAI)
+ base.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"}
+ wantModel := "upstream-model"
+ if scenario.name == "compact-override" {
+ wantModel = "compact-upstream-model"
+ base.account.Credentials["compact_model_mapping"] = map[string]any{"public-model": wantModel}
+ }
+ repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base}
+ result, upstream, recorder, err := gatewayProtocolOpenAIForward(t, scenario.route, scenario.stream, repo, ctx)
+ require.NoError(t, err)
+ require.Equal(t, wantModel, gjson.GetBytes(upstream.lastBody, "model").String())
+ require.Equal(t, scenario.stream, gjson.GetBytes(upstream.lastBody, "stream").Bool())
+ require.Equal(t, "hello", gjson.GetBytes(upstream.lastBody, "input").String())
+ wantPath := "/tenant/v1/responses"
+ if scenario.route == "compact" {
+ wantPath += "/compact"
+ }
+ require.Equal(t, wantPath, upstream.lastReq.URL.Path)
+ require.Equal(t, "public-model", result.Model)
+ require.Equal(t, wantModel, result.UpstreamModel)
+ require.Empty(t, result.BillingModel, "retain existing passthrough public-model billing")
+ require.Contains(t, recorder.Body.String(), "public-model")
+ require.Equal(t, 10, result.Usage.InputTokens)
+ })
+ }
+}
diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go
index e47bf70434c5..9b1fcabd06aa 100644
--- a/backend/internal/service/gateway_scheduling.go
+++ b/backend/internal/service/gateway_scheduling.go
@@ -1019,7 +1019,12 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr
return PlatformAnthropic, false, nil
}
-func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, bool, error) {
+func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) (accountsResult []Account, mixedResult bool, resultErr error) {
+ defer func() {
+ if resultErr == nil {
+ accountsResult, resultErr = s.appendGatewayMessagesCandidates(ctx, groupID, platform, accountsResult)
+ }
+ }()
if s.schedulerSnapshot != nil {
accounts, useMixed, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, hasForcePlatform)
if err == nil {
@@ -1157,6 +1162,9 @@ func (s *GatewayService) isAccountAllowedForPlatform(account *Account, platform
if account == nil {
return false
}
+ if account.IsGateway() {
+ return account.gatewayMessagesView != nil && platform == account.gatewaySelectionTarget
+ }
if useMixed {
if account.Platform == platform {
return true
@@ -1170,6 +1178,9 @@ func (s *GatewayService) isAccountSchedulableForSelection(account *Account) bool
if account == nil {
return false
}
+ if account.IsGateway() {
+ return account.gatewayMessagesView != nil && account.gatewayMessagesView.IsSchedulable()
+ }
return account.IsSchedulable()
}
@@ -1177,6 +1188,9 @@ func (s *GatewayService) isAccountSchedulableForModelSelection(ctx context.Conte
if account == nil {
return false
}
+ if account.IsGateway() {
+ return account.gatewayMessagesView != nil && account.gatewayMessagesView.IsSchedulableForModelWithContext(ctx, requestedModel)
+ }
return account.IsSchedulableForModelWithContext(ctx, requestedModel)
}
@@ -1490,6 +1504,17 @@ func (s *GatewayService) ReleaseAccountSession(ctx context.Context, account *Acc
}
func (s *GatewayService) getSchedulableAccount(ctx context.Context, accountID int64) (*Account, error) {
+ if group, _ := ctx.Value(ctxkey.Group).(*Group); group != nil {
+ scope, _ := ctx.Value(gatewaySelectionKey{}).(gatewaySelection)
+ if _, enabled := requestGatewaySelection(ctx, &group.ID, scope.target); enabled {
+ if reader := gatewayAccountReader(s.accountRepo, s.schedulerSnapshot); reader != nil {
+ fresh, _, err := reader.GatewayRequestAccount(ctx, accountID, group.ID)
+ if err == nil && fresh != nil && fresh.gatewayProtocolsPending() {
+ return s.refreshGatewayMessagesSelection(ctx, fresh)
+ }
+ }
+ }
+ }
var (
account *Account
err error
@@ -1540,6 +1565,9 @@ func (s *GatewayService) isAccountBlockedBySchedulingThreshold(ctx context.Conte
}
func (s *GatewayService) hydrateSelectedAccount(ctx context.Context, account *Account) (*Account, error) {
+ if account != nil && account.gatewayProtocolsPending() {
+ return s.refreshGatewayMessagesSelection(ctx, account)
+ }
if account == nil || s.schedulerSnapshot == nil {
return account, nil
}
@@ -1917,7 +1945,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context,
if clearSticky {
_ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash)
}
- if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) {
+ if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.isAccountAllowedForPlatform(account, platform, false) && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) {
if s.debugModelRoutingEnabled() {
logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] legacy routed sticky hit: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), accountID)
}
@@ -2039,7 +2067,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context,
if clearSticky {
_ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash)
}
- if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) {
+ if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.isAccountAllowedForPlatform(account, platform, false) && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) {
return account, nil
}
}
@@ -2314,7 +2342,7 @@ func (s *GatewayService) selectAccountWithMixedScheduling(ctx context.Context, g
_ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash)
}
if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) {
- if account.Platform == nativePlatform || (account.Platform == PlatformAntigravity && account.IsMixedSchedulingEnabled()) {
+ if s.isAccountAllowedForPlatform(account, nativePlatform, true) {
return account, nil
}
}
@@ -2573,6 +2601,9 @@ func isPlatformFilteredForSelection(acc *Account, platform string, allowMixedSch
if acc == nil {
return true
}
+ if acc.IsGateway() && acc.gatewayMessagesView != nil {
+ return platform != acc.gatewaySelectionTarget
+ }
if allowMixedScheduling {
if acc.Platform == PlatformAntigravity {
return !acc.IsMixedSchedulingEnabled()
diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go
index e3ca35f72612..357db7921ffb 100644
--- a/backend/internal/service/gateway_service.go
+++ b/backend/internal/service/gateway_service.go
@@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"regexp"
+ "slices"
"sort"
"strconv"
"strings"
@@ -629,6 +630,9 @@ func shouldClearStickySession(account *Account, requestedModel string) bool {
if account == nil {
return false
}
+ if account.IsGateway() && account.gatewayMessagesView != nil {
+ account = account.gatewayMessagesView
+ }
if !account.IsSchedulable() {
return true
}
@@ -1516,6 +1520,21 @@ func mixedListingModelAllowed(groupPlatform, model string) bool {
}
func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64, platform string) []string {
+ legacy := s.cachedAvailableModels(ctx, groupID, platform)
+ catalog, err := s.readGatewayModelCatalog(ctx, groupID, platform)
+ if err != nil {
+ return legacy
+ }
+ models := catalog.directModels(platform)
+ if len(models) == 0 {
+ return legacy
+ }
+ combined := append(slices.Clone(legacy), models...)
+ slices.Sort(combined)
+ return slices.Compact(combined)
+}
+
+func (s *GatewayService) cachedAvailableModels(ctx context.Context, groupID *int64, platform string) []string {
cacheKey := modelsListCacheKey(groupID, platform)
if s.modelsListCache != nil {
if cached, found := s.modelsListCache.Get(cacheKey); found {
diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go
index 40c403511825..ddd0d8c25a98 100644
--- a/backend/internal/service/gateway_usage_billing.go
+++ b/backend/internal/service/gateway_usage_billing.go
@@ -992,6 +992,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage
addCacheStorageToAccountStatsCost(usageLog, cacheStorageCost)
}
+ captureGatewayProcurementCost(usageLog, account)
simpleModeKeyRateLimitOnly := simpleModeKeyRateLimitBillingEnabled(s.cfg, apiKey)
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple && !simpleModeKeyRateLimitOnly {
writeUsageLogBestEffort(ctx, s.usageLogRepo, usageLog, "service.gateway")
diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go
index 1135b6e8c113..1071ec6bc178 100644
--- a/backend/internal/service/gemini_messages_compat_service.go
+++ b/backend/internal/service/gemini_messages_compat_service.go
@@ -541,6 +541,13 @@ func (s *GeminiMessagesCompatService) HasAntigravityAccounts(ctx context.Context
}
func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) {
+ if account.gatewayProtocolsPending() {
+ view, err := s.gatewayProtocolAccount(ctx, account, "gemini", gatewayProtocolBodyModel(body))
+ if err != nil {
+ return nil, err
+ }
+ account = view
+ }
if err := CheckUpstreamModeration(ctx, c, account); err != nil {
return nil, err
}
@@ -755,6 +762,15 @@ func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Contex
if err := checkAPIKeyLongContextRequestBeforeForward(ctx, c, upstreamReq, originalModel, mappedModel); err != nil {
return nil, err
}
+ if account.gatewayProtocolSource != nil {
+ latest, err := s.gatewayProtocolAccount(ctx, account.gatewayProtocolSource, "gemini", account.gatewayProtocolModel)
+ if err != nil {
+ return nil, err
+ }
+ if openAITurnRouteFingerprint(latest) != openAITurnRouteFingerprint(account) {
+ return nil, ErrGatewayAccountIdentity
+ }
+ }
resp, err = s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency)
s.rateLimitService.observeQualityResponse(upstreamReq.Context(), account, resp, err)
if err != nil {
@@ -1112,6 +1128,13 @@ func isGeminiSignatureRelatedError(respBody []byte) bool {
}
func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte) (*ForwardResult, error) {
+ if account.gatewayProtocolsPending() {
+ view, err := s.gatewayProtocolAccount(ctx, account, "gemini", originalModel)
+ if err != nil {
+ return nil, err
+ }
+ account = view
+ }
if err := CheckUpstreamModeration(ctx, c, account); err != nil {
return nil, err
}
@@ -1320,6 +1343,15 @@ func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.
if err := checkAPIKeyLongContextRequestBeforeForward(ctx, c, upstreamReq, originalModel, mappedModel); err != nil {
return nil, err
}
+ if account.gatewayProtocolSource != nil {
+ latest, err := s.gatewayProtocolAccount(ctx, account.gatewayProtocolSource, "gemini", account.gatewayProtocolModel)
+ if err != nil {
+ return nil, err
+ }
+ if openAITurnRouteFingerprint(latest) != openAITurnRouteFingerprint(account) {
+ return nil, ErrGatewayAccountIdentity
+ }
+ }
resp, err = s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency)
s.rateLimitService.observeQualityResponse(upstreamReq.Context(), account, resp, err)
if err != nil {
diff --git a/backend/internal/service/new_api_authorization.go b/backend/internal/service/new_api_authorization.go
index fc5eca5fbf97..85380979c21d 100644
--- a/backend/internal/service/new_api_authorization.go
+++ b/backend/internal/service/new_api_authorization.go
@@ -101,7 +101,8 @@ func (s *UpstreamBillingProbeService) newAPIAccount(ctx context.Context, id int6
if e != nil {
return nil, "", e
}
- if !isUpstreamBillingProbeAccount(a) || a.GetCredential("api_key") == "" {
+ if !isUpstreamBillingProbeAccount(a) || a.GetCredential("api_key") == "" ||
+ (a.IsGateway() && a.GetCredential(GatewayUpstreamKindCredentialKey) != "new_api") {
return nil, "", ErrUpstreamBillingProbeAccountInvalid
}
site, e := CanonicalNewAPISite(a.GetCredential("base_url"))
@@ -117,6 +118,15 @@ func (s *UpstreamBillingProbeService) GetNewAPIConfig(ctx context.Context, id in
if e != nil {
return nil, e
}
+ gateways, e := s.accountRepo.ListAllWithFilters(ctx, PlatformGateway, AccountTypeGateway, "", "", 0, "")
+ if e != nil {
+ return nil, e
+ }
+ for i := range gateways {
+ if gateways[i].IsGateway() && gateways[i].GetCredential(GatewayUpstreamKindCredentialKey) == "new_api" {
+ accounts = append(accounts, gateways[i])
+ }
+ }
found := false
for i := range accounts {
if accounts[i].ID == id {
diff --git a/backend/internal/service/new_api_authorization_test.go b/backend/internal/service/new_api_authorization_test.go
index 99b51e1b09f6..44c613d5c32b 100644
--- a/backend/internal/service/new_api_authorization_test.go
+++ b/backend/internal/service/new_api_authorization_test.go
@@ -13,10 +13,12 @@ type newAPIAccounts struct {
*upstreamBillingProbeAccountRepo
}
-func (r *newAPIAccounts) ListAllWithFilters(context.Context, string, string, string, string, int64, string) ([]Account, error) {
+func (r *newAPIAccounts) ListAllWithFilters(_ context.Context, platform, kind, _, _ string, _ int64, _ string) ([]Account, error) {
out := []Account{}
for _, a := range r.accounts {
- out = append(out, *a)
+ if (platform == "" || platform == a.Platform) && (kind == "" || kind == a.Type) {
+ out = append(out, *a)
+ }
}
return out, nil
}
@@ -67,6 +69,26 @@ func TestNewAPIConfigNoSaveForForeignOrUnmatchedAccounts(t *testing.T) {
require.Empty(t, r.bindings)
}
}
+func TestNewAPIGatewayAuthorizationUsesDeclaredProvider(t *testing.T) {
+ s, auth, _, repo := newAPIConfigFixture()
+ gateway := repo.accounts[1]
+ gateway.Platform, gateway.Type = PlatformGateway, AccountTypeGateway
+ gateway.Credentials[GatewayUpstreamKindCredentialKey] = "sub2api"
+ _, err := s.GetNewAPIConfig(context.Background(), gateway.ID)
+ require.ErrorIs(t, err, ErrUpstreamBillingProbeAccountInvalid)
+
+ gateway.Credentials[GatewayUpstreamKindCredentialKey] = "new_api"
+ preview, err := s.SaveNewAPIConfig(context.Background(), gateway.ID, NewAPIConfigRequest{UserID: 7, AccountIDs: []int64{gateway.ID}, AccessToken: "synthetic-management-token"})
+ require.NoError(t, err)
+ require.Len(t, preview.Accounts, 1)
+ require.Nil(t, preview.Accounts[0].CostMultiplier)
+ require.Equal(t, 2.5, preview.Wallet.Amount)
+ config, err := s.GetNewAPIConfig(context.Background(), repo.accounts[2].ID)
+ require.NoError(t, err)
+ require.Len(t, config.Accounts, 2)
+ require.NotNil(t, auth.bindings[gateway.ID])
+}
+
func TestNewAPIConfigSharedEncryptedAuthAndSafeRead(t *testing.T) {
s, r, h, accounts := newAPIConfigFixture()
h.bodies["GET /api/token/?p=0&page_size=100"] = `{"success":true,"data":{"items":[{"id":3,"key":"abcd**********wxyz","group":"vip"},{"id":4,"key":"nope**********xxxx","group":"auto"}],"total":2,"page":1,"page_size":100}}`
diff --git a/backend/internal/service/openai_account_scheduler.go b/backend/internal/service/openai_account_scheduler.go
index 98ce4b638e56..ab3cee1a8129 100644
--- a/backend/internal/service/openai_account_scheduler.go
+++ b/backend/internal/service/openai_account_scheduler.go
@@ -2729,7 +2729,18 @@ func (s *OpenAIGatewayService) SelectAccountWithSchedulerForCapability(
if len(platformOverride) > 0 {
platform = platformOverride[0]
}
- return s.selectAccountWithScheduler(ctx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, "", requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost)
+ selection, decision, err := s.selectAccountWithScheduler(ctx, groupID, previousResponseID, sessionHash, requestedModel, excludedIDs, requiredTransport, requiredCapability, "", requireCompact, platform, previousResponseCanMove, useUpstreamTokenCost)
+ if err == nil && selection != nil && selection.Account != nil && selection.Account.gatewayProtocolSource != nil {
+ view, readErr := s.openAIGatewaySelectionView(ctx, selection.Account)
+ if readErr != nil {
+ if selection.ReleaseFunc != nil {
+ selection.ReleaseFunc()
+ }
+ return nil, decision, readErr
+ }
+ selection.Account = view.gatewayProtocolSource
+ }
+ return selection, decision, err
}
func (s *OpenAIGatewayService) SelectAccountWithSchedulerForImages(
diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go
index a1c2eb8af092..f37b760c1ef6 100644
--- a/backend/internal/service/openai_gateway_chat_completions.go
+++ b/backend/internal/service/openai_gateway_chat_completions.go
@@ -98,6 +98,13 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions(
promptCacheKey string,
defaultMappedModel string,
) (*OpenAIForwardResult, error) {
+ if account.gatewayProtocolsPending() {
+ view, err := s.gatewayProtocolAccount(ctx, account, "openai", gatewayProtocolBodyModel(body))
+ if err != nil {
+ return nil, err
+ }
+ account = view
+ }
admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String())
if admissionErr != nil {
@@ -439,6 +446,13 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions(
}
// 5. Get access token
+ if account.gatewayProtocolSource != nil {
+ latest, err := s.admitOpenAITurn(ctx, c, account, upstreamModel, responsesBody)
+ if err != nil {
+ return nil, err
+ }
+ account = latest
+ }
token, _, err := s.GetAccessToken(ctx, account)
if err != nil {
return nil, fmt.Errorf("get access token: %w", err)
diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go
index 7d388dd8c1fb..913f0d66b9f0 100644
--- a/backend/internal/service/openai_gateway_count_tokens.go
+++ b/backend/internal/service/openai_gateway_count_tokens.go
@@ -50,6 +50,9 @@ func (s *OpenAIGatewayService) ForwardResponsesInputTokens(
account *Account,
body []byte,
) error {
+ if account.gatewayProtocolsPending() {
+ return ErrGatewayProtocolsPending
+ }
if account == nil {
writeOpenAIResponsesInputTokensError(c, http.StatusServiceUnavailable, "api_error", "No available OpenAI accounts")
return fmt.Errorf("responses input_tokens: missing account")
@@ -268,6 +271,9 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic(
body []byte,
defaultMappedModel string,
) error {
+ if account.gatewayProtocolsPending() {
+ return ErrGatewayProtocolsPending
+ }
if account == nil {
writeAnthropicCountTokensError(c, http.StatusServiceUnavailable, "api_error", "No available OpenAI accounts")
return fmt.Errorf("count_tokens: missing account")
diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go
index 7c606691cda0..d419de374ec7 100644
--- a/backend/internal/service/openai_gateway_forward.go
+++ b/backend/internal/service/openai_gateway_forward.go
@@ -91,6 +91,13 @@ func prismBrowserResponsesURL(baseURL string) string {
// Forward forwards request to OpenAI API
func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (result *OpenAIForwardResult, resultErr error) {
+ if account.gatewayProtocolsPending() {
+ view, err := s.gatewayProtocolAccount(ctx, account, "openai", gatewayProtocolBodyModel(body))
+ if err != nil {
+ return nil, err
+ }
+ account = view
+ }
ctx = s.withOAuth429Routing(ctx, gjson.GetBytes(body, "model").String(), IsOpenAIResponsesCompactPath(c))
endpoint := ""
if IsOpenAIResponsesCompactPath(c) {
diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go
index 8e78ef95a8fe..82519128e781 100644
--- a/backend/internal/service/openai_gateway_messages.go
+++ b/backend/internal/service/openai_gateway_messages.go
@@ -33,6 +33,13 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic(
promptCacheKey string,
defaultMappedModel string,
) (*OpenAIForwardResult, error) {
+ if account.gatewayProtocolsPending() {
+ view, err := s.gatewayProtocolAccount(ctx, account, "openai", gatewayProtocolBodyModel(body))
+ if err != nil {
+ return nil, err
+ }
+ account = view
+ }
admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String())
if admissionErr != nil {
@@ -419,6 +426,13 @@ func (s *OpenAIGatewayService) forwardAsAnthropic(
}
// 5. Get access token
+ if account.gatewayProtocolSource != nil {
+ latest, err := s.admitOpenAITurn(ctx, c, account, upstreamModel, responsesBody)
+ if err != nil {
+ return nil, err
+ }
+ account = latest
+ }
token, _, err := s.getRequestCredential(ctx, c, account)
if err != nil {
return nil, fmt.Errorf("get access token: %w", err)
diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go
index 5c881dc56851..e8df76c13bcb 100644
--- a/backend/internal/service/openai_gateway_passthrough.go
+++ b/backend/internal/service/openai_gateway_passthrough.go
@@ -140,6 +140,20 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough(
ctx = withOpenAITransportMode(ctx, "passthrough")
requestedModel := reqModel
upstreamPassthroughModel := ""
+ // Gateway accounts retain explicit portable mappings even though their
+ // transport uses passthrough. Legacy passthrough keeps its original contract.
+ if account != nil && account.gatewayProtocolSource != nil {
+ mappedModel := account.GetMappedModel(reqModel)
+ if mappedModel != "" && mappedModel != reqModel {
+ nextBody, setErr := sjson.SetBytes(body, "model", mappedModel)
+ if setErr != nil {
+ return nil, fmt.Errorf("set gateway passthrough model: %w", setErr)
+ }
+ body = nextBody
+ upstreamPassthroughModel = mappedModel
+ attemptImageIntentInvalidated = true
+ }
+ }
if isOpenAIResponsesCompactPath(c) && !account.IsCopilotSDKEnabled() {
compactMappedModel := s.resolveOpenAICompactFallbackModel(account, reqModel)
if compactMappedModel != "" && compactMappedModel != reqModel {
diff --git a/backend/internal/service/openai_gateway_scheduling.go b/backend/internal/service/openai_gateway_scheduling.go
index 5c2d174d50b1..dfaf7895c7bb 100644
--- a/backend/internal/service/openai_gateway_scheduling.go
+++ b/backend/internal/service/openai_gateway_scheduling.go
@@ -1706,7 +1706,7 @@ func (s *OpenAIGatewayService) listSchedulableAccounts(ctx context.Context, grou
if platform == PlatformGrok {
accounts = s.filterGrokFreeQuotaAccountsForOpenAI(ctx, accounts)
}
- return accounts, nil
+ return appendGatewayCandidates(ctx, s.accountRepo, s.schedulerSnapshot, groupID, platform, accounts), nil
}
var accounts []Account
var err error
@@ -1724,7 +1724,7 @@ func (s *OpenAIGatewayService) listSchedulableAccounts(ctx context.Context, grou
if platform == PlatformGrok {
accounts = s.filterGrokFreeQuotaAccountsForOpenAI(ctx, accounts)
}
- return accounts, nil
+ return appendGatewayCandidates(ctx, s.accountRepo, s.schedulerSnapshot, groupID, platform, accounts), nil
}
func (s *OpenAIGatewayService) tryAcquireAccountSlot(ctx context.Context, accountID int64, maxConcurrency int) (*AcquireResult, error) {
@@ -1755,7 +1755,13 @@ func (s *OpenAIGatewayService) resolveFreshSchedulableOpenAIAccountBeforeProfit(
platform = NormalizeOpenAICompatiblePlatform(platform)
fresh := account
- if s.schedulerSnapshot != nil {
+ if account.gatewayProtocolSource != nil {
+ current, err := s.openAIGatewaySelectionView(ctx, account)
+ if err != nil {
+ return nil
+ }
+ fresh = current
+ } else if s.schedulerSnapshot != nil {
current, err := s.getSchedulableAccount(ctx, account.ID)
if err != nil || current == nil {
return nil
@@ -1815,7 +1821,14 @@ func (s *OpenAIGatewayService) recheckSelectedOpenAIAccountFromDBBeforeProfit(ct
return nil
}
platform = NormalizeOpenAICompatiblePlatform(platform)
- if s.schedulerSnapshot == nil || s.accountRepo == nil {
+ if account.gatewayProtocolSource != nil {
+ view, err := s.openAIGatewaySelectionView(ctx, account)
+ if err != nil {
+ return nil
+ }
+ account = view
+ }
+ if account.gatewayProtocolSource != nil || s.schedulerSnapshot == nil || s.accountRepo == nil {
if s.openAIGroupRequiresPrivacySet(ctx, groupID) && !account.IsPrivacySet() {
return nil
}
@@ -1883,6 +1896,20 @@ func (s *OpenAIGatewayService) getSchedulableAccount(ctx context.Context, accoun
} else {
account, err = s.accountRepo.GetByID(ctx, accountID)
}
+ if account == nil && s.schedulerSnapshot != nil {
+ scope, _ := ctx.Value(gatewaySelectionKey{}).(gatewaySelection)
+ if _, ok := requestGatewaySelection(ctx, &scope.groupID, scope.target); ok {
+ if reader := gatewayAccountReader(s.accountRepo, s.schedulerSnapshot); reader != nil {
+ fresh, _, readErr := reader.GatewayRequestAccount(ctx, accountID, scope.groupID)
+ if readErr == nil && fresh != nil && fresh.IsGateway() {
+ account, err = fresh, nil
+ }
+ }
+ }
+ }
+ if err == nil && account != nil && account.IsGateway() {
+ account, err = s.openAIGatewaySelectionView(ctx, account)
+ }
if err != nil || account == nil {
return account, err
}
@@ -1930,6 +1957,9 @@ func (s *OpenAIGatewayService) isOpenAIAccountBlockedBySchedulingThreshold(ctx c
}
func (s *OpenAIGatewayService) hydrateSelectedAccount(ctx context.Context, account *Account) (*Account, error) {
+ if account != nil && account.gatewayProtocolSource != nil {
+ return s.openAIGatewaySelectionView(ctx, account)
+ }
if account == nil || s.schedulerSnapshot == nil {
return account, nil
}
diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go
index 7233f4bfdca1..66cf892c1a3f 100644
--- a/backend/internal/service/openai_gateway_usage.go
+++ b/backend/internal/service/openai_gateway_usage.go
@@ -533,6 +533,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec
)
}
+ captureGatewayProcurementCost(usageLog, account)
simpleModeKeyRateLimitOnly := simpleModeKeyRateLimitBillingEnabled(s.cfg, apiKey)
if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple && !simpleModeKeyRateLimitOnly {
writeUsageLogBestEffort(ctx, s.usageLogRepo, usageLog, "service.openai_gateway")
diff --git a/backend/internal/service/openai_model_retirement.go b/backend/internal/service/openai_model_retirement.go
index 5881808f9a05..f960749834b9 100644
--- a/backend/internal/service/openai_model_retirement.go
+++ b/backend/internal/service/openai_model_retirement.go
@@ -110,5 +110,8 @@ func supportsOpenAIRequestModel(account *Account, requestedModel string, require
if isRetiredOpenAISubscriptionModel(account, target) {
return false
}
+ if account.gatewayBindingModel != "" {
+ return account.gatewayProtocolSource.isModelMappingSupported(account.gatewayBindingModel)
+ }
return account.isModelMappingSupported(requestedModel)
}
diff --git a/backend/internal/service/openai_turn_admission.go b/backend/internal/service/openai_turn_admission.go
index b0132e0a4459..13a13831e8f6 100644
--- a/backend/internal/service/openai_turn_admission.go
+++ b/backend/internal/service/openai_turn_admission.go
@@ -11,6 +11,7 @@ import (
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/gin-gonic/gin"
)
@@ -258,7 +259,12 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup(
if selected == nil {
return nil, denyOpenAITurn("account_unavailable")
}
- if !selected.IsOpenAI() && (s.schedulerSnapshot == nil || s.schedulerSnapshot.localSnapshotReader == nil) {
+ gatewayView := selected.gatewayProtocolSource != nil
+ gatewayModel := selected.gatewayProtocolModel
+ if gatewayView {
+ selected = selected.gatewayProtocolSource
+ }
+ if !gatewayView && !selected.IsOpenAI() && (s.schedulerSnapshot == nil || s.schedulerSnapshot.localSnapshotReader == nil) {
// This patch changes OpenAI Responses admission only, not other
// providers which share the generic forwarding implementation.
return selected, nil
@@ -271,13 +277,22 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup(
// and persistence fence must never be bypassed by the process admission
// cache, including already established WebSocket turns.
var err error
- latest, err = s.schedulerSnapshot.GetAccount(ctx, selected.ID)
+ if gatewayView {
+ scope, _ := ctx.Value(gatewaySelectionKey{}).(gatewaySelection)
+ reader := gatewayAccountReader(s.accountRepo, s.schedulerSnapshot)
+ if reader == nil {
+ return nil, denyOpenAITurn("latest_state_unavailable")
+ }
+ latest, _, err = reader.GatewayRequestAccount(ctx, selected.ID, scope.groupID)
+ } else {
+ latest, err = s.schedulerSnapshot.GetAccount(ctx, selected.ID)
+ }
if err != nil || latest == nil || latest.ID != selected.ID || latest.IsShadow() {
return nil, denyOpenAITurn("latest_state_unavailable")
}
authoritativeRead = true
} else {
- if ttl := s.openAITurnAdmissionCacheTTL(); ttl > 0 {
+ if ttl := s.openAITurnAdmissionCacheTTL(); ttl > 0 && !gatewayView {
if cached, cachedParent, ok := s.openAITurnAdmissionCache.load(selected.ID, ttl); ok {
latest, parent, authoritativeRead = cached, cachedParent, true
}
@@ -285,7 +300,7 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup(
if s.accountRepo != nil {
reader, ok := s.accountRepo.(OpenAITurnAdmissionReader)
if !ok {
- if s.requireLatestTurnAdmission {
+ if s.requireLatestTurnAdmission || gatewayView {
return nil, denyOpenAITurn("latest_state_unavailable")
}
// Small direct-call fixtures may provide a repository for
@@ -304,11 +319,11 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup(
if err != nil || latest == nil || latest.ID != selected.ID {
return nil, denyOpenAITurn("latest_state_unavailable")
}
- if s.openAITurnAdmissionCacheTTL() > 0 {
+ if s.openAITurnAdmissionCacheTTL() > 0 && !gatewayView {
s.openAITurnAdmissionCache.store(latest, parent)
}
}
- } else if s.requireLatestTurnAdmission {
+ } else if s.requireLatestTurnAdmission || gatewayView {
// Real services are constructed with this flag. Small unit-test services
// can exercise the pure supplied-account predicate without a database.
return nil, denyOpenAITurn("latest_state_unavailable")
@@ -336,6 +351,31 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup(
}
}
}
+ if gatewayView {
+ // Keep the real turn reader and all common admission guards. Validate
+ // both uncached snapshots against the original neutral identity, then
+ // rebuild a view; never make the stored gateway schedulable.
+ reader := gatewayAccountReader(s.accountRepo, s.schedulerSnapshot)
+ if reader == nil || !authoritativeRead {
+ return nil, denyOpenAITurn("latest_state_unavailable")
+ }
+ group, _ := ctx.Value(ctxkey.Group).(*Group)
+ if group == nil || (enforceGroup && group.ID != groupID) {
+ return nil, denyOpenAITurn("group_membership_changed")
+ }
+ current, liveGroup, err := reader.GatewayRequestAccount(ctx, selected.ID, group.ID)
+ if err != nil {
+ return nil, &OpenAITurnAdmissionError{Reason: "latest_state_unavailable", cause: err}
+ }
+ if _, err := gatewayProtocolAccountFromSnapshot(ctx, selected, current, liveGroup, "openai", gatewayModel); err != nil {
+ return nil, &OpenAITurnAdmissionError{Reason: "account_ineligible", cause: err}
+ }
+ view, err := gatewayProtocolAccountFromSnapshot(ctx, selected, latest, liveGroup, "openai", gatewayModel)
+ if err != nil {
+ return nil, &OpenAITurnAdmissionError{Reason: "account_ineligible", cause: err}
+ }
+ latest = view
+ }
if authoritativeRead && !latest.IsSchedulable() {
return nil, denyOpenAITurn("account_ineligible")
}
@@ -416,7 +456,11 @@ func (s *OpenAIGatewayService) admitOpenAITurnWithGroup(
return nil, &OpenAITurnAdmissionError{Reason: excelOAuthRouteErrorCode, cause: err}
}
// 会话中途被收窄了分组内的可用模型、或后续 turn 换成了不允许的模型时,要求客户端重连重新选号。
- if enforceGroup && !latest.IsModelAllowedInGroup(&groupID, outboundModel) {
+ groupModel := outboundModel
+ if latest.gatewayProtocolSource != nil {
+ groupModel = latest.gatewayProtocolModel
+ }
+ if enforceGroup && !latest.IsModelAllowedInGroup(&groupID, groupModel) {
return nil, denyOpenAITurn("model_not_allowed_in_group")
}
if !latest.IsOpenAI() {
diff --git a/backend/internal/service/openai_ws_forwarder_support.go b/backend/internal/service/openai_ws_forwarder_support.go
index 2466d33bd4fc..4f59022a4f79 100644
--- a/backend/internal/service/openai_ws_forwarder_support.go
+++ b/backend/internal/service/openai_ws_forwarder_support.go
@@ -621,7 +621,10 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
}
account, err := s.getSchedulableAccount(ctx, accountID)
- if err != nil || account == nil {
+ if err != nil {
+ return 0, nil, "", nil
+ }
+ if account == nil {
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
return 0, nil, "", nil
}
@@ -659,9 +662,21 @@ func (s *OpenAIGatewayService) resolveAccountByPreviousResponseIDForCapability(
if vetoed, _ := openAIProfitControlVetoReason(ctx, account); vetoed {
return 0, nil, "", nil
}
- if s.schedulerSnapshot != nil && s.accountRepo != nil {
- latest, latestErr := s.accountRepo.GetByID(ctx, account.ID)
- if latestErr != nil || latest == nil {
+ if s.schedulerSnapshot != nil && (s.accountRepo != nil || s.schedulerSnapshot.localSnapshotReader != nil) {
+ var latest *Account
+ var latestErr error
+ switch {
+ case account.gatewayProtocolSource != nil:
+ latest, latestErr = s.openAIGatewaySelectionView(ctx, account)
+ case s.schedulerSnapshot.localSnapshotReader != nil:
+ latest, latestErr = s.schedulerSnapshot.GetAccount(ctx, account.ID)
+ default:
+ latest, latestErr = s.accountRepo.GetByID(ctx, account.ID)
+ }
+ if latestErr != nil {
+ return 0, nil, "", nil
+ }
+ if latest == nil {
_ = store.DeleteResponseAccount(ctx, derefGroupID(groupID), responseID)
return 0, nil, "", nil
}
diff --git a/backend/internal/service/procurement_cost_snapshot.go b/backend/internal/service/procurement_cost_snapshot.go
new file mode 100644
index 000000000000..d874c60af6e4
--- /dev/null
+++ b/backend/internal/service/procurement_cost_snapshot.go
@@ -0,0 +1,45 @@
+package service
+
+import "github.com/Wei-Shaw/sub2api/internal/domain"
+
+// ProcurementCostSnapshot is request-time evidence, independent of the user
+// charge and account debit multiplier. A nil CostMultiplier means unknown, not
+// zero. A nil snapshot denotes history/legacy accounts, not a current estimate.
+type ProcurementCostSnapshot struct {
+ Version int `json:"version"`
+ AccountType string `json:"account_type"`
+ Provider string `json:"provider"`
+ TargetPlatform string `json:"target_platform"`
+ Basis string `json:"basis"`
+ CostMultiplier *float64 `json:"cost_multiplier,omitempty"`
+}
+
+func captureGatewayProcurementCost(log *UsageLog, account *Account) {
+ if log == nil || !account.IsGateway() {
+ return
+ }
+ provider := account.GetCredential(GatewayUpstreamKindCredentialKey)
+ snapshot := &ProcurementCostSnapshot{Version: 1, AccountType: AccountTypeGateway,
+ Provider: provider, TargetPlatform: log.Platform, Basis: "total_cost"}
+ switch provider {
+ case "new_api":
+ if factor, ok := NewAPIGatewayCostForRequest(account, log.Platform); ok {
+ snapshot.CostMultiplier = &factor
+ }
+ case "sub2api":
+ if !domain.IsConcretePlatform(log.Platform) {
+ break
+ }
+ if !account.CostMultiplierAutoSyncEnabled() {
+ if factor, ok := accountCostMultiplierNumber(account.Extra[AccountCostMultiplierExtraKey]); ok {
+ snapshot.CostMultiplier = &factor
+ }
+ } else {
+ declaration := decodeUpstreamBillingProbeSnapshot(account.Extra)
+ if factor, ok := declaration.CostMultiplierToSync(); ok {
+ snapshot.CostMultiplier = &factor
+ }
+ }
+ }
+ log.ProcurementCostSnapshot = snapshot
+}
diff --git a/backend/internal/service/procurement_cost_snapshot_test.go b/backend/internal/service/procurement_cost_snapshot_test.go
new file mode 100644
index 000000000000..7f2ce03be94a
--- /dev/null
+++ b/backend/internal/service/procurement_cost_snapshot_test.go
@@ -0,0 +1,123 @@
+//go:build unit
+
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+func TestProcurementSnapshotMixedTargetsThroughUsageWriters(t *testing.T) {
+ for _, writer := range []string{"gateway", "openai"} {
+ t.Run(writer, func(t *testing.T) {
+ a := &Account{ID: 3, Platform: PlatformGateway, Type: AccountTypeGateway,
+ Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "new_api"}, Extra: map[string]any{UpstreamBillingProviderExtraKey: "new_api", AccountCostMultiplierExtraKey: 99.0}}
+ a.Extra[UpstreamBillingProbeExtraKey] = newAPISnapshot(a, NewAPIToken{Group: "fixed"}, &newAPIData{wallet: 12, ratios: map[string]float64{"fixed": .1}}, 30, time.Now())
+ var recorded []*UsageLog
+ for _, target := range []string{PlatformOpenAI, PlatformKimi} {
+ logs := &openAIRecordUsageLogRepoStub{inserted: true}
+ users, subs := &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{}
+ key := &APIKey{ID: 1, Group: &Group{Platform: PlatformComposite, RateMultiplier: .3}}
+ billing := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: false}}
+ if writer == "openai" {
+ svc := newOpenAIRecordUsageServiceForTest(logs, users, subs, nil)
+ svc.usageBillingRepo = billing
+ require.NoError(t, svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{
+ Result: &OpenAIForwardResult{RequestID: "procurement-" + target, Model: "gpt-5.1", Usage: OpenAIUsage{InputTokens: 100}},
+ APIKey: key, User: &User{ID: 2}, Account: a, QuotaPlatform: target}))
+ } else {
+ svc := newGatewayRecordUsageServiceWithBillingRepoForTest(logs, billing, users, subs)
+ require.NoError(t, svc.RecordUsage(context.Background(), &RecordUsageInput{
+ Result: &ForwardResult{RequestID: "procurement-" + target, Model: "claude-sonnet-4", Usage: ClaudeUsage{InputTokens: 100}},
+ APIKey: key, User: &User{ID: 2}, Account: a, QuotaPlatform: target}))
+ }
+ require.NotNil(t, logs.lastLog)
+ require.NotNil(t, logs.lastLog.ProcurementCostSnapshot)
+ require.NotNil(t, logs.lastLog.ProcurementCostSnapshot.CostMultiplier)
+ want := .7
+ if target == PlatformKimi {
+ want = .1
+ }
+ require.Equal(t, want, *logs.lastLog.ProcurementCostSnapshot.CostMultiplier)
+ require.Equal(t, target, logs.lastLog.ProcurementCostSnapshot.TargetPlatform)
+ recorded = append(recorded, logs.lastLog)
+ }
+ // Already-built asynchronous usage/events cannot be repriced by edits.
+ a.Extra[NewAPIApplyUSDRateExtraKey] = false
+ a.Extra[AccountCostMultiplierExtraKey] = 1.0
+ a.Extra[UpstreamBillingProbeExtraKey] = nil
+ for i, want := range []float64{.7, .1} {
+ raw, err := json.Marshal(&UsageBillingEvent{Version: 1, Usage: *recorded[i]})
+ require.NoError(t, err)
+ var event UsageBillingEvent
+ require.NoError(t, json.Unmarshal(raw, &event))
+ require.Equal(t, want, *event.Usage.ProcurementCostSnapshot.CostMultiplier)
+ require.Equal(t, recorded[i].TotalCost, event.Usage.TotalCost)
+ require.Equal(t, recorded[i].ActualCost, event.Usage.ActualCost)
+ }
+ })
+ }
+}
+
+func TestProcurementSnapshotUnknownAndLegacySemantics(t *testing.T) {
+ a := &Account{Platform: PlatformGateway, Type: AccountTypeGateway, Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "new_api"}}
+ log := &UsageLog{Platform: PlatformOpenAI, TotalCost: 10, ActualCost: 3}
+ captureGatewayProcurementCost(log, a)
+ require.NotNil(t, log.ProcurementCostSnapshot, "record unknown request-time evidence, never use the gateway's current account cost")
+ require.Nil(t, log.ProcurementCostSnapshot.CostMultiplier)
+ for _, kind := range []string{AccountTypeAPIKey, AccountTypeUpstream, AccountTypeOAuth} {
+ legacy := &UsageLog{Platform: PlatformOpenAI}
+ captureGatewayProcurementCost(legacy, &Account{Type: kind})
+ require.Nil(t, legacy.ProcurementCostSnapshot, "legacy single-platform reporting must retain its existing fallback")
+ }
+ require.Equal(t, 10.0, log.TotalCost)
+ require.Equal(t, 3.0, log.ActualCost)
+}
+
+func TestProcurementSnapshotZeroDisabledConversionAndUnresolvedTarget(t *testing.T) {
+ a := &Account{Platform: PlatformGateway, Type: AccountTypeGateway,
+ Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "new_api"},
+ Extra: map[string]any{UpstreamBillingProviderExtraKey: "new_api", NewAPIApplyUSDRateExtraKey: false}}
+ for _, rate := range []float64{0, .1} {
+ a.Extra[UpstreamBillingProbeExtraKey] = newAPISnapshot(a, NewAPIToken{Group: "fixed"}, &newAPIData{wallet: 12, ratios: map[string]float64{"fixed": rate}}, 30, time.Now())
+ log := &UsageLog{Platform: PlatformOpenAI}
+ captureGatewayProcurementCost(log, a)
+ require.NotNil(t, log.ProcurementCostSnapshot.CostMultiplier)
+ require.Equal(t, rate, *log.ProcurementCostSnapshot.CostMultiplier)
+ log.Platform = PlatformComposite
+ captureGatewayProcurementCost(log, a)
+ require.Nil(t, log.ProcurementCostSnapshot.CostMultiplier, "composite cannot decide the currency scale")
+ }
+}
+
+func TestProcurementSnapshotSub2APIDeclaredRate(t *testing.T) {
+ account := &Account{Type: AccountTypeGateway, Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "sub2api"},
+ Extra: map[string]any{UpstreamBillingProbeExtraKey: &UpstreamBillingProbeSnapshot{
+ Status: UpstreamBillingProbeStatusOK, LastAttemptAt: time.Now(),
+ Data: map[string]any{"billing_scope": "token", "resolved_rate_multiplier": .14, "peak_rate_enabled": false},
+ }}}
+ for _, target := range []string{PlatformKimi, PlatformOpenAI} {
+ log := &UsageLog{Platform: target}
+ captureGatewayProcurementCost(log, account)
+ require.NotNil(t, log.ProcurementCostSnapshot.CostMultiplier)
+ require.Equal(t, .14, *log.ProcurementCostSnapshot.CostMultiplier)
+ }
+}
+
+func TestProcurementSnapshotSub2APIManualRate(t *testing.T) {
+ account := &Account{Type: AccountTypeGateway, Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "sub2api"},
+ Extra: map[string]any{AccountCostAutoSyncExtraKey: false}}
+ log := &UsageLog{Platform: PlatformOpenAI}
+ captureGatewayProcurementCost(log, account)
+ require.Nil(t, log.ProcurementCostSnapshot.CostMultiplier)
+ for _, factor := range []float64{0, .25} {
+ account.Extra[AccountCostMultiplierExtraKey] = factor
+ captureGatewayProcurementCost(log, account)
+ require.NotNil(t, log.ProcurementCostSnapshot.CostMultiplier)
+ require.Equal(t, factor, *log.ProcurementCostSnapshot.CostMultiplier)
+ }
+}
diff --git a/backend/internal/service/regional_scheduler_sync.go b/backend/internal/service/regional_scheduler_sync.go
index 3765a517c73f..0939b006e201 100644
--- a/backend/internal/service/regional_scheduler_sync.go
+++ b/backend/internal/service/regional_scheduler_sync.go
@@ -9,6 +9,8 @@ import (
"net/http"
"time"
+ "github.com/Wei-Shaw/sub2api/internal/domain"
+ "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/regional"
)
@@ -69,12 +71,12 @@ func decodeRegionalScheduler(payload []byte) (RegionalSchedulerDocument, error)
if doc.Version != 1 || doc.Buckets == nil || len(doc.Buckets) > 4096 {
return doc, errors.New("invalid regional scheduler version or buckets")
}
- groups := make(map[int64]bool, len(doc.Groups))
+ groups := make(map[int64]*Group, len(doc.Groups))
for _, g := range doc.Groups {
- if g == nil || g.ID <= 0 || groups[g.ID] {
+ if g == nil || g.ID <= 0 || groups[g.ID] != nil {
return doc, errors.New("invalid regional group")
}
- groups[g.ID] = true
+ groups[g.ID] = g
}
// A repeated account must have identical credentials and policy in every
// bucket; otherwise hydration would depend on bucket iteration order.
@@ -89,7 +91,7 @@ func decodeRegionalScheduler(payload []byte) (RegionalSchedulerDocument, error)
return doc, errors.New("unsupported mixed scheduler bucket")
}
seen[b] = true
- if b.GroupID > 0 && len(entry.Accounts) > 0 && !groups[b.GroupID] {
+ if b.GroupID > 0 && len(entry.Accounts) > 0 && groups[b.GroupID] == nil {
return doc, errors.New("regional bucket missing group policy")
}
ids := make(map[int64]bool, len(entry.Accounts))
@@ -106,7 +108,13 @@ func decodeRegionalScheduler(payload []byte) (RegionalSchedulerDocument, error)
return doc, errors.New("conflicting regional account views")
}
accountViews[a.ID] = encoded
- if a.Platform != b.Platform && (b.Mode != SchedulerModeMixed || a.Platform != PlatformAntigravity || !a.IsMixedSchedulingEnabled()) {
+ if a.IsGateway() || a.Platform == PlatformGateway {
+ g := groups[b.GroupID]
+ if g == nil || !g.IsActive() || ValidateGatewayAccountGroup(a, g) != nil || !domain.IsConcretePlatform(b.Platform) ||
+ (g.Platform != PlatformComposite && g.Platform != b.Platform) {
+ return doc, errors.New("regional gateway assignment mismatch")
+ }
+ } else if a.Platform != b.Platform && (b.Mode != SchedulerModeMixed || a.Platform != PlatformAntigravity || !a.IsMixedSchedulingEnabled()) {
return doc, errors.New("regional account platform mismatch")
}
if b.GroupID > 0 {
@@ -229,6 +237,18 @@ func (s *SchedulerSnapshotService) ExportRegionalScheduler(ctx context.Context,
entry.Accounts = append(entry.Accounts, a)
}
}
+ if reader, ok := s.accountRepo.(GatewayRequestCandidateReader); ok && bucket.GroupID > 0 && len(allowed) > 0 {
+ candidates, group, err := reader.ListGatewayRequestCandidates(ctx, bucket.GroupID, bucket.Platform)
+ if err != nil {
+ return nil, err
+ }
+ for i := range candidates {
+ a := &candidates[i]
+ if allowed[a.ID] && group != nil && group.ID == bucket.GroupID && group.IsActive() && ValidateGatewayAccountGroup(a, group) == nil {
+ entry.Accounts = append(entry.Accounts, a)
+ }
+ }
+ }
doc.Buckets = append(doc.Buckets, entry)
}
payload, err := json.Marshal(doc)
@@ -361,3 +381,56 @@ func (r *RegionalSchedulerReader) GetLocalGroup(ctx context.Context, id int64) (
}
return out, nil
}
+
+// Read neutral accounts only from the configured bucket for this request. The
+// ordinary local snapshot and unscoped detail interfaces keep them invisible.
+func (r *RegionalSchedulerReader) ListGatewayRequestCandidates(ctx context.Context, groupID int64, target string) ([]Account, *Group, error) {
+ doc, expiry, err := r.detailView(ctx)
+ if err != nil {
+ return nil, nil, err
+ }
+ if _, ok := requestGatewaySelection(ctx, &groupID, target); !ok {
+ return nil, nil, ErrGatewayAccountGroup
+ }
+ var group *Group
+ for _, g := range doc.Groups {
+ if g.ID == groupID {
+ group = g
+ break
+ }
+ }
+ if group == nil || !group.IsActive() || group.RequireOAuthOnly || (group.Platform != target && group.Platform != PlatformComposite) {
+ return nil, nil, ErrGatewayAccountGroup
+ }
+ forced, _ := ctx.Value(ctxkey.ForcePlatform).(string)
+ bucket := SchedulerBucket{GroupID: groupID, Platform: target, Mode: (&SchedulerSnapshotService{}).resolveMode(target, forced != "")}
+ var accounts []Account
+ for _, entry := range doc.Buckets {
+ if entry.Bucket == bucket {
+ for _, account := range entry.Accounts {
+ if account.IsGateway() {
+ accounts = append(accounts, *account)
+ }
+ }
+ break
+ }
+ }
+ if err := regionalReadFinished(ctx, expiry); err != nil {
+ return nil, nil, err
+ }
+ return accounts, group, nil
+}
+
+func (r *RegionalSchedulerReader) GatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*Account, *Group, error) {
+ scope, _ := ctx.Value(gatewaySelectionKey{}).(gatewaySelection)
+ accounts, group, err := r.ListGatewayRequestCandidates(ctx, groupID, scope.target)
+ if err != nil {
+ return nil, nil, err
+ }
+ for i := range accounts {
+ if accounts[i].ID == accountID {
+ return &accounts[i], group, nil
+ }
+ }
+ return nil, group, ErrGatewayAccountGroup
+}
diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go
index 674f23cc672f..8557e359776e 100644
--- a/backend/internal/service/upstream_billing_probe.go
+++ b/backend/internal/service/upstream_billing_probe.go
@@ -152,7 +152,7 @@ func BuildUpstreamBillingRateSnapshotItems(accounts []Account) []UpstreamBilling
// The billing endpoint is supported by every API-key platform; limiting
// this projection to OpenAI would make the background refresh erase the
// other platforms' persisted snapshots from the table.
- if account.Type == AccountTypeAPIKey {
+ if account.Type == AccountTypeAPIKey || account.IsGateway() {
snapshot = decodeUpstreamBillingProbeSnapshot(account.Extra)
}
items = append(items, UpstreamBillingRateSnapshotItem{
@@ -630,7 +630,7 @@ func (s *UpstreamBillingProbeService) SetAccountEnabled(ctx context.Context, acc
func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, account *Account, intervalMinutes int) (*UpstreamBillingProbeSnapshot, error) {
now := s.currentTime().UTC()
- if s.newAPIRepo != nil {
+ if s.newAPIRepo != nil && (!account.IsGateway() || account.GetCredential(GatewayUpstreamKindCredentialKey) == "new_api") {
binding, err := s.newAPIRepo.GetBinding(ctx, account.ID)
if err != nil {
return nil, newAPIError("storage_unavailable")
@@ -639,6 +639,9 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac
return s.probeNewAPIAccount(ctx, account, binding, intervalMinutes)
}
}
+ if account.IsGateway() && account.GetCredential(GatewayUpstreamKindCredentialKey) == "new_api" {
+ return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "new_api_authorization_required", 0)
+ }
if s.accountTestService == nil || s.accountTestService.httpUpstream == nil {
return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "transport_unavailable", 0)
}
@@ -1125,14 +1128,11 @@ func isUpstreamBillingProbeStatus(status string) bool {
// CN providers, whose official-domain accounts are short-circuited to
// "unsupported" by upstreamBillingProbeTargetIsOfficialAPI).
// Non-sub2api upstreams return 404 and the snapshot records "unsupported".
-// Only AccountTypeAPIKey is in scope. OAuth/Bedrock hold no static API key to
-// present at all; AccountTypeUpstream (antigravity relay accounts) does carry
-// a base_url plus a static api_key, but it is deliberately left out of the
-// current supported set. New antigravity relay accounts are created with
-// type=apikey by the admin form, so only pre-existing type=upstream rows
-// cannot turn the probe on.
+// Explicit gateway accounts use either the configured New API authorization
+// or the Sub2API declaration endpoint. Other relay types retain their policy.
func IsUpstreamBillingProbeIdentity(platform, accountType string) bool {
- return accountType == AccountTypeAPIKey && domain.IsConcretePlatform(platform)
+ return (accountType == AccountTypeAPIKey && domain.IsConcretePlatform(platform)) ||
+ (accountType == AccountTypeGateway && platform == PlatformGateway)
}
func isUpstreamBillingProbeAccount(account *Account) bool {
diff --git a/backend/internal/service/usage_log.go b/backend/internal/service/usage_log.go
index c492bd6b915b..2e552399e1fc 100644
--- a/backend/internal/service/usage_log.go
+++ b/backend/internal/service/usage_log.go
@@ -103,7 +103,8 @@ func ApplyLegacyRequestFields(requestType RequestType, fallbackStream bool, fall
}
type UsageLog struct {
- CustomerCostDetails *CustomerCostDetails
+ ProcurementCostSnapshot *ProcurementCostSnapshot
+ CustomerCostDetails *CustomerCostDetails
// Platform snapshots the concrete upstream provider at request time. Gateway
// accounts use the resolved request target. Empty is unknown legacy data.
Platform string
diff --git a/backend/migrations/392_usage_procurement_cost_snapshot.sql b/backend/migrations/392_usage_procurement_cost_snapshot.sql
new file mode 100644
index 000000000000..0c7407cf9cac
--- /dev/null
+++ b/backend/migrations/392_usage_procurement_cost_snapshot.sql
@@ -0,0 +1,18 @@
+-- SQL-owned usage metadata, like account_stats_cost. Historical rows remain NULL;
+-- never backfill a request's procurement estimate from mutable account settings.
+ALTER TABLE usage_logs ADD COLUMN IF NOT EXISTS procurement_cost_snapshot JSONB;
+
+CREATE OR REPLACE FUNCTION reject_usage_procurement_cost_rewrite() RETURNS trigger
+LANGUAGE plpgsql AS $$
+BEGIN
+ IF OLD.procurement_cost_snapshot IS DISTINCT FROM NEW.procurement_cost_snapshot THEN
+ RAISE EXCEPTION 'usage procurement cost snapshot is immutable';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+
+DROP TRIGGER IF EXISTS usage_procurement_cost_immutable ON usage_logs;
+CREATE TRIGGER usage_procurement_cost_immutable
+BEFORE UPDATE OF procurement_cost_snapshot ON usage_logs
+FOR EACH ROW EXECUTE FUNCTION reject_usage_procurement_cost_rewrite();
diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue
index e831dc0665f6..95b7d122e1f4 100644
--- a/frontend/src/components/account/CreateAccountModal.vue
+++ b/frontend/src/components/account/CreateAccountModal.vue
@@ -250,6 +250,12 @@