diff --git a/CHANGELOG.md b/CHANGELOG.md index c413b6aaa6..d08806add6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — alias validation recovery + +- Return a server error before changing model aliases when namespace, rollout-history or build validation reads fail. Preserve existing alias ownership and retired-build lineage through transient store errors. + ## Release candidate v0.9.2 — Gemma QAT caching, adaptive MTP and Nemotron Lightning (not shipped; 2026-09-10) Source changes since `v0.9.1`. Provider changes require a new signed bundle. diff --git a/coordinator/api/model_alias_handlers.go b/coordinator/api/model_alias_handlers.go index 525e805404..cb964f34f0 100644 --- a/coordinator/api/model_alias_handlers.go +++ b/coordinator/api/model_alias_handlers.go @@ -2,6 +2,7 @@ package api import ( "encoding/json" + "errors" "net/http" "strings" @@ -79,9 +80,20 @@ func (s *Server) handleModelAliasUpsert(w http.ResponseWriter, r *http.Request) // name itself as a member. `takeover` is the deliberate exception for the // public-name migration: an alias adopts the name of an existing concrete // model and absorbs that same-named build as its previous_build (fallback). - collidingRec, _ := s.store.GetModelRegistryRecord(req.AliasID) + collidingRec, err := s.store.GetModelRegistryRecord(req.AliasID) + if err != nil && !errors.Is(err, store.ErrNotFound) { + writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to check model namespace")) + return + } idCollision := collidingRec != nil - prior := s.priorAlias(req.AliasID) + prior, found, err := s.store.GetModelAlias(req.AliasID) + if err != nil { + writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to get alias")) + return + } + if !found { + prior = nil + } if prior != nil && prior.OpenRouterOnly { writeJSON(w, http.StatusConflict, errorResponse("invalid_request_error", "alias_id belongs to the dedicated OpenRouter alias endpoint", withParam("alias_id"))) return @@ -117,15 +129,21 @@ func (s *Server) handleModelAliasUpsert(w http.ResponseWriter, r *http.Request) return } // Both builds must be registered models so we never alias to a phantom id. - if rec, err := s.store.GetModelRegistryRecord(req.DesiredBuild); err != nil || rec == nil { - writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", - "desired_build "+req.DesiredBuild+" is not a registered model", withParam("desired_build"))) - return - } - if req.PreviousBuild != "" { - if rec, err := s.store.GetModelRegistryRecord(req.PreviousBuild); err != nil || rec == nil { + for _, member := range []struct{ field, id string }{ + {"desired_build", req.DesiredBuild}, + {"previous_build", req.PreviousBuild}, + } { + if member.id == "" { + continue + } + rec, err := s.store.GetModelRegistryRecord(member.id) + if err != nil && !errors.Is(err, store.ErrNotFound) { + writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to get alias member")) + return + } + if rec == nil { writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", - "previous_build "+req.PreviousBuild+" is not a registered model", withParam("previous_build"))) + member.field+" "+member.id+" is not a registered model", withParam(member.field))) return } } @@ -183,17 +201,6 @@ const maxAliasIDLength = 128 // are dropped first once a (pathologically) churned alias exceeds it. const maxRetiredBuilds = 16 -// priorAlias fetches the existing alias definition, or nil when none exists -// (or the store errored — treated as "no prior" since upsert will surface real -// store failures itself). -func (s *Server) priorAlias(aliasID string) *store.ModelAlias { - prior, found, err := s.store.GetModelAlias(aliasID) - if err != nil || !found { - return nil - } - return prior -} - // retiredBuildsAfterUpsert computes the alias's lineage after an upsert: prior // retired builds, plus any prior desired/previous member rotated out by the new // pointers, minus any build the new pointers re-promote to membership. Bounded diff --git a/coordinator/api/model_alias_read_errors_test.go b/coordinator/api/model_alias_read_errors_test.go new file mode 100644 index 0000000000..c24a6b2d04 --- /dev/null +++ b/coordinator/api/model_alias_read_errors_test.go @@ -0,0 +1,132 @@ +package api + +import ( + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync/atomic" + "testing" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// A failed lookup can be transient: a following write may succeed. Keep the +// underlying store available so this test detects destructive fall-through. +type aliasReadErrorStore struct { + store.Store + aliasID string + recordID string +} + +func (s *aliasReadErrorStore) GetModelAlias(id string) (*store.ModelAlias, bool, error) { + if id == s.aliasID { + return nil, false, errors.New("temporary alias read failure") + } + return s.Store.GetModelAlias(id) +} + +func (s *aliasReadErrorStore) GetModelRegistryRecord(id string) (*store.ModelRegistryRecord, error) { + if id == s.recordID { + return nil, errors.New("temporary model read failure") + } + return s.Store.GetModelRegistryRecord(id) +} + +func TestAliasUpsertReadFailurePreservesStoredState(t *testing.T) { + t.Setenv("MODEL_REGISTRY_PUBLISHING_KEY", "publish-secret") + for _, tc := range []struct { + name, path, body, aliasID, recordID string + openRouterOnly bool + }{ + {"rollout history", "aliases", `{"alias_id":"public","desired_build":"next"}`, "public", "", false}, + {"OpenRouter ownership", "aliases", `{"alias_id":"public","desired_build":"next"}`, "public", "", true}, + {"standard namespace", "aliases", `{"alias_id":"concrete","desired_build":"next"}`, "", "concrete", false}, + {"OpenRouter namespace", "openrouter-aliases", `{"id":"concrete","source_model":"source","openrouter_slug":"vendor/model","hugging_face_id":"vendor/model"}`, "", "concrete", false}, + {"desired build", "aliases", `{"alias_id":"public","desired_build":"next"}`, "", "next", false}, + {"previous build", "aliases", `{"alias_id":"public","desired_build":"next","previous_build":"current"}`, "", "current", false}, + } { + t.Run(tc.name, func(t *testing.T) { + memory := store.NewMemory(store.Config{}) + for _, id := range []string{"next", "current", "retired", "concrete"} { + seedActiveModel(t, memory, id, id) + } + for _, alias := range []*store.ModelAlias{ + {AliasID: "source", DesiredBuild: "current", Active: true}, + {AliasID: "public", DesiredBuild: "current", RetiredBuilds: []string{"retired"}, Active: true, + OpenRouterOnly: tc.openRouterOnly, SourceModel: "source"}, + } { + if err := memory.UpsertModelAlias(alias); err != nil { + t.Fatal(err) + } + } + before, err := memory.ListModelAliases() + if err != nil { + t.Fatal(err) + } + st := &aliasReadErrorStore{Store: memory, aliasID: tc.aliasID, recordID: tc.recordID} + srv := NewServer(registry.New(slog.Default()), st, ServerConfig{}, slog.Default()) + req := httptest.NewRequest(http.MethodPost, "/v1/admin/models/"+tc.path, strings.NewReader(tc.body)) + req.Header.Set("Authorization", "Bearer publish-secret") + rec := httptest.NewRecorder() + srv.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusInternalServerError { + t.Errorf("status = %d, want 500; body = %s", rec.Code, rec.Body.String()) + } + after, err := memory.ListModelAliases() + if err != nil || !reflect.DeepEqual(before, after) { + t.Errorf("failed lookup changed aliases: before=%+v after=%+v err=%v", before, after, err) + } + }) + } +} + +func TestRegisterModelAliasReadFailurePreservesNamespace(t *testing.T) { + t.Setenv("MODEL_REGISTRY_PUBLISHING_KEY", "publish-secret") + const id = "mlx-community/test" + memory := store.NewMemory(store.Config{}) + seedActiveModel(t, memory, "current", "current") + prior := &store.ModelAlias{AliasID: id, DesiredBuild: "current", Active: true} + if err := memory.UpsertModelAlias(prior); err != nil { + t.Fatal(err) + } + var fetches atomic.Int64 + prefix := modelR2Prefix(id, "v1") + cdn := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fetches.Add(1) + switch r.URL.Path { + case "/" + prefix + "/manifest.json": + writeJSON(w, http.StatusOK, validTestManifest()) + case "/" + prefix + "/config.json": + w.Header().Set("Content-Length", "123") + w.WriteHeader(http.StatusOK) + default: + http.NotFound(w, r) + } + })) + defer cdn.Close() + t.Setenv("MODEL_REGISTRY_CDN_BASE_URL", cdn.URL) + srv := NewServer(registry.New(slog.Default()), &aliasReadErrorStore{Store: memory, aliasID: id}, ServerConfig{}, slog.Default()) + defer srv.Close() + body := `{"model_id":"mlx-community/test","version":"v1","quantization":"4bit","max_context_length":32768,"max_output_length":8192,"min_ram_gb":16,"input_price":50000,"output_price":200000,"promote":true}` + req := httptest.NewRequest(http.MethodPost, "/v1/admin/models/register", strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer publish-secret") + response := httptest.NewRecorder() + srv.Handler().ServeHTTP(response, req) + if response.Code != http.StatusInternalServerError { + t.Errorf("status=%d want500: %s", response.Code, response.Body.String()) + } + if fetches.Load() != 0 { + t.Errorf("namespace read failure fetched %d artifacts", fetches.Load()) + } + if rec, err := memory.GetModelRegistryRecord(id); !errors.Is(err, store.ErrNotFound) { + t.Errorf("concrete record created after lookup failure: %+v err=%v", rec, err) + } + after, found, err := memory.GetModelAlias(id) + if err != nil || !found || after.DesiredBuild != prior.DesiredBuild { + t.Errorf("existing alias changed: %+v found=%v err=%v", after, found, err) + } +} diff --git a/coordinator/api/model_registry_handlers.go b/coordinator/api/model_registry_handlers.go index a97449f820..5153c3de16 100644 --- a/coordinator/api/model_registry_handlers.go +++ b/coordinator/api/model_registry_handlers.go @@ -97,7 +97,10 @@ func (s *Server) handleRegisterModel(w http.ResponseWriter, r *http.Request) { // Reverse namespace guard (mirror of the alias upsert's collision check): a // concrete model id must not collide with an existing public alias, or the // alias map would hijack raw-id requests for the new model at resolution. - if _, found, err := s.store.GetModelAlias(req.ModelID); err == nil && found { + if _, found, err := s.store.GetModelAlias(req.ModelID); err != nil { + writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to check model alias namespace")) + return + } else if found { writeJSON(w, http.StatusConflict, errorResponse("invalid_request_error", "model_id collides with an existing public alias", withParam("model_id"))) return diff --git a/coordinator/api/openrouter_alias_handlers.go b/coordinator/api/openrouter_alias_handlers.go index 35b2b3fd5c..024519289a 100644 --- a/coordinator/api/openrouter_alias_handlers.go +++ b/coordinator/api/openrouter_alias_handlers.go @@ -2,6 +2,7 @@ package api import ( "encoding/json" + "errors" "net/http" "strings" @@ -97,7 +98,10 @@ func (s *Server) handleOpenRouterAliasUpsert(w http.ResponseWriter, r *http.Requ writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", "source_model must be an active standard alias or concrete catalog model", withParam("source_model"))) return } - if rec, _ := s.store.GetModelRegistryRecord(req.ID); rec != nil { + if rec, err := s.store.GetModelRegistryRecord(req.ID); err != nil && !errors.Is(err, store.ErrNotFound) { + writeJSON(w, http.StatusInternalServerError, errorResponse("internal_error", "failed to check model namespace")) + return + } else if rec != nil { writeJSON(w, http.StatusConflict, errorResponse("invalid_request_error", "id collides with an existing model id", withParam("id"))) return } diff --git a/docs/architecture/model-registry.md b/docs/architecture/model-registry.md index 27f94bc48c..35d1cdd6bc 100644 --- a/docs/architecture/model-registry.md +++ b/docs/architecture/model-registry.md @@ -1,6 +1,6 @@ # Model registry -> Last updated: 2026-09-06 · commit `32b28b0a7` +> Last updated: 2026-09-11 · commit `88e9baeed` How Darkbloom decides which model builds exist, which bytes are trusted, which providers may serve them, and what public name a consumer uses for them. The @@ -235,6 +235,18 @@ the budget. `DesiredModelsForProvider` (already a member of the alias, capable of the build) gate every send. +9. **Namespace validation reads must succeed before registration or an alias upsert.** + `handleModelAliasUpsert` preserves stored rollout lineage and endpoint + ownership when `GetModelAlias` fails. Both it and + `handleOpenRouterAliasUpsert` abort on namespace lookup errors other than + `store.ErrNotFound`; a failed desired/previous build lookup returns 500, + while a confirmed missing member remains 400 + (`coordinator/api/model_alias_handlers.go`, + `coordinator/api/openrouter_alias_handlers.go`). The reverse guard in + `handleRegisterModel` returns 500 when its alias lookup fails, before + fetching artifacts or writing a concrete model + (`coordinator/api/model_registry_handlers.go`). + ## Failure modes | Symptom | Cause | Where to look | diff --git a/docs/reference/api-contracts.md b/docs/reference/api-contracts.md index 8f67cb25aa..56036f1158 100644 --- a/docs/reference/api-contracts.md +++ b/docs/reference/api-contracts.md @@ -1,6 +1,6 @@ # HTTP API contracts -> Last updated: 2026-09-09 · commit `884d97862` +> Last updated: 2026-09-11 · commit `88e9baeed` The complete public HTTP surface of the coordinator, derived from the 108 `HandleFunc` registrations in `routes()` (`coordinator/api/server.go`), including the `/v1/` catch-all. Every route is listed once below with its handler symbol, authentication requirement, and rate-limit bucket; the second half of the page gives the wire shapes, headers, error table, SSE framing, limits, timeouts, and version-gate semantics that those routes share. For *why* the pipeline is built this way see [`../architecture/components/consumer.md`](../architecture/components/consumer.md); for the crypto model behind sealed transport see [`../architecture/security/encryption.md`](../architecture/security/encryption.md). @@ -210,11 +210,11 @@ Release publishing: [`../operations/provider-release.md`](../operations/provider | PUT | `/v1/admin/pricing` | `handleAdminPricing` (`coordinator/api/billing_handlers.go`) | `admin` | Platform default price table | | PUT | `/v1/admin/users/role` | `handleAdminSetUserRole` (`coordinator/api/billing_handlers.go`) | `admin` | Role selects the consumer or service limiter | | PUT | `/v1/admin/users/platform-fee` | `handleAdminSetUserPlatformFee` (`coordinator/api/billing_handlers.go`) | `admin` | Per-user fee override; fee policy in [`../architecture/billing.md#invariants`](../architecture/billing.md#invariants) | -| POST | `/v1/admin/models/register` | `handleRegisterModel` (`coordinator/api/model_registry_handlers.go`) | `publishing` | Publish a model build | +| POST | `/v1/admin/models/register` | `handleRegisterModel` (`coordinator/api/model_registry_handlers.go`) | `publishing` | Publish a model build; a failed alias namespace lookup returns 500 before artifact fetches or writes | | POST | `/v1/admin/models/` | `handleAdminModelRegistryAction` (`coordinator/api/model_registry_handlers.go`) | `publishing` | Registry actions selected by path suffix | -| GET / POST | `/v1/admin/models/aliases` | `handleModelAliasList`, `handleModelAliasUpsert` (`coordinator/api/model_alias_handlers.go`) | `publishing` | Two registrations; upserts fan out `desired_models` (see [Version gating](#version-gating)) | +| GET / POST | `/v1/admin/models/aliases` | `handleModelAliasList`, `handleModelAliasUpsert` (`coordinator/api/model_alias_handlers.go`) | `publishing` | Two registrations; upserts fan out `desired_models` (see [Version gating](#version-gating)). Failed namespace, prior-alias or member reads return 500 before writing; missing members remain 400 | | DELETE | `/v1/admin/models/aliases/{aliasID}` | `handleModelAliasDelete` (`coordinator/api/model_alias_handlers.go`) | `publishing` | | -| GET / POST | `/v1/admin/models/openrouter-aliases` | `handleOpenRouterAliasList`, `handleOpenRouterAliasUpsert` (`coordinator/api/openrouter_alias_handlers.go`) | `publishing` | Two registrations | +| GET / POST | `/v1/admin/models/openrouter-aliases` | `handleOpenRouterAliasList`, `handleOpenRouterAliasUpsert` (`coordinator/api/openrouter_alias_handlers.go`) | `publishing` | Two registrations; a failed namespace lookup returns 500 before writing | | DELETE | `/v1/admin/models/openrouter-aliases/{aliasID}` | `handleOpenRouterAliasDelete` (`coordinator/api/openrouter_alias_handlers.go`) | `publishing` | | | GET / DELETE | `/v1/admin/releases` | `handleAdminListReleases`, `handleAdminDeleteRelease` (`coordinator/api/release_handlers.go`) | `admin-key` | Two registrations | | GET | `/v1/admin/state-export` | `handleAdminStateExport` (`coordinator/api/admin_state_export.go`) | `admin-key` | 404 unless `EIGENINFERENCE_STATE_EXPORT_ENABLED=true`; 412 `precondition_failed` without an encryption recipient. See [`../operations/state-export.md`](../operations/state-export.md) |