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) + } +} diff --git a/web/src/features/quota/QuotaPage.tsx b/web/src/features/quota/QuotaPage.tsx index 6b970a97129..389ac2f3531 100644 --- a/web/src/features/quota/QuotaPage.tsx +++ b/web/src/features/quota/QuotaPage.tsx @@ -47,24 +47,21 @@ import { RESETS_FILTER_ALL } from './resetCalendarModel'; import { UseResetDialog, type UseResetTarget } from './components/UseResetDialog'; import { QuotaPoolCard } from './components/QuotaPoolCard'; import { QuotaPoolToolbar, type BurnWindowHours } from './components/QuotaPoolToolbar'; -import type { PoolChartMode } from './components/PoolChart'; import { LIVE_POOL_PROVIDERS, defaultPoolSpan, historyFromLiveSnapshots, isLivePoolProvider, mergeLiveHistory, + poolChartWindows, poolProvidersFromHistory, - poolWindowChoices, providerWindowLabels, providerWindows, - resolvePoolWindow, shiftPoolSpan, type FutureUsage, type LiveAccountInput, type PoolProvider, type PoolSpan, - type PoolWindowChoice, } from './poolModel'; import { formatPlanName, formatWeight } from './poolPrefs'; import { liveReadFor, type LiveRead } from './liveWindows'; @@ -278,12 +275,9 @@ export function QuotaPage() { // null = follow today (Now a quarter into a 14-day span). const [pinnedSpan, setPinnedSpan] = useState(null); const span = pinnedSpan ?? defaultPoolSpan(now); - const [chartMode, setChartMode] = useState('remaining'); const [burnWindow, setBurnWindow] = useState(3); const [futureUsage, setFutureUsage] = useState('same'); const [showAccounts, setShowAccounts] = useState(false); - // Only choices the user made; each card falls back to its provider default. - const [poolWindows, setPoolWindows] = useState>({}); const planWeights = usePlanWeights(!disableControls); // Also without credential files: the hub may record API-key upstreams (Mistral) only. @@ -915,8 +909,6 @@ export function QuotaPage() { {showViews && view === 'pools' && ( <> entry.type === provider); const rows = rowsByProvider[provider] ?? []; const lastReadAt = historyReady ? latestReadingAt(rows) : null; - const windowChoice = resolvePoolWindow(provider, poolHistory, poolWindows[provider]); const windows = isLivePoolProvider(provider) ? [] : providerWindows(poolHistory, provider); @@ -993,19 +984,14 @@ export function QuotaPage() { key={provider} provider={provider} history={poolHistory} - window={windowChoice ?? ''} - windowChoices={poolWindowChoices(provider, poolHistory)} + windows={poolChartWindows(provider, poolHistory)} windowLabels={windowLabels} - onWindowChange={(choice) => - setPoolWindows((previous) => ({ ...previous, [provider]: choice })) - } weights={planWeights.effectiveFor(provider)} defaultWeights={planWeights.defaultsFor(provider)} configuredWeights={planWeights.configuredFor(provider)} weightsMode={planWeights.mode} weightsError={planWeights.error} onSaveWeights={(changes) => handleSaveWeights(provider, changes)} - mode={chartMode} showAccounts={showAccounts} spanStart={span.start} spanEnd={span.end} @@ -1018,7 +1004,7 @@ export function QuotaPage() { loading={poolLoading} lastReadAt={lastReadAt} stale={isReadingStale(lastReadAt, now, historyIntervalSeconds)} - headlineHint={windowChoice ? budgetHint(rows, windowChoice) : undefined} + headlineHint={(window) => budgetHint(rows, window)} bankedResets={ provider === 'codex' ? totalBankedCredits( diff --git a/web/src/features/quota/components/PoolChart.module.scss b/web/src/features/quota/components/PoolChart.module.scss index 4d60af48b01..857dfde2a01 100644 --- a/web/src/features/quota/components/PoolChart.module.scss +++ b/web/src/features/quota/components/PoolChart.module.scss @@ -1,4 +1,4 @@ -/* Pool chart: series colour comes from the panel's --pool-color; the rest is neutral. */ +/* Pool chart: each line sets --series-color (the first is the panel's --pool-color); the rest is neutral. */ .wrap { position: relative; @@ -15,7 +15,7 @@ .areaRecorded, .areaProjected { - fill: var(--pool-color); + fill: var(--series-color, var(--pool-color)); stroke: none; } @@ -46,7 +46,7 @@ .line { fill: none; - stroke: var(--pool-color); + stroke: var(--series-color, var(--pool-color)); stroke-width: 1.75; stroke-linejoin: round; stroke-linecap: round; @@ -59,7 +59,7 @@ .accountLine { fill: none; - stroke: var(--pool-color); + stroke: var(--series-color, var(--pool-color)); stroke-opacity: 0.4; stroke-width: 1; stroke-linejoin: round; @@ -88,7 +88,7 @@ .nowDot, .hoverDot { - fill: var(--pool-color); + fill: var(--series-color, var(--pool-color)); stroke: var(--card); stroke-width: 2; } @@ -108,6 +108,14 @@ stroke-width: 1.5; } +.emptyRingSeries { + stroke: var(--series-color); +} + +.jumpLabelSeries { + fill: var(--series-color); +} + .tooltip { position: absolute; z-index: 2; @@ -123,3 +131,17 @@ pointer-events: none; box-shadow: var(--shadow-popover); } + +.tooltipRow { + display: flex; + align-items: center; + gap: var(--space-2); +} + +.tooltipSwatch { + display: inline-block; + width: 10px; + height: 2px; + border-radius: 1px; + background: var(--series-color); +} diff --git a/web/src/features/quota/components/PoolChart.tsx b/web/src/features/quota/components/PoolChart.tsx index 838a65665d9..fa07497c271 100644 --- a/web/src/features/quota/components/PoolChart.tsx +++ b/web/src/features/quota/components/PoolChart.tsx @@ -1,29 +1,37 @@ /** - * Pool chart: recorded (solid line, flat area) and projected (dashed) pooled - * quota over the span, with reset-jump annotations, a Now rule, an "Empty" - * marker, optional per-account lines, and a hover crosshair. + * Pool chart: one line per window (Weekly, Fable weekly, Gemini Models, ...), + * each in its own colour, recorded solid and projected dashed, with reset-jump + * annotations, a Now rule, "Empty" markers, optional per-account lines and a + * hover crosshair that reads every line at once. * * Plain SVG in pixel space (width measured with ResizeObserver) so text and * strokes never distort. */ -import { useEffect, useId, useMemo, useRef, useState, type PointerEvent } from 'react'; +import { + useEffect, + useId, + useMemo, + useRef, + useState, + type CSSProperties, + type PointerEvent, +} from 'react'; import { useTranslation } from 'react-i18next'; import { dayStarts, type PoolView, type SeriesPoint } from '../poolModel'; -import { - formatDayTick, - formatWeekdayTime, - niceCeil, - POOL_UNITS, - type PoolUnits, -} from '../poolFormat'; +import { formatDayTick, formatWeekdayTime, POOL_UNITS, type PoolUnits } from '../poolFormat'; import styles from './PoolChart.module.scss'; -export type PoolChartMode = 'remaining' | 'drain'; +export interface PoolChartSeries { + key: string; + label: string; + /** CSS colour for this line (the first series uses the provider colour). */ + color: string; + view: PoolView; +} export interface PoolChartProps { - view: PoolView; - mode: PoolChartMode; + series: readonly PoolChartSeries[]; showAccounts: boolean; spanStart: number; spanEnd: number; @@ -79,9 +87,10 @@ function valueAt(points: readonly SeriesPoint[], t: number, interpolate: boolean return a.value + ((b.value - a.value) * (t - a.t)) / (b.t - a.t); } +const seriesStyle = (color: string) => ({ '--series-color': color }) as CSSProperties; + export function PoolChart({ - view, - mode, + series, showAccounts, spanStart, spanEnd, @@ -105,10 +114,6 @@ export function PoolChart({ return () => observer.disconnect(); }, []); - const drain = mode === 'drain'; - const recordedSeries = drain ? view.recordedRate : view.recorded; - const projectedSeries = drain ? view.projectedRate : view.projected; - const height = width < COMPACT_WIDTH ? COMPACT_HEIGHT : HEIGHT; const compact = width < COMPACT_WIDTH; const plotLeft = MARGIN.left; @@ -116,23 +121,18 @@ export function PoolChart({ const plotTop = MARGIN.top; const plotBottom = height - MARGIN.bottom; const span = Math.max(1, spanEnd - spanStart); + // One line keeps its filled area; several lines would muddy each other. + const single = series.length === 1; const yMax = useMemo(() => { - if (!drain) return view.max > 0 ? view.max : 100; - const peak = Math.max( - 0, - ...recordedSeries.map((p) => p.value), - ...projectedSeries.map((p) => p.value) - ); - return niceCeil(Math.max(1, peak * 1.15)); - }, [drain, projectedSeries, recordedSeries, view.max]); + const max = Math.max(0, ...series.map((line) => line.view.max)); + return max > 0 ? max : 100; + }, [series]); const x = (time: number) => plotLeft + ((time - spanStart) / span) * (plotRight - plotLeft); const y = (value: number) => plotBottom - (Math.min(Math.max(value, 0), yMax) / yMax) * (plotBottom - plotTop); - const formatValue = (value: number) => (drain ? units.rate(value) : units.value(value)); - const days = useMemo(() => dayStarts(spanStart, spanEnd), [spanStart, spanEnd]); const dayLabels = useMemo(() => { const bounds = [spanStart, ...days.filter((d) => d > spanStart), spanEnd]; @@ -151,13 +151,14 @@ export function PoolChart({ return labels.filter((_, index) => index % step === 0); }, [days, locale, spanEnd, spanStart, width]); - // Jump annotations, greedily thinned so labels never overlap. + // Jump annotations over every line, greedily thinned so labels never overlap. const jumpLabels = useMemo(() => { - if (drain || compact) return []; - const out: { x: number; y: number; label: string; projected: boolean }[] = []; - [...view.jumps] - .sort((a, b) => a.t - b.t) - .forEach((jump) => { + if (compact) return []; + const out: { x: number; y: number; label: string; color: string }[] = []; + series + .flatMap((line) => line.view.jumps.map((jump) => ({ jump, color: line.color }))) + .sort((a, b) => a.jump.t - b.jump.t) + .forEach(({ jump, color }) => { const jx = plotLeft + ((jump.t - spanStart) / span) * (plotRight - plotLeft); const jy = plotBottom - (Math.min(Math.max(jump.value, 0), yMax) / yMax) * (plotBottom - plotTop); @@ -166,46 +167,32 @@ export function PoolChart({ (other) => Math.abs(other.x - jx) < LABEL_MIN_GAP_X && Math.abs(other.y - labelY) < 14 ); if (clash || jx < plotLeft || jx > plotRight) return; - out.push({ - x: jx, - y: labelY, - label: units.signed(jump.amount), - projected: jump.projected, - }); + out.push({ x: jx, y: labelY, label: units.signed(jump.amount), color }); }); return out; - }, [ - compact, - drain, - plotBottom, - plotLeft, - plotRight, - plotTop, - span, - spanStart, - units, - view.jumps, - yMax, - ]); + }, [compact, plotBottom, plotLeft, plotRight, plotTop, series, span, spanStart, units, yMax]); const nowVisible = now >= spanStart && now <= spanEnd; const nowX = x(now); - const nowValue = drain - ? (recordedSeries[recordedSeries.length - 1]?.value ?? view.burnRate) - : view.current; - const emptyAt = !drain ? view.poolEmptyAt : null; - // Hover lookup. + // "Empty" markers, stacked upward so two lines emptying close together stay legible. + const empties = series + .map((line) => ({ line, at: line.view.poolEmptyAt })) + .filter((item): item is { line: PoolChartSeries; at: number } => item.at !== null); + + // Hover lookup: every line's value at the hovered time. const hover = useMemo(() => { if (hoverX === null) return null; const time = spanStart + ((hoverX - plotLeft) / (plotRight - plotLeft)) * span; const projected = time > now; - const value = projected - ? valueAt(projectedSeries, time, true) - : valueAt(recordedSeries, time, false); - if (value === null) return { time, value: null, projected }; - return { time, value, projected }; - }, [hoverX, now, plotLeft, plotRight, projectedSeries, recordedSeries, span, spanStart]); + const values = series.map((line) => ({ + line, + value: projected + ? valueAt(line.view.projected, time, true) + : valueAt(line.view.recorded, time, false), + })); + return { time, projected, values }; + }, [hoverX, now, plotLeft, plotRight, series, span, spanStart]); const onPointerMove = (event: PointerEvent) => { const rect = event.currentTarget.getBoundingClientRect(); @@ -214,22 +201,19 @@ export function PoolChart({ }; const yTicks = [0, yMax / 2, yMax]; - const recordedLine = linePath(recordedSeries, x, y); - const projectedLine = linePath(projectedSeries, x, y); - const recordedArea = areaPath(recordedSeries, x, y, plotBottom); - const projectedArea = areaPath(projectedSeries, x, y, plotBottom); - - const summary = drain - ? t('quota_pool.chart_summary_drain', { - defaultValue: 'Drain rate over time; currently {{rate}}.', - rate: units.rate(view.burnRate), + + const summary = series + .map((line) => + t('quota_pool.chart_summary_series', { + defaultValue: '{{label}}: {{current}} of {{max}} left', + label: line.label, + current: units.value(line.view.current), + max: units.value(line.view.max), }) - : t('quota_pool.chart_summary', { - defaultValue: 'Pooled quota over time: {{current}} of {{max}} left.', - current: units.value(view.current), - max: units.value(view.max), - }); + ) + .join('; '); + const hoverValues = hover?.values.filter((item) => item.value !== null) ?? []; const tooltipFlip = hoverX !== null && hoverX > width / 2; return ( @@ -284,7 +268,7 @@ export function PoolChart({ textAnchor="end" dy="0.32em" > - {formatValue(tick)} + {units.value(tick)} ))} @@ -302,34 +286,53 @@ export function PoolChart({ ))} - {projectedArea && } - {recordedArea && } - - {showAccounts && - view.accounts.map((account) => { - const rec = drain ? account.recordedRate : account.recorded; - const proj = drain ? account.projectedRate : account.projected; + {single && + series.map((line) => { + const projectedArea = areaPath(line.view.projected, x, y, plotBottom); + const recordedArea = areaPath(line.view.recorded, x, y, plotBottom); return ( - - - + + {projectedArea && } + {recordedArea && } ); })} - {projectedLine && ( - - )} - {recordedLine && } + {showAccounts && + series.map((line) => ( + + {line.view.accounts.map((account) => ( + + + + + ))} + + ))} + + {/* Later series first so the provider's own line draws on top. */} + {[...series].reverse().map((line) => { + const projectedLine = linePath(line.view.projected, x, y); + const recordedLine = linePath(line.view.recorded, x, y); + return ( + + {projectedLine && ( + + )} + {recordedLine && } + + ); + })} {jumpLabels.map((label) => ( {t('quota_pool.now', { defaultValue: 'Now' })} - {recordedSeries.length > 0 && ( - - )} + {series + .filter((line) => line.view.recorded.length > 0) + .map((line) => ( + + ))} )} - {emptyAt !== null && ( - + {empties.map(({ line, at }, index) => ( + - {t('quota_pool.empty_at', { - defaultValue: 'Empty {{time}}', - time: formatWeekdayTime(emptyAt, locale), - })} + {single + ? t('quota_pool.empty_at', { + defaultValue: 'Empty {{time}}', + time: formatWeekdayTime(at, locale), + }) + : t('quota_pool.empty_at_series', { + defaultValue: '{{label}} empty {{time}}', + label: line.label, + time: formatWeekdayTime(at, locale), + })} - + - )} + ))} {hover && hoverX !== null && ( @@ -376,14 +401,21 @@ export function PoolChart({ y1={plotTop} y2={plotBottom} /> - {hover.value !== null && ( - - )} + {hoverValues.map(({ line, value }) => ( + + ))} )} - {hover && hoverX !== null && hover.value !== null && ( + {hover && hoverX !== null && hoverValues.length > 0 && (
- {formatWeekdayTime(hover.time, locale)} - {' · '} - {drain - ? units.rate(hover.value) - : t('quota_pool.tooltip_left', { - defaultValue: '{{value}} left', - value: units.value(hover.value), - })} - {' · '} - {hover.projected - ? t('quota_pool.projected_lower', { defaultValue: 'projected' }) - : t('quota_pool.recorded_lower', { defaultValue: 'recorded' })} +
+ {formatWeekdayTime(hover.time, locale)} + {' · '} + {hover.projected + ? t('quota_pool.projected_lower', { defaultValue: 'projected' }) + : t('quota_pool.recorded_lower', { defaultValue: 'recorded' })} +
+ {hoverValues.map(({ line, value }) => ( +
+ {!single && ( +
+ ))}
)} diff --git a/web/src/features/quota/components/QuotaPoolCard.module.scss b/web/src/features/quota/components/QuotaPoolCard.module.scss index 13e288ac808..b133ce17007 100644 --- a/web/src/features/quota/components/QuotaPoolCard.module.scss +++ b/web/src/features/quota/components/QuotaPoolCard.module.scss @@ -35,11 +35,6 @@ max-width: 100%; } -.windowSelect { - min-width: 0; - max-width: 220px; -} - /* ---------- plan weights popover ---------- */ .weightsAnchor { @@ -125,6 +120,11 @@ .panel { --pool-color: #c96442; + /* Further lines on a multi-window chart, chosen to stay apart from every provider colour. */ + --pool-series-1: #7c4ddb; + --pool-series-2: #0f9d76; + --pool-series-3: #c2417e; + --pool-series-4: #8a7a12; display: flex; flex-direction: column; @@ -142,6 +142,10 @@ :global([data-theme='dark']) .panel { --pool-color: #d97757; + --pool-series-1: #a98bf5; + --pool-series-2: #3ccf9f; + --pool-series-3: #f07ab3; + --pool-series-4: #d8c552; &[data-provider='codex'] { --pool-color: #7aa2f7; @@ -193,6 +197,79 @@ text-align: center; } +/* ---------- per-window summary (several lines) ---------- */ + +.seriesTableWrap { + display: flex; + flex-direction: column; + gap: var(--space-3); + min-width: 0; + overflow-x: auto; +} + +.seriesTable { + width: 100%; + border-collapse: collapse; + font-size: var(--text-sm); + font-variant-numeric: tabular-nums; + + th, + td { + padding: var(--space-2) var(--space-4) var(--space-2) 0; + text-align: left; + vertical-align: baseline; + white-space: nowrap; + } + + thead th { + padding-top: 0; + color: var(--muted-foreground); + font-weight: 400; + } + + tbody tr + tr > * { + border-top: 1px solid var(--border); + } + + tbody th { + font-weight: 500; + color: var(--foreground); + } + + td { + color: var(--foreground); + } +} + +.seriesName { + display: inline-flex; + align-items: center; + gap: var(--space-2); +} + +.seriesSwatch { + display: inline-block; + width: 16px; + height: 0; + border-top: 2px solid var(--series-color); +} + +.seriesValue { + font-size: var(--text-lg); + font-weight: 600; +} + +.seriesMax { + margin-left: var(--space-1); + color: var(--muted-foreground); +} + +.seriesHint { + display: block; + color: var(--muted-foreground); + font-size: var(--text-xs); +} + /* ---------- legend ---------- */ .legend { diff --git a/web/src/features/quota/components/QuotaPoolCard.tsx b/web/src/features/quota/components/QuotaPoolCard.tsx index 59768e636ee..02583469f80 100644 --- a/web/src/features/quota/components/QuotaPoolCard.tsx +++ b/web/src/features/quota/components/QuotaPoolCard.tsx @@ -1,7 +1,8 @@ /** - * One provider's pooled quota: a section with the window picker, a panel - * holding the headline, projection stats, chart and legend, then the - * per-account table. All numbers come from the pure pool model (poolModel.ts). + * One provider's pooled quota: a section holding the headline (or, with + * several windows, one stats row per window), the chart with one coloured + * line per window, the legend, then the per-account table. All numbers come + * from the pure pool model (poolModel.ts). * * Pools are capacity-weighted by plan and read in percent of the heaviest plan * in the pool: with a Max 5x and a Pro account, Max 5x is 100% and Pro 20%, so @@ -27,8 +28,6 @@ import { IconSlidersHorizontal } from '@/components/ui/icons'; import { Section } from '@/components/ui/Section'; import { Skeleton } from '@/components/ui/Skeleton'; import { Stat } from '@/components/ui/Stat'; -import { Select } from '@/components/ui/Select'; -import { SegmentedControl } from '@/components/ui/Tabs'; import type { QuotaHistory } from '@/services/api'; import type { ResolvedTheme } from '@/types'; import { getAuthFileIcon, getTypeColor, getTypeLabel } from '@/features/authFiles/constants'; @@ -39,24 +38,23 @@ import { type FutureUsage, type PlanWeights, type PoolProvider, + type PoolView, type PoolWindowChoice, } from '../poolModel'; import { formatDuration, formatMonthDay, formatWeekdayTime, POOL_UNITS } from '../poolFormat'; import { formatPlanName, formatWeight, planKey } from '../poolPrefs'; -import { groupWindowChoices, windowLabel } from '../poolWindowLabels'; +import { windowLabel } from '../poolWindowLabels'; import type { PlanWeightsMode } from '../hooks/usePlanWeights'; -import { PoolChart, type PoolChartMode } from './PoolChart'; +import { PoolChart, type PoolChartSeries } from './PoolChart'; import styles from './QuotaPoolCard.module.scss'; export interface QuotaPoolCardProps { provider: PoolProvider; history: QuotaHistory; - window: PoolWindowChoice; - /** Choices for the window picker; hidden when there is only one. */ - windowChoices: readonly PoolWindowChoice[]; + /** Windows drawn as lines, the provider's main window first. */ + windows: readonly PoolWindowChoice[]; /** Names the provider gives its own windows, by window key. */ windowLabels?: Record; - onWindowChange: (window: PoolWindowChoice) => void; /** Effective plan weights (plan → weight). */ weights: PlanWeights; /** Hub defaults per plan; empty when the hub does not report them. */ @@ -68,7 +66,6 @@ export interface QuotaPoolCardProps { weightsError?: string; /** Save edits: a weight, or null to go back to the default. Rejects on failure. */ onSaveWeights: (changes: Record) => Promise; - mode: PoolChartMode; showAccounts: boolean; spanStart: number; spanEnd: number; @@ -84,8 +81,8 @@ export interface QuotaPoolCardProps { /** Newest recorded reading; null hides the line (live-only view). */ lastReadAt?: number | null; stale?: boolean; - /** A line under the headline, e.g. money spent in a window with a budget. */ - headlineHint?: string; + /** A line under a window's figure, e.g. money spent in a window with a budget. */ + headlineHint?: (window: PoolWindowChoice) => string | undefined; /** Codex: banked resets over all accounts; null while unknown. */ bankedResets?: number | null; /** Per-account table. */ @@ -96,8 +93,11 @@ export interface QuotaPoolCardProps { reading?: boolean; } -/** More window choices than this switch the picker to a menu so it fits narrow screens. */ -const MAX_SEGMENTED_WINDOWS = 3; +/** Line colour by position: the provider colour first, then the panel's series palette. */ +const seriesColor = (index: number) => + index === 0 ? 'var(--pool-color)' : `var(--pool-series-${Math.min(index, 4)})`; + +type StatItem = { key: string; label: string; value: ReactNode }; const formatClock = (ms: number, locale: string) => new Date(ms).toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' }); @@ -106,17 +106,14 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const { provider, history, - window: windowChoice, - windowChoices, + windows, windowLabels, - onWindowChange, weights, defaultWeights = {}, configuredWeights = {}, weightsMode, weightsError = '', onSaveWeights, - mode, showAccounts, spanStart, spanEnd, @@ -142,11 +139,12 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const [saveError, setSaveError] = useState(''); const weightsRef = useRef(null); - const view = useMemo( - () => - buildPoolView(history, { + const lines = useMemo(() => { + const built = windows.map((window) => ({ + window, + view: buildPoolView(history, { provider, - window: windowChoice, + window, weights, now, spanStart, @@ -154,18 +152,11 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { burnWindowHours, futureUsage, }), - [ - burnWindowHours, - futureUsage, - history, - now, - provider, - spanEnd, - spanStart, - weights, - windowChoice, - ] - ); + })); + // A window no account draws on (Fable on a Pro-only pool) gets no line. + const drawn = built.filter((line) => line.view.tracks.length > 0); + return drawn.length > 0 ? drawn : built.slice(0, 1); + }, [burnWindowHours, futureUsage, history, now, provider, spanEnd, spanStart, weights, windows]); const plans = useMemo(() => { const set = new Set(); @@ -176,7 +167,14 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { }, [history.accounts, provider]); const units = POOL_UNITS; - const single = view.tracks.length === 1; + const series: PoolChartSeries[] = lines.map((line, index) => ({ + key: line.window, + label: windowLabel(t, line.window, windowLabels), + color: seriesColor(index), + view: line.view, + })); + const primary = series[0]; + const multi = series.length > 1; const currentWeight = (plan: string) => weights[plan] ?? defaultWeights[plan] ?? 1; const openWeights = () => { @@ -244,98 +242,81 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { const providerLabel = getTypeLabel(t, provider); const notBy = t('quota_pool.not_by', { date: formatMonthDay(spanEnd, locale) }); - const hasData = view.tracks.length > 0; - const firstEmptyValue = view.firstEmpty ? ( - <> - - {view.firstEmpty.label} - {' '} - {view.firstEmpty.at <= now - ? t('quota_pool.empty_now') - : t('quota_pool.in_duration', { duration: formatDuration(view.firstEmpty.at - now) })} - - ) : ( - notBy - ); + const hasData = series.some((line) => line.view.tracks.length > 0); + const firstEmptyValue = (view: PoolView): ReactNode => + view.firstEmpty ? ( + <> + + {view.firstEmpty.label} + {' '} + {view.firstEmpty.at <= now + ? t('quota_pool.empty_now') + : t('quota_pool.in_duration', { duration: formatDuration(view.firstEmpty.at - now) })} + + ) : ( + notBy + ); - const currentWindowLabel = windowLabel(t, windowChoice, windowLabels); - // Many scoped windows (Antigravity): a group picker plus short period tabs. - const windowGroups = groupWindowChoices(t, windowChoices, windowLabels); - const currentItem = windowGroups?.items.find((item) => item.choice === windowChoice); - const currentGroup = currentItem?.group ?? windowGroups?.groups[0] ?? ''; - const groupItems = windowGroups - ? windowGroups.items.filter((item) => (item.group ?? '') === currentGroup) - : []; - const selectGroup = (group: string) => { - if (!windowGroups) return; - const inGroup = windowGroups.items.filter((item) => (item.group ?? '') === group); - // Keep the period the user is looking at when the new group has it. - const same = inGroup.find((item) => item.period === currentItem?.period); - const next = same ?? inGroup[0]; - if (next) onWindowChange(next.choice); + // Labels follow the main window; every line uses the same burn window. + const limited = primary?.view.burnEstimate.confidence === 'limited'; + const statsFor = (view: PoolView): StatItem[] => { + const hasTracks = view.tracks.length > 0; + const collecting = !view.burnEstimate.ready && futureUsage !== 'none'; + return [ + { + key: 'pool-empty', + label: t(limited ? 'quota_pool.stat_pool_empty_limited' : 'quota_pool.stat_pool_empty'), + value: !hasTracks + ? '—' + : collecting + ? t('quota_pool.collecting_data') + : view.poolEmptyAt !== null + ? formatWeekdayTime(view.poolEmptyAt, locale) + : notBy, + }, + { + key: 'first-empty', + label: t('quota_pool.stat_first_empty'), + // With one account the first account to run dry is the pool itself. + value: + view.tracks.length < 2 + ? '—' + : collecting + ? t('quota_pool.collecting_data') + : firstEmptyValue(view), + }, + { + key: 'next-reset', + label: t('quota_pool.stat_next_reset'), + value: view.nextReset + ? `${units.signed(view.nextReset.amount)}, ${formatWeekdayTime(view.nextReset.at, locale)}` + : '—', + }, + { + key: 'burn', + label: t(limited ? 'quota_pool.stat_burn_limited' : 'quota_pool.stat_burn', { + hours: Number((primary?.view.burnEstimate.windowHours ?? burnWindowHours).toFixed(1)), + }), + value: !hasTracks + ? '—' + : view.burnEstimate.ready + ? units.rate(view.burnRate) + : t('quota_pool.collecting_data'), + }, + ]; }; - const stats: { key: string; label: string; value: ReactNode }[] = [ - { - key: 'pool-empty', - label: t( - view.burnEstimate.confidence === 'limited' - ? 'quota_pool.stat_pool_empty_limited' - : 'quota_pool.stat_pool_empty' - ), - value: !hasData - ? '—' - : !view.burnEstimate.ready && futureUsage !== 'none' - ? t('quota_pool.collecting_data') - : view.poolEmptyAt !== null - ? formatWeekdayTime(view.poolEmptyAt, locale) - : notBy, - }, - { - key: 'first-empty', - label: t('quota_pool.stat_first_empty'), - value: !hasData - ? '—' - : !view.burnEstimate.ready && futureUsage !== 'none' - ? t('quota_pool.collecting_data') - : firstEmptyValue, - }, - { - key: 'next-reset', - label: t('quota_pool.stat_next_reset'), - value: view.nextReset - ? `${units.signed(view.nextReset.amount)}, ${formatWeekdayTime(view.nextReset.at, locale)}` - : '—', - }, - { - key: 'burn', - label: t( - view.burnEstimate.confidence === 'limited' - ? 'quota_pool.stat_burn_limited' - : 'quota_pool.stat_burn', - { - hours: Number(view.burnEstimate.windowHours.toFixed(1)), - } - ), - value: !hasData - ? '—' - : view.burnEstimate.ready - ? units.rate(view.burnRate) - : t('quota_pool.collecting_data'), - }, - ]; - // With one account the first account to run dry is the pool itself. - if (single) - stats.splice( - stats.findIndex((stat) => stat.key === 'first-empty'), - 1 - ); - if (bankedResets !== undefined) { - stats.push({ - key: 'banked', - label: t('quota_pool.stat_banked'), - value: bankedResets === null ? '—' : String(bankedResets), - }); - } + // The first-empty stat only means something when a line pools several accounts. + const showFirstEmpty = series.some((line) => line.view.tracks.length > 1); + const shownStats = (view: PoolView) => + statsFor(view).filter((stat) => stat.key !== 'first-empty' || showFirstEmpty); + const banked: StatItem | null = + bankedResets === undefined + ? null + : { + key: 'banked', + label: t('quota_pool.stat_banked'), + value: bankedResets === null ? '—' : String(bankedResets), + }; const description = ( @@ -351,6 +332,93 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) { ); + let summary: ReactNode = null; + if (loading) { + summary = ( +
+ } + /> +
+ ); + } else if (hasData && primary && !multi) { + summary = ( +
+ +
+ {[...shownStats(primary.view), ...(banked ? [banked] : [])].map((stat) => ( + + ))} +
+
+ ); + } else if (hasData && primary) { + summary = ( +
+ + + + + + {shownStats(primary.view).map((stat) => ( + + ))} + + + + {series.map((line) => { + const hint = headlineHint?.(line.key); + return ( + + + + {shownStats(line.view).map((stat) => ( + + ))} + + ); + })} + +
{t('quota_pool.series_window')}{t('quota_pool.series_left')} + {stat.label} +
+ + + + {units.value(line.view.current)} + {line.view.tracks.length > 1 && ( + + {t('quota_pool.of_max', { max: units.value(line.view.max) })} + + )} + {hint && {hint}} + {stat.value}
+ {banked && ( +
+ +
+ )} +
+ ); + } + return (
- {windowGroups ? ( - <> - ({ - value: choice, - label: windowLabel(t, choice, windowLabels), - }))} - onChange={onWindowChange} - /> - ) : windowChoices.length > 1 ? ( - ({ - value: choice, - label: windowLabel(t, choice, windowLabels), - }))} - value={windowChoice} - onChange={onWindowChange} - /> - ) : null}
{/* Nothing read yet: the empty-state panel alone, no row of dashes. */} - {(hasData || loading) && ( -
- - ) : hasData ? ( - units.value(view.current) - ) : ( - '—' - ) - } - unit={ - // One account: "38%" says it all; "of 100%" adds nothing. - !hasData || single - ? undefined - : t('quota_pool.of_max', { max: units.value(view.max) }) - } - hint={hasData && !loading ? headlineHint : undefined} - /> -
- {stats.map((stat) => ( - - ))} -
-
- )} + {summary} {loading ? ( @@ -589,8 +574,7 @@ export function QuotaPoolCard(props: QuotaPoolCardProps) {
) : (
  • {showAccounts && (
  • diff --git a/web/src/features/quota/components/QuotaPoolToolbar.tsx b/web/src/features/quota/components/QuotaPoolToolbar.tsx index 8c22f13509d..f579eb5e849 100644 --- a/web/src/features/quota/components/QuotaPoolToolbar.tsx +++ b/web/src/features/quota/components/QuotaPoolToolbar.tsx @@ -1,6 +1,6 @@ /** - * Pool chart toolbar: chart value and date range up front; the rarely - * changed burn window, future usage and per-account lines sit in a menu. + * Pool chart toolbar: the date range up front; the rarely changed burn + * window, future usage and per-account lines sit in a menu. */ import { useTranslation } from 'react-i18next'; @@ -11,10 +11,8 @@ import { DropdownMenuSeparator, } from '@/components/ui/DropdownMenu'; import { IconSlidersHorizontal } from '@/components/ui/icons'; -import { SegmentedControl } from '@/components/ui/Tabs'; import { Toolbar } from '@/components/ui/Toolbar'; import type { FutureUsage } from '../poolModel'; -import type { PoolChartMode } from './PoolChart'; import { SpanNav } from './SpanNav'; import styles from './QuotaPoolToolbar.module.scss'; @@ -28,8 +26,6 @@ const FUTURE_OPTIONS: { value: FutureUsage; key: string }[] = [ ]; export interface QuotaPoolToolbarProps { - mode: PoolChartMode; - onModeChange: (mode: PoolChartMode) => void; burnWindow: BurnWindowHours; onBurnWindowChange: (hours: BurnWindowHours) => void; futureUsage: FutureUsage; @@ -46,8 +42,6 @@ export interface QuotaPoolToolbarProps { export function QuotaPoolToolbar(props: QuotaPoolToolbarProps) { const { - mode, - onModeChange, burnWindow, onBurnWindowChange, futureUsage, @@ -114,16 +108,6 @@ export function QuotaPoolToolbar(props: QuotaPoolToolbarProps) { } > - choice !== 'five_hour') + : (() => { + const windows = history ? providerWindows(history, provider) : []; + const long = windows.filter( + (window) => window.periodHours === null || window.periodHours >= SHORT_WINDOW_HOURS + ); + return (long.length > 0 ? long : windows).map((window) => window.key); + })(); + const first = defaultPoolWindow(provider, history); + return first && choices.includes(first) + ? [first, ...choices.filter((choice) => choice !== first)] + : choices; } /* --------------------------------------------------------------------------- diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 7a7cdb235b3..ba6cf3006a9 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -1743,9 +1743,11 @@ "tooltip_left": "{{value}} left", "projected_lower": "projected", "recorded_lower": "recorded", - "chart_summary": "Pooled quota over time: {{current}} of {{max}} left.", - "chart_summary_drain": "Drain rate over time; currently {{rate}}.", - "window_label": "Quota window", + "chart_summary_series": "{{label}}: {{current}} of {{max}} left", + "empty_at_series": "{{label}} empty {{time}}", + "tooltip_series_left": "{{label}}: {{value}} left", + "series_window": "Window", + "series_left": "Left", "window_weekly": "Weekly", "window_fable": "Fable weekly", "window_five_hour": "5-hour", @@ -1757,7 +1759,6 @@ "window_span_month": "{{count}}-month", "window_scoped": "{{scope}} {{window}}", "window_unknown": "Quota window", - "window_group_label": "Quota group", "window_group_account": "Whole account", "plan_weights": "Plan weights", "plan_weights_for": "{{provider}} plan weights", @@ -1795,9 +1796,6 @@ "legend_recorded": "Recorded", "legend_projected": "Projected", "legend_accounts": "Accounts", - "mode_label": "Chart value", - "mode_remaining": "Remaining", - "mode_drain": "Drain rate", "burn_rate": "Burn rate", "future_usage": "Future usage", "future_same": "Same as now", @@ -1817,8 +1815,6 @@ "burn_window_option": "Last {{count}} hours", "range_label": "Date range", "legend_label": "Chart legend", - "legend_recorded_drain": "Recorded drain", - "legend_projected_drain": "Projected drain", "last_reading": "Last reading {{time}}", "stale": "Stale, {{duration}} old", "stale_hint": "The hub has not recorded a new reading recently. Refresh to take one.", diff --git a/web/tests/quotaPoolModel.test.ts b/web/tests/quotaPoolModel.test.ts index c7e7d671a34..5c6092f8f69 100644 --- a/web/tests/quotaPoolModel.test.ts +++ b/web/tests/quotaPoolModel.test.ts @@ -29,7 +29,7 @@ import { poolWindowChoices, providerWindowLabels, providerWindows, - resolvePoolWindow, + poolChartWindows, pooledAt, poolMax, remainingAt, @@ -568,8 +568,11 @@ describe('pools for every provider', () => { })] ); expect(defaultPoolWindow('antigravity', h)).toBe('group_gemini_models_gemini_weekly'); - expect(resolvePoolWindow('antigravity', h, 'group_claude_and_gpt_models_3p_weekly')) - .toBe('group_claude_and_gpt_models_3p_weekly'); + // One line per weekly group, Gemini first; the 5-hour window gets no line. + expect(poolChartWindows('antigravity', h)).toEqual([ + 'group_gemini_models_gemini_weekly', + 'group_claude_and_gpt_models_3p_weekly', + ]); }); test('Gemini falls back to an available window when its own models are absent', () => { @@ -589,12 +592,20 @@ describe('pools for every provider', () => { expect(defaultPoolWindow('codex')).toBe('weekly'); }); - test('a remembered choice that is no longer offered falls back to the default', () => { + test('chart lines leave out 5-hour windows and lead with the default window', () => { const h = multi(); - expect(resolvePoolWindow('xai', h, 'seven_day')).toBe('seven_day'); - expect(resolvePoolWindow('xai', h, 'fable')).toBe('monthly'); - expect(resolvePoolWindow('xai', h, undefined)).toBe('monthly'); - expect(resolvePoolWindow('claude', h, undefined)).toBe('weekly'); + expect(poolChartWindows('xai', h)).toEqual(['monthly', 'seven_day']); + expect(poolChartWindows('claude', h)).toEqual(['weekly', 'fable']); + expect(poolChartWindows('codex')).toEqual(['weekly']); + expect(poolChartWindows('antigravity', h)).toEqual(['seven_day_gemini_pro', 'image_gen']); + }); + + test('a provider that reports only a short window still gets its line', () => { + const h = history( + [{ id: 's', provider: 'muse' }], + [sample(NOW, 's', { five_hour: { used: 10, period: 5 } })] + ); + expect(poolChartWindows('muse', h)).toEqual(['five_hour']); }); test('xAI pools by the weight the hub reports per account', () => { @@ -896,7 +907,7 @@ describe('percent of the heaviest plan (owner pools)', () => { }; const view = buildPoolView(h, { provider: 'mistral', - window: resolvePoolWindow('mistral', h, undefined) as string, + window: poolChartWindows('mistral', h)[0], now: NOW, spanStart: NOW - 3 * 24 * H, spanEnd: NOW + 11 * 24 * H, @@ -1033,9 +1044,7 @@ describe('retired windows', () => { 'group_gemini_models_gemini_weekly', ]); expect(poolWindowChoices('antigravity', h)).toEqual(['group_gemini_models_gemini_weekly']); - expect( - resolvePoolWindow('antigravity', h, 'group_gemini_4_argon_gemini_argon_wtu_weekly') - ).toBe('group_gemini_models_gemini_weekly'); + expect(poolChartWindows('antigravity', h)).toEqual(['group_gemini_models_gemini_weekly']); }); test('partial reads and failed polls within six hours keep a window', () => {