diff --git a/internal/api/handlers/management/auth_files_fields.go b/internal/api/handlers/management/auth_files_fields.go index 1627b145cf1..00e6940d77e 100644 --- a/internal/api/handlers/management/auth_files_fields.go +++ b/internal/api/handlers/management/auth_files_fields.go @@ -662,6 +662,10 @@ func syncAuthFileMetadataFields(auth *coreauth.Auth, touchedRoots map[string]str auth.ProxyURL = strings.TrimSpace(proxyURL) } } + if _, ok := touchedRoots[coreauth.ProxyConnectionPoolMetadataKey]; ok { + auth.ProxyConnectionPool = nil + coreauth.ApplyProxyConnectionPoolMetadata(auth, auth.Metadata) + } if _, ok := touchedRoots["headers"]; ok { syncAuthFileHeaderAttributes(auth) } diff --git a/internal/api/handlers/management/auth_files_patch_fields_test.go b/internal/api/handlers/management/auth_files_patch_fields_test.go index 5978a002225..007b4746e19 100644 --- a/internal/api/handlers/management/auth_files_patch_fields_test.go +++ b/internal/api/handlers/management/auth_files_patch_fields_test.go @@ -1512,3 +1512,52 @@ func mustGetAuthByID(t *testing.T, manager *coreauth.Manager, id string) *coreau } return got } + +func TestPatchAuthFileFields_ProxyConnectionPool(t *testing.T) { + t.Setenv("MANAGEMENT_PASSWORD", "") + + store := &memoryAuthStore{} + manager := coreauth.NewManager(store, nil, nil) + record := &coreauth.Auth{ + ID: "xai.json", + FileName: "xai.json", + Provider: "xai", + Attributes: map[string]string{"path": "/tmp/xai.json"}, + Metadata: map[string]any{"type": "xai"}, + } + if _, errRegister := manager.Register(context.Background(), record); errRegister != nil { + t.Fatalf("failed to register auth record: %v", errRegister) + } + h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager) + + patch := func(body string) *coreauth.Auth { + t.Helper() + rec := httptest.NewRecorder() + ctx, _ := gin.CreateTestContext(rec) + req := httptest.NewRequest(http.MethodPatch, "/v0/management/auth-files/fields", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + ctx.Request = req + h.PatchAuthFileFields(ctx) + if rec.Code != http.StatusOK { + t.Fatalf("expected status %d, got %d with body %s", http.StatusOK, rec.Code, rec.Body.String()) + } + updated, ok := manager.GetByID("xai.json") + if !ok || updated == nil { + t.Fatal("expected auth record to exist after patch") + } + return updated + } + + updated := patch(`{"name":"xai.json","proxy_url":"socks5://user:pass@127.0.0.1:1080","proxy_connection_pool":{"max-idle-conns-per-host":4}}`) + if updated.ProxyConnectionPool == nil || updated.ProxyConnectionPool.MaxIdleConnsPerHost == nil || *updated.ProxyConnectionPool.MaxIdleConnsPerHost != 4 { + t.Fatalf("ProxyConnectionPool = %+v, want max-idle-conns-per-host 4", updated.ProxyConnectionPool) + } + + updated = patch(`{"name":"xai.json","proxy_connection_pool":null}`) + if updated.ProxyConnectionPool != nil { + t.Fatalf("ProxyConnectionPool = %+v, want nil after removing the field", updated.ProxyConnectionPool) + } + if updated.ProxyURL != "socks5://user:pass@127.0.0.1:1080" { + t.Fatalf("ProxyURL = %q, want it untouched", updated.ProxyURL) + } +} diff --git a/internal/api/middleware/request_logging.go b/internal/api/middleware/request_logging.go index 699e59c1459..a4d8ff49aee 100644 --- a/internal/api/middleware/request_logging.go +++ b/internal/api/middleware/request_logging.go @@ -12,6 +12,7 @@ import ( "net/http" "os" "strings" + "sync" "time" "github.com/gin-gonic/gin" @@ -80,7 +81,7 @@ func RequestLoggingMiddleware(logger logging.RequestLogger) gin.HandlerFunc { deferredCapture := attachDeferredRequestBodyCapture(c.Request, logger, requestInfo, false, false) if captureBody { c.Set(authenticatedRequestBodyCapturerContextKey, func() { - if deferredCapture != nil && deferredCapture.bytesRead == 0 { + if deferredCapture != nil && !deferredCapture.hasRead() { c.Request.Body = deferredCapture.body requestInfo.deferredBodyCapture = nil deferredCapture.Cleanup() @@ -151,6 +152,7 @@ func CaptureAuthenticatedRequestBody(c *gin.Context) { } type deferredRequestBodyCapture struct { + mu sync.Mutex body io.ReadCloser factory fileBodySourceFactory memBuf bytes.Buffer @@ -188,7 +190,13 @@ func (c *deferredRequestBodyCapture) Read(payload []byte) (int, error) { if c == nil || c.body == nil { return 0, io.EOF } + // Close must be able to unblock the underlying read. n, errRead := c.body.Read(payload) + c.mu.Lock() + defer c.mu.Unlock() + if c.finished { + return n, errRead + } if errRead == io.EOF { c.sawEOF = true } @@ -196,7 +204,7 @@ func (c *deferredRequestBodyCapture) Read(payload []byte) (int, error) { return n, errRead } c.bytesRead += int64(n) - if c.skipCapture || c.captureErr != nil || c.finished { + if c.skipCapture || c.captureErr != nil { return n, errRead } @@ -273,17 +281,16 @@ func (c *deferredRequestBodyCapture) Close() error { if c == nil { return nil } - _ = c.Finish() + c.mu.Lock() + _ = c.finishLocked() + c.mu.Unlock() if c.body == nil { return nil } return c.body.Close() } -func (c *deferredRequestBodyCapture) Finish() error { - if c == nil { - return nil - } +func (c *deferredRequestBodyCapture) finishLocked() error { if c.finished { return c.captureErr } @@ -301,7 +308,9 @@ func (c *deferredRequestBodyCapture) Bytes() ([]byte, string, error) { if c == nil || c.skipCapture { return nil, "", nil } - if errFinish := c.Finish(); errFinish != nil { + c.mu.Lock() + defer c.mu.Unlock() + if errFinish := c.finishLocked(); errFinish != nil { return nil, "", errFinish } if c.source != nil { @@ -309,31 +318,37 @@ func (c *deferredRequestBodyCapture) Bytes() ([]byte, string, error) { if errBytes != nil { return nil, "", errBytes } - return body, c.statusMarker(), nil + return body, c.statusMarkerLocked(), nil } var body []byte if c.memBuf.Len() > 0 { body = bytes.Clone(c.memBuf.Bytes()) } - return body, c.statusMarker(), nil + return body, c.statusMarkerLocked(), nil } func (c *deferredRequestBodyCapture) isComplete() bool { - if c == nil { - return true - } + c.mu.Lock() + defer c.mu.Unlock() + return c.isCompleteLocked() +} + +func (c *deferredRequestBodyCapture) hasRead() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.bytesRead > 0 +} + +func (c *deferredRequestBodyCapture) isCompleteLocked() bool { return c.sawEOF || (c.contentLength >= 0 && c.bytesRead >= c.contentLength) } -func (c *deferredRequestBodyCapture) statusMarker() string { - if c == nil { - return "" - } +func (c *deferredRequestBodyCapture) statusMarkerLocked() string { var markers []string if c.truncated { markers = append(markers, fmt.Sprintf("[REQUEST BODY TRUNCATED: captured first %d bytes]", c.bytesCaptured)) } - if !c.isComplete() { + if !c.isCompleteLocked() { if c.contentLength >= 0 { markers = append(markers, fmt.Sprintf("[REQUEST BODY CAPTURE INCOMPLETE: consumed %d of %d bytes]", c.bytesRead, c.contentLength)) } else { @@ -347,7 +362,9 @@ func (c *deferredRequestBodyCapture) Cleanup() { if c == nil { return } - if errFinish := c.Finish(); errFinish != nil { + c.mu.Lock() + defer c.mu.Unlock() + if errFinish := c.finishLocked(); errFinish != nil { log.WithError(errFinish).Warn("failed to finish deferred request body capture") } c.memBuf.Reset() diff --git a/internal/api/middleware/request_logging_test.go b/internal/api/middleware/request_logging_test.go index 7bb8e2b4443..439bc27ffa5 100644 --- a/internal/api/middleware/request_logging_test.go +++ b/internal/api/middleware/request_logging_test.go @@ -1621,3 +1621,40 @@ func TestRequestLoggingMiddlewareIsolatesDeferredResponseAcrossStreamCancelAndGi } }) } + +type blockedCaptureBody struct { + started chan struct{} + closed chan struct{} +} + +func (b *blockedCaptureBody) Read(p []byte) (int, error) { + close(b.started) + <-b.closed + return copy(p, "late bytes"), io.EOF +} + +func (b *blockedCaptureBody) Close() error { + close(b.closed) + return nil +} + +func TestDeferredRequestBodyCaptureCloseDuringBlockedRead(t *testing.T) { + body := &blockedCaptureBody{started: make(chan struct{}), closed: make(chan struct{})} + capture := &deferredRequestBodyCapture{body: body, contentLength: -1} + done := make(chan string, 1) + go func() { + payload := make([]byte, 32) + n, _ := capture.Read(payload) + done <- string(payload[:n]) + }() + <-body.started + if errClose := capture.Close(); errClose != nil { + t.Fatal(errClose) + } + if got := <-done; got != "late bytes" { + t.Fatalf("reader got %q", got) + } + if payload, _, errRead := capture.Bytes(); errRead != nil || len(payload) != 0 || capture.hasRead() || capture.isComplete() { + t.Fatalf("late read changed the finalized capture: %q, %v", payload, errRead) + } +} diff --git a/internal/api/middleware/response_writer.go b/internal/api/middleware/response_writer.go index e28fe90baa9..9eebc0ed081 100644 --- a/internal/api/middleware/response_writer.go +++ b/internal/api/middleware/response_writer.go @@ -326,7 +326,7 @@ func (w *ResponseWriterWrapper) currentCapturedRequestBody() []byte { if len(w.requestInfo.Body) > 0 { return w.requestInfo.Body } - if w.requestInfo.deferredBodyCapture == nil || w.requestInfo.deferredBodyCapture.bytesRead == 0 { + if w.requestInfo.deferredBodyCapture == nil || !w.requestInfo.deferredBodyCapture.hasRead() { return nil } body, _, errRead := w.requestInfo.deferredBodyCapture.Bytes() diff --git a/internal/pluginhost/auth_callbacks.go b/internal/pluginhost/auth_callbacks.go index d90325c152b..8a74c3c0ccb 100644 --- a/internal/pluginhost/auth_callbacks.go +++ b/internal/pluginhost/auth_callbacks.go @@ -496,6 +496,7 @@ func (h *Host) buildAuthsFromFileData(ctx context.Context, path string, data []b } } coreauth.ApplyCustomHeadersFromMetadata(auth) + coreauth.ApplyProxyConnectionPoolMetadata(auth, metadata) if existing := h.findExistingAuthForSave(auth.ID, path, len(out) == 1); existing != nil { preserveExistingAuthState(auth, existing) } @@ -545,6 +546,7 @@ func (h *Host) buildAuthsFromFileData(ctx context.Context, path string, data []b } coreauth.ApplyAuthPriorityMetadata(auth, metadata) coreauth.ApplyCustomHeadersFromMetadata(auth) + coreauth.ApplyProxyConnectionPoolMetadata(auth, metadata) return []*coreauth.Auth{auth}, nil } diff --git a/internal/quotahistory/recorder.go b/internal/quotahistory/recorder.go index ef6ee583b7c..ec9c82b48c1 100644 --- a/internal/quotahistory/recorder.go +++ b/internal/quotahistory/recorder.go @@ -214,6 +214,9 @@ func (r *Recorder) Apply(s Settings) error { coreauth.ObserveAuthPlan(auth.ID, plan) } } + if errRestore := r.restoreRouting(store, s); errRestore != nil { + log.WithError(errRestore).Warn("quota-history: restore routing readings") + } r.wg.Add(1) go r.run(r.ctx, store, s) log.Infof("quota-history: recording every %s to %s (retention %s)", s.Interval, s.Path, s.Retention) @@ -419,6 +422,16 @@ func (r *Recorder) sample(ctx context.Context, auth *coreauth.Auth) record { } rec.Windows = windows rec.Plan = plan + rec.RoutingVersion = 1 + rec.RoutingScopes = make(map[string][]string) + for key, window := range windows { + if len(window.modelScope) > 0 { + rec.RoutingScopes[key] = window.modelScope + } + if window.estimated { + rec.EstimatedWindows = append(rec.EstimatedWindows, key) + } + } if plan != "" { r.setPlan(auth.Index, plan) } @@ -427,7 +440,17 @@ func (r *Recorder) sample(ctx context.Context, auth *coreauth.Auth) record { if providerOf(auth) == "mistral" { return rec } - r.publishRouting(auth, plan, windows, time.UnixMilli(rec.T)) + r.publishWindows(auth, plan, windows, time.UnixMilli(rec.T)) + if r.deps.RecoverQuota != nil && showsAllowance(auth, windows) { + r.deps.RecoverQuota(ctx, auth, time.UnixMilli(rec.T)) + } + return rec +} + +// publishWindows is shared by live polls and startup restoration. Observation +// timestamps always identify the original provider sample. +func (r *Recorder) publishWindows(auth *coreauth.Auth, plan string, windows map[string]Window, observedAt time.Time) { + r.publishRouting(auth, plan, windows, observedAt) observations := make([]coreauth.QuotaWindow, 0, len(windows)) for key, window := range windows { // A usage figure the parser had to assume is charted but does not steer routing. @@ -441,14 +464,10 @@ func (r *Recorder) sample(ctx context.Context, auth *coreauth.Auth) record { observations = append(observations, coreauth.QuotaWindow{Key: key, UsedPercent: window.UsedPercent, ResetAt: time.UnixMilli(*window.ResetsAt), Period: time.Duration(window.PeriodHours * float64(time.Hour)), ModelScope: scope}) } - coreauth.ObserveQuotaWindows(auth.ID, time.UnixMilli(rec.T), observations) + coreauth.ObserveQuotaWindows(auth.ID, observedAt, observations) if providerOf(auth) == "claude" { - coreauth.ObserveScopedWeeklyWindows(auth.ID, time.UnixMilli(rec.T), scopedWeeklyWindows(windows)) - } - if r.deps.RecoverQuota != nil && showsAllowance(auth, windows) { - r.deps.RecoverQuota(ctx, auth, time.UnixMilli(rec.T)) + coreauth.ObserveScopedWeeklyWindows(auth.ID, observedAt, scopedWeeklyWindows(windows)) } - return rec } // showsAllowance reports whether a Claude or Codex reading has allowance left @@ -777,7 +796,9 @@ func (r *Recorder) forgetUntracked(enabled bool) { // The last plugin list keeps plugin-provider accounts tracked across a // settings change; trackable applies the new allowlist to them. for _, auth := range r.trackable(r.pluginProviders(context.Background(), false)) { - tracked[auth.ID] = true + if !isDisabled(auth) { + tracked[auth.ID] = true + } } } for _, auth := range r.deps.ListAuths() { diff --git a/internal/quotahistory/restore.go b/internal/quotahistory/restore.go new file mode 100644 index 00000000000..5e0fdeda381 --- /dev/null +++ b/internal/quotahistory/restore.go @@ -0,0 +1,95 @@ +package quotahistory + +import ( + "context" + "math" + "time" +) + +// restoreRouting reuses the latest successful sample, like a live poll failure +// which leaves the preceding reading intact. A newer successful empty sample +// supersedes earlier windows. Removed, disabled and untracked accounts are ignored. +func (r *Recorder) restoreRouting(store *Store, settings Settings) error { + now := r.now() + latest := make(map[string]record) + tracked := r.trackable(r.pluginProviders(context.Background(), false)) + wanted := make(map[string]bool, len(tracked)) + for _, auth := range tracked { + if !isDisabled(auth) { + wanted[auth.Index] = true + } + } + if errScan := store.scan(now.Add(-settings.Retention).UnixMilli(), now.UnixMilli(), func(rec record) { + if wanted[rec.AuthIndex] && rec.Error == "" { + latest[rec.AuthIndex] = rec + } + }); errScan != nil { + return errScan + } + for _, auth := range tracked { + rec, found := latest[auth.Index] + if !found || isDisabled(auth) || providerOf(auth) == "mistral" { + continue + } + // Re-read after the history scan. A removed or replaced credential + // must not receive an older incarnation's reading. + current := r.current(auth.ID) + if current == nil || isDisabled(current) || current.Index != rec.AuthIndex || providerOf(current) != providerOf(auth) { + continue + } + auth = current + observedAt := time.UnixMilli(rec.T) + if rec.T <= 0 || observedAt.After(now) || (!auth.CreatedAt.IsZero() && auth.CreatedAt.UnixMilli() > rec.T) { + continue + } + windows := make(map[string]Window) + for key, window := range rec.Windows { + if rec.RoutingVersion == 0 { + // Claude's legacy parser always read utilization and has recoverable + // weekly family scopes. Codex's assumed 100% was indistinguishable from + // a measured exhausted window. Other providers may have lost arbitrary model scopes. + switch providerOf(auth) { + case "claude": + case "codex": + if window.UsedPercent == 100 { + continue + } + default: + continue + } + } else if rec.RoutingVersion == 1 { + window.modelScope = rec.RoutingScopes[key] + for _, estimated := range rec.EstimatedWindows { + if estimated == key { + window.estimated = true + break + } + } + } else { + continue + } + if !restorableWindow(window, observedAt, now) { + continue + } + windows[key] = window + } + // Use the already restored plan. A historical reading must not overwrite + // a plan learned more recently in this recorder's lifetime. + r.publishWindows(auth, r.plan(auth.Index), windows, observedAt) + } + return nil +} + +func restorableWindow(window Window, observedAt, now time.Time) bool { + if window.estimated || window.ResetsAt == nil || *window.ResetsAt <= 0 || + window.PeriodHours <= 0 || math.IsNaN(window.PeriodHours) || math.IsInf(window.PeriodHours, 0) || + math.IsNaN(window.UsedPercent) || math.IsInf(window.UsedPercent, 0) || window.UsedPercent < 0 { + return false + } + // Match routing's period-plus-one-day tolerance without overflowing a + // duration from malformed history. A passed reset is never rolled forward. + maxAge := (window.PeriodHours + 24) * float64(time.Hour) + reset := time.UnixMilli(*window.ResetsAt) + return reset.After(now) && !observedAt.After(now) && + float64(now.Sub(observedAt)) <= maxAge && float64(reset.Sub(observedAt)) <= maxAge +} diff --git a/internal/quotahistory/restore_test.go b/internal/quotahistory/restore_test.go new file mode 100644 index 00000000000..7a29ed3ec94 --- /dev/null +++ b/internal/quotahistory/restore_test.go @@ -0,0 +1,213 @@ +package quotahistory + +import ( + "context" + "sync/atomic" + "testing" + "time" + + coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +func forgetRouting(t *testing.T, auths ...*coreauth.Auth) { + t.Helper() + clear := func() { + for _, auth := range auths { + coreauth.ForgetQuotaWindows(auth.ID) + coreauth.ForgetScopedWeeklyWindows(auth.ID) + coreauth.ForgetShortWindowUsage(auth.ID) + coreauth.ObserveAuthPlan(auth.ID, "") + } + } + clear() + t.Cleanup(clear) +} + +func historyWindow(now time.Time, after time.Duration, used, period float64) Window { + reset := now.Add(after).UnixMilli() + return Window{UsedPercent: used, PeriodHours: period, ResetsAt: &reset} +} + +func seedHistory(t *testing.T, settings Settings, records ...record) { + t.Helper() + store, err := OpenStore(settings.Path) + if err != nil { + t.Fatal(err) + } + for _, rec := range records { + if err := store.put(rec); err != nil { + t.Fatal(err) + } + } + if err := store.Close(); err != nil { + t.Fatal(err) + } +} + +func TestRecorderRestoresRoutingBeforeInitialPoll(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + observed := now.Add(-2 * time.Minute) + a := &coreauth.Auth{ID: "restore-a", Index: "restore-a", Provider: "codex"} + b := &coreauth.Auth{ID: "restore-b", Index: "restore-b", Provider: "codex"} + forgetRouting(t, a, b) + settings := enabledSettings(t) + seedHistory(t, settings, + record{Sample: Sample{T: observed.UnixMilli(), AuthIndex: a.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 4*24*time.Hour, 20, 168)}}}, + record{Sample: Sample{T: observed.UnixMilli(), AuthIndex: b.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 24*time.Hour, 20, 168)}}}, + record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: b.Index, Error: "HTTP 503"}}, + ) + var requests atomic.Int64 + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return []*coreauth.Auth{a, b} }, Do: func(context.Context, *coreauth.Auth, string, string, map[string]string) (int, []byte, error) { + requests.Add(1) + return 500, nil, nil + }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + for _, auth := range []*coreauth.Auth{a, b} { + got, windows := coreauth.ObservedQuotaWindows(auth.ID) + if !got.Equal(observed) || len(windows) != 1 { + t.Fatalf("%s reading = %v, %+v", auth.ID, got, windows) + } + } + selector := &coreauth.SoonestResetFirstSelector{} + got, err := selector.Pick(context.Background(), "codex", "gpt-5", cliproxyexecutor.Options{}, []*coreauth.Auth{a, b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("restored Pick = %v, %v, want %s", got, err, b.ID) + } + if requests.Load() != 0 { + t.Fatal("startup performed an upstream poll") + } + // Reconfiguration must preserve a live observation newer than the snapshot. + newer := now.Add(-time.Second) + coreauth.ObserveQuotaWindows(b.ID, newer, []coreauth.QuotaWindow{{Key: "new", UsedPercent: 30, ResetAt: now.Add(48 * time.Hour), Period: 168 * time.Hour}}) + settings.Interval += time.Minute + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + if ts, windows := coreauth.ObservedQuotaWindows(b.ID); !ts.Equal(newer) || len(windows) != 1 || windows[0].Key != "new" { + t.Fatalf("reload replaced newer reading: %v, %+v", ts, windows) + } +} + +func TestRecorderRestoreRejectsUnsafeHistory(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + for _, name := range []string{"expired", "stale", "future-observation", "far-reset", "missing-reset", "estimated", "legacy-codex-estimate", "disabled", "removed", "api-key", "untracked", "unknown-version", "replaced"} { + t.Run(name, func(t *testing.T) { + auth := &coreauth.Auth{ID: "restore-unsafe-" + name, Index: "restore-unsafe-" + name, Provider: "codex"} + forgetRouting(t, auth) + settings := enabledSettings(t) + rec := record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: auth.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 24*time.Hour, 100, 168)}}, RoutingVersion: 1} + auths := []*coreauth.Auth{auth} + switch name { + case "expired": + rec.Windows[WindowSevenDay] = historyWindow(now, 0, 100, 168) + case "stale": + rec.T = now.Add(-9 * 24 * time.Hour).UnixMilli() + case "future-observation": + rec.T = now.Add(time.Millisecond).UnixMilli() + case "far-reset": + rec.Windows[WindowSevenDay] = historyWindow(now, 30*24*time.Hour, 100, 168) + case "missing-reset": + rec.Windows[WindowSevenDay] = Window{UsedPercent: 100, PeriodHours: 168} + case "estimated": + rec.EstimatedWindows = []string{WindowSevenDay} + case "legacy-codex-estimate": + rec.RoutingVersion = 0 + case "disabled": + auth.Disabled = true + case "removed": + auths = nil + case "api-key": + auth.Attributes = map[string]string{"api_key": "synthetic-key"} + case "untracked": + settings.Providers = "claude" + case "unknown-version": + rec.RoutingVersion = 99 + case "replaced": + auth.CreatedAt = now + } + seedHistory(t, settings, rec) + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return auths }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + if _, windows := coreauth.ObservedQuotaWindows(auth.ID); len(windows) != 0 { + t.Fatalf("unsafe history restored: %+v", windows) + } + }) + } +} + +func TestRecorderPersistsParserSafetyMetadata(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + auth := &coreauth.Auth{ID: "restore-parser", Index: "restore-parser", Provider: "codex"} + forgetRouting(t, auth) + source := NewRecorder(Deps{Do: func(context.Context, *coreauth.Auth, string, string, map[string]string) (int, []byte, error) { + return 200, []byte(`{"rate_limit":{"limit_reached":true,"primary_window":{"limit_window_seconds":18000,"reset_after_seconds":3600},"secondary_window":{"used_percent":20,"limit_window_seconds":604800,"reset_after_seconds":86400}}}`), nil + }}) + source.now = func() time.Time { return now.Add(-time.Minute) } + rec := source.sample(context.Background(), auth) + if rec.Error != "" || len(rec.EstimatedWindows) != 1 { + t.Fatalf("sample = %+v", rec) + } + // A provider-specific model scope must survive storage even though Window's + // internal modelScope field is absent from the public history API. + rec.RoutingScopes = map[string][]string{WindowSevenDay: {"gpt-5-*"}} + settings := enabledSettings(t) + seedHistory(t, settings, rec) + coreauth.ForgetQuotaWindows(auth.ID) + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return []*coreauth.Auth{auth} }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + ts, windows := coreauth.ObservedQuotaWindows(auth.ID) + if !ts.Equal(time.UnixMilli(rec.T)) || len(windows) != 1 || windows[0].Key != WindowSevenDay || len(windows[0].ModelScope) != 1 || windows[0].ModelScope[0] != "gpt-5-*" { + t.Fatalf("restored = %v, %+v", ts, windows) + } +} + +func TestRecorderRestoreScopedCapsAndEmptySuccess(t *testing.T) { + now := time.Now().Truncate(time.Millisecond) + auth := &coreauth.Auth{ID: "restore-scoped", Index: "restore-scoped", Provider: "claude"} + other := &coreauth.Auth{ID: "restore-scoped-other", Index: "restore-scoped-other", Provider: "claude"} + forgetRouting(t, auth, other) + settings := enabledSettings(t) + seedHistory(t, settings, + record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: auth.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 24*time.Hour, 10, 168), WindowSevenDayFable: historyWindow(now, 48*time.Hour, 100, 168)}}}, + record{Sample: Sample{T: now.Add(-time.Minute).UnixMilli(), AuthIndex: other.Index, Windows: map[string]Window{WindowSevenDay: historyWindow(now, 72*time.Hour, 10, 168)}}}, + ) + r := NewRecorder(Deps{ListAuths: func() []*coreauth.Auth { return []*coreauth.Auth{auth, other} }}) + r.now = func() time.Time { return now } + r.startupDelay = time.Hour + t.Cleanup(r.Close) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + for _, tc := range []struct{ model, want string }{{"claude-fable-5", other.ID}, {"claude-sonnet-5", auth.ID}} { + got, err := (&coreauth.SoonestResetFirstSelector{}).Pick(context.Background(), "claude", tc.model, cliproxyexecutor.Options{}, []*coreauth.Auth{auth, other}) + if err != nil || got == nil || got.ID != tc.want { + t.Fatalf("Pick(%s)=%v,%v,want %s", tc.model, got, err, tc.want) + } + } + r.Close() + seedHistory(t, settings, record{Sample: Sample{T: now.UnixMilli(), AuthIndex: auth.Index, Windows: map[string]Window{}}}) + coreauth.ForgetQuotaWindows(auth.ID) + coreauth.ForgetScopedWeeklyWindows(auth.ID) + if err := r.Apply(settings); err != nil { + t.Fatal(err) + } + if _, windows := coreauth.ObservedQuotaWindows(auth.ID); len(windows) != 0 { + t.Fatalf("empty success revived old windows: %+v", windows) + } +} diff --git a/internal/quotahistory/store.go b/internal/quotahistory/store.go index 2772d08aad9..567b0fff619 100644 --- a/internal/quotahistory/store.go +++ b/internal/quotahistory/store.go @@ -32,6 +32,11 @@ type Sample struct { type record struct { Sample Plan string `json:"plan,omitempty"` + // Routing metadata was absent in older history. Persist the parser's safety + // information separately so the management sample shape stays stable. + RoutingVersion int `json:"routing_version,omitempty"` + RoutingScopes map[string][]string `json:"routing_scopes,omitempty"` + EstimatedWindows []string `json:"estimated_windows,omitempty"` } // Store persists samples in bbolt. Keys are an 8-byte big-endian unix-ms diff --git a/internal/runtime/executor/claude_executor_execute.go b/internal/runtime/executor/claude_executor_execute.go index 1b094a5693d..ce4136134e0 100644 --- a/internal/runtime/executor/claude_executor_execute.go +++ b/internal/runtime/executor/claude_executor_execute.go @@ -358,7 +358,7 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } - return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) + return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, &helps.AcceptedResponseError{Err: err}) } defer func() { if errClose := decodedBody.Close(); errClose != nil { @@ -369,7 +369,15 @@ func (e *ClaudeExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r helps.AppendAPIResponseChunk(ctx, e.cfg, data) if err != nil { helps.RecordAPIResponseError(ctx, e.cfg, err) - return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) + var responseErr error = &helps.AcceptedResponseError{Err: err} + if upstreamStream { + // A complete vendor error event remains authoritative even if the + // decoder subsequently fails while reading the response trailer. + if vendorErr, ok := validateClaudeStreamingResponse(data).(statusErr); ok && !vendorErr.streamTruncated { + responseErr = vendorErr + } + } + return resp, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, responseErr) } var streamUsage helps.StreamUsageBuffer threadMessageID := "" diff --git a/internal/runtime/executor/claude_executor_stream.go b/internal/runtime/executor/claude_executor_stream.go index 0a51f523a5a..5fb010fef60 100644 --- a/internal/runtime/executor/claude_executor_stream.go +++ b/internal/runtime/executor/claude_executor_stream.go @@ -352,7 +352,7 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if errClose := httpResp.Body.Close(); errClose != nil { log.Errorf("response body close error: %v", errClose) } - return nil, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, err) + return nil, wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, &helps.AcceptedResponseError{Err: err}) } out := make(chan cliproxyexecutor.StreamChunk, 1) go func() { @@ -454,12 +454,12 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if emitCancellation(scanner.Err()) { return } - errScan := scanner.Err() - if errScan == nil { - errScan = upstreamStreamErr + errScan := upstreamStreamErr + if errScan == nil && scanner.Err() != nil { + errScan = &helps.AcceptedResponseError{Err: scanner.Err()} } if errScan == nil && ctx.Err() == nil { - errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop"} + errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop", streamTruncated: true} } if errScan != nil { errScan = wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, errScan) @@ -557,12 +557,12 @@ func (e *ClaudeExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A if emitCancellation(scanner.Err()) { return } - errScan := scanner.Err() - if errScan == nil { - errScan = upstreamStreamErr + errScan := upstreamStreamErr + if errScan == nil && scanner.Err() != nil { + errScan = &helps.AcceptedResponseError{Err: scanner.Err()} } if errScan == nil && ctx.Err() == nil { - errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop"} + errScan = statusErr{code: http.StatusBadGateway, msg: "upstream stream closed before message_stop", streamTruncated: true} } if errScan != nil { errScan = wrapClaudeFastRequestError(fastRequest, httpResp.StatusCode, errScan) @@ -594,6 +594,7 @@ func validateClaudeStreamingResponse(data []byte) error { hasData := false hasMessageStart := false hasMessageDelta := false + hasMessageStop := false for scanner.Scan() { line := bytes.TrimSpace(scanner.Bytes()) @@ -606,7 +607,7 @@ func validateClaudeStreamingResponse(data []byte) error { } hasData = true if !ojson.ValidBytes(payload) { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned malformed stream data"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned malformed stream data", streamTruncated: true} } root := util.ParseGJSONBytesNoCopy(payload) @@ -623,24 +624,26 @@ func validateClaudeStreamingResponse(data []byte) error { case "message_start": message := root.Get("message") if strings.TrimSpace(message.Get("id").String()) == "" || strings.TrimSpace(message.Get("model").String()) == "" { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream message_start is missing id or model"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream message_start is missing id or model", streamTruncated: true} } hasMessageStart = true case "message_delta": hasMessageDelta = true + case "message_stop": + hasMessageStop = true } } if errScan := scanner.Err(); errScan != nil { - return errScan + return &helps.AcceptedResponseError{Err: errScan} } if !hasData { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned empty stream response"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream returned empty stream response", streamTruncated: true} } if !hasMessageStart { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response is missing message_start"} + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response is missing message_start", streamTruncated: true} } - if !hasMessageDelta { - return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response ended before message completion"} + if !hasMessageDelta || !hasMessageStop { + return statusErr{code: http.StatusBadGateway, msg: "claude executor: upstream stream response ended before message completion", streamTruncated: true} } return nil } diff --git a/internal/runtime/executor/claude_executor_truncation_test.go b/internal/runtime/executor/claude_executor_truncation_test.go new file mode 100644 index 00000000000..43ecc857f16 --- /dev/null +++ b/internal/runtime/executor/claude_executor_truncation_test.go @@ -0,0 +1,239 @@ +package executor + +import ( + "bytes" + "compress/gzip" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/config" + "github.com/rune-oai/t3code-proxy/internal/registry" + "github.com/rune-oai/t3code-proxy/internal/runtime/executor/helps" + cliproxyauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + sdktranslator "github.com/rune-oai/t3code-proxy/sdk/translator" +) + +func TestClaudeExecutorManagerPrematureEOFKeepsCredentialWithoutReplay(t *testing.T) { + const model = "claude-sonnet-4-5" + const start = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_partial\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-sonnet-4-5\",\"content\":[],\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\n" + const delta = "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\n" + const stop = "event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n" + for _, failure := range []string{"message_start", "message_delta", "gzip-trailer", "gzip-header", "incomplete-json"} { + for _, rule := range []string{"none", "miss", "continue-and-cooldown"} { + for _, mode := range []string{"nonstream", "stream-claude", "stream-openai"} { + t.Run(failure+"/rule="+rule+"/"+mode, func(t *testing.T) { + var truncated atomic.Bool + var hits atomic.Int32 + accounts := make(chan string, 16) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + hits.Add(1) + accounts <- r.Header.Get("Authorization") + w.Header().Set("Content-Type", "text/event-stream") + payload := []byte(start) + if failure != "message_start" || !truncated.Load() { + payload = append(payload, delta...) + } + if !truncated.Load() { + payload = append(payload, stop...) + } else if failure == "incomplete-json" { + payload = append(payload, `data: {"type":"content_block_delta","delta":{"text":"unfinished`...) + } + if failure == "gzip-trailer" || failure == "gzip-header" { + var compressed bytes.Buffer + writer := gzip.NewWriter(&compressed) + _, _ = writer.Write(payload) + _ = writer.Close() + payload = compressed.Bytes() + if truncated.Load() { + if failure == "gzip-header" { + payload = payload[:5] + } else { + payload = payload[:len(payload)-5] + } + } + w.Header().Set("Content-Encoding", "gzip") + } + _, _ = w.Write(payload) + w.(http.Flusher).Flush() + })) + t.Cleanup(server.Close) + t.Cleanup(helps.ResetProxyTransports) + cfg := &config.Config{} + if rule != "none" { + pattern := ".+" + if rule == "miss" { + pattern = "never-match-this-upstream-error" + } + cfg.OAuthRequestScopedErrors = map[string][]config.RequestScopedErrorRule{ + "claude": {{Status: http.StatusBadGateway, MatchRegexr: []string{pattern}, Action: cliproxyauth.RequestScopedActionContinueAndCooldown}}, + } + } + + selector := cliproxyauth.NewSessionAffinitySelector(&cliproxyauth.RoundRobinSelector{}) + t.Cleanup(selector.Stop) + manager := cliproxyauth.NewManager(nil, selector, nil) + manager.SetConfig(cfg) + manager.SetRetryConfig(3, 0, 0) + manager.RegisterExecutor(NewClaudeExecutor(cfg)) + for _, name := range []string{"one.json", "two.json"} { + id := t.Name() + "/" + name + auth := &cliproxyauth.Auth{ + ID: id, FileName: name, Provider: "claude", ProxyURL: "direct", + Metadata: map[string]any{"access_token": "sk-ant-oat-test-" + name, "refresh_token": "refresh-" + name, "account_uuid": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"}, + Attributes: map[string]string{"base_url": server.URL}, + } + if _, errRegister := manager.Register(t.Context(), auth); errRegister != nil { + t.Fatal(errRegister) + } + registry.GetGlobalRegistry().RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(id) }) + } + payload := []byte(`{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatOpenAI, + OriginalRequest: payload, Headers: http.Header{"X-Claude-Code-Session-Id": []string{t.Name()}}, + } + if mode == "stream-claude" { + opts.ResponseFormat = sdktranslator.FormatClaude + } + request := cliproxyexecutor.Request{Model: model, Payload: payload} + run := func() error { + if mode == "nonstream" { + _, errExecute := manager.Execute(t.Context(), []string{"claude"}, request, opts) + return errExecute + } + result, errStream := manager.ExecuteStream(t.Context(), []string{"claude"}, request, opts) + if errStream != nil { + return errStream + } + var chunkErr error + var sawPayload bool + for chunk := range result.Chunks { + if len(chunk.Payload) > 0 { + sawPayload = true + } + if chunk.Err != nil { + chunkErr = chunk.Err + } + } + if !sawPayload && !(failure == "gzip-header" && truncated.Load()) { + t.Fatal("stream did not deliver accepted message_start") + } + return chunkErr + } + if errWarm := run(); errWarm != nil { + t.Fatal(errWarm) + } + firstAccount := <-accounts + if firstAccount == "" { + t.Fatal("request did not carry the selected OAuth credential") + } + truncated.Store(true) + errPartial := run() + var truncErr cliproxyexecutor.StreamTruncatedError + if !errors.As(errPartial, &truncErr) || !truncErr.IsStreamTruncated() { + t.Fatalf("error = %T (%v), want typed stream truncation", errPartial, errPartial) + } + if (failure == "gzip-header" || failure == "gzip-trailer") && mode == "nonstream" && !errors.Is(errPartial, io.ErrUnexpectedEOF) { + t.Fatalf("decoder cause lost: %v", errPartial) + } + if hits.Load() != 2 { + t.Fatalf("requests = %d, want 2 including warm-up", hits.Load()) + } + for _, name := range []string{"one.json", "two.json"} { + auth, _ := manager.GetByID(t.Name() + "/" + name) + if auth.Unavailable || auth.Quota.Exceeded || !auth.NextRetryAfter.IsZero() { + t.Fatalf("credential %s cooled after accepted partial response: %s", name, auth.StatusMessage) + } + for _, state := range auth.ModelStates { + if state.Unavailable || state.Quota.Exceeded || !state.NextRetryAfter.IsZero() { + t.Fatalf("model cooled after accepted partial response: %+v", state) + } + } + } + truncated.Store(false) + if errNext := run(); errNext != nil { + t.Fatal(errNext) + } + if hits.Load() != 3 || <-accounts != firstAccount || <-accounts != firstAccount { + t.Fatal("accepted partial response replayed or rebound the session") + } + }) + } + } + } +} + +func TestClaudeExecutorPreservesExplicitVendorErrors(t *testing.T) { + for _, failure := range []string{"http-status", "sse-error", "sse-error-gzip-cutoff"} { + for _, mode := range []string{"nonstream", "stream-claude", "stream-openai"} { + t.Run(failure+"/"+mode, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = io.Copy(io.Discard, r.Body) + if failure == "http-status" { + w.WriteHeader(http.StatusTooManyRequests) + _, _ = io.WriteString(w, `{"type":"error","error":{"type":"rate_limit_error","message":"explicit vendor rejection"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + payload := []byte("event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"explicit vendor rejection\"}}\n\n") + if failure == "sse-error-gzip-cutoff" { + var compressed bytes.Buffer + writer := gzip.NewWriter(&compressed) + _, _ = writer.Write(payload) + _ = writer.Close() + payload = compressed.Bytes()[:compressed.Len()-5] + w.Header().Set("Content-Encoding", "gzip") + } + _, _ = w.Write(payload) + })) + t.Cleanup(server.Close) + t.Cleanup(helps.ResetProxyTransports) + executor := NewClaudeExecutor(&config.Config{}) + auth := &cliproxyauth.Auth{Attributes: map[string]string{"api_key": "test-key", "base_url": server.URL}, ProxyURL: "direct"} + payload := []byte(`{"model":"claude-sonnet-4-5","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`) + request := cliproxyexecutor.Request{Model: "claude-sonnet-4-5", Payload: payload} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude, ResponseFormat: sdktranslator.FormatOpenAI, OriginalRequest: payload} + if mode == "stream-claude" { + opts.ResponseFormat = sdktranslator.FormatClaude + } + var responseErr error + if mode == "nonstream" { + _, responseErr = executor.Execute(t.Context(), auth, request, opts) + } else { + var result *cliproxyexecutor.StreamResult + result, responseErr = executor.ExecuteStream(t.Context(), auth, request, opts) + if responseErr == nil { + for chunk := range result.Chunks { + if chunk.Err != nil { + responseErr = chunk.Err + } + } + } + } + if responseErr == nil || !strings.Contains(responseErr.Error(), "explicit vendor rejection") { + t.Fatalf("vendor error lost: %v", responseErr) + } + var truncated cliproxyexecutor.StreamTruncatedError + if errors.As(responseErr, &truncated) && truncated.IsStreamTruncated() { + t.Fatalf("vendor error classified as response interruption: %v", responseErr) + } + var status interface{ StatusCode() int } + want := http.StatusBadGateway + if failure == "http-status" { + want = http.StatusTooManyRequests + } + if !errors.As(responseErr, &status) || status.StatusCode() != want { + t.Fatalf("vendor status lost: %v", responseErr) + } + }) + } + } +} diff --git a/internal/runtime/executor/codex_executor_execute.go b/internal/runtime/executor/codex_executor_execute.go index f208015a7c4..5f2c602aea0 100644 --- a/internal/runtime/executor/codex_executor_execute.go +++ b/internal/runtime/executor/codex_executor_execute.go @@ -272,6 +272,7 @@ func (e *CodexExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, re } eventData := bytes.TrimSpace(line[5:]) + helps.ObserveCodexQuotaEvent(ctx, eventData) eventData = helps.RestoreCodexMultiAgentV2Response(eventData, optimizeMultiAgentV2) reporter.ObserveResponseModel(eventData) eventType := ojson.GetBytesNoCopy(eventData, "type").String() diff --git a/internal/runtime/executor/codex_executor_stream.go b/internal/runtime/executor/codex_executor_stream.go index 6b6bfe5eea7..fa353611767 100644 --- a/internal/runtime/executor/codex_executor_stream.go +++ b/internal/runtime/executor/codex_executor_stream.go @@ -269,6 +269,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au isHandshake = true } else if bytes.HasPrefix(line, dataTag) { data := bytes.TrimSpace(line[5:]) + helps.ObserveCodexQuotaEvent(ctx, data) data = helps.RestoreCodexMultiAgentV2Response(data, optimizeMultiAgentV2) observeCodexTokenEvent(reporter, data) translatedLine = append([]byte("data: "), data...) @@ -469,6 +470,7 @@ func (e *CodexExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.Au translatedLine = transformed } else if bytes.HasPrefix(line, dataTag) { data := bytes.TrimSpace(line[5:]) + helps.ObserveCodexQuotaEvent(ctx, data) data = helps.RestoreCodexMultiAgentV2Response(data, optimizeMultiAgentV2) observeCodexTokenEvent(reporter, data) translatedLine = append([]byte("data: "), data...) diff --git a/internal/runtime/executor/codex_http_quota_observation_test.go b/internal/runtime/executor/codex_http_quota_observation_test.go new file mode 100644 index 00000000000..d476ba4b7ba --- /dev/null +++ b/internal/runtime/executor/codex_http_quota_observation_test.go @@ -0,0 +1,74 @@ +package executor + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/registry" + cliproxyauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + sdktranslator "github.com/rune-oai/t3code-proxy/sdk/translator" +) + +func TestCodexHTTPQuotaEventsReachCredentialWithoutHeaderPassthrough(t *testing.T) { + for _, mode := range []string{"buffered", "stream", "bootstrap-stream"} { + t.Run(mode, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("X-Codex-Turn-State", "opaque-continuation") + for _, event := range []string{ + codexCreatedEvent, + `{"type":"codex.rate_limits","rate_limits":{"primary":{"used_percent":42,"window_minutes":300,"reset_at":1893456000}},"metered_limit_name":"codex","headers":{"X-Codex-Turn-State":"opaque-event"}}`, + codexCompletedEventBody, + } { + _, _ = fmt.Fprint(w, "data: "+event+"\n\n") + } + })) + defer server.Close() + cfg := codexBufferingConfig(mode == "bootstrap-stream") + cfg.PassthroughHeaders = false + cfg.RequestLog = false + manager := cliproxyauth.NewManager(nil, nil, nil) + manager.SetConfig(cfg) + manager.RegisterExecutor(NewCodexExecutor(cfg)) + auth := codexAPIKeyTestAuth(server.URL) + auth.ID = "http-quota-" + mode + auth.Status = cliproxyauth.StatusActive + const model = "gpt-5.6-terra" + registry.GetGlobalRegistry().RegisterClient(auth.ID, "codex", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { registry.GetGlobalRegistry().UnregisterClient(auth.ID) }) + ctx := context.Background() + if _, err := manager.Register(ctx, auth); err != nil { + t.Fatal(err) + } + req := cliproxyexecutor.Request{Model: model, Payload: []byte(`{"model":"gpt-5.6-terra","input":"hello"}`)} + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString("openai-response"), Stream: mode != "buffered"} + if opts.Stream { + result, err := manager.ExecuteStream(ctx, []string{"codex"}, req, opts) + if err != nil { + t.Fatal(err) + } + for chunk := range result.Chunks { + if chunk.Err != nil { + t.Fatal(chunk.Err) + } + } + } else if _, err := manager.Execute(ctx, []string{"codex"}, req, opts); err != nil { + t.Fatal(err) + } + updated, ok := manager.GetByID(auth.ID) + if !ok { + t.Fatal("selected credential missing") + } + if updated.Quota.Signals["X-Codex-Primary-Used-Percent"] != "42" || updated.Quota.Signals["X-Codex-Active-Limit"] != "codex" { + t.Fatalf("SSE quota event did not reach selected credential: %+v", updated.Quota.Signals) + } + if _, exists := updated.Quota.Signals["X-Codex-Turn-State"]; exists { + t.Fatal("opaque continuation state reached quota diagnostics") + } + }) + } +} diff --git a/internal/runtime/executor/helps/codex_quota.go b/internal/runtime/executor/helps/codex_quota.go index aa96f8f5e7c..0b14a6a7b4a 100644 --- a/internal/runtime/executor/helps/codex_quota.go +++ b/internal/runtime/executor/helps/codex_quota.go @@ -1,13 +1,21 @@ package helps import ( + "context" "net/http" "strings" "github.com/MoeForge/moego/ojson" + "github.com/rune-oai/t3code-proxy/internal/logging" "github.com/rune-oai/t3code-proxy/internal/util" ) +// ObserveCodexQuotaEvent records quota data before transport-specific event +// filtering, independently of request logging and downstream header passthrough. +func ObserveCodexQuotaEvent(ctx context.Context, payload []byte) { + logging.MergeResponseHeaders(ctx, ParseCodexQuotaEventHeaders(payload)) +} + const ( codexRateLimitsEventType = "codex.rate_limits" codexQuotaAdditionalHeaderKey = "X-Codex-Additional-" diff --git a/internal/runtime/executor/helps/logging_helpers.go b/internal/runtime/executor/helps/logging_helpers.go index e5b5bb3d6ec..e02e5d63ef6 100644 --- a/internal/runtime/executor/helps/logging_helpers.go +++ b/internal/runtime/executor/helps/logging_helpers.go @@ -539,7 +539,7 @@ func AppendAPIWebsocketResponse(ctx context.Context, cfg *config.Config, payload // AppendCodexAPIWebsocketResponse stores a codex upstream websocket response frame and merges any // quota event headers carried by the frame into the request log. func AppendCodexAPIWebsocketResponse(ctx context.Context, cfg *config.Config, payload []byte) { - logging.MergeResponseHeaders(ctx, ParseCodexQuotaEventHeaders(payload)) + ObserveCodexQuotaEvent(ctx, payload) AppendAPIWebsocketResponse(ctx, cfg, payload) } diff --git a/internal/runtime/executor/helps/proxy_pool_override_test.go b/internal/runtime/executor/helps/proxy_pool_override_test.go index e4e717b8b67..01bd2a0ccc1 100644 --- a/internal/runtime/executor/helps/proxy_pool_override_test.go +++ b/internal/runtime/executor/helps/proxy_pool_override_test.go @@ -143,3 +143,31 @@ func TestProxyPoolCredentialOptInWithoutProxyURL(t *testing.T) { } } } + +// TestProxyPoolFileCredentialMetadataOptIn pins the auth-file opt-in: an OAuth +// credential whose file carries proxy_connection_pool reuses one SOCKS5 transport +// instead of dialing the proxy again for every request. +func TestProxyPoolFileCredentialMetadataOptIn(t *testing.T) { + ResetProxyTransports() + t.Cleanup(ResetProxyTransports) + + const proxyURL = "socks5://user:pass@127.0.0.1:1080" + metadata := map[string]any{"proxy_url": proxyURL, cliproxyauth.ProxyConnectionPoolMetadataKey: true} + auth := &cliproxyauth.Auth{ID: "xai.json", Provider: "xai", ProxyURL: proxyURL, Metadata: metadata} + cliproxyauth.ApplyProxyConnectionPoolMetadata(auth, metadata) + + first := NewProxyAwareHTTPClient(context.Background(), testConfig(), auth, 0) + second := NewProxyAwareHTTPClient(context.Background(), testConfig(), auth, 0) + firstTransport, ok := first.Transport.(*http.Transport) + if !ok || firstTransport == nil { + t.Fatalf("first transport = %T, want *http.Transport", first.Transport) + } + if second.Transport != first.Transport { + t.Fatal("opted-in file credential did not reuse its proxied transport") + } + + plain := &cliproxyauth.Auth{ID: "xai-plain.json", Provider: "xai", ProxyURL: proxyURL} + if NewProxyAwareHTTPClient(context.Background(), testConfig(), plain, 0).Transport == NewProxyAwareHTTPClient(context.Background(), testConfig(), plain, 0).Transport { + t.Fatal("file credential without the field must keep a per-request transport") + } +} diff --git a/internal/runtime/executor/helps/response_decode.go b/internal/runtime/executor/helps/response_decode.go index 6f1419cc719..1465164e313 100644 --- a/internal/runtime/executor/helps/response_decode.go +++ b/internal/runtime/executor/helps/response_decode.go @@ -16,6 +16,14 @@ import ( log "github.com/sirupsen/logrus" ) +// AcceptedResponseError marks a read or decoding failure after upstream acceptance. +// The generation may have run, so it must not be replayed or cool the credential. +type AcceptedResponseError struct{ Err error } + +func (e *AcceptedResponseError) Error() string { return e.Err.Error() } +func (e *AcceptedResponseError) Unwrap() error { return e.Err } +func (e *AcceptedResponseError) IsStreamTruncated() bool { return true } + type compositeReadCloser struct { io.Reader closers []func() error diff --git a/internal/watcher/synthesizer/file.go b/internal/watcher/synthesizer/file.go index 410a57d0942..ff05372c07e 100644 --- a/internal/watcher/synthesizer/file.go +++ b/internal/watcher/synthesizer/file.go @@ -203,6 +203,7 @@ func synthesizeFileAuths(ctx *SynthesisContext, fullPath string, data []byte) ([ applyVertexOpenAPISettingsAttribute(auth, metadata) ApplyAuthExcludedModelsMeta(auth, perAccountExcluded, "oauth") coreauth.ApplyCustomHeadersFromMetadata(auth) + coreauth.ApplyProxyConnectionPoolMetadata(auth, metadata) applyFingerprintProfileAttribute(auth, metadata) auth.BindFileSnapshot(fullPath, data) } @@ -281,6 +282,7 @@ func synthesizeFileAuths(ctx *SynthesisContext, fullPath string, data []byte) ([ } } coreauth.ApplyCustomHeadersFromMetadata(a) + coreauth.ApplyProxyConnectionPoolMetadata(a, metadata) coreauth.SetOAuthModelAliasesAttribute(a, perAccountModelAliases) applyOpenAPIModelsAttribute(a, metadata) applyVertexOpenAPISettingsAttribute(a, metadata) diff --git a/internal/watcher/synthesizer/file_test.go b/internal/watcher/synthesizer/file_test.go index e9f87a1efdd..1a9cca79091 100644 --- a/internal/watcher/synthesizer/file_test.go +++ b/internal/watcher/synthesizer/file_test.go @@ -1244,3 +1244,36 @@ func TestFileSynthesizerRecordsIncompleteFiles(t *testing.T) { } }) } + +func TestFileSynthesizer_Synthesize_ProxyConnectionPool(t *testing.T) { + tempDir := t.TempDir() + authData := map[string]any{ + "type": "xai", + "email": "test@example.com", + "proxy_url": "socks5://user:pass@127.0.0.1:1080", + "proxy_connection_pool": true, + } + data, _ := json.Marshal(authData) + if err := os.WriteFile(filepath.Join(tempDir, "xai-auth.json"), data, 0o600); err != nil { + t.Fatalf("failed to write auth file: %v", err) + } + + synth := NewFileSynthesizer() + ctx := &SynthesisContext{ + Config: &config.Config{}, + AuthDir: tempDir, + Now: time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC), + IDGenerator: NewStableIDGenerator(), + } + auths, err := synth.Synthesize(ctx) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(auths) != 1 { + t.Fatalf("expected 1 auth, got %d", len(auths)) + } + pool := auths[0].ProxyConnectionPool + if pool == nil || pool.Enabled == nil || !*pool.Enabled { + t.Fatalf("ProxyConnectionPool = %+v, want enabled", pool) + } +} diff --git a/sdk/auth/filestore.go b/sdk/auth/filestore.go index 7dcf8f731d8..5984a9b435e 100644 --- a/sdk/auth/filestore.go +++ b/sdk/auth/filestore.go @@ -311,6 +311,7 @@ func (s *FileTokenStore) readAuthFiles(path, baseDir string) ([]*cliproxyauth.Au } } cliproxyauth.ApplyCustomHeadersFromMetadata(auth) + cliproxyauth.ApplyProxyConnectionPoolMetadata(auth, metadata) } return auths, nil } @@ -364,6 +365,7 @@ func (s *FileTokenStore) readAuthFiles(path, baseDir string) ([]*cliproxyauth.Au auth.Attributes["email"] = email } cliproxyauth.ApplyCustomHeadersFromMetadata(auth) + cliproxyauth.ApplyProxyConnectionPoolMetadata(auth, metadata) return []*cliproxyauth.Auth{auth}, nil } diff --git a/sdk/auth/filestore_proxy_test.go b/sdk/auth/filestore_proxy_test.go index 03c13c1cea9..96ef2ef9736 100644 --- a/sdk/auth/filestore_proxy_test.go +++ b/sdk/auth/filestore_proxy_test.go @@ -92,3 +92,37 @@ func TestFileTokenStoreList_DoesNotBlockColdStartWithUnproxiedNetworkRequest(t * t.Fatalf("List took %v, expected < 2s (should not perform blocking network calls during file load)", elapsed) } } + +// TestFileTokenStoreList_LoadsProxyConnectionPool verifies that an auth file can opt +// its proxied transport into connection pooling, which config-only credentials could +// do before. +func TestFileTokenStoreList_LoadsProxyConnectionPool(t *testing.T) { + dir := t.TempDir() + store := NewFileTokenStore() + store.SetBaseDir(dir) + + content := []byte(`{ + "type": "xai", + "proxy_url": "socks5://user:pass@127.0.0.1:1080", + "proxy_connection_pool": {"idle-conn-timeout": "120s"}, + "access_token": "test-token" + }`) + if err := os.WriteFile(filepath.Join(dir, "xai.json"), content, 0o600); err != nil { + t.Fatalf("failed to write test file: %v", err) + } + + auths, err := store.List(context.Background()) + if err != nil { + t.Fatalf("List error: %v", err) + } + if len(auths) != 1 { + t.Fatalf("got %d auths, want 1", len(auths)) + } + pool := auths[0].ProxyConnectionPool + if pool == nil { + t.Fatal("ProxyConnectionPool = nil, want the file's block") + } + if pool.IdleConnTimeout != "120s" { + t.Fatalf("IdleConnTimeout = %q, want 120s", pool.IdleConnTimeout) + } +} diff --git a/sdk/cliproxy/auth/conductor.go b/sdk/cliproxy/auth/conductor.go index 2a0dc84e4d8..bde6b7a563f 100644 --- a/sdk/cliproxy/auth/conductor.go +++ b/sdk/cliproxy/auth/conductor.go @@ -182,6 +182,7 @@ type Manager struct { pendingCooldownStateStore CooldownStateStore executors map[string]ProviderExecutor selector Selector + affinityPersistence *sessionAffinityPersistence hook Hook resultPolicy atomic.Pointer[resultPolicyHolder] mu sync.RWMutex @@ -277,6 +278,11 @@ func NewManager(store Store, selector Selector, hook Hook) *Manager { providerOffsets: make(map[string]int), modelPoolOffsets: make(map[string]int), } + if affinity, ok := selector.(*SessionAffinitySelector); ok { + manager.affinityPersistence = affinity.persistence + affinity.persistenceManaged = true + affinity.authCandidates = manager.List + } // atomic.Value requires non-nil initial value. manager.runtimeConfig.Store(&internalconfig.Config{}) manager.apiKeyModelRouting.Store(&apiKeyModelRoutingSnapshot{config: &internalconfig.Config{}}) diff --git a/sdk/cliproxy/auth/conductor_lifecycle.go b/sdk/cliproxy/auth/conductor_lifecycle.go index d4c28141e0a..1cb678abdb3 100644 --- a/sdk/cliproxy/auth/conductor_lifecycle.go +++ b/sdk/cliproxy/auth/conductor_lifecycle.go @@ -661,10 +661,19 @@ func (m *Manager) updateInternalLocked(ctx context.Context, base, auth *Auth, mo executorKeyFromAuth(existingBeforeSave) != executorKeyFromAuth(authClone) forgetEpoch := authClone.RegistrationEpoch forgetGen := authClone.Generation + if shouldForgetWeighted && m.affinityPersistence != nil { + m.affinityPersistence.retireAuth(authClone.ID, forgetEpoch, forgetGen) + } m.mu.Unlock() _ = schedulerSnapshot if shouldForgetWeighted { m.forgetWeightedAuthUpTo(authClone.ID, forgetEpoch, forgetGen) + // Keep the live binding observable for the supported disabled/never + // contract, while removing it from durable restart state. + m.mu.RLock() + persistence := m.affinityPersistence + m.mu.RUnlock() + persistence.flush() } return auth.Clone(), true, cooldownStateChanged, nil } @@ -717,6 +726,9 @@ func (m *Manager) RemoveIf(ctx context.Context, id string, predicate func(*Auth) return false } provider := strings.TrimSpace(existing.Provider) + if m.affinityPersistence != nil { + m.affinityPersistence.retireAuth(id, existing.RegistrationEpoch, ^uint64(0)) + } delete(m.auths, id) m.notifyAuthChangeLocked(id) if m.modelPoolOffsets != nil { @@ -741,6 +753,11 @@ func (m *Manager) RemoveIf(ctx context.Context, id string, predicate func(*Auth) tombstoneEpoch := m.authEpochs[id] m.mu.Unlock() m.forgetWeightedAuthUpTo(id, tombstoneEpoch, ^uint64(0)) + m.invalidateSessionAffinity(id) + ForgetQuotaWindows(id) + ForgetScopedWeeklyWindows(id) + ForgetShortWindowUsage(id) + ObserveAuthPlan(id, "") releaseMutation() if !shouldDeferAPIKeyModelAliasRebuild(ctx) { @@ -751,7 +768,6 @@ func (m *Manager) RemoveIf(ctx context.Context, id string, predicate func(*Auth) } m.structuralEpoch.Add(1) m.queueRefreshUnschedule(id) - m.invalidateSessionAffinity(id) if provider != "" { if exec, ok := m.Executor(provider); ok && exec != nil { @@ -770,6 +786,10 @@ func (m *Manager) invalidateSessionAffinity(authID string) { if m == nil || authID == "" { return } + m.mu.RLock() + persistence := m.affinityPersistence + m.mu.RUnlock() + persistence.invalidateAuth(authID) sel := m.Selector() if invalidator, ok := sel.(interface{ InvalidateAuth(string) }); ok && invalidator != nil { invalidator.InvalidateAuth(authID) diff --git a/sdk/cliproxy/auth/conductor_request_scoped_errors.go b/sdk/cliproxy/auth/conductor_request_scoped_errors.go index 4a01ee709ef..fb52a5131d1 100644 --- a/sdk/cliproxy/auth/conductor_request_scoped_errors.go +++ b/sdk/cliproxy/auth/conductor_request_scoped_errors.go @@ -194,7 +194,8 @@ func ResolveRequestScopedErrorRules(auth *Auth, cfg *internalconfig.Config) []in // MatchRequestScopedErrorRules evaluates an error against a pre-resolved rule list. func MatchRequestScopedErrorRules(rules []internalconfig.RequestScopedErrorRule, err error) (string, bool) { - if err == nil || len(rules) == 0 || cliproxyexecutor.IsUpstreamWebsocketTurnError(err) { + // A locally truncated response already reached the provider and must not be retried. + if err == nil || len(rules) == 0 || isStreamTruncatedError(err) || cliproxyexecutor.IsUpstreamWebsocketTurnError(err) { return "", false } diff --git a/sdk/cliproxy/auth/conductor_selection.go b/sdk/cliproxy/auth/conductor_selection.go index 3d22270b795..c3096d5ccbc 100644 --- a/sdk/cliproxy/auth/conductor_selection.go +++ b/sdk/cliproxy/auth/conductor_selection.go @@ -748,6 +748,14 @@ func (m *Manager) SetSelector(selector Selector) { m.mu.Unlock() return } + if affinity, ok := selector.(*SessionAffinitySelector); ok { + if m.affinityPersistence == nil { + m.affinityPersistence = affinity.persistence + } + affinity.persistence = m.affinityPersistence + affinity.persistenceManaged = true + affinity.authCandidates = m.List + } m.selector = selector m.mu.Unlock() diff --git a/sdk/cliproxy/auth/proxy_pool_metadata.go b/sdk/cliproxy/auth/proxy_pool_metadata.go new file mode 100644 index 00000000000..5d69bcd76ec --- /dev/null +++ b/sdk/cliproxy/auth/proxy_pool_metadata.go @@ -0,0 +1,69 @@ +package auth + +import ( + "encoding/json" + "strings" +) + +// ProxyConnectionPoolMetadataKey is the auth-file field that opts a file-backed +// credential into a pooled upstream transport, mirroring the per-api-key +// `connection-pool` config block. Without it, a credential with a proxy_url gets a +// fresh transport, and so a fresh proxied TCP and TLS handshake, on every request. +const ProxyConnectionPoolMetadataKey = "proxy_connection_pool" + +// ApplyProxyConnectionPoolMetadata sets auth.ProxyConnectionPool from the +// credential metadata. The value is either a boolean (true asks for the pool +// defaults, false keeps the historical per-request transport) or an object with +// the config block's fields: enabled, idle-conn-timeout and +// max-idle-conns-per-host. An absent field leaves the override untouched; an +// unrecognized value clears it. +func ApplyProxyConnectionPoolMetadata(auth *Auth, metadata map[string]any) { + if auth == nil { + return + } + raw, ok := metadata[ProxyConnectionPoolMetadataKey] + if !ok { + return + } + auth.ProxyConnectionPool = proxyConnectionPoolFromMetadata(raw) +} + +func proxyConnectionPoolFromMetadata(raw any) *ProxyConnectionPoolOverride { + switch value := raw.(type) { + case bool: + return &ProxyConnectionPoolOverride{Enabled: &value} + case map[string]any: + // An empty object is still the opt-in, matching `connection-pool: {}`. + out := &ProxyConnectionPoolOverride{} + if enabled, ok := value["enabled"].(bool); ok { + out.Enabled = &enabled + } + if idle, ok := value["idle-conn-timeout"].(string); ok { + out.IdleConnTimeout = strings.TrimSpace(idle) + } + if maxIdle, ok := metadataInt(value["max-idle-conns-per-host"]); ok { + out.MaxIdleConnsPerHost = &maxIdle + } + return out + default: + return nil + } +} + +// metadataInt reads an integer from file-decoded (float64) or management-decoded +// (json.Number) metadata. +func metadataInt(raw any) (int, bool) { + switch value := raw.(type) { + case float64: + return int(value), true + case int: + return value, true + case int64: + return int(value), true + case json.Number: + n, err := value.Int64() + return int(n), err == nil + default: + return 0, false + } +} diff --git a/sdk/cliproxy/auth/proxy_pool_metadata_test.go b/sdk/cliproxy/auth/proxy_pool_metadata_test.go new file mode 100644 index 00000000000..eb4347881ed --- /dev/null +++ b/sdk/cliproxy/auth/proxy_pool_metadata_test.go @@ -0,0 +1,66 @@ +package auth + +import ( + "encoding/json" + "testing" +) + +func TestApplyProxyConnectionPoolMetadata(t *testing.T) { + existing := func() *ProxyConnectionPoolOverride { + enabled := true + return &ProxyConnectionPoolOverride{Enabled: &enabled, IdleConnTimeout: "9s"} + } + tests := []struct { + name string + raw string + wantNil bool + wantEnabled *bool + wantIdle string + wantMax *int + }{ + {name: "absent keeps existing", raw: `{}`, wantEnabled: boolValue(true), wantIdle: "9s"}, + {name: "true asks for defaults", raw: `{"proxy_connection_pool": true}`, wantEnabled: boolValue(true)}, + {name: "false opts out", raw: `{"proxy_connection_pool": false}`, wantEnabled: boolValue(false)}, + {name: "empty object is the opt-in", raw: `{"proxy_connection_pool": {}}`}, + {name: "object fields", raw: `{"proxy_connection_pool": {"enabled": true, "idle-conn-timeout": " 120s ", "max-idle-conns-per-host": 4}}`, wantEnabled: boolValue(true), wantIdle: "120s", wantMax: intValue(4)}, + {name: "unrecognized value clears", raw: `{"proxy_connection_pool": "yes"}`, wantNil: true}, + {name: "null clears", raw: `{"proxy_connection_pool": null}`, wantNil: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var metadata map[string]any + if err := json.Unmarshal([]byte(tt.raw), &metadata); err != nil { + t.Fatalf("unmarshal: %v", err) + } + auth := &Auth{ProxyConnectionPool: existing()} + ApplyProxyConnectionPoolMetadata(auth, metadata) + got := auth.ProxyConnectionPool + if tt.wantNil { + if got != nil { + t.Fatalf("ProxyConnectionPool = %+v, want nil", got) + } + return + } + if got == nil { + t.Fatal("ProxyConnectionPool = nil, want an override") + } + if (got.Enabled == nil) != (tt.wantEnabled == nil) || (got.Enabled != nil && *got.Enabled != *tt.wantEnabled) { + t.Fatalf("Enabled = %v, want %v", got.Enabled, tt.wantEnabled) + } + if got.IdleConnTimeout != tt.wantIdle { + t.Fatalf("IdleConnTimeout = %q, want %q", got.IdleConnTimeout, tt.wantIdle) + } + if (got.MaxIdleConnsPerHost == nil) != (tt.wantMax == nil) || (got.MaxIdleConnsPerHost != nil && *got.MaxIdleConnsPerHost != *tt.wantMax) { + t.Fatalf("MaxIdleConnsPerHost = %v, want %v", got.MaxIdleConnsPerHost, tt.wantMax) + } + }) + } +} + +func TestApplyProxyConnectionPoolMetadataNilAuth(t *testing.T) { + ApplyProxyConnectionPoolMetadata(nil, map[string]any{ProxyConnectionPoolMetadataKey: true}) +} + +func boolValue(v bool) *bool { return &v } + +func intValue(v int) *int { return &v } diff --git a/sdk/cliproxy/auth/selector.go b/sdk/cliproxy/auth/selector.go index 70131c26b94..f33d9422c80 100644 --- a/sdk/cliproxy/auth/selector.go +++ b/sdk/cliproxy/auth/selector.go @@ -1411,12 +1411,15 @@ func availabilityBlock(unavailable, quotaExceeded bool, nextRetryAfter, nextReco // It extracts session ID from multiple sources and maintains session-to-auth // mappings with automatic failover when the bound auth becomes unavailable. type SessionAffinitySelector struct { - fallback Selector - cache *SessionCache - matcher *cliproxysession.MerklePrefixMatcher - subagentAffinity bool - rebindOnQuotaOnly bool - rebindOnNever bool + fallback Selector + cache *SessionCache + persistence *sessionAffinityPersistence + persistenceManaged bool + authCandidates func() []*Auth + matcher *cliproxysession.MerklePrefixMatcher + subagentAffinity bool + rebindOnQuotaOnly bool + rebindOnNever bool } const ( @@ -1608,6 +1611,7 @@ func NewSessionAffinitySelectorWithConfig(cfg SessionAffinityConfig) *SessionAff return &SessionAffinitySelector{ fallback: cfg.Fallback, cache: NewSessionCache(cfg.TTL), + persistence: newSessionAffinityPersistence(), matcher: cliproxysession.NewMerklePrefixMatcher(cfg.TTL), subagentAffinity: subagentAffinity, rebindOnQuotaOnly: rebindMode == SessionAffinityRebindOnQuota, @@ -1713,7 +1717,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri fallbackAuths := highestPriorityAuths(available) modelKey := canonicalModelKey(model) - cacheKey := providerAffinityNamespace(provider, opts.Metadata) + "::" + primaryID + "::" + modelKey + cacheKey := affinityRequestNamespace(provider, opts.Metadata) + "::" + primaryID + "::" + modelKey isFork := false if opts.Metadata != nil { if forkFlag, ok := opts.Metadata[cliproxyexecutor.IsForkMetadataKey].(bool); ok && forkFlag { @@ -1723,29 +1727,57 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri isSubagent := !isFork && isSubagentSession(primaryID, fallbackID) fallbackKey := "" if fallbackID != "" && fallbackID != primaryID { - fallbackKey = providerAffinityNamespace(provider, opts.Metadata) + "::" + fallbackID + "::" + modelKey + fallbackKey = affinityRequestNamespace(provider, opts.Metadata) + "::" + fallbackID + "::" + modelKey + } + // Capture incarnations before reading any binding. A later preservation must + // not adopt a replacement registration that appeared while fallback waited. + preservedCandidates := auths + if explicitID != "" && s.authCandidates != nil { + preservedCandidates = s.authCandidates() } bind := func(authID string, recordSelection bool) { keys := []string{cacheKey} if fallbackKey != "" && !isSubagent && !isFork { keys = append(keys, fallbackKey) } - if !recordSelection { - s.cache.SetAliases(authID, keys...) + publish := func() { + if !recordSelection { + s.cache.SetAliases(authID, keys...) + return + } + bindingProvider := canonicalSchedulingProvider(provider) + for _, candidate := range auths { + if candidate != nil && candidate.ID == authID { + if candidateProvider := canonicalSchedulingProvider(executorKeyFromAuth(candidate)); candidateProvider != "" { + bindingProvider = candidateProvider + } + break + } + } + s.cache.setAliases(authID, sessionBinding{provider: bindingProvider, sessionID: primaryID, scope: affinityRequestScope(opts.Metadata), model: modelKey}, keys...) + } + if explicitID == "" { + publish() return } - bindingProvider := canonicalSchedulingProvider(provider) - for _, candidate := range auths { + bindingCandidates := auths + if !recordSelection { + bindingCandidates = preservedCandidates + } + for _, candidate := range bindingCandidates { if candidate != nil && candidate.ID == authID { - if candidateProvider := canonicalSchedulingProvider(executorKeyFromAuth(candidate)); candidateProvider != "" { - bindingProvider = candidateProvider - } - break + s.persistence.bind(candidate, s.cache.ttl, publish, keys...) + return } } - s.cache.setSessionAliases(authID, bindingProvider, primaryID, keys...) } + if explicitID != "" { + s.restoreExplicitBinding(cacheKey, auths) + if fallbackKey != "" { + s.restoreExplicitBinding(fallbackKey, auths) + } + } if cachedAuthID, ok := s.cache.GetAndRefresh(cacheKey); ok { for _, auth := range available { if auth.ID == cachedAuthID { @@ -1793,7 +1825,7 @@ func (s *SessionAffinitySelector) Pick(ctx context.Context, provider, model stri providers[candidateProvider] = struct{}{} } } - if parentAuthID := s.cache.latestSessionAuth(fallbackID, providers); parentAuthID != "" { + if parentAuthID := s.cache.latestSessionAuth(fallbackID, providers, affinityRequestScope(opts.Metadata)); parentAuthID != "" { for _, auth := range available { if auth.ID == parentAuthID { bind(auth.ID, true) @@ -2138,6 +2170,11 @@ func (s *SessionAffinitySelector) Stop() { if s == nil { return } + if s.persistenceManaged { + s.persistence.flush() + } else { + s.persistence.close() + } if s.cache != nil { s.cache.Stop() } @@ -2152,6 +2189,7 @@ func (s *SessionAffinitySelector) InvalidateAuth(authID string) { if s == nil { return } + s.persistence.invalidateAuth(authID) if s.cache != nil { s.cache.InvalidateAuth(authID) } @@ -2244,6 +2282,11 @@ func (s *SessionAffinitySelector) LookupAffinity(provider, model, sessionID stri } foundAuths[authID] = struct{}{} } + for _, authID := range s.cache.lookupScopedSessionAuths(candProvider, modelKey, bounded) { + if authFilter == nil || authFilter(authID) { + foundAuths[authID] = struct{}{} + } + } } } @@ -2374,19 +2417,28 @@ func (s *SessionAffinitySelector) OnResult(res Result) { fallbackID = cliproxysession.BoundSessionIdentity(fallbackID) } - cacheKey := providerAffinityNamespace(ns, res.Options.Metadata) + "::" + primaryID + "::" + nsModel + cacheKey := affinityRequestNamespace(ns, res.Options.Metadata) + "::" + primaryID + "::" + nsModel var fallbackKey string if fallbackID != "" && fallbackID != primaryID && !isSubagentSession(primaryID, fallbackID) { - fallbackKey = providerAffinityNamespace(ns, res.Options.Metadata) + "::" + fallbackID + "::" + nsModel + fallbackKey = affinityRequestNamespace(ns, res.Options.Metadata) + "::" + fallbackID + "::" + nsModel } if res.Success { - s.cache.Touch(cacheKey, res.AuthID) + if s.cache.Touch(cacheKey, res.AuthID) && explicitID != "" { + s.persistence.touch(res.AuthID, s.cache.ttl, cacheKey) + } if fallbackKey != "" { - s.cache.Touch(fallbackKey, res.AuthID) + if s.cache.Touch(fallbackKey, res.AuthID) && explicitID != "" { + s.persistence.touch(res.AuthID, s.cache.ttl, fallbackKey) + } } return } - + if explicitID != "" { + s.persistence.remove(res.AuthID, cacheKey) + if fallbackKey != "" { + s.persistence.remove(res.AuthID, fallbackKey) + } + } s.cache.CompareAndDelete(cacheKey, res.AuthID) if fallbackKey != "" { s.cache.CompareAndDelete(fallbackKey, res.AuthID) @@ -2447,14 +2499,14 @@ func (s *SessionAffinitySelector) boundAuthForRequest(providers []string, model if primaryID != "" { for _, candProvider := range candidateProviders { - if authID, ok := s.cache.Get(providerAffinityNamespace(candProvider, opts.Metadata) + "::" + primaryID + "::" + modelKey); ok && authID != "" { + if authID, ok := s.cache.Get(affinityRequestNamespace(candProvider, opts.Metadata) + "::" + primaryID + "::" + modelKey); ok && authID != "" { return authID, true } } } if fallbackID != "" && fallbackID != primaryID && !isSubagent && !isFork { for _, candProvider := range candidateProviders { - if authID, ok := s.cache.Get(providerAffinityNamespace(candProvider, opts.Metadata) + "::" + fallbackID + "::" + modelKey); ok && authID != "" { + if authID, ok := s.cache.Get(affinityRequestNamespace(candProvider, opts.Metadata) + "::" + fallbackID + "::" + modelKey); ok && authID != "" { return authID, true } } diff --git a/sdk/cliproxy/auth/session_cache.go b/sdk/cliproxy/auth/session_cache.go index eb3482550da..fc7501e078f 100644 --- a/sdk/cliproxy/auth/session_cache.go +++ b/sdk/cliproxy/auth/session_cache.go @@ -17,12 +17,15 @@ type sessionBinding struct { sessionID string provider string sequence uint64 + scope string + model string } // sessionEntry stores an auth binding, its identifier aliases, and expiration. type sessionEntry struct { authID string expiresAt time.Time + touchedAt time.Time aliases []string binding sessionBinding } @@ -40,6 +43,14 @@ type SessionCache struct { stopOnce sync.Once sessionGroups map[string]map[string]struct{} bindingSequence uint64 + nowFunc func() time.Time +} + +func (c *SessionCache) now() time.Time { + if c.nowFunc != nil { + return c.nowFunc() + } + return time.Now() } // NewSessionCache creates a cache with the specified TTL. @@ -94,7 +105,7 @@ func (c *SessionCache) Get(sessionID string) (string, bool) { return "", false } c.mu.RLock() - now := time.Now() + now := c.now() entry, ok := c.entries[sessionID] if ok && now.Before(entry.expiresAt) { c.mu.RUnlock() @@ -112,7 +123,7 @@ func (c *SessionCache) Get(sessionID string) (string, bool) { if !ok { return "", false } - if time.Now().Before(entry.expiresAt) { + if c.now().Before(entry.expiresAt) { return entry.authID, true } c.removeAliasGroupLocked(entry) @@ -132,7 +143,7 @@ func (c *SessionCache) GetAndRefresh(sessionID string) (string, bool) { if !ok { return "", false } - now := time.Now() + now := c.now() if !now.Before(entry.expiresAt) { c.removeAliasGroupLocked(entry) return "", false @@ -170,7 +181,7 @@ func (c *SessionCache) setAliases(authID string, binding sessionBinding, session c.mu.Lock() defer c.mu.Unlock() c.ensureInitializedLocked() - now := time.Now() + now := c.now() aliases := mergeSessionAliases(nil, sessionIDs...) previousGroups := make([]sessionEntry, 0, len(sessionIDs)) @@ -214,13 +225,13 @@ func (c *SessionCache) replaceAliasGroupsLocked(authID string, expiresAt time.Ti if existing, ok := c.groups[primaryKey]; ok { c.removeAliasGroupLocked(existing) } - entry := sessionEntry{authID: authID, expiresAt: expiresAt, aliases: append([]string(nil), aliases...), binding: binding} + entry := sessionEntry{authID: authID, expiresAt: expiresAt, touchedAt: expiresAt.Add(-c.ttl), aliases: append([]string(nil), aliases...), binding: binding} c.groups[primaryKey] = entry - if binding.sequence != 0 { - if c.sessionGroups[binding.sessionID] == nil { - c.sessionGroups[binding.sessionID] = make(map[string]struct{}) + for _, sessionID := range indexedSessionIDs(entry) { + if c.sessionGroups[sessionID] == nil { + c.sessionGroups[sessionID] = make(map[string]struct{}) } - c.sessionGroups[binding.sessionID][primaryKey] = struct{}{} + c.sessionGroups[sessionID][primaryKey] = struct{}{} } for _, alias := range aliases { c.entries[alias] = entry @@ -255,10 +266,12 @@ func (c *SessionCache) removeAliasGroupLocked(entry sessionEntry) { primaryKey := entry.aliases[0] if currentGroup, ok := c.groups[primaryKey]; ok && sameSessionEntryGroup(currentGroup, entry) { delete(c.groups, primaryKey) - if groups := c.sessionGroups[entry.binding.sessionID]; groups != nil { - delete(groups, primaryKey) - if len(groups) == 0 { - delete(c.sessionGroups, entry.binding.sessionID) + for _, sessionID := range indexedSessionIDs(entry) { + if groups := c.sessionGroups[sessionID]; groups != nil { + delete(groups, primaryKey) + if len(groups) == 0 { + delete(c.sessionGroups, sessionID) + } } } if elem, ok := c.evictionElements[primaryKey]; ok { @@ -356,16 +369,19 @@ func mergeSessionAliases(existing []string, candidates ...string) []string { // latestSessionAuth observes the newest live selection on the requested real providers. // It does not refresh TTL or eviction order and visits only this session's groups. -func (c *SessionCache) latestSessionAuth(sessionID string, providers map[string]struct{}) string { +func (c *SessionCache) latestSessionAuth(sessionID string, providers map[string]struct{}, scopes ...string) string { if c == nil || sessionID == "" || len(providers) == 0 { return "" } c.mu.RLock() defer c.mu.RUnlock() - now := time.Now() + now := c.now() var latest sessionEntry for key := range c.sessionGroups[sessionID] { entry := c.groups[key] + if len(scopes) > 0 && entry.binding.scope != scopes[0] { + continue + } if _, ok := providers[entry.binding.provider]; !ok || !now.Before(entry.expiresAt) { continue } @@ -384,7 +400,7 @@ func (c *SessionCache) Touch(sessionID, expectedAuthID string) bool { c.mu.Lock() defer c.mu.Unlock() c.ensureInitializedLocked() - now := time.Now() + now := c.now() entry, ok := c.entries[sessionID] if !ok || entry.authID != expectedAuthID || !now.Before(entry.expiresAt) { return false @@ -502,7 +518,7 @@ func (c *SessionCache) Len() int { } func (c *SessionCache) cleanup() { - now := time.Now() + now := c.now() c.mu.Lock() defer c.mu.Unlock() c.ensureInitializedLocked() @@ -512,3 +528,44 @@ func (c *SessionCache) cleanup() { } } } + +// indexedSessionIDs indexes explicit aliases for read-only lookup without +// putting raw identifiers into the separate persistent cache. +func indexedSessionIDs(entry sessionEntry) []string { + ids := []string{entry.binding.sessionID} + for _, alias := range entry.aliases { + _, rest, ok := strings.Cut(alias, "::") + if !ok { + continue + } + if entry.binding.sequence != 0 { + if id, okSuffix := strings.CutSuffix(rest, "::"+entry.binding.model); okSuffix { + ids = append(ids, id) + } + } else if last := strings.LastIndex(rest, "::"); last >= 0 { + ids = append(ids, rest[:last]) + } + } + return mergeSessionAliases(nil, ids...) +} + +func (c *SessionCache) lookupScopedSessionAuths(provider, model, sessionID string) []string { + c.mu.RLock() + defer c.mu.RUnlock() + var authIDs []string + suffix := "::" + sessionID + "::" + model + for key := range c.sessionGroups[sessionID] { + entry := c.groups[key] + if !c.now().Before(entry.expiresAt) { + continue + } + for _, alias := range entry.aliases { + namespace, _, _ := strings.Cut(alias, "::") + if strings.HasPrefix(namespace, provider+"/request/") && strings.HasSuffix(alias, suffix) { + authIDs = append(authIDs, entry.authID) + break + } + } + } + return authIDs +} diff --git a/sdk/cliproxy/auth/session_persistence.go b/sdk/cliproxy/auth/session_persistence.go new file mode 100644 index 00000000000..5e6f86bfcec --- /dev/null +++ b/sdk/cliproxy/auth/session_persistence.go @@ -0,0 +1,430 @@ +package auth + +import ( + "context" + "sync" + "time" + + "github.com/MoeForge/moego/ojson" + "github.com/rune-oai/t3code-proxy/internal/kvstore" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + log "github.com/sirupsen/logrus" +) + +const affinitySnapshotKey = "session-affinity:v1" + +// sessionAffinityPersistence is shared by a manager's selectors, including while +// affinity is disabled. Only explicit identities enter this bounded cache. Keys +// and credential IDs are hashed before entering it, so snapshots contain neither +// session text nor caller keys. The local KV store remains optional. +type sessionAffinityPersistence struct { + mu sync.Mutex + flushMu sync.Mutex + cache *SessionCache + client *kvstore.BoltStore + dirty bool + now func() time.Time + stop chan struct{} + done chan struct{} + closed bool + suspended bool + nextRefresh time.Time + flushInterval time.Duration + retired map[string]affinityAuthVersion +} + +func newSessionAffinityPersistence() *sessionAffinityPersistence { + p := &sessionAffinityPersistence{now: time.Now, flushInterval: time.Second, retired: make(map[string]affinityAuthVersion)} + p.cache = &SessionCache{maxEntries: defaultMaxSessionEntries, nowFunc: func() time.Time { return p.now() }} + p.cache.ensureInitializedLocked() + return p +} + +// localLocked loads once per local store instance. Home owns its routing state. +func (p *sessionAffinityPersistence) localLocked() bool { + client, _, errClient := kvstore.CurrentKVClient() + local, ok := client.(*kvstore.BoltStore) + if errClient != nil || !ok || p.closed || p.suspended { + return false + } + if local == p.client { + return true + } + raw, found, errGet := local.KVGet(context.Background(), affinitySnapshotKey) + if errGet != nil { + log.WithError(errGet).Warn("session-affinity: load local bindings") + return false + } + p.client = local + previous := p.cache.groups + p.cache = &SessionCache{maxEntries: defaultMaxSessionEntries, nowFunc: func() time.Time { return p.now() }} + p.cache.ensureInitializedLocked() + p.dirty = false + if found { + root := ojson.ParseBytes(raw) + for _, item := range root.Get("groups").Array() { + expires := time.Unix(0, item.Get("expires").Int()) + touched := time.Unix(0, item.Get("touched").Int()) + authHash := item.Get("auth").String() + aliases := []string{} + for _, alias := range item.Get("aliases").Array() { + aliases = append(aliases, alias.String()) + } + if _, retired := p.retired[authHash]; retired { + continue + } + if !p.now().Before(expires) || touched.After(p.now()) || authHash == "" || len(aliases) == 0 { + continue + } + p.cache.replaceAliasGroupsLocked(authHash, expires, compactSessionAliases(aliases), sessionBinding{}) + entry := p.cache.groups[aliases[0]] + entry.touchedAt = touched + p.cache.groups[aliases[0]] = entry + for _, alias := range entry.aliases { + p.cache.entries[alias] = entry + } + } + } + // Runtime bindings can be newer than this store's last snapshot, including + // bindings made with disk persistence disabled. + for _, entry := range previous { + if !p.now().Before(entry.expiresAt) { + continue + } + conflicts := []sessionEntry{} + for _, alias := range entry.aliases { + if existing, ok := p.cache.entries[alias]; ok { + conflicts = append(conflicts, existing) + } + } + p.cache.replaceAliasGroupsLocked(entry.authID, entry.expiresAt, entry.aliases, sessionBinding{}, conflicts...) + p.cache.groups[entry.aliases[0]] = entry + for _, alias := range entry.aliases { + p.cache.entries[alias] = entry + } + p.dirty = true + } + if p.stop == nil { + p.stop, p.done = make(chan struct{}), make(chan struct{}) + go p.run() + } + return true +} + +func (p *sessionAffinityPersistence) run() { + defer close(p.done) + ticker := time.NewTicker(p.flushInterval) + defer ticker.Stop() + for { + select { + case <-p.stop: + return + case <-ticker.C: + p.flush() + } + } +} + +func persistedAffinityKey(key string) string { + prefix := "session:" + if isLocalPromptCacheSessionAlias(key) { + prefix = "pck:" + } + return prefix + kvstore.HashKeyPart(key) +} + +func (p *sessionAffinityPersistence) get(key string, ttl time.Duration, candidates []*Auth) (string, time.Time, bool) { + if p == nil { + return "", time.Time{}, false + } + p.mu.Lock() + defer p.mu.Unlock() + return p.getLocked(key, ttl, candidates) +} + +// getLocked allows restoration to publish into the live cache before retirement. +func (p *sessionAffinityPersistence) getLocked(key string, ttl time.Duration, candidates []*Auth) (string, time.Time, bool) { + if p.closed { + return "", time.Time{}, false + } + p.localLocked() + key = persistedAffinityKey(key) + entry, ok := p.cache.entries[key] + now := p.now() + if !ok || !now.Before(entry.expiresAt) || !now.Before(entry.touchedAt.Add(ttl)) { + return "", time.Time{}, false + } + for _, auth := range candidates { + if auth != nil && !auth.Disabled && auth.Status != StatusDisabled && kvstore.HashKeyPart(auth.ID) == entry.authID { + return auth.ID, minAffinityExpiry(entry, ttl), true + } + } + return "", time.Time{}, false +} + +// bind publishes live and durable state under the retirement lock. Publication +// must only touch the selector cache; manager lookups must happen before this call. +func (p *sessionAffinityPersistence) bind(auth *Auth, ttl time.Duration, publish func(), keys ...string) { + if p == nil || auth == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return + } + p.localLocked() + authHash := kvstore.HashKeyPart(auth.ID) + if version, retired := p.retired[authHash]; retired && (auth.RegistrationEpoch < version.epoch || (auth.RegistrationEpoch == version.epoch && auth.Generation <= version.generation)) { + return + } + if publish != nil { + publish() + } + if auth.Disabled || auth.Status == StatusDisabled { + return + } + aliases := make([]string, 0, len(keys)) + for _, key := range keys { + aliases = append(aliases, persistedAffinityKey(key)) + } + changed := false + for _, alias := range aliases { + previous, ok := p.cache.entries[alias] + if !ok || previous.authID != authHash { + changed = true + break + } + } + p.cache.ttl = ttl + p.cache.SetAliases(authHash, aliases...) + p.markDirtyLocked(ttl, changed) +} + +func (p *sessionAffinityPersistence) remove(authID string, keys ...string) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return + } + p.localLocked() + for _, key := range keys { + if p.cache.CompareAndDelete(persistedAffinityKey(key), kvstore.HashKeyPart(authID)) { + p.dirty = true + } + } +} + +func (p *sessionAffinityPersistence) invalidateAuth(authID string) { + if p == nil { + return + } + p.mu.Lock() + p.localLocked() + p.cache.InvalidateAuth(kvstore.HashKeyPart(authID)) + p.dirty = true + p.mu.Unlock() + // Credential removal is administrative. Commit the deletion before returning, + // serialized with earlier snapshots so an in-flight write cannot restore it. + p.flush() +} + +func (p *sessionAffinityPersistence) flush() { + if p == nil { + return + } + p.flushMu.Lock() + defer p.flushMu.Unlock() + p.mu.Lock() + current, _, _ := kvstore.CurrentKVClient() + if !p.dirty || p.client == nil || current != p.client || p.suspended { + p.mu.Unlock() + return + } + p.cache.cleanup() + groups := make([]map[string]any, 0, len(p.cache.groups)) + var expiresAt time.Time + for _, entry := range p.cache.groups { + groups = append(groups, map[string]any{"auth": entry.authID, "expires": entry.expiresAt.UnixNano(), "touched": entry.touchedAt.UnixNano(), "aliases": entry.aliases}) + if entry.expiresAt.After(expiresAt) { + expiresAt = entry.expiresAt + } + } + client := p.client + p.dirty = false + p.nextRefresh = p.now().Add(min(p.cache.ttl/4, time.Minute)) + p.mu.Unlock() + var errWrite error + if len(groups) == 0 { + _, errWrite = client.KVDel(context.Background(), affinitySnapshotKey) + } else { + doc := ojson.NewDocString(`{}`) + errWrite = doc.Set("groups", groups) + if errWrite == nil { + ttl := expiresAt.Sub(p.now()) + if ttl > 0 { + _, errWrite = client.KVSet(context.Background(), affinitySnapshotKey, doc.Bytes(), kvstore.KVSetOptions{PX: ttl}) + } + } + } + if errWrite != nil { + p.mu.Lock() + p.dirty = true + p.mu.Unlock() + log.WithError(errWrite).Warn("session-affinity: persist local bindings") + } +} + +func (p *sessionAffinityPersistence) close() { + if p == nil { + return + } + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return + } + p.closed = true + p.dirty = p.dirty || len(p.cache.groups) > 0 + stop, done := p.stop, p.done + p.mu.Unlock() + if stop != nil { + close(stop) + <-done + } + p.flush() +} + +// affinityRequestNamespace scopes explicit bindings just as tightly in memory +// as on disk. Empty legacy metadata retains its existing namespace. +func affinityRequestNamespace(provider string, metadata map[string]any) string { + namespace := providerAffinityNamespace(provider, metadata) + if scope := affinityRequestScope(metadata); scope != "" { + return namespace + "/request/" + scope + } + return namespace +} + +func affinityRequestScope(metadata map[string]any) string { + caller := sessionMetadataString(metadata, cliproxyexecutor.CallerScopeMetadataKey) + if caller == "" { + return "" + } + return kvstore.HashKeyPart(caller) +} + +func (p *sessionAffinityPersistence) touch(authID string, ttl time.Duration, key string) { + if p == nil { + return + } + p.mu.Lock() + defer p.mu.Unlock() + if p.closed { + return + } + p.localLocked() + p.cache.ttl = ttl + if p.cache.Touch(persistedAffinityKey(key), kvstore.HashKeyPart(authID)) { + p.markDirtyLocked(ttl, false) + } +} + +type affinityAuthVersion struct{ epoch, generation uint64 } + +func (p *sessionAffinityPersistence) retireAuth(authID string, epoch, generation uint64) { + p.mu.Lock() + defer p.mu.Unlock() + p.retired[kvstore.HashKeyPart(authID)] = affinityAuthVersion{epoch: epoch, generation: generation} + p.localLocked() + p.cache.InvalidateAuth(kvstore.HashKeyPart(authID)) + p.dirty = true +} + +func (s *SessionAffinitySelector) restoreExplicitBinding(key string, candidates []*Auth) { + if _, ok := s.cache.Get(key); ok { + return + } + if s.authCandidates != nil { + candidates = s.authCandidates() + } + // Match bind's lock order so a retired snapshot cannot be published after + // removal has already invalidated the live cache. + s.persistence.mu.Lock() + defer s.persistence.mu.Unlock() + if authID, expiresAt, ok := s.persistence.getLocked(key, s.cache.ttl, candidates); ok { + s.cache.mu.Lock() + s.cache.ensureInitializedLocked() + // A concurrent request may already have installed a newer binding. + if entry, exists := s.cache.entries[key]; !exists || !s.cache.now().Before(entry.expiresAt) { + s.cache.replaceAliasGroupsLocked(authID, expiresAt, []string{key}, sessionBinding{}) + } + s.cache.mu.Unlock() + } +} + +// CloseSessionAffinityPersistence flushes pending local bindings during shutdown. +func (m *Manager) CloseSessionAffinityPersistence() { + if m == nil { + return + } + m.mu.RLock() + persistence := m.affinityPersistence + m.mu.RUnlock() + persistence.close() +} + +func minAffinityExpiry(entry sessionEntry, ttl time.Duration) time.Time { + if limit := entry.touchedAt.Add(ttl); limit.Before(entry.expiresAt) { + return limit + } + return entry.expiresAt +} + +func (p *sessionAffinityPersistence) markDirtyLocked(ttl time.Duration, changed bool) { + if changed || !p.now().Before(p.nextRefresh) { + p.dirty = true + p.nextRefresh = p.now().Add(min(ttl/4, time.Minute)) + } +} + +// SetSessionAffinityPersistenceEnabled keeps memory affinity available while +// local storage is disabled. Clear old snapshots when disabling so removals +// during that interval cannot revive old bindings in a later process. +func (m *Manager) SetSessionAffinityPersistenceEnabled(enabled bool) { + if m == nil { + return + } + m.mu.Lock() + if m.affinityPersistence == nil { + m.affinityPersistence = newSessionAffinityPersistence() + } + p := m.affinityPersistence + m.mu.Unlock() + p.flushMu.Lock() + defer p.flushMu.Unlock() + p.mu.Lock() + if enabled { + p.suspended = false + if p.client != nil || len(p.cache.groups) > 0 { + p.localLocked() + } + p.mu.Unlock() + return + } + if p.suspended { + p.mu.Unlock() + return + } + p.localLocked() + p.suspended = true + client := p.client + p.mu.Unlock() + if client != nil { + if _, errDelete := client.KVDel(context.Background(), affinitySnapshotKey); errDelete != nil { + log.WithError(errDelete).Warn("session-affinity: clear disabled persistence") + } + } +} diff --git a/sdk/cliproxy/auth/session_persistence_lifecycle_test.go b/sdk/cliproxy/auth/session_persistence_lifecycle_test.go new file mode 100644 index 00000000000..abddd586ab2 --- /dev/null +++ b/sdk/cliproxy/auth/session_persistence_lifecycle_test.go @@ -0,0 +1,142 @@ +package auth + +import ( + "context" + "net/http" + "sync/atomic" + "testing" + "time" + + "github.com/rune-oai/t3code-proxy/internal/registry" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +type lifecycleBlockingFallback struct { + entered chan struct{} + release chan struct{} + calls atomic.Int32 +} + +func (f *lifecycleBlockingFallback) Pick(ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth) (*Auth, error) { + if f.calls.Add(1) == 1 { + close(f.entered) + <-f.release + } + return (&FillFirstSelector{}).Pick(ctx, provider, model, opts, auths) +} + +func TestRemovedIncarnationCannotBecomeDurableThroughLiveCache(t *testing.T) { + affinityKV(t) + f := &lifecycleBlockingFallback{entered: make(chan struct{}), release: make(chan struct{})} + s := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{TTL: time.Hour, Fallback: f}) + t.Cleanup(s.Stop) + m := NewManager(nil, s, nil) + t.Cleanup(m.CloseSessionAffinityPersistence) + m.RegisterExecutor(schedulerProviderTestExecutor{provider: "claude"}) + b, err := m.Register(t.Context(), &Auth{ID: "sol-removed-b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + const model = "sol-lifecycle-model" + reg := registry.GetGlobalRegistry() + registerModel := func(id string) { reg.RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) } + registerModel(b.ID) + t.Cleanup(func() { reg.UnregisterClient(b.ID); reg.UnregisterClient("sol-a") }) + options := func() cliproxyexecutor.Options { + return cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"sol-remove-session"}}} + } + done := make(chan error, 1) + go func() { _, errPick := m.SelectAuth(t.Context(), "claude", model, options()); done <- errPick }() + <-f.entered + m.Remove(t.Context(), b.ID) + close(f.release) + if errPick := <-done; errPick != nil { + t.Fatal(errPick) + } + s.persistence.mu.Lock() + durableImmediatelyAfterRemoval := len(s.persistence.cache.entries) + s.persistence.mu.Unlock() + if durableImmediatelyAfterRemoval != 0 { + t.Fatalf("stale selection directly persisted %d aliases", durableImmediatelyAfterRemoval) + } + // Administrative removal has finished before the old selection installs + // its live binding. Its direct durable write is correctly tombstoned. + a, err := m.Register(t.Context(), &Auth{ID: "sol-a", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + registerModel(a.ID) + replacement, err := m.Register(t.Context(), &Auth{ID: b.ID, Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + registerModel(replacement.ID) + got, err := m.SelectAuth(t.Context(), "claude", model, options()) + if err != nil { + t.Fatal(err) + } + s.persistence.flush() + fresh := persistentSelector(t, time.Hour) + restored, err := fresh.Pick(t.Context(), "claude", model, options(), []*Auth{a, replacement}) + if err != nil { + t.Fatal(err) + } + if got.ID != a.ID || restored.ID != a.ID { + t.Fatalf("removed incarnation's session revived: live=%s restarted=%s, want fresh selection %s", got.ID, restored.ID, a.ID) + } +} + +func TestDelayedPreserveCannotReviveRemovedIncarnation(t *testing.T) { + affinityKV(t) + f := &lifecycleBlockingFallback{entered: make(chan struct{}), release: make(chan struct{})} + f.calls.Store(1) + s := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{TTL: time.Hour, Fallback: f, RebindOn: SessionAffinityRebindOnQuota}) + t.Cleanup(s.Stop) + m := NewManager(nil, s, nil) + t.Cleanup(m.CloseSessionAffinityPersistence) + m.RegisterExecutor(schedulerProviderTestExecutor{provider: "claude"}) + const model = "review-delayed-preserve-model" + reg := registry.GetGlobalRegistry() + register := func(id string) *Auth { + t.Helper() + a, err := m.Register(t.Context(), &Auth{ID: id, Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + reg.RegisterClient(id, "claude", []*registry.ModelInfo{{ID: model}}) + t.Cleanup(func() { reg.UnregisterClient(id) }) + return a + } + b := register("review-b") + options := func() cliproxyexecutor.Options { + return cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"review-preserve-session"}}} + } + if got, err := m.SelectAuth(t.Context(), "claude", model, options()); err != nil || got.ID != b.ID { + t.Fatalf("seed %v %v", got, err) + } + a := register("review-a") + m.MarkResult(t.Context(), Result{AuthID: b.ID, Provider: "claude", Model: model, Error: &Error{HTTPStatus: 502, Message: "overloaded"}, Options: options()}) + f.calls.Store(0) + done := make(chan error, 1) + go func() { _, err := m.SelectAuth(t.Context(), "claude", model, options()); done <- err }() + <-f.entered + m.Remove(t.Context(), b.ID) + replacement := register(b.ID) + close(f.release) + if err := <-done; err != nil { + t.Fatal(err) + } + got, err := m.SelectAuth(t.Context(), "claude", model, options()) + if err != nil { + t.Fatal(err) + } + s.persistence.flush() + fresh := persistentSelector(t, time.Hour) + restored, err := fresh.Pick(t.Context(), "claude", model, options(), []*Auth{a, replacement}) + if err != nil { + t.Fatal(err) + } + if got.ID != a.ID || restored.ID != a.ID { + t.Fatalf("retired binding revived: live=%s restarted=%s want=%s", got.ID, restored.ID, a.ID) + } +} diff --git a/sdk/cliproxy/auth/session_persistence_test.go b/sdk/cliproxy/auth/session_persistence_test.go new file mode 100644 index 00000000000..22c2de9cdcf --- /dev/null +++ b/sdk/cliproxy/auth/session_persistence_test.go @@ -0,0 +1,394 @@ +package auth + +import ( + "bytes" + "context" + "net/http" + "path/filepath" + "sync/atomic" + "testing" + "time" + + "github.com/rune-oai/t3code-proxy/internal/kvstore" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +func affinityKV(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "kv.db") + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := kvstore.ShutdownLocal(); err != nil { + t.Error(err) + } + }) + return path +} + +func persistentSelector(t *testing.T, ttl time.Duration) *SessionAffinitySelector { + t.Helper() + selector := NewSessionAffinitySelectorWithConfig(SessionAffinityConfig{TTL: ttl, Fallback: &FillFirstSelector{}}) + selector.persistence.flushInterval = time.Hour // Flush explicitly for deterministic crash/restart boundaries. + t.Cleanup(selector.Stop) + return selector +} + +func affinityOptions() cliproxyexecutor.Options { + return cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"private-session-text"}}, + OriginalRequest: []byte(`{"messages":[{"role":"user","content":"private-prompt-text"}]}`), + Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "private-caller-key", cliproxyexecutor.ServiceTierMetadataKey: "default"}} +} + +func expectAffinityPick(t *testing.T, selector *SessionAffinitySelector, ctx context.Context, provider, model string, opts cliproxyexecutor.Options, auths []*Auth, want string) { + t.Helper() + got, err := selector.Pick(ctx, provider, model, opts, auths) + if err != nil || got == nil || got.ID != want { + t.Fatalf("Pick() = %v, %v, want %s", got, err, want) + } +} + +func TestPersistentAffinityRestartAndIsolation(t *testing.T) { + path := affinityKV(t) + a, b := &Auth{ID: "a", Provider: "claude"}, &Auth{ID: "b-private-auth", Provider: "claude"} + original := persistentSelector(t, time.Hour) + expectAffinityPick(t, original, context.Background(), "claude", "model", affinityOptions(), []*Auth{b}, b.ID) + original.Stop() // A graceful stop commits queued writes. + client, _, _ := kvstore.CurrentKVClient() + raw, found, err := client.KVGet(context.Background(), affinitySnapshotKey) + if err != nil || !found { + t.Fatalf("missing snapshot: %v", err) + } + for _, private := range []string{"private-session-text", "private-prompt-text", "private-caller-key", b.ID} { + if bytes.Contains(raw, []byte(private)) { + t.Fatalf("snapshot contains %q", private) + } + } + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + for _, name := range []string{"same", "caller", "model", "provider", "tier", "transport", "provider-scope"} { + t.Run(name, func(t *testing.T) { + restored := persistentSelector(t, time.Hour) + opts := affinityOptions() + ctx, provider, model, want := context.Background(), "claude", "model", "a" + switch name { + case "same": + want = b.ID + case "caller": + opts.Metadata[cliproxyexecutor.CallerScopeMetadataKey] = "other-caller" + case "model": + model = "other-model" + case "provider": + provider = "other-provider" + case "tier": + opts.Metadata[cliproxyexecutor.ServiceTierMetadataKey] = "priority" + want = b.ID + case "transport": + ctx = cliproxyexecutor.WithDownstreamWebsocket(ctx) + want = b.ID + case "provider-scope": + opts.Metadata[cliproxyexecutor.ProviderScopeMetadataKey] = "restricted" + } + expectAffinityPick(t, restored, ctx, provider, model, opts, []*Auth{a, b}, want) + }) + } +} + +func TestSessionAffinityLiveTierToggleKeepsBinding(t *testing.T) { + selector := persistentSelector(t, time.Hour) + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + opts := affinityOptions() + opts.Metadata[cliproxyexecutor.ServiceTierMetadataKey] = "auto" + expectAffinityPick(t, selector, context.Background(), "codex", "model", opts, []*Auth{b}, b.ID) + for _, tier := range []string{"priority", "auto", "", "default", "priority"} { + opts.Metadata[cliproxyexecutor.ServiceTierMetadataKey] = tier + expectAffinityPick(t, selector, context.Background(), "codex", "model", opts, []*Auth{a, b}, b.ID) + if got, ok := selector.boundAuthForRequest([]string{"codex"}, "model", opts); !ok || got != b.ID { + t.Fatalf("tier %q lost bound request lookup: %s, %t", tier, got, ok) + } + } + // Results use the same tier-independent key as selection. + selector.OnResult(Result{AuthID: b.ID, Provider: "codex", Model: "model", Options: opts}) + expectAffinityPick(t, selector, context.Background(), "codex", "model", affinityOptions(), []*Auth{a, b}, a.ID) +} + +func TestPersistentAffinityTransportSwitchRestoresLatestBinding(t *testing.T) { + for _, firstTransport := range []string{"http", "ws"} { + t.Run(firstTransport, func(t *testing.T) { + path := affinityKV(t) + httpCtx := context.Background() + wsCtx := cliproxyexecutor.WithDownstreamWebsocket(httpCtx) + firstCtx, secondCtx := httpCtx, wsCtx + if firstTransport == "ws" { + firstCtx, secondCtx = wsCtx, httpCtx + } + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + original := persistentSelector(t, time.Hour) + firstOpts, secondOpts := affinityOptions(), affinityOptions() + expectAffinityPick(t, original, firstCtx, "codex", "model", firstOpts, []*Auth{a}, a.ID) + expectAffinityPick(t, original, secondCtx, "codex", "model", secondOpts, []*Auth{b}, b.ID) + // An older transport's delayed failure cannot delete the newer binding. + original.OnResult(Result{AuthID: a.ID, Provider: "codex", Model: "model", Options: firstOpts}) + original.Stop() + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + restored := persistentSelector(t, time.Hour) + expectAffinityPick(t, restored, firstCtx, "codex", "model", affinityOptions(), []*Auth{a, b}, b.ID) + // A result on the original transport invalidates the shared durable binding. + restored.OnResult(Result{AuthID: b.ID, Provider: "codex", Model: "model", Options: affinityOptions()}) + restored.Stop() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, secondCtx, "codex", "model", affinityOptions(), []*Auth{a, b}, a.ID) + }) + } +} + +func TestPersistentAffinityTransportRestoreRespectsEligibleCandidates(t *testing.T) { + affinityKV(t) + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + original := persistentSelector(t, time.Hour) + wsCtx := cliproxyexecutor.WithDownstreamWebsocket(context.Background()) + expectAffinityPick(t, original, wsCtx, "codex", "model", affinityOptions(), []*Auth{b}, b.ID) + original.Stop() + restored := persistentSelector(t, time.Hour) + // Managers expose all registered credentials for restoration, while the + // request's candidates have already passed provider/model/caller eligibility. + restored.authCandidates = func() []*Auth { return []*Auth{a, b} } + expectAffinityPick(t, restored, context.Background(), "codex", "model", affinityOptions(), []*Auth{a}, a.ID) + restored.Stop() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, wsCtx, "codex", "model", affinityOptions(), []*Auth{a, b}, a.ID) +} + +func TestPersistentAffinityReloadBeforeFlushAndRemoval(t *testing.T) { + affinityKV(t) + first := persistentSelector(t, time.Hour) + manager := NewManager(nil, first, nil) + t.Cleanup(manager.CloseSessionAffinityPersistence) + a, err := manager.Register(context.Background(), &Auth{ID: "a", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + b, err := manager.Register(context.Background(), &Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + opts := affinityOptions() + expectAffinityPick(t, first, context.Background(), "claude", "model", opts, []*Auth{b}, "b") + second := persistentSelector(t, time.Hour) + manager.SetSelector(second) + if second.persistence != first.persistence { + t.Fatal("reload did not retain pending bindings") + } + expectAffinityPick(t, second, context.Background(), "claude", "model", affinityOptions(), []*Auth{a, b}, "b") + // Removal while session affinity is disabled must still invalidate snapshots + // which the next selector has not loaded into its own session cache. + manager.SetSelector(&FillFirstSelector{}) + manager.Remove(context.Background(), "b") + // An already-running selection cannot write the removed incarnation back. + first.persistence.bind(b, time.Hour, nil, "delayed-selection") + third := persistentSelector(t, time.Hour) + manager.SetSelector(third) + readded, err := manager.Register(context.Background(), &Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + expectAffinityPick(t, third, context.Background(), "claude", "model", affinityOptions(), []*Auth{a, readded}, "a") + third.persistence.mu.Lock() + _, resurrected := third.persistence.cache.Get(persistedAffinityKey("delayed-selection")) + third.persistence.mu.Unlock() + if resurrected { + t.Fatal("delayed selection resurrected removed auth") + } + // The deletion must also survive a fresh process with no in-memory tombstones. + third.persistence.flush() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, context.Background(), "claude", "model", affinityOptions(), []*Auth{a, readded}, "a") +} + +func TestPersistentAffinityTTLAndSlidingRefresh(t *testing.T) { + affinityKV(t) + var clock atomic.Int64 + clock.Store(time.Now().UnixNano()) + now := func() time.Time { return time.Unix(0, clock.Load()) } + p := newSessionAffinityPersistence() + p.now, p.flushInterval = now, time.Hour + t.Cleanup(p.close) + auth := &Auth{ID: "auth"} + p.bind(auth, time.Hour, nil, "route") + clock.Add(int64(40 * time.Minute)) + p.touch(auth.ID, time.Hour, "route") + p.flush() + fresh := newSessionAffinityPersistence() + fresh.now, fresh.flushInterval = now, time.Hour + t.Cleanup(fresh.close) + clock.Add(int64(40 * time.Minute)) + if _, _, ok := fresh.get("route", time.Hour, []*Auth{auth}); !ok { + t.Fatal("sliding refresh lost across restart") + } + if _, _, ok := fresh.get("route", 30*time.Minute, []*Auth{auth}); ok { + t.Fatal("shorter reload TTL reused an expired binding") + } + clock.Add(int64(20 * time.Minute)) + if _, _, ok := fresh.get("route", time.Hour, []*Auth{auth}); ok { + t.Fatal("binding survived its exact expiration") + } +} + +func TestPersistentAffinityAliasRebindAndResultInvalidation(t *testing.T) { + affinityKV(t) + p := newSessionAffinityPersistence() + p.flushInterval = time.Hour + t.Cleanup(p.close) + a, b := &Auth{ID: "a"}, &Auth{ID: "b"} + p.bind(a, time.Hour, nil, "conversation", "pck:old") + p.bind(b, time.Hour, nil, "conversation", "pck:new") + // An older result must not delete the new account's alias. + p.remove(a.ID, "conversation") + p.flush() + fresh := newSessionAffinityPersistence() + fresh.flushInterval = time.Hour + t.Cleanup(fresh.close) + for _, key := range []string{"conversation", "pck:new"} { + if got, _, ok := fresh.get(key, time.Hour, []*Auth{a, b}); !ok || got != b.ID { + t.Fatalf("%s = %s, %t", key, got, ok) + } + } + if _, _, ok := fresh.get("pck:old", time.Hour, []*Auth{a, b}); ok { + t.Fatal("obsolete prompt alias resurrected") + } + fresh.remove(b.ID, "conversation", "pck:new") + fresh.flush() + restarted := newSessionAffinityPersistence() + restarted.flushInterval = time.Hour + t.Cleanup(restarted.close) + if _, _, ok := restarted.get("conversation", time.Hour, []*Auth{a, b}); ok { + t.Fatal("failed binding resurrected") + } +} + +func TestPersistentAffinityDisabledCredentialAndOptionalStore(t *testing.T) { + affinityKV(t) + selector := persistentSelector(t, time.Hour) + manager := NewManager(nil, selector, nil) + t.Cleanup(manager.CloseSessionAffinityPersistence) + b, err := manager.Register(context.Background(), &Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + expectAffinityPick(t, selector, context.Background(), "claude", "model", affinityOptions(), []*Auth{b}, "b") + disabled := b.Clone() + disabled.Disabled = true + if _, err := manager.Update(context.Background(), disabled); err != nil { + t.Fatal(err) + } + selector.persistence.flush() + fresh := persistentSelector(t, time.Hour) + expectAffinityPick(t, fresh, context.Background(), "claude", "model", affinityOptions(), []*Auth{{ID: "a"}, b}, "a") + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + memory := persistentSelector(t, time.Hour) + expectAffinityPick(t, memory, context.Background(), "claude", "model", affinityOptions(), []*Auth{b}, "b") + expectAffinityPick(t, memory, context.Background(), "claude", "model", affinityOptions(), []*Auth{{ID: "a"}, b}, "b") + if memory.persistence.client != nil || memory.persistence.stop != nil { + t.Fatal("disabled storage started persistence") + } +} + +func TestPersistentAffinityDoesNotWriteOnPick(t *testing.T) { + affinityKV(t) + selector := persistentSelector(t, time.Hour) + expectAffinityPick(t, selector, context.Background(), "claude", "model", affinityOptions(), []*Auth{{ID: "b"}}, "b") + client, _, _ := kvstore.CurrentKVClient() + if _, found, err := client.KVGet(context.Background(), affinitySnapshotKey); err != nil || found { + t.Fatalf("Pick wrote disk: %t, %v", found, err) + } + selector.persistence.flush() + if _, found, err := client.KVGet(context.Background(), affinitySnapshotKey); err != nil || !found { + t.Fatalf("flush failed: %t, %v", found, err) + } +} + +func TestPersistentAffinityConcurrentRemovalCannotResurrect(t *testing.T) { + affinityKV(t) + p := newSessionAffinityPersistence() + p.flushInterval = time.Hour + t.Cleanup(p.close) + old := &Auth{ID: "removed", RegistrationEpoch: 1, Generation: 1} + p.bind(old, time.Hour, nil, "route") + p.flush() + // Both asynchronous work and old in-flight selections compete with removal. + start := make(chan struct{}) + done := make(chan struct{}) + go func() { + defer close(done) + <-start + for range 50 { + p.bind(old, time.Hour, nil, "route") + p.flush() + } + }() + close(start) + p.retireAuth(old.ID, old.RegistrationEpoch, ^uint64(0)) + p.invalidateAuth(old.ID) + <-done + p.flush() + fresh := newSessionAffinityPersistence() + fresh.flushInterval = time.Hour + t.Cleanup(fresh.close) + if _, _, ok := fresh.get("route", time.Hour, []*Auth{{ID: old.ID, RegistrationEpoch: 3}}); ok { + t.Fatal("concurrent stale selection revived removed binding") + } +} + +func TestPersistentAffinityRefreshWritesAreThrottled(t *testing.T) { + affinityKV(t) + var timestamp atomic.Int64 + timestamp.Store(time.Now().UnixNano()) + p := newSessionAffinityPersistence() + p.now = func() time.Time { return time.Unix(0, timestamp.Load()) } + p.flushInterval = time.Hour + t.Cleanup(p.close) + auth := &Auth{ID: "auth"} + p.bind(auth, time.Hour, nil, "route") + p.flush() + timestamp.Add(int64(30 * time.Second)) + p.bind(auth, time.Hour, nil, "route") + p.touch(auth.ID, time.Hour, "route") + p.mu.Lock() + dirty := p.dirty + p.mu.Unlock() + if dirty { + t.Fatal("unchanged binding scheduled another snapshot inside refresh throttle") + } + timestamp.Add(int64(30 * time.Second)) + p.touch(auth.ID, time.Hour, "route") + p.mu.Lock() + dirty = p.dirty + p.mu.Unlock() + if !dirty { + t.Fatal("due TTL refresh did not schedule persistence") + } +} + +func TestSessionAffinityScopedLookupAndGuardianIsolation(t *testing.T) { + selector := persistentSelector(t, time.Hour) + a, b := &Auth{ID: "a", Provider: "codex"}, &Auth{ID: "b", Provider: "codex"} + opts := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"main-thread"}}, Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller-a"}} + expectAffinityPick(t, selector, context.Background(), "codex", "team::model", opts, []*Auth{b}, "b") + if authID, status := selector.LookupAffinity("codex", "team::model", "main-thread"); authID != "b" || status != "bound" { + t.Fatalf("scoped lookup = %s, %s", authID, status) + } + child := cliproxyexecutor.Options{Headers: http.Header{"Session_id": {"main-thread:agent:child"}, "X-Openai-Subagent": {"guardian"}}, Metadata: map[string]any{cliproxyexecutor.CallerScopeMetadataKey: "caller-b"}} + expectAffinityPick(t, selector, context.Background(), "codex", "review", child, []*Auth{a, b}, "a") +} diff --git a/sdk/cliproxy/auth/session_restart_regression_test.go b/sdk/cliproxy/auth/session_restart_regression_test.go new file mode 100644 index 00000000000..006b3e30c18 --- /dev/null +++ b/sdk/cliproxy/auth/session_restart_regression_test.go @@ -0,0 +1,47 @@ +package auth + +import ( + "context" + "net/http" + "path/filepath" + "testing" + "time" + + "github.com/rune-oai/t3code-proxy/internal/kvstore" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" +) + +// This public-entry regression also runs against the audit baseline using a Go +// source overlay. It needs no persistence implementation details. +func TestSessionAffinityPublicRestartRegression(t *testing.T) { + path := filepath.Join(t.TempDir(), "kv.db") + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := kvstore.ShutdownLocal(); err != nil { + t.Error(err) + } + }) + opts := cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"restart-regression"}}} + cfg := SessionAffinityConfig{TTL: time.Hour, Fallback: &FillFirstSelector{}} + first := NewSessionAffinitySelectorWithConfig(cfg) + a, b := &Auth{ID: "a"}, &Auth{ID: "b"} + got, err := first.Pick(context.Background(), "claude", "model", opts, []*Auth{b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("first Pick = %v, %v", got, err) + } + first.Stop() + if err := kvstore.ShutdownLocal(); err != nil { + t.Fatal(err) + } + if err := kvstore.ConfigureLocal(true, path); err != nil { + t.Fatal(err) + } + restarted := NewSessionAffinitySelectorWithConfig(cfg) + t.Cleanup(restarted.Stop) + got, err = restarted.Pick(context.Background(), "claude", "model", opts, []*Auth{a, b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("restart changed warm account: Pick = %v, %v, want b", got, err) + } +} diff --git a/sdk/cliproxy/kv_store.go b/sdk/cliproxy/kv_store.go index e6874620574..93014b42a72 100644 --- a/sdk/cliproxy/kv_store.go +++ b/sdk/cliproxy/kv_store.go @@ -16,18 +16,26 @@ func (s *Service) applyKVStoreConfig(cfg *config.Config) { } s.kvStoreManaged.Store(true) if cfg == nil || cfg.Home.Enabled || home.Current() != nil || cfg.KVStore.Disabled { + if s.coreManager != nil { + s.coreManager.SetSessionAffinityPersistenceEnabled(false) + } if errShutdown := kvstore.ShutdownLocal(); errShutdown != nil { log.Errorf("failed to shutdown local kv store: %v", errShutdown) } return } - _ = kvstore.ConfigureLocal(true, cfg.EffectiveKVStorePath()) + if errConfigure := kvstore.ConfigureLocal(true, cfg.EffectiveKVStorePath()); errConfigure == nil && s.coreManager != nil { + s.coreManager.SetSessionAffinityPersistenceEnabled(true) + } } func (s *Service) shutdownKVStore() error { if s == nil { return nil } + if s.coreManager != nil { + s.coreManager.CloseSessionAffinityPersistence() + } s.kvStoreManaged.Store(false) return kvstore.ShutdownLocal() } diff --git a/sdk/cliproxy/service_affinity_persistence_test.go b/sdk/cliproxy/service_affinity_persistence_test.go new file mode 100644 index 00000000000..72600c5d5d1 --- /dev/null +++ b/sdk/cliproxy/service_affinity_persistence_test.go @@ -0,0 +1,102 @@ +package cliproxy + +import ( + "context" + "net/http" + "path/filepath" + "testing" + + "github.com/rune-oai/t3code-proxy/internal/config" + "github.com/rune-oai/t3code-proxy/internal/kvstore" + coreauth "github.com/rune-oai/t3code-proxy/sdk/cliproxy/auth" + cliproxyexecutor "github.com/rune-oai/t3code-proxy/sdk/cliproxy/executor" + log "github.com/sirupsen/logrus" + logtest "github.com/sirupsen/logrus/hooks/test" +) + +func TestServiceRoutingReloadPreservesExplicitAffinity(t *testing.T) { + cfg := &config.Config{Routing: config.RoutingConfig{Strategy: "fill-first", SessionAffinity: true, SessionAffinityTTL: "1h"}} + selector := newRoutingSelector(normalizedRoutingRuntimeState(cfg)) + manager := coreauth.NewManager(nil, selector, nil) + t.Cleanup(manager.CloseSessionAffinityPersistence) + service := &Service{coreManager: manager, cfg: cfg} + a, err := manager.Register(context.Background(), &coreauth.Auth{ID: "a", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + b, err := manager.Register(context.Background(), &coreauth.Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + opts := cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"service-reload-session"}}} + if _, err := selector.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{b}); err != nil { + t.Fatal(err) + } + next := *cfg + next.Routing.SessionAffinityRebindOn = "quota" + if !service.applyManagerConfig(context.Background(), configCommit{cfg: &next, sequence: 1}) { + t.Fatal("routing reload failed") + } + replacement := manager.Selector() + if replacement == selector { + t.Fatal("test did not replace selector") + } + t.Cleanup(func() { + if stoppable, ok := replacement.(coreauth.StoppableSelector); ok { + stoppable.Stop() + } + }) + got, err := replacement.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{a, b}) + if err != nil || got == nil || got.ID != b.ID { + t.Fatalf("reload changed warm account: %v, %v", got, err) + } +} + +func TestServiceAffinityStorageDisableDoesNotResurrectRemovedCredential(t *testing.T) { + cfg := &config.Config{KVStore: config.KVStoreConfig{Path: filepath.Join(t.TempDir(), "kv.db")}} + first := coreauth.NewSessionAffinitySelector(&coreauth.FillFirstSelector{}) + manager := coreauth.NewManager(nil, first, nil) + service := &Service{coreManager: manager} + service.applyKVStoreConfig(cfg) + t.Cleanup(func() { + first.Stop() + if err := service.shutdownKVStore(); err != nil { + t.Error(err) + } + }) + b, err := manager.Register(context.Background(), &coreauth.Auth{ID: "b", Provider: "claude"}) + if err != nil { + t.Fatal(err) + } + opts := cliproxyexecutor.Options{Headers: http.Header{"X-Claude-Code-Session-Id": {"disable-storage-session"}}} + if _, err := first.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{b}); err != nil { + t.Fatal(err) + } + first.Stop() // Flush while the initial store is still enabled. + disabled := *cfg + disabled.KVStore.Disabled = true + service.applyKVStoreConfig(&disabled) + previousHooks := log.StandardLogger().Hooks + hook := logtest.NewLocal(log.StandardLogger()) + t.Cleanup(func() { log.StandardLogger().ReplaceHooks(previousHooks) }) + for range 3 { + service.applyKVStoreConfig(&disabled) + } + for _, entry := range hook.AllEntries() { + if entry.Message == "session-affinity: clear disabled persistence" { + t.Fatal("disabled reload tried to clear a closed KV store") + } + } + manager.Remove(context.Background(), b.ID) + service.applyKVStoreConfig(cfg) + // A new manager simulates a new process with no runtime removal tombstones. + fresh := coreauth.NewSessionAffinitySelector(&coreauth.FillFirstSelector{}) + t.Cleanup(fresh.Stop) + got, err := fresh.Pick(context.Background(), "claude", "model", opts, []*coreauth.Auth{{ID: "a"}, b}) + if err != nil || got == nil || got.ID != "a" { + t.Fatalf("disabled storage revived removed binding: %v, %v", got, err) + } + if _, enabled, err := kvstore.CurrentKVClient(); err != nil || !enabled { + t.Fatalf("KV did not re-enable: %t, %v", enabled, err) + } +}