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 <neko@nekomya.dev>
This commit is contained in:
NEKOMYAandNekomyaDev authored and GitHub committed 2026-11-05 11:41:52 +08:00
1 parent 6fbe12c4df
commit cee32f7047
14 files changed
+504 -41

No files matched your search

+4
View File
@@ -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
+6
View File
@@ -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
+3
View File
@@ -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
+368
View File
@@ -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)
}
}
+4 -4
View File
@@ -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
}
+44 -35
View File
@@ -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)
}
}
}()
+7
View File
@@ -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
+50 -1
View File
@@ -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 == "" {