Skip to content

Commit 0cb1f6b

Browse files
rdimitrovclaude
andauthored
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>
1 parent c5f50e8 commit 0cb1f6b

6 files changed

Lines changed: 465 additions & 5 deletions

File tree

internal/database/database.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ type Database interface {
5757
CheckVersionExists(ctx context.Context, tx pgx.Tx, serverName, version string) (bool, error)
5858
// UnmarkAsLatest marks the current latest version of a server as no longer latest
5959
UnmarkAsLatest(ctx context.Context, tx pgx.Tx, serverName string) error
60+
// SetLatestVersion sets is_latest=true on the given version and false on all other
61+
// versions of the same server. Passing an empty version clears is_latest for all rows.
62+
// Callers must hold the per-server publish lock to avoid races.
63+
SetLatestVersion(ctx context.Context, tx pgx.Tx, serverName, version string) error
6064
// AcquirePublishLock acquires an exclusive advisory lock for publishing a server
6165
// This prevents race conditions when multiple versions are published concurrently
6266
AcquirePublishLock(ctx context.Context, tx pgx.Tx, serverName string) error
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
-- Heal servers whose is_latest flag is on a deleted version (or missing entirely)
2+
-- by promoting the highest-semver non-deleted version. Falls back to published_at
3+
-- for non-semver versions and as a tiebreaker for prereleases.
4+
-- See https://github.com/modelcontextprotocol/registry/issues/1081.
5+
--
6+
-- The migration framework wraps each migration in its own transaction, so no explicit
7+
-- BEGIN/COMMIT here.
8+
9+
-- Pre-compute the version to promote per affected server. A temp table is used
10+
-- (rather than CTEs) because the two UPDATEs that follow run as separate statements:
11+
-- the unique partial index idx_unique_latest_per_server is non-deferrable and Postgres
12+
-- checks it row-by-row inside a single UPDATE, so the clear and the set must be split.
13+
CREATE TEMP TABLE _heal_picks ON COMMIT DROP AS
14+
WITH broken AS (
15+
-- Servers where no non-deleted version is flagged is_latest, but at least one
16+
-- non-deleted version exists. Catches "is_latest is on a deleted row" and the
17+
-- defensive case where no row has is_latest at all.
18+
SELECT server_name
19+
FROM servers
20+
GROUP BY server_name
21+
HAVING COUNT(*) FILTER (WHERE is_latest AND status <> 'deleted') = 0
22+
AND COUNT(*) FILTER (WHERE status <> 'deleted') > 0
23+
),
24+
parsed AS (
25+
SELECT s.server_name, s.version, s.published_at,
26+
(regexp_match(s.version, '^(\d+)\.(\d+)\.(\d+)'))[1]::int AS major,
27+
(regexp_match(s.version, '^(\d+)\.(\d+)\.(\d+)'))[2]::int AS minor,
28+
(regexp_match(s.version, '^(\d+)\.(\d+)\.(\d+)'))[3]::int AS patch
29+
FROM servers s
30+
JOIN broken b USING (server_name)
31+
WHERE s.status <> 'deleted'
32+
)
33+
SELECT DISTINCT ON (server_name) server_name, version
34+
FROM parsed
35+
ORDER BY server_name,
36+
major DESC NULLS LAST,
37+
minor DESC NULLS LAST,
38+
patch DESC NULLS LAST,
39+
published_at DESC;
40+
41+
-- Clear stale is_latest=true on rows of affected servers (typically the deleted row).
42+
UPDATE servers s
43+
SET is_latest = false
44+
WHERE s.server_name IN (SELECT server_name FROM _heal_picks)
45+
AND s.is_latest;
46+
47+
-- Promote the chosen version.
48+
UPDATE servers s
49+
SET is_latest = true
50+
FROM _heal_picks p
51+
WHERE s.server_name = p.server_name AND s.version = p.version;

internal/database/postgres.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -877,6 +877,40 @@ func (db *PostgreSQL) UnmarkAsLatest(ctx context.Context, tx pgx.Tx, serverName
877877
return nil
878878
}
879879

880+
// SetLatestVersion sets is_latest=true on the given version and false on all other versions
881+
// of the same server. Passing an empty version clears is_latest for all rows.
882+
//
883+
// The clear and set are issued as separate statements because the unique partial index
884+
// idx_unique_latest_per_server is non-deferrable and Postgres checks it row-by-row within
885+
// a single UPDATE, which would trip when flipping one row's flag off and another's on.
886+
func (db *PostgreSQL) SetLatestVersion(ctx context.Context, tx pgx.Tx, serverName, version string) error {
887+
if ctx.Err() != nil {
888+
return ctx.Err()
889+
}
890+
891+
executor := db.getExecutor(tx)
892+
893+
if _, err := executor.Exec(ctx,
894+
`UPDATE servers SET is_latest = false WHERE server_name = $1 AND is_latest = true AND version <> $2`,
895+
serverName, version,
896+
); err != nil {
897+
return fmt.Errorf("failed to clear previous latest version: %w", err)
898+
}
899+
900+
if version == "" {
901+
return nil
902+
}
903+
904+
if _, err := executor.Exec(ctx,
905+
`UPDATE servers SET is_latest = true WHERE server_name = $1 AND version = $2 AND is_latest = false`,
906+
serverName, version,
907+
); err != nil {
908+
return fmt.Errorf("failed to set latest version: %w", err)
909+
}
910+
911+
return nil
912+
}
913+
880914
// Close closes the database connection
881915
func (db *PostgreSQL) Close() error {
882916
db.pool.Close()

internal/database/postgres_test.go

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package database_test
33
import (
44
"context"
55
"fmt"
6+
"os"
67
"testing"
78
"time"
89

@@ -1734,6 +1735,152 @@ func TestPostgreSQL_IncludeDeletedFilter(t *testing.T) {
17341735
})
17351736
}
17361737

1738+
// TestMigration014_HealIsLatest exercises migrations/014_heal_is_latest.sql against
1739+
// synthetic broken states by re-running its SQL after seeding rows directly. The migration
1740+
// itself ran via the template DB; since it's idempotent (only matches servers with no
1741+
// non-deleted is_latest row), re-running it here only acts on the rows we just broke.
1742+
func TestMigration014_HealIsLatest(t *testing.T) {
1743+
db := database.NewTestDB(t)
1744+
ctx := context.Background()
1745+
1746+
migrationSQL, err := os.ReadFile("migrations/014_heal_is_latest.sql")
1747+
require.NoError(t, err)
1748+
1749+
createVersion := func(t *testing.T, name, version string, publishedAt time.Time, status model.Status, isLatest bool) {
1750+
t.Helper()
1751+
serverJSON := &apiv0.ServerJSON{
1752+
Schema: model.CurrentSchemaURL,
1753+
Name: name,
1754+
Description: "test",
1755+
Version: version,
1756+
}
1757+
officialMeta := &apiv0.RegistryExtensions{
1758+
Status: status,
1759+
StatusChangedAt: publishedAt,
1760+
PublishedAt: publishedAt,
1761+
UpdatedAt: publishedAt,
1762+
IsLatest: isLatest,
1763+
}
1764+
_, err := db.CreateServer(ctx, nil, serverJSON, officialMeta)
1765+
require.NoError(t, err)
1766+
}
1767+
1768+
runHeal := func(t *testing.T) {
1769+
t.Helper()
1770+
err := db.InTransaction(ctx, func(ctx context.Context, tx pgx.Tx) error {
1771+
_, err := tx.Exec(ctx, string(migrationSQL))
1772+
return err
1773+
})
1774+
require.NoError(t, err)
1775+
}
1776+
1777+
versionState := func(t *testing.T, name, version string) (model.Status, bool) {
1778+
t.Helper()
1779+
v, err := db.GetServerByNameAndVersion(ctx, nil, name, version, true)
1780+
require.NoError(t, err)
1781+
return v.Meta.Official.Status, v.Meta.Official.IsLatest
1782+
}
1783+
1784+
t.Run("kubernetes-mcp-server scenario picks highest semver", func(t *testing.T) {
1785+
name := "io.test/k8s-scenario"
1786+
base := time.Now().Add(-10 * time.Hour)
1787+
// 1.0.0 published first, then 0.0.50, 0.0.51, 0.0.59, 0.0.60, 0.0.61.
1788+
// 1.0.0 was the original latest and got soft-deleted, leaving is_latest stranded.
1789+
createVersion(t, name, "1.0.0", base, model.StatusDeleted, true)
1790+
createVersion(t, name, "0.0.50", base.Add(1*time.Hour), model.StatusActive, false)
1791+
createVersion(t, name, "0.0.51", base.Add(2*time.Hour), model.StatusActive, false)
1792+
createVersion(t, name, "0.0.59", base.Add(3*time.Hour), model.StatusActive, false)
1793+
createVersion(t, name, "0.0.60", base.Add(4*time.Hour), model.StatusActive, false)
1794+
createVersion(t, name, "0.0.61", base.Add(5*time.Hour), model.StatusActive, false)
1795+
1796+
runHeal(t)
1797+
1798+
_, isLatest := versionState(t, name, "1.0.0")
1799+
assert.False(t, isLatest, "deleted 1.0.0 should no longer be latest")
1800+
_, isLatest = versionState(t, name, "0.0.61")
1801+
assert.True(t, isLatest, "highest active version should become latest")
1802+
for _, v := range []string{"0.0.50", "0.0.51", "0.0.59", "0.0.60"} {
1803+
_, isLatest := versionState(t, name, v)
1804+
assert.False(t, isLatest, "version %s should not be latest", v)
1805+
}
1806+
})
1807+
1808+
t.Run("backport scenario picks highest semver not most recent", func(t *testing.T) {
1809+
// Published 2.0.0 (deleted), then 1.0.1 hotfix, then 1.0.0 (older patch backported later).
1810+
// Most-recent-published would pick 1.0.0; semver-aware picks 1.0.1.
1811+
name := "io.test/backport-scenario"
1812+
base := time.Now().Add(-10 * time.Hour)
1813+
createVersion(t, name, "2.0.0", base, model.StatusDeleted, true)
1814+
createVersion(t, name, "1.0.1", base.Add(1*time.Hour), model.StatusActive, false)
1815+
createVersion(t, name, "1.0.0", base.Add(2*time.Hour), model.StatusActive, false)
1816+
1817+
runHeal(t)
1818+
1819+
_, isLatest := versionState(t, name, "1.0.1")
1820+
assert.True(t, isLatest, "1.0.1 should win on semver despite 1.0.0 being published more recently")
1821+
_, isLatest = versionState(t, name, "1.0.0")
1822+
assert.False(t, isLatest)
1823+
})
1824+
1825+
t.Run("no is_latest row at all gets healed", func(t *testing.T) {
1826+
// Defensive case: nothing flagged latest, but active versions exist.
1827+
name := "io.test/no-latest-flag"
1828+
base := time.Now().Add(-10 * time.Hour)
1829+
createVersion(t, name, "1.0.0", base, model.StatusActive, false)
1830+
createVersion(t, name, "1.1.0", base.Add(1*time.Hour), model.StatusActive, false)
1831+
1832+
runHeal(t)
1833+
1834+
_, isLatest := versionState(t, name, "1.1.0")
1835+
assert.True(t, isLatest)
1836+
_, isLatest = versionState(t, name, "1.0.0")
1837+
assert.False(t, isLatest)
1838+
})
1839+
1840+
t.Run("all-deleted server is left untouched", func(t *testing.T) {
1841+
// No non-deleted version → nothing to promote, leave existing flags alone so the
1842+
// server remains addressable via includeDeleted=true admin lookups.
1843+
name := "io.test/all-deleted"
1844+
base := time.Now().Add(-10 * time.Hour)
1845+
createVersion(t, name, "1.0.0", base, model.StatusDeleted, true)
1846+
createVersion(t, name, "2.0.0", base.Add(1*time.Hour), model.StatusDeleted, false)
1847+
1848+
runHeal(t)
1849+
1850+
_, isLatest := versionState(t, name, "1.0.0")
1851+
assert.True(t, isLatest, "all-deleted server should keep its existing latest flag")
1852+
_, isLatest = versionState(t, name, "2.0.0")
1853+
assert.False(t, isLatest)
1854+
})
1855+
1856+
t.Run("healthy server is left untouched", func(t *testing.T) {
1857+
name := "io.test/healthy"
1858+
base := time.Now().Add(-10 * time.Hour)
1859+
createVersion(t, name, "1.0.0", base, model.StatusActive, false)
1860+
createVersion(t, name, "2.0.0", base.Add(1*time.Hour), model.StatusActive, true)
1861+
1862+
runHeal(t)
1863+
1864+
_, isLatest := versionState(t, name, "2.0.0")
1865+
assert.True(t, isLatest)
1866+
_, isLatest = versionState(t, name, "1.0.0")
1867+
assert.False(t, isLatest)
1868+
})
1869+
1870+
t.Run("non-semver versions fall back to published_at", func(t *testing.T) {
1871+
name := "io.test/non-semver"
1872+
base := time.Now().Add(-10 * time.Hour)
1873+
createVersion(t, name, "rolling", base, model.StatusDeleted, true)
1874+
createVersion(t, name, "build-100", base.Add(1*time.Hour), model.StatusActive, false)
1875+
createVersion(t, name, "build-200", base.Add(2*time.Hour), model.StatusActive, false)
1876+
1877+
runHeal(t)
1878+
1879+
_, isLatest := versionState(t, name, "build-200")
1880+
assert.True(t, isLatest, "without semver, most recently published wins")
1881+
})
1882+
}
1883+
17371884
// Helper functions for creating pointers to basic types
17381885
func stringPtr(s string) *string {
17391886
return &s

internal/service/registry_service.go

Lines changed: 75 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,59 @@ func (s *registryServiceImpl) createServerInTransaction(ctx context.Context, tx
164164
return s.db.CreateServer(ctx, tx, &serverJSON, officialMeta)
165165
}
166166

167+
// recalculateLatest picks the highest non-deleted version of the given server and flags it
168+
// as latest, clearing is_latest on every other row. If every version is deleted, the highest
169+
// deleted version keeps the flag so admin lookups (GetServerByName with includeDeleted=true)
170+
// still find the server. Caller must hold the per-server publish lock.
171+
func (s *registryServiceImpl) recalculateLatest(ctx context.Context, tx pgx.Tx, serverName string) error {
172+
versions, err := s.db.GetAllVersionsByServerName(ctx, tx, serverName, true)
173+
if err != nil {
174+
if errors.Is(err, database.ErrNotFound) {
175+
return s.db.SetLatestVersion(ctx, tx, serverName, "")
176+
}
177+
return fmt.Errorf("failed to load versions for latest recalculation: %w", err)
178+
}
179+
180+
winner := pickLatestVersion(versions, false)
181+
if winner == nil {
182+
// No non-deleted versions — fall back to highest deleted so the server is still
183+
// addressable via includeDeleted=true lookups.
184+
winner = pickLatestVersion(versions, true)
185+
}
186+
187+
winnerVersion := ""
188+
if winner != nil {
189+
winnerVersion = winner.Server.Version
190+
}
191+
return s.db.SetLatestVersion(ctx, tx, serverName, winnerVersion)
192+
}
193+
194+
// pickLatestVersion returns the highest version from the given slice. If allowDeleted is
195+
// false, deleted versions are skipped.
196+
func pickLatestVersion(versions []*apiv0.ServerResponse, allowDeleted bool) *apiv0.ServerResponse {
197+
var winner *apiv0.ServerResponse
198+
for _, v := range versions {
199+
if !allowDeleted && v.Meta.Official != nil && v.Meta.Official.Status == model.StatusDeleted {
200+
continue
201+
}
202+
if winner == nil {
203+
winner = v
204+
continue
205+
}
206+
var winnerPublishedAt, candidatePublishedAt time.Time
207+
if winner.Meta.Official != nil {
208+
winnerPublishedAt = winner.Meta.Official.PublishedAt
209+
}
210+
if v.Meta.Official != nil {
211+
candidatePublishedAt = v.Meta.Official.PublishedAt
212+
}
213+
if CompareVersions(v.Server.Version, winner.Server.Version, candidatePublishedAt, winnerPublishedAt) > 0 {
214+
winner = v
215+
}
216+
}
217+
return winner
218+
}
219+
167220
// validateNoDuplicateRemoteURLs checks that no other server is using the same remote URLs
168221
func (s *registryServiceImpl) validateNoDuplicateRemoteURLs(ctx context.Context, tx pgx.Tx, serverDetail apiv0.ServerJSON) error {
169222
// Check each remote URL in the new server for conflicts
@@ -237,11 +290,14 @@ func (s *registryServiceImpl) updateServerInTransaction(ctx context.Context, tx
237290

238291
// Handle status change if provided
239292
if statusChange != nil {
240-
updatedWithStatus, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage)
241-
if err != nil {
293+
if _, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage); err != nil {
242294
return nil, err
243295
}
244-
return updatedWithStatus, nil
296+
if err := s.recalculateLatest(ctx, tx, serverName); err != nil {
297+
return nil, err
298+
}
299+
// Re-read to pick up the possibly updated is_latest flag.
300+
return s.db.GetServerByNameAndVersion(ctx, tx, serverName, version, true)
245301
}
246302

247303
return updatedServerResponse, nil
@@ -279,7 +335,14 @@ func (s *registryServiceImpl) updateServerStatusInTransaction(ctx context.Contex
279335
}
280336

281337
// Update only the status metadata
282-
return s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage)
338+
if _, err := s.db.SetServerStatus(ctx, tx, serverName, version, statusChange.NewStatus, statusChange.StatusMessage); err != nil {
339+
return nil, err
340+
}
341+
if err := s.recalculateLatest(ctx, tx, serverName); err != nil {
342+
return nil, err
343+
}
344+
// Re-read to pick up the possibly updated is_latest flag.
345+
return s.db.GetServerByNameAndVersion(ctx, tx, serverName, version, true)
283346
}
284347

285348
// 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
319382
}
320383

321384
// Update all versions' status in a single database call
322-
return s.db.SetAllVersionsStatus(ctx, tx, serverName, statusChange.NewStatus, statusChange.StatusMessage)
385+
if _, err := s.db.SetAllVersionsStatus(ctx, tx, serverName, statusChange.NewStatus, statusChange.StatusMessage); err != nil {
386+
return nil, err
387+
}
388+
if err := s.recalculateLatest(ctx, tx, serverName); err != nil {
389+
return nil, err
390+
}
391+
// Re-read to pick up the possibly updated is_latest flags.
392+
return s.db.GetAllVersionsByServerName(ctx, tx, serverName, true)
323393
}

0 commit comments

Comments
 (0)