fix: recalculate isLatest after status changes (#1081) (#1201)

## Summary

Fixes #1081. When the version flagged `is_latest` was soft-deleted, no
other version was promoted, and because `GetCurrentLatestVersion` didn't
filter deleted rows, subsequent publishes with a lower semver never
became latest — leaving `/v0/servers/{name}/versions/latest` permanently
404.

This PR has two parts:

### 1. Code fix — recalculate `is_latest` on every status change

- Recalculate `is_latest` after every status mutation
(`UpdateServerStatus`, `UpdateAllVersionsStatus`, and the inline status
change in `UpdateServer`), in the same transaction that already holds
the per-server advisory lock.
- Winner selection reuses the existing `CompareVersions` logic: highest
non-deleted version gets the flag; if every version is deleted, the
highest deleted version keeps it so admin lookups via
`includeDeleted=true` still resolve the server (important for restore
flows).
- New `SetLatestVersion` DB primitive issues two statements (clear old,
set new) — `idx_unique_latest_per_server` is a non-deferrable unique
partial index, so a single `UPDATE` that flips two rows trips the
constraint.

### 2. One-shot migration — heal servers already affected (no manual SQL
needed)

`014_heal_is_latest.sql` promotes the highest non-deleted version on
every server whose `is_latest` flag is on a deleted row (or absent
entirely). Picker parses `major.minor.patch` numerically and falls back
to `published_at` for non-semver or as a tiebreaker. Heals
`io.github.containers/kubernetes-mcp-server` to `0.0.61` automatically
and catches any other servers silently affected by the original bug,
without hardcoded version numbers.

Picker behavior vs. `CompareVersions`:
- Standard `M.m.p` semver: matches exactly, including the
backport-after-delete case (e.g. published 1.0.1 then 1.0.0 hotfix after
deleting 2.0.0 → picks 1.0.1, not 1.0.0).
- Non-semver: falls through to `published_at DESC`. Reasonable.
- Prereleases (`1.0.0-alpha` vs `1.0.0`): both parse to `(1,0,0)`,
tiebreak by `published_at`. Diverges from `CompareVersions` (which
always says `1.0.0 > 1.0.0-alpha`). Edge case requires (a) server hit by
this bug AND (b) prereleases at the top of the version list. Acceptable;
the publisher can flip it with one `mcp-publisher status` call (which
now triggers proper recalc thanks to part 1).

## Verification

End-to-end curl repro of the exact scenario from the issue, run against
both `main` and this branch:

**Before (main):**
```
publish 1.0.0 → 200
publish 0.0.59 → 200
PATCH .../1.0.0/status {deleted} → 200
GET /versions/latest → 404            ← bug
publish 0.0.60 → 200
GET /versions/latest → 404            ← bug persists, 0.0.60 has isLatest=False
```

**After (this branch):**
```
publish 1.0.0 → 200
publish 0.0.59 → 200
PATCH .../1.0.0/status {deleted} → 200
GET /versions/latest → 200 (0.0.59, isLatest=true)
publish 0.0.60 → 200
GET /versions/latest → 200 (0.0.60, isLatest=true)
```

## Test plan

- [x] Service tests covering: soft-delete latest → next highest active
promoted; the exact #1081 repro end-to-end through the service;
all-versions-deleted still keeps highest addressable for admin;
restore-to-higher-version reclaims latest.
- [x] Migration tests covering: kubernetes-mcp-server scenario (heals to
highest semver); backport scenario (semver beats most-recent-published);
no-is_latest-row defensive case; all-deleted server left untouched;
healthy server left untouched; non-semver versions fall back to
`published_at`.
- [x] Full unit test suite (`./internal/... ./cmd/...`) passes against a
real Postgres.
- [x] `make lint` (0 issues) and `make validate` pass.
- [x] Manual curl repro against a running registry confirms the fix
resolves the failure mode and `main` still reproduces it.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Radoslav Dimitrov 2026-04-25 11:59:28 -04:00 • committed by GitHub
commit 0cb1f6bf52
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 465 additions and 5 deletions

View file

@ -164,6 +164,59 @@ func (s *registryServiceImpl) createServerInTransaction(ctx context.Context, tx
return s.db.CreateServer(ctx, tx, &serverJSON, officialMeta)
}
// recalculateLatest picks the highest non-deleted version of the given server and flags it
// as latest, clearing is_latest on every other row. If every version is deleted, the highest
// deleted version keeps the flag so admin lookups (GetServerByName with includeDeleted=true)
// still find the server. Caller must hold the per-server publish lock.
func (s *registryServiceImpl) recalculateLatest(ctx context.Context, tx pgx.Tx, serverName string) error {
versions, err := s.db.GetAllVersionsByServerName(ctx, tx, serverName, true)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
return s.db.SetLatestVersion(ctx, tx, serverName, "")
}
return fmt.Errorf("failed to load versions for latest recalculation: %w", err)
}
winner := pickLatestVersion(versions, false)
if winner == nil {
// No non-deleted versions — fall back to highest deleted so the server is still
// addressable via includeDeleted=true lookups.
winner = pickLatestVersion(versions, true)
}
winnerVersion := ""
if winner != nil {
winnerVersion = winner.Server.Version
}
return s.db.SetLatestVersion(ctx, tx, serverName, winnerVersion)
}
// pickLatestVersion returns the highest version from the given slice. If allowDeleted is
// false, deleted versions are skipped.
func pickLatestVersion(versions []*apiv0.ServerResponse, allowDeleted bool) *apiv0.ServerResponse {
var winner *apiv0.ServerResponse
for _, v := range versions {
if !allowDeleted && v.Meta.Official != nil && v.Meta.Official.Status == model.StatusDeleted {
continue
}
if winner == nil {
winner = v
continue
}
var winnerPublishedAt, candidatePublishedAt time.Time
if winner.Meta.Official != nil {
winnerPublishedAt = winner.Meta.Official.PublishedAt
}
if v.Meta.Official != nil {
candidatePublishedAt = v.Meta.Official.PublishedAt
}
if CompareVersions(v.Server.Version, winner.Server.Version, candidatePublishedAt, winnerPublishedAt) > 0 {
winner = v
}
}
return winner
}
// validateNoDuplicateRemoteURLs checks that no other server is using the same remote URLs
func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context, tx pgx.Tx, serverDetail apiv0.ServerJSON) error {
// Check each remote URL in the new server for conflicts
@ -237,11 +290,14 @@ func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx
// Handle status change if provided
if statusChange != nil {
updatedWithStatus, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage)
if err != nil {
if _, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage); err != nil {
return nil, err
}
return updatedWithStatus, nil
if err := s.recalculateLatest(ctx, tx, serverName); err != nil {
return nil, err
}
// Re-read to pick up the possibly updated is_latest flag.
return s.db.GetServerByNameAndVersion(ctx, tx, serverName, version, true)
}
return updatedServerResponse, nil
@ -279,7 +335,14 @@ func (s *registryServiceImpl) updateServerStatusInTransaction(ctx context.Contex
}
// Update only the status metadata
return s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage)
if _, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage); err != nil {
return nil, err
}
if err := s.recalculateLatest(ctx, tx, serverName); err != nil {
return nil, err
}
// Re-read to pick up the possibly updated is_latest flag.
return s.db.GetServerByNameAndVersion(ctx, tx, serverName, version, true)
}
// UpdateAllVersionsStatus updates the status metadata of all versions of a server in a single transaction
@ -319,5 +382,12 @@ func (s *registryServiceImpl) updateAllVersionsStatusInTransaction(ctx context.C
}
// Update all versions' status in a single database call
return s.db.SetAllVersionsStatus(ctx, tx, serverName, statusChange.NewStatus, statusChange.StatusMessage)
if _, err := s.db.SetAllVersionsStatus(ctx, tx, serverName, statusChange.NewStatus, statusChange.StatusMessage); err != nil {
return nil, err
}
if err := s.recalculateLatest(ctx, tx, serverName); err != nil {
return nil, err
}
// Re-read to pick up the possibly updated is_latest flags.
return s.db.GetAllVersionsByServerName(ctx, tx, serverName, true)
}

View file

@ -982,6 +982,160 @@ func TestUpdateServerStatus_NoConflictWhenRestoringWithUniqueURLs(t *testing.T)
assert.Equal(t, model.StatusActive, result.Meta.Official.Status)
}
func TestRecalculateLatest_PromotesNextHighestWhenLatestSoftDeleted(t *testing.T) {
ctx := context.Background()
testDB := database.NewTestDB(t)
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
serverName := "com.example/delete-latest-server"
// Publish 1.0.0, then 0.0.59. 1.0.0 is latest.
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v1", Version: "1.0.0",
})
require.NoError(t, err)
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v0.0.59", Version: "0.0.59",
})
require.NoError(t, err)
// Soft-delete 1.0.0.
_, err = service.UpdateServerStatus(ctx, serverName, "1.0.0", &StatusChangeRequest{
NewStatus: model.StatusDeleted,
})
require.NoError(t, err)
// 0.0.59 should now be latest.
latest, err := service.GetServerByName(ctx, serverName, false)
require.NoError(t, err)
assert.Equal(t, "0.0.59", latest.Server.Version)
assert.True(t, latest.Meta.Official.IsLatest)
}
func TestRecalculateLatest_ReproFromIssue1081(t *testing.T) {
ctx := context.Background()
testDB := database.NewTestDB(t)
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
serverName := "com.example/issue-1081-repro"
// 1. Publish 1.0.0.
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v1", Version: "1.0.0",
})
require.NoError(t, err)
// 2. Publish 0.0.59 — expected not latest at this point.
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v0.0.59", Version: "0.0.59",
})
require.NoError(t, err)
// 3. Delete 1.0.0.
_, err = service.UpdateServerStatus(ctx, serverName, "1.0.0", &StatusChangeRequest{
NewStatus: model.StatusDeleted,
})
require.NoError(t, err)
// 4. /versions/latest must not 404.
latest, err := service.GetServerByName(ctx, serverName, false)
require.NoError(t, err)
assert.Equal(t, "0.0.59", latest.Server.Version)
// 5. Publish 0.0.60 — should become latest because compare now excludes deleted 1.0.0.
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v0.0.60", Version: "0.0.60",
})
require.NoError(t, err)
latest, err = service.GetServerByName(ctx, serverName, false)
require.NoError(t, err)
assert.Equal(t, "0.0.60", latest.Server.Version)
assert.True(t, latest.Meta.Official.IsLatest)
// Only one row should be flagged latest.
all, err := service.GetAllVersionsByServerName(ctx, serverName, true)
require.NoError(t, err)
latestCount := 0
for _, v := range all {
if v.Meta.Official.IsLatest {
latestCount++
}
}
assert.Equal(t, 1, latestCount)
}
func TestRecalculateLatest_AllDeletedKeepsHighestAsLatest(t *testing.T) {
ctx := context.Background()
testDB := database.NewTestDB(t)
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
serverName := "com.example/all-deleted-server"
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v1", Version: "1.0.0",
})
require.NoError(t, err)
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v2", Version: "2.0.0",
})
require.NoError(t, err)
// Delete all versions in one call.
_, err = service.UpdateAllVersionsStatus(ctx, serverName, &StatusChangeRequest{
NewStatus: model.StatusDeleted,
})
require.NoError(t, err)
// Public lookup (includeDeleted=false) must now 404.
_, err = service.GetServerByName(ctx, serverName, false)
require.ErrorIs(t, err, database.ErrNotFound)
// Admin lookup (includeDeleted=true) must still find the server: the highest deleted
// version keeps is_latest=true so the server remains addressable for restore flows.
latest, err := service.GetServerByName(ctx, serverName, true)
require.NoError(t, err)
assert.Equal(t, "2.0.0", latest.Server.Version)
assert.True(t, latest.Meta.Official.IsLatest)
}
func TestRecalculateLatest_RestoringHigherVersionPromotesIt(t *testing.T) {
ctx := context.Background()
testDB := database.NewTestDB(t)
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
serverName := "com.example/restore-server"
// Publish 2.0.0 and 1.0.0 — 2.0.0 is latest.
_, err := service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v2", Version: "2.0.0",
})
require.NoError(t, err)
_, err = service.CreateServer(ctx, &apiv0.ServerJSON{
Schema: model.CurrentSchemaURL, Name: serverName, Description: "v1", Version: "1.0.0",
})
require.NoError(t, err)
// Delete 2.0.0 — 1.0.0 gets promoted.
_, err = service.UpdateServerStatus(ctx, serverName, "2.0.0", &StatusChangeRequest{
NewStatus: model.StatusDeleted,
})
require.NoError(t, err)
latest, err := service.GetServerByName(ctx, serverName, false)
require.NoError(t, err)
require.Equal(t, "1.0.0", latest.Server.Version)
// Restore 2.0.0 — it should reclaim latest.
_, err = service.UpdateServerStatus(ctx, serverName, "2.0.0", &StatusChangeRequest{
NewStatus: model.StatusActive,
})
require.NoError(t, err)
latest, err = service.GetServerByName(ctx, serverName, false)
require.NoError(t, err)
assert.Equal(t, "2.0.0", latest.Server.Version)
assert.True(t, latest.Meta.Official.IsLatest)
}
// Helper functions
func stringPtr(s string) *string {
return &s