Fix atomic latest version update to prevent missing isLatest flags (#530)

## Summary
Fixes a race condition where a server could have no version marked as
`isLatest` if the database operations failed independently.

## Changes
- **CreateServer signature**: Now accepts `oldLatestVersionID` parameter
to atomically unmark previous latest version
- **PostgreSQL implementation**: Uses a transaction to ensure UPDATE
(unmark old latest) and INSERT (create new version) happen atomically
- **Service layer**: Maintains `WithPublishLock` for concurrent
operation serialization
- **Two-level protection**: Advisory lock prevents races, transaction
ensures atomicity

## Test plan
- [x] Existing race condition tests pass
- [x] Integration tests pass
- [x] Unit tests pass

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
adam jones 2025-09-24 18:27:36 +01:00 • committed by GitHub
commit 747ad310bb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -107,7 +107,7 @@ func TestValidateNoDuplicateRemoteURLs(t *testing.T) {
ctx := context.Background()
impl := service.(*registryServiceImpl)
err := impl.validateNoDuplicateRemoteURLs(ctx, tt.serverDetail)
err := impl.validateNoDuplicateRemoteURLs(ctx, nil, tt.serverDetail)
if tt.expectError {
assert.Error(t, err)
@ -384,7 +384,7 @@ func TestPublishConcurrentVersionsNoRace(t *testing.T) {
testDB := database.NewTestDB(t)
service := NewRegistryService(testDB, &config.Config{EnableRegistryValidation: false})
const concurrency = 1 // @Maintainers: Fix this and increase to higher number, previously 100
const concurrency = 100
results := make([]*apiv0.ServerJSON, concurrency)
errors := make([]error, concurrency)
@ -419,12 +419,25 @@ func TestPublishConcurrentVersionsNoRace(t *testing.T) {
}
}
// Query database to check the final state after all publishes complete
// This is necessary because the returned results reflect state at publish time,
// but concurrent publishes may have updated the latest flag since then
filter := &database.ServerFilter{Name: strPtr("com.example/test-concurrent")}
dbResults, _, err := testDB.List(context.Background(), nil, filter, "", 1000)
assert.NoError(t, err, "failed to query database")
latestCount := 0
for _, result := range results {
if result != nil && result.Meta != nil && result.Meta.Official != nil &&
result.Meta.Official.IsLatest {
var latestVersion string
for _, r := range dbResults {
if r.Meta != nil && r.Meta.Official != nil && r.Meta.Official.IsLatest {
latestCount++
latestVersion = r.Version
}
}
assert.Equal(t, 1, latestCount, "should have exactly one latest version")
assert.Equal(t, 1, latestCount, "should have exactly one latest version in database, found version: %s", latestVersion)
}
func strPtr(s string) *string {
return &s
}