Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e02fee7
fix(auth): persist explicit session affinity across restarts and reloads
rune-gh Nov 17, 2026
be2aea1
fix(quota): restore safe persisted routing readings before polling
rune-gh Nov 17, 2026
3e890a3
fix(codex): observe HTTP SSE quota events before filtering
rune-gh Nov 17, 2026
a0b8f71
fix(auth): preserve affinity across tier and transport changes
rune-gh Nov 17, 2026
38d3bee
fix(auth): serialize affinity publication with credential retirement
rune-gh Nov 17, 2026
a2175f8
fix(auth): preserve observed credential epochs during failover
rune-gh Nov 17, 2026
6314e0f
fix(claude): stop replay after accepted responses are interrupted
rune-gh Nov 29, 2026
327e0d3
fix(logging): synchronize deferred request capture finalization
rune-gh Nov 29, 2026
fba00ea
fix(claude): preserve Fast response decoding error status
rune-gh Nov 29, 2026
5589fc9
fix(mistral): give Mistral models their real reasoning levels
rune-gh Nov 29, 2026
dfbb8b9
feat(auth): let auth files opt proxied transports into connection poo…
rune-gh Dec 1, 2026
4cec7dd
fix(auth): answer 404 when every account rejects the model
rune-gh Nov 29, 2026
751fe62
fix(quota): lift quota cooldowns when a usage poll shows allowance again
rune-gh Dec 2, 2026
a46eb66
fix(quota): judge renewal from every reported window and skip non-quo…
rune-gh Dec 2, 2026
8f43d14
fix(quota): keep cooldowns a renewal poll cannot vouch for
rune-gh Dec 2, 2026
f1545a4
fix(quota): judge only live quota and account-only 429s against the p…
rune-gh Dec 2, 2026
3ec412a
fix(quota): let traffic on other models not delay a model quota recovery
rune-gh Dec 2, 2026
0cbe386
Merge verified audit and test fixes onto the deployed Windows hub
rune-gh Dec 2, 2026
2411ed3
fix(opencode): restrict catalog and routing to selected providers
rune-gh Dec 2, 2026
e7f14e1
Merge remote-tracking branch 'origin/main' into t3/qoder-quota-panel
rune-gh Dec 3, 2026
a3e45d3
feat(web): draw each quota window as its own line, drop drain rate an…
rune-gh Dec 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions internal/api/handlers/management/auth_files_fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
49 changes: 49 additions & 0 deletions internal/api/handlers/management/auth_files_patch_fields_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
55 changes: 36 additions & 19 deletions internal/api/middleware/request_logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -151,6 +152,7 @@ func CaptureAuthenticatedRequestBody(c *gin.Context) {
}

type deferredRequestBodyCapture struct {
mu sync.Mutex
body io.ReadCloser
factory fileBodySourceFactory
memBuf bytes.Buffer
Expand Down Expand Up @@ -188,15 +190,21 @@ 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
}
if n == 0 {
return n, errRead
}
c.bytesRead += int64(n)
if c.skipCapture || c.captureErr != nil || c.finished {
if c.skipCapture || c.captureErr != nil {
return n, errRead
}

Expand Down Expand Up @@ -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
}
Expand All @@ -301,39 +308,47 @@ 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 {
body, errBytes := c.source.Bytes()
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 {
Expand All @@ -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()
Expand Down
37 changes: 37 additions & 0 deletions internal/api/middleware/request_logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
2 changes: 1 addition & 1 deletion internal/api/middleware/response_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 2 additions & 0 deletions internal/pluginhost/auth_callbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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
}

Expand Down
37 changes: 29 additions & 8 deletions internal/quotahistory/recorder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
}
Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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() {
Expand Down
Loading