diff --git a/README.md b/README.md index 78d3932..8ed0381 100644 --- a/README.md +++ b/README.md @@ -2401,9 +2401,12 @@ providers: `modelBaseUrls` read the body for this purpose. - **Discovery and `metadataPath`** query `baseUrl` and every distinct `modelBaseUrls` upstream, one request per upstream. An id is taken only from - the upstream its requests route to. Discovery fails as a whole when any - upstream fails, keeping the last-known set; metadata keeps the ids of the - upstreams that answered. `modelBaseUrls` ids stay declared models. + the upstream its requests route to. Discovery fails as a whole only when `baseUrl` + fails, keeping the last-known set. A failing `modelBaseUrls` upstream does not + degrade the provider: its explicit `models` stay served, the other upstreams' + ids still merge, and the admin overview lists it under `upstreamErrors` (also + logged, at most once per 10 minutes). Metadata keeps the ids of the upstreams + that answered. `modelBaseUrls` ids stay declared models. - **Admin catalog**: each `pathBaseUrls` key appears as a pseudo-model row (`gx10/v1/decide`). It is display only and never routable as a model. `kinds` labels a model id or a path key. The Models page then groups the diff --git a/admin.go b/admin.go index 8766676..481f737 100644 --- a/admin.go +++ b/admin.go @@ -336,6 +336,26 @@ func replaceURLForm(msg, form string) string { // base URL names no credential by itself, and any credential-shaped // userinfo/query an operator mistakenly embedded in it is stripped by // sanitizeBaseURL before this view is ever built. +// adminUpstreamErrorView is one tolerated modelBaseUrls discovery failure. +type adminUpstreamErrorView struct { + Upstream string `json:"upstream"` + Error string `json:"error"` +} + +func adminUpstreamErrors(fails []upstreamFailure, rawBaseURL string) []adminUpstreamErrorView { + if len(fails) == 0 { + return nil + } + out := make([]adminUpstreamErrorView, len(fails)) + for i, f := range fails { + out[i] = adminUpstreamErrorView{ + Upstream: sanitizeBaseURL(f.Upstream), + Error: sanitizeProviderErr(sanitizeProviderErr(f.Err, f.Upstream), rawBaseURL), + } + } + return out +} + type adminProviderView struct { LastRefresh time.Time `json:"lastRefresh"` // OpenUntil is when this provider's breaker will next attempt a @@ -394,6 +414,8 @@ type adminProviderView struct { Type string `json:"type"` BaseURL string `json:"baseUrl"` LastErr string `json:"lastErr,omitempty"` + // UpstreamErrors lists modelBaseUrls upstreams whose discovery failed while the provider stayed healthy. + UpstreamErrors []adminUpstreamErrorView `json:"upstreamErrors,omitempty"` // HealthState is this provider's discovery circuit breaker state // (feat/provider-health): "closed" (normal), "open" (backing off // after repeated discovery failures — maybeRefresh skips it until @@ -840,6 +862,7 @@ func (g *Gateway) buildAdminOverview() adminOverviewResponse { ModelCount: s.modelCount, LastRefresh: s.lastRefresh, LastErr: sanitizeProviderErr(s.lastErr, s.baseURL), + UpstreamErrors: adminUpstreamErrors(s.upstreamErrs, s.baseURL), DiscoveryEnabled: s.discoveryEnabled, HealthState: s.health.String(), OpenUntil: s.openUntil, diff --git a/provider_openai.go b/provider_openai.go index 41f4265..1ea61bf 100644 --- a/provider_openai.go +++ b/provider_openai.go @@ -8,6 +8,7 @@ import ( "net/http" "sort" "strings" + "sync" "time" ) @@ -36,6 +37,8 @@ type openaiAdapter struct { // newOpenAIAdapter call site (every test, and any caller that never // sets this) keeps behaving exactly as before this feature existed. metadataPath string + // upstreamErrs is the modelBaseUrls failures of the latest listModels call; guarded by upstreamMu. + upstreamErrs []upstreamFailure // timeout is this adapter's resolved per-request timeout // (resolveProviderTimeout, timeout.go) — UNLIKE retry above, it is NOT // left at its zero value by a bare newOpenAIAdapter call: a @@ -45,7 +48,8 @@ type openaiAdapter struct { // sets it to defaultRequestTimeout; buildAdapters (providers.go) // overwrites it with the real, config-resolved value for production // use, the same way it overwrites retry/metadataPath above. - timeout time.Duration + timeout time.Duration + upstreamMu sync.Mutex } // newOpenAIAdapter returns an openaiAdapter for provider name, with base as @@ -441,18 +445,51 @@ type modelsPayload struct { } `json:"data"` } +// upstreamFailure is one modelBaseUrls upstream that failed discovery. +type upstreamFailure struct { + Upstream string + Err string +} + +// upstreamErrorReporter is implemented by adapters whose discovery tolerates +// a failing secondary upstream and reports it out of band. +type upstreamErrorReporter interface { + upstreamErrors() []upstreamFailure +} + +// upstreamErrors returns the modelBaseUrls failures of the latest listModels call. +func (a *openaiAdapter) upstreamErrors() []upstreamFailure { + a.upstreamMu.Lock() + defer a.upstreamMu.Unlock() + return append([]upstreamFailure(nil), a.upstreamErrs...) +} + +func (a *openaiAdapter) setUpstreamErrors(errs []upstreamFailure) { + a.upstreamMu.Lock() + a.upstreamErrs = errs + a.upstreamMu.Unlock() +} + // listModels implements providerAdapter. It queries baseURL and every // distinct modelBaseUrls upstream; an id counts only when the upstream -// that lists it is the one requests for that id are routed to. Any failing -// upstream fails the whole listing, so a refresh never drops the models of -// an upstream that is briefly down. +// that lists it is the one requests for that id are routed to. A baseURL +// failure fails the listing, so a refresh never drops the models of a +// down baseURL. A failing modelBaseUrls upstream is recorded (see +// upstreamErrors) and skipped: its configured models stay served, and the +// other upstreams' ids still merge. func (a *openaiAdapter) listModels(ctx context.Context) ([]string, error) { var ids []string + var failures []upstreamFailure seen := make(map[string]bool) - for _, base := range a.upstreamBases() { + for i, base := range a.upstreamBases() { listed, err := a.listModelsFrom(ctx, base) if err != nil { - return nil, err + if i == 0 || ctx.Err() != nil { + a.setUpstreamErrors(nil) + return nil, err + } + failures = append(failures, upstreamFailure{Upstream: base, Err: err.Error()}) + continue } for _, id := range listed { if a.baseForModel(id) != base || seen[id] { @@ -462,6 +499,7 @@ func (a *openaiAdapter) listModels(ctx context.Context) ([]string, error) { ids = append(ids, id) } } + a.setUpstreamErrors(failures) return ids, nil } diff --git a/registry.go b/registry.go index f097ff3..d46ffb7 100644 --- a/registry.go +++ b/registry.go @@ -382,6 +382,9 @@ func (st *providerState) tryBeginWarmFillRetry(sinceWarmFill time.Time) bool { return true } +// upstreamErrLogEvery bounds how often a provider's tolerated upstream failures are logged. +const upstreamErrLogEvery = 10 * time.Minute + // finishRefresh records the outcome of a refresh attempt started by // tryBeginRefresh (or, for the synchronous warm fill, run unconditionally). // lastRefresh always advances to now, on success or failure alike — that is @@ -721,6 +724,8 @@ type modelRegistry struct { modelMeta map[string]*ModelMetaConfig nowFn func() time.Time warned map[string]bool + // upstreamErrLogAt is each provider's last upstream-failure log time; guarded by warnedMu. + upstreamErrLogAt map[string]time.Time // routerShadowClean maps a router name to modelsGen+1 of its last collision-free scan; guarded by warnedMu. routerShadowClean map[string]int64 // modelsCache holds one encoded GET /v1/models response body per @@ -864,6 +869,7 @@ func newModelRegistry(adapters map[string]providerAdapter, cfg *Config, log func warmFillRetryDelay: warmFillRetryDelay, warmFillTimeout: warmFillTimeout, warned: make(map[string]bool), + upstreamErrLogAt: make(map[string]time.Time), routerShadowClean: make(map[string]int64), providerNames: make([]string, 0, len(adapters)), modelsCache: make(map[string]modelsCacheEntry), @@ -1095,6 +1101,39 @@ func (m *modelRegistry) discoveryHealthy(name string) bool { func (m *modelRegistry) finishRefresh(st *providerState, now time.Time, ids []string, err error) { st.finishRefresh(now, ids, err) atomic.AddInt64(&m.modelsGen, 1) + if err == nil { + m.logUpstreamErrors(st.name, now) + } +} + +// logUpstreamErrors logs name's tolerated modelBaseUrls failures, at most once per upstreamErrLogEvery per provider. +func (m *modelRegistry) logUpstreamErrors(name string, now time.Time) { + adapter := m.adapters[name] + if adapter == nil { + return + } + rep, ok := adapter.(upstreamErrorReporter) + if !ok { + return + } + errs := rep.upstreamErrors() + if len(errs) == 0 { + return + } + m.warnedMu.Lock() + due := now.Sub(m.upstreamErrLogAt[name]) >= upstreamErrLogEvery + if due { + m.upstreamErrLogAt[name] = now + } + m.warnedMu.Unlock() + if !due { + return + } + base := adapter.base() + for _, f := range errs { + m.log("%s", fmt.Sprintf("model registry: discovery of provider %q upstream %s failed: %v", + name, sanitizeBaseURL(f.Upstream), sanitizeProviderErr(sanitizeProviderErr(f.Err, f.Upstream), base))) + } } // warmFillFailure records ONE provider whose synchronous warmFill @@ -2357,13 +2396,15 @@ type providerSnapshot struct { // (feat/provider-health) — see providerState.snapshot's doc comment // for why it is read in the same locked pass as the rest of this // struct's fields. - openUntil time.Time - name string - typeName string - baseURL string - lastErr string - models []string - modelCount int + openUntil time.Time + name string + typeName string + baseURL string + lastErr string + models []string + // upstreamErrs lists modelBaseUrls upstreams that failed the latest discovery without failing the provider. + upstreamErrs []upstreamFailure + modelCount int // health mirrors providerState's own field of the same name (feat/ // provider-health): the admin dashboard's breaker-state column. Every // provider reads closed until a discovery failure actually trips its @@ -2463,7 +2504,15 @@ func (m *modelRegistry) snapshot() []providerSnapshot { discoveryEnabled: m.states[name].discoveryEnabled, health: health, openUntil: openUntil, + upstreamErrs: upstreamErrorsOf(adapter), }) } return out } + +func upstreamErrorsOf(adapter providerAdapter) []upstreamFailure { + if rep, ok := adapter.(upstreamErrorReporter); ok { + return rep.upstreamErrors() + } + return nil +} diff --git a/upstreams_discovery_test.go b/upstreams_discovery_test.go index 88e881f..a65f781 100644 --- a/upstreams_discovery_test.go +++ b/upstreams_discovery_test.go @@ -2,6 +2,7 @@ package traefikllmgateway import ( "context" + "encoding/json" "fmt" "net/http" "net/http/httptest" @@ -57,22 +58,113 @@ func TestOpenAIAdapter_ModelBaseURLs_DiscoveryAndMetadataQueryEveryUpstream(t *t assert.EqualValues(t, 2, hitsB.Load(), "shared modelBaseUrls upstream queried once per call, not once per model") } +func statusServer(t *testing.T, code int) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(code) + })) + t.Cleanup(srv.Close) + return srv +} + func TestOpenAIAdapter_ModelBaseURLs_FailingUpstream(t *testing.T) { t.Parallel() good := modelsServer(t, `{"data":[{"id":"main-model","max_model_len":1000}]}`, nil) - bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - })) - t.Cleanup(bad.Close) + bad := statusServer(t, http.StatusInternalServerError) ad := newOpenAIAdapter("d1", good.URL, "") ad.modelBases = map[string]string{"glm": bad.URL} ad.metadataPath = "/v1/models" - _, err := ad.listModels(context.Background()) - assert.Error(t, err, "discovery must fail rather than drop the failing upstream's models") + ids, err := ad.listModels(context.Background()) + require.NoError(t, err, "a failing modelBaseUrls upstream must not fail discovery") + assert.Equal(t, []string{"main-model"}, ids) + errs := ad.upstreamErrors() + require.Len(t, errs, 1) + assert.Equal(t, bad.URL, errs[0].Upstream) got, err := ad.fetchModelMetadata(context.Background()) require.NoError(t, err) assert.Equal(t, map[string]int{"main-model": 1000}, got, "metadata keeps the healthy upstream's ids") } + +func TestOpenAIAdapter_BaseURLFailure_FailsDiscovery(t *testing.T) { + t.Parallel() + good := modelsServer(t, `{"data":[{"id":"glm"}]}`, nil) + bad := statusServer(t, http.StatusBadGateway) + + ad := newOpenAIAdapter("d1", bad.URL, "") + ad.modelBases = map[string]string{"glm": good.URL} + + _, err := ad.listModels(context.Background()) + assert.Error(t, err) + assert.Empty(t, ad.upstreamErrors()) +} + +// Mirrors uni on d1: a TEI upstream answering 404 and a scaled-to-zero +// reranker answering 502 must not degrade the provider. +func TestGateway_ModelBaseURLsFailures_ProviderStaysHealthy(t *testing.T) { + t.Parallel() + main := modelsServer(t, `{"data":[{"id":"main-model"}]}`, nil) + other := modelsServer(t, `{"data":[{"id":"glm"},{"id":"main-model"}]}`, nil) + tei := statusServer(t, http.StatusNotFound) + rerank := statusServer(t, http.StatusBadGateway) + + cfg := newAdminTestConfig() + cfg.Providers = map[string]*ProviderConfig{ + "uni": { + Type: "openai", BaseURL: main.URL, APIKey: "sk", Discovery: true, + Models: []string{"e5-tei", "reranker"}, + ModelBaseURLs: map[string]string{ + "glm": other.URL, "e5-tei": tei.URL, "reranker": rerank.URL, + }, + }, + } + h, _ := newAdminGatewayHandle(t, cfg) + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1")) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + var got adminOverviewResponse + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + require.Len(t, got.Providers, 1) + p := got.Providers[0] + + assert.Empty(t, p.LastErr) + assert.Equal(t, "closed", p.HealthState) + assert.Equal(t, []string{"e5-tei", "glm", "main-model", "reranker"}, p.Models) + + require.Len(t, p.UpstreamErrors, 2) + byUp := map[string]string{} + for _, e := range p.UpstreamErrors { + byUp[e.Upstream] = e.Error + } + assert.Contains(t, byUp[tei.URL], "404") + assert.Contains(t, byUp[rerank.URL], "502") + assert.Contains(t, rec.Body.String(), `"upstreamErrors"`) +} + +func TestGateway_BaseURLFailure_ProviderDegradedAsBefore(t *testing.T) { + t.Parallel() + bad := statusServer(t, http.StatusNotFound) + good := modelsServer(t, `{"data":[{"id":"glm"}]}`, nil) + + cfg := newAdminTestConfig() + cfg.Providers = map[string]*ProviderConfig{ + "uni": { + Type: "openai", BaseURL: bad.URL, APIKey: "sk", Discovery: true, + Models: []string{"glm"}, + ModelBaseURLs: map[string]string{"glm": good.URL}, + }, + } + h, _ := newAdminGatewayHandle(t, cfg) + + rec := httptest.NewRecorder() + h.ServeHTTP(rec, adminRequest(http.MethodGet, adminOverviewPath, "sk-admin1")) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + var got adminOverviewResponse + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + require.Len(t, got.Providers, 1) + assert.Contains(t, got.Providers[0].LastErr, "404") + assert.Empty(t, got.Providers[0].UpstreamErrors) +}