mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
fix: enhance build session identity handling and response ownership tracking
This commit is contained in:
1 parent
539a6ae20e
commit
3c4e0ef174
17 files changed
+384
-75
No files matched your search
@@ -18,6 +18,8 @@ type buildSessionIdentity struct {
|
||||
upstreamID string
|
||||
// affinityKey 用于账号粘滞;按模型隔离,避免不同模型能力账号互相覆盖。
|
||||
affinityKey string
|
||||
// replayKey 仅由客户端显式会话信号生成;soft 消息锚点不得驱动 encrypted reasoning 回放。
|
||||
replayKey string
|
||||
// soft 表示由消息内容兜底生成(无显式 session 时),仍须稳定。
|
||||
soft bool
|
||||
}
|
||||
@@ -38,9 +40,11 @@ func resolveBuildSessionIdentity(clientKeyID uint64, provider accountdomain.Prov
|
||||
if seed != "" {
|
||||
upstreamSource := fmt.Sprintf("grok2api:build-session:%s:%d:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, seed)
|
||||
affinitySource := fmt.Sprintf("grok2api:build-affinity:%s:%d:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, model, seed)
|
||||
replaySource := fmt.Sprintf("grok2api:build-replay:%s:%d:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, seed)
|
||||
return buildSessionIdentity{
|
||||
upstreamID: digestUUID(upstreamSource),
|
||||
affinityKey: hexDigest(affinitySource),
|
||||
replayKey: hexDigest(replaySource),
|
||||
}
|
||||
}
|
||||
// CPA 风格消息 hash 兜底:无 session 时仍尽量粘账号 + 稳定 conv-id,服务 Sub2API 未透传 session 的场景。
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
func TestResolveBuildSessionIdentityIsStableAndTenantIsolated(t *testing.T) {
|
||||
base := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-1", nil)
|
||||
if len(base.upstreamID) != 36 || len(base.affinityKey) != 64 || base != resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-1", nil) {
|
||||
if len(base.upstreamID) != 36 || len(base.affinityKey) != 64 || len(base.replayKey) != 64 || base != resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-1", nil) {
|
||||
t.Fatalf("unstable identity = %#v", base)
|
||||
}
|
||||
for name, value := range map[string]buildSessionIdentity{
|
||||
@@ -55,6 +55,9 @@ func TestResolveBuildSessionIdentitySoftFromMessagesIsStableAcrossTurns(t *testi
|
||||
if !first.soft || first.upstreamID == "" {
|
||||
t.Fatalf("expected soft identity, got %#v", first)
|
||||
}
|
||||
if first.replayKey != "" {
|
||||
t.Fatalf("soft identity must not enable reasoning replay: %#v", first)
|
||||
}
|
||||
if first.upstreamID != second.upstreamID || first.affinityKey != second.affinityKey {
|
||||
t.Fatalf("soft identity drifted across turns: first=%#v second=%#v", first, second)
|
||||
}
|
||||
@@ -72,6 +75,9 @@ func TestResolveBuildSessionIdentitySoftFromResponsesInput(t *testing.T) {
|
||||
if first.upstreamID == "" || first != second || !first.soft {
|
||||
t.Fatalf("responses soft identity unstable: %#v %#v", first, second)
|
||||
}
|
||||
if first.replayKey != "" {
|
||||
t.Fatalf("responses soft identity must not enable reasoning replay: %#v", first)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveBuildSessionIdentityUsesInstructionsAsSystemAnchor(t *testing.T) {
|
||||
|
||||
@@ -440,25 +440,37 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
|
||||
return nil, clientkeyapp.ErrModelNotAllowed
|
||||
}
|
||||
affinityKey := ""
|
||||
ownershipPromptCacheKey := ""
|
||||
reasoningReplayKey := ""
|
||||
if route.Provider == accountdomain.ProviderBuild {
|
||||
// 显式 key / session seed / 消息锚点 soft session(CPA 风格),禁止空 session 随机 conv-id。
|
||||
identity := resolveBuildSessionIdentity(
|
||||
input.ClientKey.ID,
|
||||
route.Provider,
|
||||
route.UpstreamModel,
|
||||
input.PromptCacheKey,
|
||||
input.PromptCacheSeed,
|
||||
input.Body,
|
||||
)
|
||||
identity := buildSessionIdentity{}
|
||||
if ownership != nil && ownership.PromptCacheKey != "" {
|
||||
// previous_response_id 属于既有 Response 链,必须继承根会话身份,
|
||||
// 不能用本轮增量 input 重新计算 soft key。
|
||||
identity.upstreamID = ownership.PromptCacheKey
|
||||
identity.replayKey = ownership.ReasoningReplayKey
|
||||
} else {
|
||||
identity = resolveBuildSessionIdentity(
|
||||
input.ClientKey.ID,
|
||||
route.Provider,
|
||||
route.UpstreamModel,
|
||||
input.PromptCacheKey,
|
||||
input.PromptCacheSeed,
|
||||
input.Body,
|
||||
)
|
||||
}
|
||||
input.PromptCacheKey = identity.upstreamID
|
||||
affinityKey = identity.affinityKey
|
||||
ownershipPromptCacheKey = identity.upstreamID
|
||||
reasoningReplayKey = identity.replayKey
|
||||
if identity.upstreamID == "" {
|
||||
s.logger.Debug("prompt_cache_session_empty", "request_id", input.RequestID, "model", route.UpstreamModel, "provider", route.Provider)
|
||||
} else if identity.soft {
|
||||
s.logger.Debug("prompt_cache_session_soft", "request_id", input.RequestID, "model", route.UpstreamModel)
|
||||
}
|
||||
}
|
||||
adapter, ok := s.providers.Responses(route.Provider)
|
||||
adapter, ok := s.providers.Responses(route.Provider)
|
||||
if !ok {
|
||||
return nil, ErrNoAvailableAccount
|
||||
}
|
||||
@@ -490,7 +502,7 @@ adapter, ok := s.providers.Responses(route.Provider)
|
||||
failureAttempts := newFailureAttemptRecorder(http.MethodPost, path)
|
||||
forwardResponse := func(credential accountdomain.Credential, billing *accountdomain.Billing) (*provider.Response, error) {
|
||||
started := time.Now()
|
||||
response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)})
|
||||
response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, ReasoningReplayKey: reasoningReplayKey, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)})
|
||||
err = failureAttempts.captureResponse(credential, started, response, err)
|
||||
timing.markUpstream(time.Since(started))
|
||||
return response, err
|
||||
@@ -796,7 +808,9 @@ attemptLoop:
|
||||
}
|
||||
}
|
||||
if supportsStoredResponses && operation == audit.OperationResponses && responseID != "" && response.StatusCode >= 200 && response.StatusCode < 300 {
|
||||
_ = s.responses.Save(persistCtx, inferencedomain.ResponseOwnership{ResponseID: responseID, AccountID: accountID, ClientKeyID: input.ClientKey.ID, Provider: route.Provider, ExpiresAt: now.Add(responseOwnershipTTL), CreatedAt: now, UpdatedAt: now})
|
||||
if err := s.responses.Save(persistCtx, inferencedomain.ResponseOwnership{ResponseID: responseID, AccountID: accountID, ClientKeyID: input.ClientKey.ID, Provider: route.Provider, PromptCacheKey: ownershipPromptCacheKey, ReasoningReplayKey: reasoningReplayKey, ExpiresAt: now.Add(responseOwnershipTTL), CreatedAt: now, UpdatedAt: now}); err != nil {
|
||||
s.logger.Error("response_ownership_save_failed", "response_id", responseID, "client_key_id", input.ClientKey.ID, "account_id", accountID, "provider", route.Provider, "error", err)
|
||||
}
|
||||
}
|
||||
outcome := "failed"
|
||||
if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" {
|
||||
|
||||
@@ -145,6 +145,9 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
if adapter.lastPromptCacheKey != expectedCacheKey {
|
||||
t.Fatalf("prompt cache key = %q, want %q", adapter.lastPromptCacheKey, expectedCacheKey)
|
||||
}
|
||||
if adapter.lastReasoningReplayKey != identity.replayKey {
|
||||
t.Fatalf("reasoning replay key = %q, want %q", adapter.lastReasoningReplayKey, identity.replayKey)
|
||||
}
|
||||
if boundID, ok, err := sticky.Get(ctx, stickySessionKey(identity.affinityKey), time.Now().UTC()); err != nil || !ok || boundID != second.ID {
|
||||
t.Fatalf("failover sticky binding = %d, %v, err = %v; want account %d", boundID, ok, err, second.ID)
|
||||
}
|
||||
@@ -161,7 +164,7 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
t.Fatalf("audit detail = %#v, err = %v", detail, err)
|
||||
}
|
||||
ownership, err := responseRepo.Get(ctx, "resp-test", clientKey.ID, time.Now().UTC())
|
||||
if err != nil || ownership.AccountID != second.ID {
|
||||
if err != nil || ownership.AccountID != second.ID || ownership.PromptCacheKey != expectedCacheKey || ownership.ReasoningReplayKey != identity.replayKey {
|
||||
t.Fatalf("ownership = %#v, err = %v", ownership, err)
|
||||
}
|
||||
|
||||
@@ -194,6 +197,13 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) {
|
||||
if len(adapter.attempts) != 1 || adapter.attempts[0] != second.ID {
|
||||
t.Fatalf("continued attempts = %#v", adapter.attempts)
|
||||
}
|
||||
if adapter.lastPromptCacheKey != expectedCacheKey || adapter.lastReasoningReplayKey != identity.replayKey {
|
||||
t.Fatalf("continued session identity drifted: cache=%q replay=%q", adapter.lastPromptCacheKey, adapter.lastReasoningReplayKey)
|
||||
}
|
||||
nextOwnership, err := responseRepo.Get(ctx, "resp-next", clientKey.ID, time.Now().UTC())
|
||||
if err != nil || nextOwnership.PromptCacheKey != expectedCacheKey || nextOwnership.ReasoningReplayKey != identity.replayKey {
|
||||
t.Fatalf("continued ownership = %#v, err = %v", nextOwnership, err)
|
||||
}
|
||||
|
||||
adapter.resetAttempts()
|
||||
resource, err := service.GetResponse(ctx, ResourceInput{ClientKey: clientKey, ResponseID: "resp-test", RawQuery: "include=reasoning.encrypted_content"})
|
||||
@@ -580,6 +590,69 @@ func TestGatewayDoesNotPersistStatelessConsoleResponses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayWebOwnershipDoesNotPersistRawPromptCacheKey(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "web-ownership.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
responseRepo := relational.NewResponseRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
credential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, Name: "web", SourceKey: "web",
|
||||
EncryptedAccessToken: "encrypted", Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const model = "grok-web-ownership"
|
||||
if err := modelRepo.UpsertDiscovered(ctx, account.ProviderWeb, []string{model}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{model}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "web-key", Prefix: "web-key", SecretHash: strings.Repeat("d", 64), EncryptedSecret: "encrypted",
|
||||
Enabled: true, RPMLimit: 60, MaxConcurrent: 4,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adapter := webStoredResponseAdapter{}
|
||||
registry := provider.NewRegistry(adapter)
|
||||
sticky := memory.NewStickyStore()
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 1)
|
||||
|
||||
rawKey := strings.Repeat("raw-session-", 16)
|
||||
result, err := service.CreateResponse(ctx, Input{
|
||||
RequestID: "req-web-ownership", ClientKey: key, PublicModel: model, PromptCacheKey: rawKey,
|
||||
Body: []byte(`{"model":"grok-web-ownership","input":"hello"}`),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _ = io.ReadAll(result.Body)
|
||||
result.Finalize(Usage{}, "resp-web-ownership", "")
|
||||
_ = result.Body.Close()
|
||||
ownership, err := responseRepo.Get(ctx, "resp-web-ownership", key.ID, time.Now().UTC())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ownership.AccountID != credential.ID || ownership.Provider != account.ProviderWeb || ownership.PromptCacheKey != "" || ownership.ReasoningReplayKey != "" {
|
||||
t.Fatalf("web ownership = %#v", ownership)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFreeQuotaExhaustion(t *testing.T) {
|
||||
body := []byte(`{"error":{"code":"subscription:free-usage-exhausted","message":"tokens (actual/limit): 1065387/1000000; Usage resets over a rolling 24-hour window"}}`)
|
||||
used, limit, exhausted := parseFreeQuotaExhaustion(body)
|
||||
@@ -1284,13 +1357,14 @@ func runQuotaRefreshWorkers(t *testing.T, service *accountapp.Service) {
|
||||
}
|
||||
|
||||
type failoverAdapter struct {
|
||||
mu sync.Mutex
|
||||
firstID uint64
|
||||
attempts []uint64
|
||||
lastMethod string
|
||||
lastPath string
|
||||
lastPromptCacheKey string
|
||||
resourceStatus int
|
||||
mu sync.Mutex
|
||||
firstID uint64
|
||||
attempts []uint64
|
||||
lastMethod string
|
||||
lastPath string
|
||||
lastPromptCacheKey string
|
||||
lastReasoningReplayKey string
|
||||
resourceStatus int
|
||||
}
|
||||
|
||||
type ssoUnauthorizedAdapter struct {
|
||||
@@ -1444,6 +1518,25 @@ func (a *systemicForbiddenAdapter) Attempts() []uint64 {
|
||||
return append([]uint64(nil), a.attempts...)
|
||||
}
|
||||
|
||||
type webStoredResponseAdapter struct{}
|
||||
|
||||
func (webStoredResponseAdapter) Provider() account.Provider { return account.ProviderWeb }
|
||||
func (webStoredResponseAdapter) Definition() provider.Definition {
|
||||
return provider.Definition{
|
||||
Provider: account.ProviderWeb,
|
||||
Conversation: provider.ConversationSurface{
|
||||
Responses: true, StoredResponses: true,
|
||||
},
|
||||
Inference: provider.InferencePolicy{Usage: provider.UsageEstimated},
|
||||
}
|
||||
}
|
||||
func (webStoredResponseAdapter) ForwardResponse(context.Context, provider.ResponseResourceRequest) (*provider.Response, error) {
|
||||
return &provider.Response{
|
||||
StatusCode: http.StatusOK, Status: "200 OK", Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"id":"resp-web-ownership"}`)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type webRateLimitAdapter struct{}
|
||||
|
||||
type webImageStreamAdapter struct {
|
||||
@@ -1626,6 +1719,7 @@ func (a *failoverAdapter) ForwardResponse(_ context.Context, request provider.Re
|
||||
a.lastMethod = request.Method
|
||||
a.lastPath = request.Path
|
||||
a.lastPromptCacheKey = request.PromptCacheKey
|
||||
a.lastReasoningReplayKey = request.ReasoningReplayKey
|
||||
resourceStatus := a.resourceStatus
|
||||
a.mu.Unlock()
|
||||
status, body := http.StatusOK, "ok"
|
||||
@@ -1650,6 +1744,7 @@ func (a *failoverAdapter) resetAttempts() {
|
||||
a.lastMethod = ""
|
||||
a.lastPath = ""
|
||||
a.lastPromptCacheKey = ""
|
||||
a.lastReasoningReplayKey = ""
|
||||
}
|
||||
func (a *failoverAdapter) ListModels(context.Context, account.Credential) ([]string, error) {
|
||||
return nil, nil
|
||||
|
||||
@@ -8,13 +8,15 @@ import (
|
||||
|
||||
// ResponseOwnership 记录上游 Response 资源所属账号,不保存请求或响应正文。
|
||||
type ResponseOwnership struct {
|
||||
ResponseID string
|
||||
AccountID uint64
|
||||
ClientKeyID uint64
|
||||
Provider account.Provider
|
||||
ExpiresAt time.Time
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
ResponseID string
|
||||
AccountID uint64
|
||||
ClientKeyID uint64
|
||||
Provider account.Provider
|
||||
PromptCacheKey string
|
||||
ReasoningReplayKey string
|
||||
ExpiresAt time.Time
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// WebResponseState 保存 Grok Web 本地 Responses 资源及其上游会话游标。
|
||||
|
||||
@@ -340,15 +340,17 @@ type requestAuditAttemptModel struct {
|
||||
func (requestAuditAttemptModel) TableName() string { return "request_audit_attempts" }
|
||||
|
||||
type responseOwnershipModel struct {
|
||||
ResponseID string `gorm:"size:255;primaryKey;check:chk_response_ownership_id,length(response_id) BETWEEN 1 AND 255"`
|
||||
AccountID uint64 `gorm:"not null"`
|
||||
ClientKeyID uint64 `gorm:"not null"`
|
||||
Provider string `gorm:"size:32;not null;check:chk_response_ownership_provider,provider IN ('grok_build','grok_web','grok_console')"`
|
||||
ExpiresAt time.Time `gorm:"not null;check:chk_response_ownership_expiry,expires_at > created_at"`
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
Account *accountModel `gorm:"foreignKey:AccountID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
||||
ClientKey *clientKeyModel `gorm:"foreignKey:ClientKeyID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
||||
ResponseID string `gorm:"size:255;primaryKey;check:chk_response_ownership_id,length(response_id) BETWEEN 1 AND 255"`
|
||||
AccountID uint64 `gorm:"not null"`
|
||||
ClientKeyID uint64 `gorm:"not null"`
|
||||
Provider string `gorm:"size:32;not null;check:chk_response_ownership_provider,provider IN ('grok_build','grok_web','grok_console')"`
|
||||
PromptCacheKey string `gorm:"size:64;not null;default:'';check:chk_response_ownership_cache_key,length(prompt_cache_key) <= 64"`
|
||||
ReasoningReplayKey string `gorm:"size:64;not null;default:'';check:chk_response_ownership_replay_key,length(reasoning_replay_key) <= 64"`
|
||||
ExpiresAt time.Time `gorm:"not null;check:chk_response_ownership_expiry,expires_at > created_at"`
|
||||
CreatedAt time.Time `gorm:"not null"`
|
||||
UpdatedAt time.Time `gorm:"not null"`
|
||||
Account *accountModel `gorm:"foreignKey:AccountID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
||||
ClientKey *clientKeyModel `gorm:"foreignKey:ClientKeyID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
||||
}
|
||||
|
||||
func (responseOwnershipModel) TableName() string { return "response_ownership" }
|
||||
|
||||
@@ -435,7 +435,7 @@ func TestFreshSchemaContract(t *testing.T) {
|
||||
assertTableColumns(t, database, "admin_sessions", nil, []string{"revoked_at"})
|
||||
assertTableColumns(t, database, "account_model_capabilities", []string{"account_id", "upstream_model"}, []string{"provider", "synced_at"})
|
||||
assertTableColumns(t, database, "request_audits", []string{"media_input_images", "media_output_images", "media_output_seconds"}, nil)
|
||||
assertTableColumns(t, database, "response_ownership", []string{"response_id", "account_id", "client_key_id", "provider", "expires_at"}, []string{"parent_response_id", "model_route_id"})
|
||||
assertTableColumns(t, database, "response_ownership", []string{"response_id", "account_id", "client_key_id", "provider", "prompt_cache_key", "reasoning_replay_key", "expires_at"}, []string{"parent_response_id", "model_route_id"})
|
||||
|
||||
var expiresNotNull int
|
||||
if err := database.db.Raw("SELECT `notnull` FROM pragma_table_info('account_credentials') WHERE name = 'expires_at'").Scan(&expiresNotNull).Error; err != nil {
|
||||
|
||||
@@ -18,6 +18,7 @@ func (r *ResponseRepository) Save(ctx context.Context, value inferencedomain.Res
|
||||
row := responseOwnershipModel{
|
||||
ResponseID: value.ResponseID, AccountID: value.AccountID,
|
||||
ClientKeyID: value.ClientKeyID, Provider: string(value.Provider),
|
||||
PromptCacheKey: value.PromptCacheKey, ReasoningReplayKey: value.ReasoningReplayKey,
|
||||
ExpiresAt: value.ExpiresAt, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt,
|
||||
}
|
||||
return r.db.db.WithContext(ctx).Save(&row).Error
|
||||
@@ -31,6 +32,7 @@ func (r *ResponseRepository) Get(ctx context.Context, responseID string, clientK
|
||||
return inferencedomain.ResponseOwnership{
|
||||
ResponseID: row.ResponseID, AccountID: row.AccountID,
|
||||
ClientKeyID: row.ClientKeyID, Provider: account.Provider(row.Provider),
|
||||
PromptCacheKey: row.PromptCacheKey, ReasoningReplayKey: row.ReasoningReplayKey,
|
||||
ExpiresAt: row.ExpiresAt, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -34,12 +34,12 @@ func TestResponseRepositoryScopesOwnershipByClientAndExpiry(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewResponseRepository(database)
|
||||
value := inferencedomain.ResponseOwnership{ResponseID: "resp_1", AccountID: accountValue.ID, ClientKeyID: keyValue.ID, Provider: account.ProviderBuild, ExpiresAt: now.Add(time.Hour), CreatedAt: now, UpdatedAt: now}
|
||||
value := inferencedomain.ResponseOwnership{ResponseID: "resp_1", AccountID: accountValue.ID, ClientKeyID: keyValue.ID, Provider: account.ProviderBuild, PromptCacheKey: "cache-key", ReasoningReplayKey: "replay-key", ExpiresAt: now.Add(time.Hour), CreatedAt: now, UpdatedAt: now}
|
||||
if err := repo.Save(ctx, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := repo.Get(ctx, value.ResponseID, value.ClientKeyID, now)
|
||||
if err != nil || got.AccountID != value.AccountID || got.Provider != account.ProviderBuild {
|
||||
if err != nil || got.AccountID != value.AccountID || got.Provider != account.ProviderBuild || got.PromptCacheKey != value.PromptCacheKey || got.ReasoningReplayKey != value.ReasoningReplayKey {
|
||||
t.Fatalf("ownership = %#v, err = %v", got, err)
|
||||
}
|
||||
if _, err := repo.Get(ctx, value.ResponseID, 99, now); !errors.Is(err, repository.ErrNotFound) {
|
||||
@@ -53,3 +53,65 @@ func TestResponseRepositoryScopesOwnershipByClientAndExpiry(t *testing.T) {
|
||||
t.Fatalf("deleted = %d, err = %v", deleted, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseOwnershipIdentityMigrationPreservesExistingRows(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "responses-upgrade.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
accountValue, _, err := NewAccountRepository(database).UpsertByIdentity(ctx, account.Credential{Provider: account.ProviderBuild, Name: "legacy-owner", SourceKey: "legacy-owner", EncryptedAccessToken: testEncryptedToken, AuthStatus: account.AuthStatusActive})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keyValue, err := NewClientKeyRepository(database).Create(ctx, clientkeydomain.Key{Name: "legacy-owner", Prefix: "legacy-prefix", SecretHash: testSecretHash, EncryptedSecret: testEncryptedToken, Enabled: true, RPMLimit: 120, MaxConcurrent: 8})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := NewResponseRepository(database)
|
||||
value := inferencedomain.ResponseOwnership{ResponseID: "resp_legacy", AccountID: accountValue.ID, ClientKeyID: keyValue.ID, Provider: account.ProviderBuild, PromptCacheKey: "old-cache", ReasoningReplayKey: "old-replay", ExpiresAt: now.Add(time.Hour), CreatedAt: now, UpdatedAt: now}
|
||||
if err := repo.Save(ctx, value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := database.withSQLiteForeignKeysDisabled(ctx, func() error {
|
||||
statements := []string{
|
||||
`CREATE TABLE response_ownership_legacy (
|
||||
response_id text PRIMARY KEY,
|
||||
account_id integer NOT NULL,
|
||||
client_key_id integer NOT NULL,
|
||||
provider text NOT NULL,
|
||||
expires_at datetime NOT NULL,
|
||||
created_at datetime NOT NULL,
|
||||
updated_at datetime NOT NULL,
|
||||
CONSTRAINT fk_response_ownership_account FOREIGN KEY (account_id) REFERENCES provider_accounts(id) ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
CONSTRAINT fk_response_ownership_client_key FOREIGN KEY (client_key_id) REFERENCES client_keys(id) ON UPDATE CASCADE ON DELETE CASCADE
|
||||
)`,
|
||||
`INSERT INTO response_ownership_legacy (response_id, account_id, client_key_id, provider, expires_at, created_at, updated_at)
|
||||
SELECT response_id, account_id, client_key_id, provider, expires_at, created_at, updated_at FROM response_ownership`,
|
||||
`DROP TABLE response_ownership`,
|
||||
`ALTER TABLE response_ownership_legacy RENAME TO response_ownership`,
|
||||
}
|
||||
for _, statement := range statements {
|
||||
if err := database.db.WithContext(ctx).Exec(statement).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatalf("upgrade response ownership identity columns: %v", err)
|
||||
}
|
||||
got, err := repo.Get(ctx, value.ResponseID, value.ClientKeyID, now)
|
||||
if err != nil || got.AccountID != value.AccountID || got.Provider != value.Provider || got.PromptCacheKey != "" || got.ReasoningReplayKey != "" {
|
||||
t.Fatalf("migrated ownership = %#v, err = %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,7 @@ func TestInitializeSchemaUpgradesProviderChecksForConsole(t *testing.T) {
|
||||
}
|
||||
assertSQLiteUniqueIndexes(t, database, "provider_accounts", "idx_provider_accounts_identity_key")
|
||||
assertSQLiteUniqueIndexes(t, database, "model_routes", "idx_model_routes_public_id", "uidx_provider_upstream")
|
||||
assertTableColumns(t, database, "response_ownership", []string{"prompt_cache_key", "reasoning_replay_key"}, nil)
|
||||
}
|
||||
|
||||
func assertSQLiteUniqueIndexes(t *testing.T, database *Database, table string, expected ...string) {
|
||||
|
||||
@@ -156,10 +156,6 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
return invalidResponsesResponse(err), nil
|
||||
}
|
||||
}
|
||||
// 服务端推理回放:在 prompt_cache_key 写入后、出站前注入上一轮 encrypted items。
|
||||
if a.replay != nil && request.PromptCacheKey != "" && !isCompactPath(request.Path) && !compactionRequested {
|
||||
body = a.replay.Apply(ctx, request.Model, request.PromptCacheKey, body)
|
||||
}
|
||||
}
|
||||
if compactionRequested {
|
||||
warnings := ""
|
||||
@@ -171,6 +167,10 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
// 显式模式优先;auto 下仅已确认 Super 且 bot_flag_source=1 的账号默认走 XAI。
|
||||
primaryBase := a.primaryBaseURL()
|
||||
base := a.inferenceBaseForOperation(request.Credential, request.Billing, request.Method, request.Path)
|
||||
// 缓存亲和与推理回放使用不同身份。回放还必须绑定实际账号和上游平面,
|
||||
// 避免把一个账号或 Build 平面签发的 opaque reasoning 发给另一作用域。
|
||||
replayBaseBody := body
|
||||
body, replayKey := a.applyReasoningReplay(ctx, request, replayBaseBody, base)
|
||||
resp, reqURL, err := a.doResponseRequest(ctx, request, accessToken, body, base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -190,17 +190,18 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
primaryResp := cloneBufferedResponse(resp, primaryBody, primaryTruncated)
|
||||
fallbackBase := a.fallbackBaseURL()
|
||||
if fallbackBase != "" && !strings.EqualFold(fallbackBase, base) {
|
||||
fallbackResp, fallbackURL, fallbackErr := a.doResponseRequest(ctx, request, accessToken, body, fallbackBase)
|
||||
fallbackBody, fallbackReplayKey := a.applyReasoningReplay(ctx, request, replayBaseBody, fallbackBase)
|
||||
fallbackResp, fallbackURL, fallbackErr := a.doResponseRequest(ctx, request, accessToken, fallbackBody, fallbackBase)
|
||||
if fallbackErr == nil {
|
||||
fallbackErr = normalizeGzipResponse(fallbackResp)
|
||||
}
|
||||
fallbackRecovered := false
|
||||
if fallbackErr == nil {
|
||||
fallbackResp, fallbackURL, fallbackRecovered = a.recoverReasoningDecodeFailure(ctx, request, accessToken, body, fallbackBase, fallbackResp, fallbackURL)
|
||||
fallbackResp, fallbackURL, fallbackRecovered = a.recoverReasoningDecodeFailure(ctx, request, accessToken, fallbackBody, fallbackBase, fallbackResp, fallbackURL)
|
||||
}
|
||||
if fallbackErr == nil && isHTTPSuccess(fallbackResp.StatusCode) {
|
||||
a.activateBuildAPIFallback(ctx, &request.Credential)
|
||||
resp, reqURL, base = fallbackResp, fallbackURL, fallbackBase
|
||||
resp, reqURL, base, body, replayKey = fallbackResp, fallbackURL, fallbackBase, fallbackBody, fallbackReplayKey
|
||||
reasoningRecovered = reasoningRecovered || fallbackRecovered
|
||||
} else {
|
||||
if fallbackErr == nil {
|
||||
@@ -215,8 +216,8 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
}
|
||||
modelCatalogChanged := a.modelCatalogChanged(request.Credential.ID, resp.Header.Get("x-models-etag"))
|
||||
// 在协议转换前捕获上游 Responses 形态,写入/清理推理回放缓存。
|
||||
if a.shouldCaptureReplay(request, resp) {
|
||||
resp.Body = a.replay.CaptureBody(resp.Body, request.Model, request.PromptCacheKey, request.Streaming, isCompactPath(request.Path))
|
||||
if a.shouldCaptureReplay(request, resp, replayKey) {
|
||||
resp.Body = a.replay.CaptureBody(resp.Body, request.Model, replayKey, request.Streaming, isCompactPath(request.Path))
|
||||
}
|
||||
responsesOperation := request.Operation == "" || request.Operation == conversation.OperationResponses || request.Operation == conversation.OperationCompaction
|
||||
if responsesOperation && toolCompatibility != nil {
|
||||
@@ -291,11 +292,11 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
|
||||
return &provider.Response{StatusCode: resp.StatusCode, Status: resp.Status, Header: resp.Header.Clone(), Body: resp.Body, UpstreamURL: reqURL, ModelCatalogChanged: modelCatalogChanged}, nil
|
||||
}
|
||||
|
||||
func (a *Adapter) shouldCaptureReplay(request provider.ResponseResourceRequest, resp *http.Response) bool {
|
||||
func (a *Adapter) shouldCaptureReplay(request provider.ResponseResourceRequest, resp *http.Response, replayKey string) bool {
|
||||
if a.replay == nil || !a.replay.Enabled() || resp == nil {
|
||||
return false
|
||||
}
|
||||
if request.Method != http.MethodPost || strings.TrimSpace(request.PromptCacheKey) == "" {
|
||||
if request.Method != http.MethodPost || strings.TrimSpace(replayKey) == "" {
|
||||
return false
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
@@ -304,6 +305,34 @@ func (a *Adapter) shouldCaptureReplay(request provider.ResponseResourceRequest,
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Adapter) applyReasoningReplay(ctx context.Context, request provider.ResponseResourceRequest, body []byte, base string) ([]byte, string) {
|
||||
if a.replay == nil || !a.replay.Enabled() || request.Method != http.MethodPost {
|
||||
return body, ""
|
||||
}
|
||||
key := a.scopedReasoningReplayKey(request, base)
|
||||
if key == "" {
|
||||
return body, ""
|
||||
}
|
||||
if isCompactPath(request.Path) {
|
||||
// compact 不注入历史,但成功后仍需用同一作用域清理旧 replay。
|
||||
return body, key
|
||||
}
|
||||
return a.replay.Apply(ctx, request.Model, key, body), key
|
||||
}
|
||||
|
||||
func (a *Adapter) scopedReasoningReplayKey(request provider.ResponseResourceRequest, base string) string {
|
||||
seed := strings.TrimSpace(request.ReasoningReplayKey)
|
||||
if seed == "" || request.Credential.ID == 0 {
|
||||
return ""
|
||||
}
|
||||
plane := "build"
|
||||
if fallback := a.fallbackBaseURL(); fallback != "" && strings.EqualFold(strings.TrimRight(base, "/"), fallback) {
|
||||
plane = "xai"
|
||||
}
|
||||
digest := sha256.Sum256([]byte(fmt.Sprintf("grok2api:reasoning-replay:v2:%s:%d:%s", seed, request.Credential.ID, plane)))
|
||||
return hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
func isCompactPath(path string) bool {
|
||||
return strings.Contains(strings.ToLower(path), "compact")
|
||||
}
|
||||
|
||||
@@ -194,10 +194,10 @@ func TestForwardResponseReplaysReasoningAcrossMessagesTurns(t *testing.T) {
|
||||
}, nil
|
||||
})
|
||||
|
||||
credential := account.Credential{Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}
|
||||
credential := account.Credential{ID: 7, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted}
|
||||
first, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
|
||||
Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.5",
|
||||
NormalizeBody: true, Operation: conversation.OperationMessages, PromptCacheKey: "messages-replay-key",
|
||||
NormalizeBody: true, Operation: conversation.OperationMessages, PromptCacheKey: "messages-cache-key", ReasoningReplayKey: "messages-replay-key",
|
||||
Body: []byte(`{"model":"public","max_tokens":128,"messages":[{"role":"user","content":"first"}]}`),
|
||||
})
|
||||
if err != nil {
|
||||
@@ -212,7 +212,7 @@ func TestForwardResponseReplaysReasoningAcrossMessagesTurns(t *testing.T) {
|
||||
|
||||
second, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
|
||||
Credential: credential, Method: http.MethodPost, Path: "/responses", Model: "grok-4.5",
|
||||
NormalizeBody: true, Operation: conversation.OperationMessages, PromptCacheKey: "messages-replay-key",
|
||||
NormalizeBody: true, Operation: conversation.OperationMessages, PromptCacheKey: "messages-cache-key", ReasoningReplayKey: "messages-replay-key",
|
||||
Body: []byte(`{"model":"public","max_tokens":128,"messages":[{"role":"user","content":"first"},{"role":"assistant","content":"first"},{"role":"user","content":"second"}]}`),
|
||||
})
|
||||
if err != nil {
|
||||
@@ -227,6 +227,33 @@ func TestForwardResponseReplaysReasoningAcrossMessagesTurns(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReasoningReplayScopeSeparatesAccountAndPlane(t *testing.T) {
|
||||
adapter := NewAdapter(Config{
|
||||
BaseURL: "https://build.example/v1",
|
||||
FallbackBaseURL: "https://xai.example/v1",
|
||||
}, nil)
|
||||
request := provider.ResponseResourceRequest{
|
||||
Credential: account.Credential{ID: 7},
|
||||
ReasoningReplayKey: "explicit-session",
|
||||
}
|
||||
buildKey := adapter.scopedReasoningReplayKey(request, "https://build.example/v1")
|
||||
if buildKey == "" {
|
||||
t.Fatal("explicit session did not produce replay scope")
|
||||
}
|
||||
otherAccount := request
|
||||
otherAccount.Credential.ID = 8
|
||||
if got := adapter.scopedReasoningReplayKey(otherAccount, "https://build.example/v1"); got == buildKey {
|
||||
t.Fatal("reasoning replay scope was shared across accounts")
|
||||
}
|
||||
if got := adapter.scopedReasoningReplayKey(request, "https://xai.example/v1"); got == buildKey {
|
||||
t.Fatal("reasoning replay scope was shared across Build and XAI")
|
||||
}
|
||||
request.ReasoningReplayKey = ""
|
||||
if got := adapter.scopedReasoningReplayKey(request, "https://build.example/v1"); got != "" {
|
||||
t.Fatalf("soft/empty session unexpectedly enabled replay: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListModelsUsesOfficialMetadataHeaders(t *testing.T) {
|
||||
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
|
||||
if err != nil {
|
||||
|
||||
@@ -787,3 +787,34 @@ func TestConvertResponsesStreamMessagesInputTokens(t *testing.T) {
|
||||
t.Fatalf("message_delta should retain upstream usage extensions:\n%s", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertResponsesStreamMergesPartialUsageFrames(t *testing.T) {
|
||||
stream := strings.Join([]string{
|
||||
`event: response.created`,
|
||||
`data: {"type":"response.created","response":{"id":"resp_usage","model":"grok-4.5","status":"in_progress","usage":{"input_tokens":120,"output_tokens":30,"total_tokens":150,"cost_in_usd_ticks":9000,"output_tokens_details":{"reasoning_tokens":12},"context_details":{"input_tokens":110,"output_tokens":25}}}}`, "",
|
||||
`event: response.in_progress`,
|
||||
`data: {"type":"response.in_progress","response":{"usage":{"input_tokens_details":{"cached_tokens":80}}}}`, "",
|
||||
`event: response.completed`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_usage","model":"grok-4.5","status":"completed"}}`, "", "",
|
||||
}, "\n")
|
||||
|
||||
tests := []struct {
|
||||
operation string
|
||||
want []string
|
||||
}{
|
||||
{operation: OperationChat, want: []string{`"prompt_tokens":120`, `"completion_tokens":30`, `"cached_tokens":80`, `"reasoning_tokens":12`, `"cost_in_usd_ticks":9000`}},
|
||||
{operation: OperationMessages, want: []string{`"input_tokens":120`, `"output_tokens":30`, `"cache_read_input_tokens":80`, `"cost_in_usd_ticks":9000`}},
|
||||
}
|
||||
for _, test := range tests {
|
||||
converted, err := io.ReadAll(ConvertResponseStream(io.NopCloser(strings.NewReader(stream)), test.operation))
|
||||
if err != nil {
|
||||
t.Fatalf("%s conversion: %v", test.operation, err)
|
||||
}
|
||||
text := string(converted)
|
||||
for _, want := range test.want {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Fatalf("%s partial usage lost %s:\n%s", test.operation, want, text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,9 +344,41 @@ func (c *streamConverter) setResponse(value responseEnvelope) {
|
||||
if value.CreatedAt != 0 {
|
||||
c.created = value.CreatedAt
|
||||
}
|
||||
if value.Usage.InputTokens != 0 || value.Usage.OutputTokens != 0 || value.Usage.TotalTokens != 0 || value.Usage.InputTokensDetails.CachedTokens != 0 || value.Usage.OutputTokensDetails.ReasoningTokens != 0 || value.Usage.CostInUSDTicks != 0 {
|
||||
c.usage = value.Usage
|
||||
c.usage = mergeResponseUsage(c.usage, value.Usage)
|
||||
}
|
||||
|
||||
func mergeResponseUsage(current, update responseUsage) responseUsage {
|
||||
if update.InputTokens != 0 {
|
||||
current.InputTokens = update.InputTokens
|
||||
}
|
||||
if update.OutputTokens != 0 {
|
||||
current.OutputTokens = update.OutputTokens
|
||||
}
|
||||
if update.TotalTokens != 0 {
|
||||
current.TotalTokens = update.TotalTokens
|
||||
}
|
||||
if update.CostInUSDTicks != 0 {
|
||||
current.CostInUSDTicks = update.CostInUSDTicks
|
||||
}
|
||||
if update.NumSourcesUsed != 0 {
|
||||
current.NumSourcesUsed = update.NumSourcesUsed
|
||||
}
|
||||
if update.NumServerSideToolsUsed != 0 {
|
||||
current.NumServerSideToolsUsed = update.NumServerSideToolsUsed
|
||||
}
|
||||
if update.InputTokensDetails.CachedTokens != 0 {
|
||||
current.InputTokensDetails.CachedTokens = update.InputTokensDetails.CachedTokens
|
||||
}
|
||||
if update.OutputTokensDetails.ReasoningTokens != 0 {
|
||||
current.OutputTokensDetails.ReasoningTokens = update.OutputTokensDetails.ReasoningTokens
|
||||
}
|
||||
if update.ContextDetails.InputTokens != 0 {
|
||||
current.ContextDetails.InputTokens = update.ContextDetails.InputTokens
|
||||
}
|
||||
if update.ContextDetails.OutputTokens != 0 {
|
||||
current.ContextDetails.OutputTokens = update.ContextDetails.OutputTokens
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
func (c *streamConverter) start() error {
|
||||
|
||||
@@ -120,10 +120,12 @@ type ResponseResourceRequest struct {
|
||||
Body []byte
|
||||
Model string
|
||||
PromptCacheKey string
|
||||
IdempotencyID string
|
||||
Streaming bool
|
||||
NormalizeBody bool
|
||||
Operation string
|
||||
// ReasoningReplayKey 只来自客户端显式会话身份;soft cache identity 不得用于密文回放。
|
||||
ReasoningReplayKey string
|
||||
IdempotencyID string
|
||||
Streaming bool
|
||||
NormalizeBody bool
|
||||
Operation string
|
||||
}
|
||||
|
||||
// Response 表示尚未写入下游的上游响应。
|
||||
|
||||
@@ -1161,23 +1161,23 @@ type responsePayloadDTO struct {
|
||||
}
|
||||
|
||||
type responseUsageDTO struct {
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
InputTokensCamel int64 `json:"inputTokens"`
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
OutputTokensCamel int64 `json:"outputTokens"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
TotalTokensCamel int64 `json:"totalTokens"`
|
||||
CostInUSDTicks int64 `json:"cost_in_usd_ticks"`
|
||||
NumSourcesUsed int64 `json:"num_sources_used"`
|
||||
NumServerSideToolsUsed int64 `json:"num_server_side_tools_used"`
|
||||
InputTokens int64 `json:"input_tokens"`
|
||||
InputTokensCamel int64 `json:"inputTokens"`
|
||||
OutputTokens int64 `json:"output_tokens"`
|
||||
OutputTokensCamel int64 `json:"outputTokens"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
TotalTokensCamel int64 `json:"totalTokens"`
|
||||
CostInUSDTicks int64 `json:"cost_in_usd_ticks"`
|
||||
NumSourcesUsed int64 `json:"num_sources_used"`
|
||||
NumServerSideToolsUsed int64 `json:"num_server_side_tools_used"`
|
||||
// Responses 协议:input_tokens_details.cached_tokens
|
||||
InputTokensDetails responseInputDetailsDTO `json:"input_tokens_details"`
|
||||
// OpenAI Chat Completions 协议:prompt_tokens_details.cached_tokens
|
||||
PromptTokensDetails responseInputDetailsDTO `json:"prompt_tokens_details"`
|
||||
// Anthropic Messages 协议:顶层 cache_read_input_tokens
|
||||
CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
|
||||
OutputTokensDetails responseOutputDetailsDTO `json:"output_tokens_details"`
|
||||
CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
|
||||
OutputTokensDetails responseOutputDetailsDTO `json:"output_tokens_details"`
|
||||
// OpenAI Chat Completions 协议:completion_tokens_details.reasoning_tokens
|
||||
CompletionTokensDetails responseOutputDetailsDTO `json:"completion_tokens_details"`
|
||||
ContextDetails responseContextDetailsDTO `json:"context_details"`
|
||||
|
||||
@@ -23,10 +23,10 @@ func TestExtractPromptCacheSeedSupportsClaudeCodeForms(t *testing.T) {
|
||||
{name: "suffix user id", body: `{"metadata":{"user_id":"user_account_session_123e4567-e89b-12d3-a456-426614174000"}}`, want: "123e4567-e89b-12d3-a456-426614174000"},
|
||||
{name: "conversation snake case", body: `{"conversation_id":"conversation-session"}`, want: "conversation-session"},
|
||||
{name: "conversation camel case", body: `{"conversationId":"camel-conversation"}`, want: "camel-conversation"},
|
||||
{name: "body prompt_cache_key", body: `{"prompt_cache_key":"sub2api-session"}`, want: "sub2api-session"},
|
||||
// http.Header canonical key is Session-Id for "session_id"
|
||||
{name: "sub2api session_id via Set", headers: func() http.Header { h := make(http.Header); h.Set("session_id", "sub2-header-session"); return h }(), want: "sub2-header-session"},
|
||||
{name: "grok conv header", headers: http.Header{"X-Grok-Conv-Id": {"grok-conv-session"}}, want: "grok-conv-session"},
|
||||
{name: "body prompt_cache_key", body: `{"prompt_cache_key":"sub2api-session"}`, want: "sub2api-session"},
|
||||
// http.Header canonical key is Session-Id for "session_id"
|
||||
{name: "sub2api session_id via Set", headers: func() http.Header { h := make(http.Header); h.Set("session_id", "sub2-header-session"); return h }(), want: "sub2-header-session"},
|
||||
{name: "grok conv header", headers: http.Header{"X-Grok-Conv-Id": {"grok-conv-session"}}, want: "grok-conv-session"},
|
||||
{name: "per request id ignored", headers: http.Header{"X-Client-Request-Id": {"request-123"}}, want: ""},
|
||||
{name: "ordinary user id", body: `{"metadata":{"user_id":"user-123"}}`, want: ""},
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user