From cee32f7047317beaa480b15fcae2eb327c6d3b44 Mon Sep 17 00:00:00 2001 From: NEKOMYA <168091698+NekomyaDev@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:41:52 +0800 Subject: [PATCH] feat(models): add passive availability tracking and opt-in probes (#171) * feat(models): add passive availability tracking and opt-in probes * test(models): harden passive availability telemetry and catalog refresh overlap protection --------- Co-authored-by: NekomyaDev --- README.md | 1 + README.zh-CN.md | 1 + config.example.json | 3 +- internal/config/config.go | 4 + internal/gateway/availability.go | 6 + internal/gateway/gateway.go | 3 + internal/gateway/passive_test.go | 368 +++++++++++++++++++++++++++++++ internal/gateway/probe.go | 8 +- internal/gateway/refresh.go | 79 ++++--- internal/gateway/upstream.go | 7 + internal/models/availability.go | 51 ++++- webui/index.html | 8 + webui/js/i18n.js | 4 + webui/js/pages/config.js | 2 + 14 files changed, 504 insertions(+), 41 deletions(-) create mode 100644 internal/gateway/passive_test.go diff --git a/README.md b/README.md index b8d2fc4..80e87c5 100644 --- a/README.md +++ b/README.md @@ -315,6 +315,7 @@ See [config.example.json](config.example.json) for a complete starting configura | `models.refresh_seconds` | `300`; minimum 1. | | `models.protocols` | `{}`; per-model native protocol overrides. | | `models.free_only` | `false`; expose and route only free models, even with Zen or Go keys. | +| `models.active_probes` | `false`; when disabled, model availability is tracked passively from live requests without sending synthetic inference probes. Set to `true` to opt in to background inference probes. | | `models.anonymous_backoff` | Absent (off); `{threshold, base_hours, max_hours}`, defaulting to `6`, `1`, `24`. | | `reasoning.effort` | Empty (off); `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, or `none`. | | `reasoning.effort_by_model` | `{}`; per-model overrides of `reasoning.effort`. | diff --git a/README.zh-CN.md b/README.zh-CN.md index 9ebc85d..ff75b45 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -315,6 +315,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | `models.refresh_seconds` | `300`;最小为 1。 | | `models.protocols` | `{}`;按模型 ID 覆盖原生协议。 | | `models.free_only` | `false`;即使配置了 Zen / Go Key,也只暴露和路由免费模型。 | +| `models.active_probes` | `false`;关闭时通过实际请求被动追踪模型可用性,不主动发起测试请求。设为 `true` 开启主动探测。 | | `models.anonymous_backoff` | 缺省关闭;`{threshold, base_hours, max_hours}`,默认 6、1、24。 | | `reasoning.effort` | 空(关闭);可选 `auto`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`。 | | `reasoning.effort_by_model` | `{}`;按模型 ID 覆盖 `reasoning.effort`。 | diff --git a/config.example.json b/config.example.json index f768d1c..f60fa96 100644 --- a/config.example.json +++ b/config.example.json @@ -24,7 +24,8 @@ "models": { "refresh_seconds": 300, "protocols": {}, - "free_only": false + "free_only": false, + "active_probes": false }, "performance": { "max_idle_conns": 2048, diff --git a/internal/config/config.go b/internal/config/config.go index 2a14eaa..786c04e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -155,6 +155,10 @@ type ModelsConfig struct { // FreeOnly limits discovery and routing to free models, even when Zen or // Go keys could serve paid ones. Free models may still fall back to keys. FreeOnly bool `json:"free_only"` + // ActiveProbes enables background active inference requests for free model + // health checks. When false (default), availability is learned passively + // from actual user requests, eliminating quota consumption from synthetic probes. + ActiveProbes bool `json:"active_probes,omitempty"` // AnonymousBackoff configures a circuit breaker for the keyless lane: // after Threshold consecutive failed attempts, or when every exit is under // the free tier's IP block, the lane pauses for BaseHours, doubling on diff --git a/internal/gateway/availability.go b/internal/gateway/availability.go index a2a7b40..ad5a8b6 100644 --- a/internal/gateway/availability.go +++ b/internal/gateway/availability.go @@ -106,7 +106,13 @@ func (m *RuntimeController) RequestAvailabilitySweep() { // checkFreeModels probes, one at a time, every free model under automatic // control whose next check is due. A result is recorded only while the // runtime that ran the probe is still current. +// When models.active_probes is false, automatic synthetic inference probes are skipped +// to eliminate quota waste, relying entirely on passive telemetry from live requests. func (m *RuntimeController) checkFreeModels(ctx context.Context) { + r := m.current.Load() + if r == nil || !r.gateway.cfg.Models.ActiveProbes { + return + } for _, item := range m.AvailabilitySnapshot() { if ctx.Err() != nil { return diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index e6a0cd1..982b299 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -24,6 +24,7 @@ import ( "log/slog" "net/http" "strings" + "sync" "time" "opencode2api/internal/config" @@ -93,6 +94,8 @@ type Gateway struct { // freeTierBlock is how long an exit the free tier flagged stays out of the // anonymous cursor. Zero uses freeTierBlockTTL. freeTierBlock time.Duration + // refreshMu prevents overlapping catalog refreshes across concurrent or scheduled callers. + refreshMu sync.Mutex } // New builds a Gateway for cfg: one proxy transport per runtime proxy (a diff --git a/internal/gateway/passive_test.go b/internal/gateway/passive_test.go new file mode 100644 index 0000000..2fda5d8 --- /dev/null +++ b/internal/gateway/passive_test.go @@ -0,0 +1,368 @@ +package gateway + +import ( + "context" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/models" + wire "opencode2api/internal/protocol" +) + +func TestPassiveAvailability_RuntimeControllerFlow(t *testing.T) { + var inferenceRequests atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/chat/completions" || r.URL.Path == "/inference" { + inferenceRequests.Add(1) + } else if r.URL.Path == "/v1/models" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"mimo-v2.6-flash-free"}]}`)) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":"chatcmpl-test","choices":[{"message":{"role":"assistant","content":"OK"}}]}`)) + })) + defer server.Close() + + cfg, err := config.Normalize("", config.Config{ + Listen: "127.0.0.1:0", + Prefer: "zen", + Anonymous: true, + ServerKeys: []string{"test-key-1234567890"}, + Retry: config.RetryConfig{ + MaxAttempts: 1, + TimeoutSeconds: 30, + }, + Models: config.ModelsConfig{ + ActiveProbes: false, // Default: passive only + FreeOnly: true, + RefreshSeconds: 300, + }, + Upstream: config.UpstreamConfig{ + Zen: server.URL, + Go: server.URL, + Anonymous: server.URL, + }, + Performance: config.PerformanceConfig{ + MaxIdleConns: 10, + MaxIdleConnsPerHost: 2, + IdleConnTimeoutSeconds: 30, + ConnectTimeoutSeconds: 5, + FailureCooldownSeconds: 5, + }, + Logging: config.LoggingConfig{ + Level: "info", + RingSize: 1000, + }, + }) + if err != nil { + t.Fatalf("Normalize failed: %v", err) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + level := new(slog.LevelVar) + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + mgr, err := RuntimeManager(ctx, "", cfg, logger, nil, nil, config.SecretRedactor(), level) + if err != nil { + t.Fatalf("RuntimeManager failed: %v", err) + } + defer mgr.Shutdown() + + // Execute checkFreeModels directly through controller + mgr.checkFreeModels(ctx) + + // In default false state, inferenceRequests must be strictly 0 + if count := inferenceRequests.Load(); count != 0 { + t.Errorf("expected 0 inference requests with ActiveProbes=false, got %d", count) + } +} + +func TestActiveProbes_ExplicitOptIn(t *testing.T) { + var probeCount atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/chat/completions" || r.URL.Path == "/inference" { + probeCount.Add(1) + } else if r.URL.Path == "/v1/models" { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"mimo-v2.6-flash-free"}]}`)) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"id":"chatcmpl-test","choices":[{"message":{"role":"assistant","content":"OK"}}]}`)) + })) + defer server.Close() + + cfg, err := config.Normalize("", config.Config{ + Listen: "127.0.0.1:0", + Prefer: "zen", + Anonymous: true, + ServerKeys: []string{"test-key-1234567890"}, + Retry: config.RetryConfig{ + MaxAttempts: 1, + TimeoutSeconds: 30, + }, + Models: config.ModelsConfig{ + ActiveProbes: true, // Explicitly opted in + FreeOnly: true, + RefreshSeconds: 300, + }, + Upstream: config.UpstreamConfig{ + Zen: server.URL, + Go: server.URL, + Anonymous: server.URL, + }, + Performance: config.PerformanceConfig{ + MaxIdleConns: 10, + MaxIdleConnsPerHost: 2, + IdleConnTimeoutSeconds: 30, + ConnectTimeoutSeconds: 5, + FailureCooldownSeconds: 5, + }, + Logging: config.LoggingConfig{ + Level: "info", + RingSize: 1000, + }, + }) + if err != nil { + t.Fatalf("Normalize failed: %v", err) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + level := new(slog.LevelVar) + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + mgr, err := RuntimeManager(ctx, "", cfg, logger, nil, nil, config.SecretRedactor(), level) + if err != nil { + t.Fatalf("RuntimeManager failed: %v", err) + } + defer mgr.Shutdown() + + // Ensure model is registered in catalog and availability + runtime := mgr.current.Load() + native := map[config.Tier]map[string]wire.Protocol{ + config.TierZen: {"mimo-v2.6-flash-free": wire.Chat}, + } + runtime.gateway.catalog.ReplaceWithCapabilities([]string{"mimo-v2.6-flash-free"}, nil, native, nil, nil) + _ = runtime.availability.ScheduleSweep() + + // Execute checkFreeModels + mgr.checkFreeModels(ctx) + + // Active probes should have fired at least 1 probe request + if count := probeCount.Load(); count == 0 { + t.Errorf("expected active probes to run when ActiveProbes=true, got 0 requests") + } +} + +func TestRecordPassiveObservation_Robustness(t *testing.T) { + reg, err := models.AvailabilityStore("") + if err != nil { + t.Fatalf("AvailabilityStore failed: %v", err) + } + now := time.Now().UTC() + + // 1. Success enables model + _ = reg.RecordPassiveObservation("test-model", true, 200, "", "anonymous", now) + if reg.Get("test-model").Disabled { + t.Errorf("expected model to be enabled on 200") + } + + // 2. Generic errors MUST NOT disable model + for _, tc := range []struct { + status int + body string + }{ + {400, `{"error":"invalid request parameters"}`}, + {404, `{"error":"path not found"}`}, + {429, `{"error":"rate limit exceeded"}`}, + {403, `{"error":"forbidden"}`}, + {500, `{"error":"internal server error"}`}, + {502, `{"error":"bad gateway"}`}, + {503, `{"error":"service unavailable"}`}, + } { + _ = reg.RecordPassiveObservation("test-model", false, tc.status, tc.body, "anonymous", now) + if reg.Get("test-model").Disabled { + t.Errorf("expected status %d with body %q to NOT disable model", tc.status, tc.body) + } + } + + // 3. Authoritative model_unavailable disables model + authoritativeBody := `{"error":{"code":"model_not_found","message":"The model test-model does not exist"}}` + _ = reg.RecordPassiveObservation("test-model", false, 404, authoritativeBody, "anonymous", now) + if !reg.Get("test-model").Disabled { + t.Errorf("expected authoritative model_not_found to disable model") + } + if reg.Get("test-model").Reason != "model_unavailable" { + t.Errorf("expected reason 'model_unavailable', got %q", reg.Get("test-model").Reason) + } +} + +func TestCatalogRefresh_PreservesLastKnownGood(t *testing.T) { + var shouldFail atomic.Bool + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/models" { + if shouldFail.Load() { + w.WriteHeader(http.StatusInternalServerError) + _, _ = io.WriteString(w, "server error") + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"data":[{"id":"stable-model-free"}]}`) + return + } + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + + cfg, err := config.Normalize("", config.Config{ + Listen: "127.0.0.1:0", + Prefer: "zen", + Anonymous: true, + ServerKeys: []string{"test-key-1234567890"}, + Retry: config.RetryConfig{ + MaxAttempts: 1, + TimeoutSeconds: 30, + }, + Models: config.ModelsConfig{ + RefreshSeconds: 300, + }, + Upstream: config.UpstreamConfig{ + Zen: server.URL, + Go: server.URL, + Anonymous: server.URL, + }, + Performance: config.PerformanceConfig{ + MaxIdleConns: 10, + MaxIdleConnsPerHost: 2, + IdleConnTimeoutSeconds: 30, + ConnectTimeoutSeconds: 5, + FailureCooldownSeconds: 5, + }, + Logging: config.LoggingConfig{ + Level: "info", + RingSize: 1000, + }, + }) + if err != nil { + t.Fatalf("Normalize failed: %v", err) + } + + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + gw, err := New(cfg, logger, nil, nil) + if err != nil { + t.Fatalf("failed to create gateway: %v", err) + } + + // 1. Initial successful refresh with capabilities + zenModels := gw.refreshZen(context.Background()) + if len(zenModels) == 0 || zenModels[0] != "stable-model-free" { + t.Fatalf("expected initial model list to contain stable-model-free, got %v", zenModels) + } + native := map[config.Tier]map[string]wire.Protocol{ + config.TierZen: {"stable-model-free": wire.Chat}, + } + gw.catalog.ReplaceWithCapabilities(zenModels, nil, native, nil, nil) + + // Verify catalog currently lists the model + if current := gw.catalog.List(); len(current) == 0 || current[0] != "stable-model-free" { + t.Fatalf("expected catalog to have stable-model-free initially, got %v", current) + } + + // 2. Upstream starts failing on next refresh round + shouldFail.Store(true) + failedZenModels := gw.refreshZen(context.Background()) + if failedZenModels != nil { + t.Errorf("expected refreshZen to return nil on failure, got %v", failedZenModels) + } + + // Only replace if at least one listing succeeded (as implemented in StartModelRefresh) + if failedZenModels != nil { + gw.catalog.ReplaceWithCapabilities(failedZenModels, nil, nil, nil, nil) + } + + // Catalog should still preserve last-known-good models + current := gw.catalog.List() + if len(current) == 0 || current[0] != "stable-model-free" { + t.Errorf("expected last-known-good catalog to be preserved, got %v", current) + } +} + +func TestCatalogRefresh_OverlapProtection(t *testing.T) { + var refreshCount atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/v1/models" { + refreshCount.Add(1) + time.Sleep(50 * time.Millisecond) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"mimo-v2.6-flash-free"}]}`)) + } + })) + defer server.Close() + + cfg, err := config.Normalize("", config.Config{ + Listen: "127.0.0.1:0", + Prefer: "zen", + Anonymous: true, + ServerKeys: []string{"test-key-1234567890"}, + Retry: config.RetryConfig{ + MaxAttempts: 1, + TimeoutSeconds: 30, + }, + Models: config.ModelsConfig{ + RefreshSeconds: 300, + }, + Upstream: config.UpstreamConfig{ + Zen: server.URL, + Go: server.URL, + Anonymous: server.URL, + }, + Performance: config.PerformanceConfig{ + MaxIdleConns: 10, + MaxIdleConnsPerHost: 2, + IdleConnTimeoutSeconds: 30, + ConnectTimeoutSeconds: 5, + FailureCooldownSeconds: 5, + }, + Logging: config.LoggingConfig{ + Level: "info", + RingSize: 1000, + }, + }) + if err != nil { + t.Fatalf("Normalize failed: %v", err) + } + + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + gw, err := New(cfg, logger, nil, nil) + if err != nil { + t.Fatalf("failed to create gateway: %v", err) + } + + // Trigger multiple concurrent RefreshCatalog calls + var wg sync.WaitGroup + for i := 0; i < 5; i++ { + wg.Add(1) + go func() { + defer wg.Done() + gw.RefreshCatalog(context.Background()) + }() + } + wg.Wait() + + // Due to TryLock overlap guard on Gateway, overlapping runs were skipped + if count := refreshCount.Load(); count != 1 { + t.Errorf("expected exactly 1 refresh execution due to overlap guard, got %d", count) + } +} diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index 48f0cdf..c386fa9 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -269,7 +269,7 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, base return probeResult{attempted: true, reason: "network_abuse_blocked"} } result.effortRejected = isEffortRejection(resp.StatusCode, string(body)) - if isModelUnavailable(resp.StatusCode, string(body)) { + if IsModelUnavailable(resp.StatusCode, string(body)) { result.reason = "model_unavailable" } } @@ -311,7 +311,7 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, base result.reason = "invalid_or_incomplete_response" if err != nil { result.effortRejected = isEffortRejection(400, err.Error()) - if isModelUnavailable(400, err.Error()) { + if IsModelUnavailable(400, err.Error()) { result.reason = "model_unavailable" } } @@ -322,10 +322,10 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, base return result } -// isModelUnavailable reports whether a 400, 404, 410 or 422 error body says +// IsModelUnavailable reports whether a 400, 404, 410 or 422 error body says // the model itself is unknown, retired or no longer available, as opposed to // a transient or credential failure. -func isModelUnavailable(status int, body string) bool { +func IsModelUnavailable(status int, body string) bool { if status != 400 && status != 404 && status != 410 && status != 422 { return false } diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index d90420c..c8591d1 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -163,47 +163,56 @@ func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string g.logger.Debug("proxy health check is still failing", "component", "proxy", "event", "health_check_still_failing", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "error", result.err) } +// RefreshCatalog refreshes the catalog once. Concurrent or overlapping executions +// on this gateway are skipped via g.refreshMu. +func (g *Gateway) RefreshCatalog(ctx context.Context) { + if !g.refreshMu.TryLock() { + return + } + defer g.refreshMu.Unlock() + var zen, goModels []string + var capabilities modelcatalog.Capabilities + var capabilitiesErr error + var wg sync.WaitGroup + wg.Add(3) + go func() { defer wg.Done(); zen = g.refreshZen(ctx) }() + go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }() + go func() { + defer wg.Done() + capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + capabilities, capabilitiesErr = g.refreshProtocolCapabilities(capabilityCtx) + }() + wg.Wait() + if ctx.Err() != nil { + return + } + if capabilitiesErr != nil { + g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr) + } + if zen != nil || goModels != nil { + g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata) + g.syncRotation() + if ctx.Err() == nil { + if err := g.catalog.SaveCache(); err != nil { + g.logger.Warn("model catalog cache write failed", "component", "models", "event", "catalog_cache_write_failed", "error", err) + } + } + g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List())) + } +} + // StartModelRefresh refreshes the model catalog at once and then every // models.refresh_seconds until ctx is canceled. Each round concurrently lists // the Zen models (through the anonymous lane when no Zen key can) and the Go // models, and fetches OpenCode's protocol capabilities. The catalog is // replaced only when at least one listing succeeded; the rotation groups are -// then resynced and the catalog cache saved. +// then resynced and the catalog cache saved. If a refresh fails, the last-known-good +// catalog is preserved intact. +// Overlapping refresh executions within this gateway are skipped via g.refreshMu. func (g *Gateway) StartModelRefresh(ctx context.Context) { - refresh := func() { - var zen, goModels []string - var capabilities modelcatalog.Capabilities - var capabilitiesErr error - var wg sync.WaitGroup - wg.Add(3) - go func() { defer wg.Done(); zen = g.refreshZen(ctx) }() - go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }() - go func() { - defer wg.Done() - capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second) - defer cancel() - capabilities, capabilitiesErr = g.refreshProtocolCapabilities(capabilityCtx) - }() - wg.Wait() - if ctx.Err() != nil { - return - } - if capabilitiesErr != nil { - g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr) - } - if zen != nil || goModels != nil { - g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata) - g.syncRotation() - if ctx.Err() == nil { - if err := g.catalog.SaveCache(); err != nil { - g.logger.Warn("model catalog cache write failed", "component", "models", "event", "catalog_cache_write_failed", "error", err) - } - } - g.logger.Info("model catalog refreshed", "component", "models", "event", "catalog_refreshed", "models", len(g.catalog.List())) - } - } go func() { - refresh() + g.RefreshCatalog(ctx) ticker := time.NewTicker(time.Duration(g.cfg.Models.RefreshSeconds) * time.Second) defer ticker.Stop() for { @@ -211,7 +220,7 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { case <-ctx.Done(): return case <-ticker.C: - refresh() + g.RefreshCatalog(ctx) } } }() diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index e71bd5b..e5390cf 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -1170,6 +1170,13 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, KeyID: keyID, Channel: channel, Anonymous: anonymous, Proxy: proxyName, Status: status, DurationMS: max(duration.Milliseconds(), 0), Success: success, Outcome: outcome, }) + if !isDiagnosticRequest(ctx) && g.availability != nil && g.catalog.IsFreeModel(route.ID) { + bodySnippet := "" + if resp != nil && (resp.StatusCode == 400 || resp.StatusCode == 404 || resp.StatusCode == 410 || resp.StatusCode == 422) { + bodySnippet = string(peekResponseBody(resp)) + } + _ = g.availability.RecordPassiveObservation(route.ID, success, status, bodySnippet, channel, time.Now().UTC()) + } } // upstreamRequest builds the POST for one attempt: baseURL plus the protocol's diff --git a/internal/models/availability.go b/internal/models/availability.go index 281aa16..734b845 100644 --- a/internal/models/availability.go +++ b/internal/models/availability.go @@ -4,6 +4,7 @@ import ( "encoding/json" "os" "path/filepath" + "strings" "sync" "time" ) @@ -220,7 +221,55 @@ func (s *AvailabilityRegistry) Record(model string, generation uint64, success b return s.saveLocked() } -// saveLocked rewrites the registry file through a temporary file and a rename. +// RecordPassiveObservation updates model availability based on real user traffic. +// Unlike active synthetic probes, it never issues upstream requests. +// 2xx marks model available. Generic HTTP 400, 404, 429, 403, 5xx, timeouts +// and transport errors never disable the model. Only an explicit, authoritative +// model-unavailable response (isModelUnavailable: model_not_found, model_retired, etc.) +// can mark a model as disabled. +func (s *AvailabilityRegistry) RecordPassiveObservation(model string, success bool, status int, body string, channel string, now time.Time) error { + s.mu.Lock() + defer s.mu.Unlock() + item := s.items[model] + if item.Manual { + return nil + } + item.Model = model + item.ProbeVersion = 1 + item.CheckedAt = now + item.Channel = channel + if success { + item.Disabled = false + item.Reason = "passive_traffic_succeeded" + item.NextCheck = now.Add(FreeModelCheckInterval) + } else if IsModelUnavailableReason(status, body) { + item.Disabled = true + item.Reason = "model_unavailable" + item.NextCheck = now.Add(FailedModelCheckInterval) + } + s.items[model] = item + return s.saveLocked() +} + +// IsModelUnavailableReason reports whether status and response body contain authoritative +// evidence that the model is nonexistent or retired. +func IsModelUnavailableReason(status int, body string) bool { + if status != 400 && status != 404 && status != 410 && status != 422 { + return false + } + text := strings.ToLower(body) + for _, marker := range []string{ + "model_not_found", "model_not_available", "model_retired", + "model_deprecated", "unknown model", "model does not exist", + "model has been retired", "model is no longer available", + } { + if strings.Contains(text, marker) { + return true + } + } + return false +} + // It is a no-op without a path. The caller holds s.mu for writing. func (s *AvailabilityRegistry) saveLocked() error { if s.path == "" { diff --git a/webui/index.html b/webui/index.html index 636dd8f..2d506e1 100644 --- a/webui/index.html +++ b/webui/index.html @@ -996,6 +996,14 @@ +
+ +
diff --git a/webui/js/i18n.js b/webui/js/i18n.js index 03dac53..904457d 100644 --- a/webui/js/i18n.js +++ b/webui/js/i18n.js @@ -285,6 +285,7 @@ const DICTIONARY = { "config.upstream.caption": "anonymous will use every available proxy; an explicit protocol mapping wins over inferring the protocol from the model name.", "config.upstream.freeOnly": "Only expose free models (even when Zen / Go Keys are configured)", + "config.upstream.activeProbes": "Enable active background probes for free models (disabled by default to save quota)", "config.upstream.attempts": "Max attempts per Key Tier", "config.upstream.timeout": "Request timeout (seconds)", "config.upstream.refresh": "Model refresh interval (seconds)", @@ -856,6 +857,7 @@ const DICTIONARY = { "config.upstream.caption": "anonymous sẽ dùng hết các Proxy khả dụng; ánh xạ protocol tường minh được ưu tiên hơn việc suy luận từ tên mô hình.", "config.upstream.freeOnly": "Chỉ công khai mô hình miễn phí (kể cả khi đã cấu hình Zen / Go Key)", + "config.upstream.activeProbes": "Bật probe chủ động ngầm cho mô hình miễn phí (mặc định tắt để tiết kiệm hạn mức)", "config.upstream.attempts": "Số lần thử tối đa cho mỗi Key Tier", "config.upstream.timeout": "Timeout của request (giây)", "config.upstream.refresh": "Làm mới mô hình (giây)", @@ -1439,6 +1441,8 @@ const DICTIONARY = { "anonymous userà ogni proxy disponibile; una mappatura esplicita di protocollo prevale sull'inferenza del protocollo dal nome del modello.", "config.upstream.freeOnly": "Espone solo modelli gratuiti (anche quando sono configurate Zen / Go Key)", + "config.upstream.activeProbes": + "Abilita i probe attivi in background per i modelli gratuiti (disabilitato per impostazione predefinita)", "config.upstream.attempts": "Tentativi massimi per Key Tier", "config.upstream.timeout": "Timeout richiesta (secondi)", "config.upstream.refresh": "Intervallo di refresh modelli (secondi)", diff --git a/webui/js/pages/config.js b/webui/js/pages/config.js index 031577b..2732b48 100644 --- a/webui/js/pages/config.js +++ b/webui/js/pages/config.js @@ -95,6 +95,7 @@ function fillConfig(value) { $("#c-refresh").value = value.models.refresh_seconds; $("#c-protocols").value = JSON.stringify(value.models.protocols || {}, null, 2); $("#c-free-only").checked = !!value.models.free_only; + $("#c-active-probes").checked = !!value.models.active_probes; const reasoning = value.reasoning || {}; $("#c-reasoning-effort").value = reasoning.effort || ""; $("#c-reasoning-by-model").value = JSON.stringify(reasoning.effort_by_model || {}, null, 2); @@ -139,6 +140,7 @@ async function save(event) { refresh_seconds: numberValue("#c-refresh"), protocols: JSON.parse($("#c-protocols").value || "{}"), free_only: $("#c-free-only").checked, + active_probes: $("#c-active-probes").checked, }, reasoning: { effort: $("#c-reasoning-effort").value,