carlos / platform Public

retire-app-lock-407: console record writes and the canary retire's final section share the app lock (WIP)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 32cb2b1571dc58cacbd077a43f85ee88a749f54d parent 5634538
12 files changed, +272 −21
  • internal/console/apiinstances.go +1 −1
  • internal/console/appsettings.go +2 −2
  • internal/console/channelmove.go +2 −3
  • internal/console/domainattach.go +1 −1
  • internal/console/hostsused.go +2 −0
  • internal/console/record_write_lock_test.go +203 −0
  • internal/console/recordlock.go +31 −0
  • internal/console/remoteinstances.go +3 −2
  • internal/console/server.go +18 −10
  • internal/console/server_test.go +1 −0
  • internal/console/updatescore.go +2 −2
  • internal/console/view_test.go +6 −0
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index ab11b4593..7d4ed1275 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -2391,7 +2391,7 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
// writer: nothing here hand-builds an object body, so upstream ORDER —
// which the reconcile pass's shapeMismatch compares verbatim against the
// registry's joined column — lands exactly as the caller stated it.
- if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil {
+ if err := s.updateRecordLocked(ctx, *rec, etag); err != nil {
if errors.Is(err, release.ErrCASConflict) {
jsonError(w, http.StatusConflict,
"instance "+host+" changed while this request was in flight — read it again and re-apply")
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index fbbe08ab9..d03f2f455 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -1119,7 +1119,7 @@ func (s *Server) handleAppGate(w http.ResponseWriter, r *http.Request) {
back("err", err.Error()+".")
return
}
- if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil {
+ if err := s.updateRecordLocked(ctx, *rec, etag); err != nil {
if errors.Is(err, release.ErrCASConflict) {
back("err", "The instance changed while this request was in flight — try again.")
return
@@ -1246,7 +1246,7 @@ func (s *Server) handleAppRateLimit(w http.ResponseWriter, r *http.Request) {
back("err", rateLimitFailedCopy)
return
}
- if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil {
+ if err := s.updateRecordLocked(ctx, *rec, etag); err != nil {
log.Printf("console: rate limit write %s/%s/%s: %v", acct.Sqid, app, host, err)
back("err", rateLimitFailedCopy)
return
diff --git a/internal/console/channelmove.go b/internal/console/channelmove.go
index c41024a4a..fb07f7bd4 100644
--- a/internal/console/channelmove.go
+++ b/internal/console/channelmove.go
@@ -28,7 +28,6 @@ import (
"os"
"strings"
- "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -175,7 +174,7 @@ func (s *Server) handleAPIInstanceChannel(w http.ResponseWriter, r *http.Request
return
}
rec.Channel = to
- if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil {
+ if err := s.updateRecordLocked(ctx, *rec, etag); err != nil {
if errors.Is(err, release.ErrCASConflict) {
jsonError(w, http.StatusConflict, "this instance changed while the request was in flight — try again")
return
@@ -217,7 +216,7 @@ func (s *Server) executePendingRouteChannel(ctx context.Context, acct *Account,
return "", staleProposal("the instance is on " + rec.Channel + " now")
}
rec.Channel = p.To
- if err := provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag); err != nil {
+ if err := s.updateRecordLocked(ctx, *rec, etag); err != nil {
log.Printf("console: execute route-channel %s/%s/%s: %v", acct.Sqid, app, p.Host, err)
return "", errors.New("could not change the channel — try again")
}
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index eac4f59ad..f73fdec56 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -256,7 +256,7 @@ func (s *Server) attachDomainAs(ctx context.Context, acct *Account, app, host, k
log.Printf("console: attach %s/%s %s: %v", acct.Sqid, app, host, err)
return attachResult{}, &doorRefusal{http.StatusBadGateway, "could not create the instance — try again"}
}
- if err := provision.CreateRecord(ctx, s.cfg.Releases, rec); err != nil {
+ if err := s.createRecordLocked(ctx, rec); err != nil {
// A record already at this key is NOT a failure to undo. The key is
// account+app scoped, so a create that lost the race lost it to this
// app's own record — a retry after a half-failed attach, or a record
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go
index b3fd81990..2ff70d84c 100644
--- a/internal/console/hostsused.go
+++ b/internal/console/hostsused.go
@@ -165,6 +165,7 @@ func recordUse(rec provision.Record) provision.HostUse {
// (the instance, seed and import doors): the mark for a data kind, then
// provision.CreateRecord. Exempt kinds write as before.
func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) error {
+ defer s.lockApp(rec.Account, rec.App)() // record writes hold the app lock (recordlock.go)
if rec.DataKind() {
if err := s.markBeforeCreate(ctx, recordUse(rec), provision.RecordKey(rec.Account, rec.App, rec.Host)); err != nil {
return err
@@ -176,6 +177,7 @@ func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) e
// createSidecarMarked is the sidecar door's create: a sidecar is always a
// data kind, marked at its host, then provision.CreateSidecarRecord.
func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarRecord) error {
+ defer s.lockApp(rec.Account, rec.App)() // record writes hold the app lock (recordlock.go)
u := provision.HostUse{Host: rec.Host, Account: rec.Account, App: rec.App, Kind: "sidecar", Source: "create"}
if err := s.markBeforeCreate(ctx, u, provision.SidecarRecordKey(rec.Account, rec.App, rec.Name)); err != nil {
return err
diff --git a/internal/console/record_write_lock_test.go b/internal/console/record_write_lock_test.go
new file mode 100644
index 000000000..58241e955
--- /dev/null
+++ b/internal/console/record_write_lock_test.go
@@ -0,0 +1,203 @@
+package console
+
+import (
+ "net/http"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// witnessRecordWritesLocked checks, in every console fixture, the invariant
+// the canary retire's final check rests on (#407): the console writes an
+// instance or sidecar record only while it holds the record's app lock
+// (s.lockApp), which the retire holds from its last re-list through the
+// pointer delete, so a create or channel change cannot land between them. A
+// write the test itself makes (a frame in a _test.go file calls the store
+// directly) is not checked. A violation fails the test when it ends, naming
+// the key and the console function that wrote it.
+func witnessRecordWritesLocked(t *testing.T, srv *Server, rel release.Store) {
+ t.Helper()
+ ds, ok := rel.(*deletableStore)
+ if !ok {
+ return
+ }
+ var (
+ mu sync.Mutex
+ done bool
+ violations []string
+ )
+ w := func(key string) {
+ acct, app, ok := recordKeyOwner(key)
+ if !ok {
+ return
+ }
+ caller, console := consoleCaller()
+ if !console || srv.appLocks.held(acct+"/"+app) {
+ return
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if !done {
+ violations = append(violations, key+" written by "+caller+" without the app lock of "+acct+"/"+app)
+ }
+ }
+ ds.putWitness.Store(&w)
+ t.Cleanup(func() {
+ mu.Lock()
+ defer mu.Unlock()
+ done = true
+ for _, v := range violations {
+ t.Errorf("record write lock (#407): %s", v)
+ }
+ })
+}
+
+// held reports whether key's mutex is held now, by anyone.
+func (l *keyedLocks) held(key string) bool {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ e := l.m[key]
+ if e == nil {
+ return false
+ }
+ if e.mu.TryLock() {
+ e.mu.Unlock()
+ return false
+ }
+ return true
+}
+
+// recordKeyOwner is the account and app of an instance or sidecar record
+// key: apps/<acct>/<app>/{instances,sidecars}/<name>.json.
+func recordKeyOwner(key string) (acct, app string, ok bool) {
+ parts := strings.Split(key, "/")
+ if len(parts) != 5 || parts[0] != "apps" || (parts[3] != "instances" && parts[3] != "sidecars") ||
+ !strings.HasSuffix(parts[4], ".json") || parts[4] == ".json" {
+ return "", "", false
+ }
+ return parts[1], parts[2], true
+}
+
+// consoleCaller walks the write's stack, past the store doubles and any
+// other package (release, provision), to the first frame in
+// internal/console, and reports its function and whether it is console code.
+// A _test.go frame reached first is the test writing behind the console's
+// back.
+func consoleCaller() (string, bool) {
+ pcs := make([]uintptr, 64)
+ n := runtime.Callers(3, pcs)
+ frames := runtime.CallersFrames(pcs[:n])
+ for {
+ f, more := frames.Next()
+ switch {
+ case strings.HasSuffix(f.File, "/internal/console/record_write_lock_test.go"),
+ strings.HasSuffix(f.File, "/internal/console/view_test.go"):
+ case strings.HasSuffix(f.File, "_test.go") && writeStoreMethod(f.Function):
+ // A test's store wrapper passing the console's write on.
+ case strings.HasSuffix(f.File, "_test.go"):
+ return f.Function, false
+ case strings.Contains(f.File, "/internal/console/"):
+ return f.Function, true
+ }
+ if !more {
+ return "", false
+ }
+ }
+}
+
+// writeStoreMethod reports whether fn is a release.Store method of some
+// type (a test's wrapper around the fixture's bucket).
+func writeStoreMethod(fn string) bool {
+ parts := strings.Split(fn[strings.LastIndex(fn, "/")+1:], ".")
+ if len(parts) < 3 {
+ return false // a plain function, not a method
+ }
+ switch parts[len(parts)-1] {
+ case "Put", "Delete", "DeleteIfMatch", "Get", "List", "ListMod":
+ return true
+ }
+ return false
+}
+
+// #407: a console write that would make a follower of the canary, starting
+// once the retire holds the app lock (between its follower check and its
+// final re-list), waits for the lock. It cannot land between the re-list
+// and the pointer delete: the retire goes through, and the write lands
+// after it, on a channel with no pointer.
+func TestRetireSerialisesWithFollowerWrites(t *testing.T) {
+ for _, tc := range []struct {
+ name, start string // start: the channel the existing instance follows
+ write func(tb *twoBoxes) (int, string)
+ want int
+ }{
+ {"create", "stable", func(tb *twoBoxes) (int, string) {
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(tb.fx, tb.sqid, "shop"), tb.token,
+ `{"host":"late.shop.example.com","region":"uk","channel":"canary/rc"}`)
+ return code, out
+ }, http.StatusCreated},
+ {"channel", "canary/next", func(tb *twoBoxes) (int, string) {
+ code, _, out := rawReq(t, http.MethodPost, instancesURL(tb.fx, tb.sqid, "shop")+"/"+remoteHost+"/channel", tb.token,
+ `{"channel":"canary/rc"}`)
+ return code, out
+ }, http.StatusOK},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ tb := newTwoBoxes(t)
+ shipAndPromote(t, tb.fx, tb.sqid, "shop", "v4", "canary/rc")
+ shipAndPromote(t, tb.fx, tb.sqid, "shop", "v5", "canary/next")
+ tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", tc.start)
+ tb.reconcile(t, "v3")
+ report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096)
+ ageRecords(t, tb)
+ tb.fx.srv.boxReports.expire()
+
+ appKey := tb.sqid + "/shop"
+ waiting := make(chan struct{}, 8)
+ hook := func(kind, key, event string) {
+ if kind == "app" && key == appKey && event == lockWaiting {
+ select {
+ case waiting <- struct{}{}:
+ default:
+ }
+ }
+ }
+ t.Cleanup(func() { lifetimeLockHook.Store(nil) })
+ type result struct {
+ code int
+ out string
+ }
+ wrote := make(chan result, 1)
+ tb.fx.srv.retireBeforeDeleteHook = func() {
+ lifetimeLockHook.Store(&hook)
+ go func() {
+ code, out := tc.write(tb)
+ wrote <- result{code, out}
+ }()
+ select {
+ case <-waiting: // the write waits for the retire's lock
+ case r := <-wrote:
+ t.Errorf("the %s landed (%d) while the retire held the app lock", tc.name, r.code)
+ wrote <- r
+ case <-time.After(10 * time.Second):
+ t.Errorf("the %s neither waited for the app lock nor finished", tc.name)
+ }
+ lifetimeLockHook.Store(nil)
+ }
+ if page := retireRC(t, tb); !strings.Contains(page, "Retired canary rc") || rcPointer(t, tb) {
+ t.Fatalf("retire with a %s waiting on the lock:\n%s", tc.name, page)
+ }
+ select {
+ case r := <-wrote:
+ if r.code != tc.want {
+ t.Fatalf("the %s after the retire = %d %s, want %d", tc.name, r.code, r.out, tc.want)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatalf("the %s never finished after the retire", tc.name)
+ }
+ })
+ }
+}
diff --git a/internal/console/recordlock.go b/internal/console/recordlock.go
new file mode 100644
index 000000000..acf438013
--- /dev/null
+++ b/internal/console/recordlock.go
@@ -0,0 +1,31 @@
+package console
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// Record writes and the canary retire (#407). The canary retire re-lists the
+// app's records just before it deletes the channel pointer, and refuses if
+// anything changed since its follower check (recordStamps). It holds the
+// app lock (s.lockApp) from that re-list through the delete. Every console
+// write of an instance or sidecar record holds the same lock, so a create
+// or a channel change lands either before the re-list, where the retire
+// sees it and refuses, or after the pointer is gone, which is the same as
+// creating an instance on a channel nobody has promoted (the create door
+// allows that). The lifetime paths take the lock through withAppHost; the
+// helpers below are the other writers' way in. The witness in
+// record_write_lock_test.go checks every write in every console test.
+
+// updateRecordLocked is provision.UpdateRecord under rec's app lock.
+func (s *Server) updateRecordLocked(ctx context.Context, rec provision.Record, etag string) error {
+ defer s.lockApp(rec.Account, rec.App)()
+ return provision.UpdateRecord(ctx, s.cfg.Releases, rec, etag)
+}
+
+// createRecordLocked is provision.CreateRecord under rec's app lock.
+func (s *Server) createRecordLocked(ctx context.Context, rec provision.Record) error {
+ defer s.lockApp(rec.Account, rec.App)()
+ return provision.CreateRecord(ctx, s.cfg.Releases, rec)
+}
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go
index 60bf9f849..ad93d9888 100644
--- a/internal/console/remoteinstances.go
+++ b/internal/console/remoteinstances.go
@@ -640,8 +640,9 @@ func recordKeyUnder(key, prefix string) bool {
// recordStamps is every instance and sidecar record key of acct/app with
// its modification time. The canary retire takes it before its check and
// again just before deleting the pointer, and refuses on any difference:
-// no lock covers record writes, so this is what notices a follower
-// created, moved or deleted in between.
+// the check runs without the app lock, so this is what notices a follower
+// created, moved or deleted in between. The second listing and the delete
+// run under the app lock every console record write takes (recordlock.go).
func (s *Server) recordStamps(ctx context.Context, acct, app string) (map[string]time.Time, error) {
out := map[string]time.Time{}
if s.cfg.Releases == nil {
diff --git a/internal/console/server.go b/internal/console/server.go
index 93ce5ce98..1945d1758 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1306,7 +1306,8 @@ type Server struct {
// is "nothing read yet": every label is its code.
labelNames regionNamesState
// retireBeforeDeleteHook, when set, runs in the canary retire between
- // the follower check and the final record comparison. Tests only.
+ // the follower check and the final record comparison, holding the app
+ // lock. Tests only.
retireBeforeDeleteHook func()
// startedAt overrides when this console started (zero: the process
// start, processStart; tests set it), and deletions is when it last
@@ -5903,8 +5904,9 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) {
// couldn't check" must never be read as "nobody follows this channel".
checkCtx, cancelCheck := context.WithTimeout(r.Context(), 15*time.Second)
// The app's records as they stand before the check, compared again just
- // before the delete: no lock covers record writes, so a record created,
- // changed or deleted in between refuses the retire (recordStamps).
+ // before the delete: the check itself runs without the app lock, so a
+ // record created, changed or deleted in between refuses the retire
+ // (recordStamps).
before, err := s.recordStamps(checkCtx, acct.Sqid, app)
var hosts []string
if err == nil {
@@ -5944,6 +5946,11 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) {
s.confirmRetireCanary(w, r, addr, raw, acct, role, app, name)
return
}
+ // The app lock from the re-list through the delete: every console
+ // record write holds it too (recordlock.go), so a follower created or
+ // moved onto this channel lands before the re-list, which refuses, or
+ // after the pointer is gone (#407).
+ unlockApp := s.lockApp(acct.Sqid, app)
err = s.appMutation(ctx, acct, app, "canary-retire", func(ctx context.Context) error {
if h := s.retireBeforeDeleteHook; h != nil {
h()
@@ -5972,15 +5979,16 @@ func (s *Server) handleRetireCanary(w http.ResponseWriter, r *http.Request) {
}
return err
}
- // A record written after the comparison above and before this delete
- // reaches its box only after the serial bump, by which time the
- // pointer is gone: the same as creating an instance on a channel
- // nobody has promoted, which the create door allows. No restore is
- // attempted: the store cannot tell "deleted the revision read" from
- // "already gone", so putting bytes back could resurrect a pointer
- // someone else removed.
+ // No console record write lands between the comparison above and
+ // this delete: each holds the app lock held here. One that waited
+ // lands after it, on a channel with no pointer: the same as creating
+ // an instance on a channel nobody has promoted, which the create
+ // door allows. No restore is attempted: the store cannot tell
+ // "deleted the revision read" from "already gone", so putting bytes
+ // back could resurrect a pointer someone else removed.
return nil
})
+ unlockApp()
if errors.Is(err, errRetireUnsettled) {
log.Printf("console: retire %s %s: %v", app, channel, err)
back("err", "Could not verify no hosts follow this channel — try again.")
diff --git a/internal/console/server_test.go b/internal/console/server_test.go
index 8cdddaf20..064ae2c74 100644
--- a/internal/console/server_test.go
+++ b/internal/console/server_test.go
@@ -156,6 +156,7 @@ func newConsoleFixtureWith(t *testing.T, o consoleFixtureOptions) *consoleFixtur
if _, err := st.CreateAppIn(OpsAccountID, "kass", "paul@keymail.dev", time.Now()); err != nil {
t.Fatal(err)
}
+ witnessRecordWritesLocked(t, srv, relStore)
return &consoleFixture{ts: ts, srv: srv, st: st, fk: fk, rel: relStore, regPath: regPath,
priv: priv, pub: pub, sqid: release.OpsAccount}
}
diff --git a/internal/console/updatescore.go b/internal/console/updatescore.go
index e867968c7..fad907ffb 100644
--- a/internal/console/updatescore.go
+++ b/internal/console/updatescore.go
@@ -175,7 +175,7 @@ func (s *Server) applyUpdates(ctx context.Context, acct *Account, app, principal
return updatesView{}, st, msg
}
}
- if err := provision.UpdateRecord(ctx, s.cfg.Releases, next, etag); err != nil {
+ if err := s.updateRecordLocked(ctx, next, etag); err != nil {
if errors.Is(err, release.ErrCASConflict) {
return updatesView{}, http.StatusConflict, updatewords.Text("settings.console.changed")
}
@@ -215,7 +215,7 @@ func (s *Server) requestInstall(ctx context.Context, acct *Account, app, princip
}
next := *rec
next.InstallRequest = &provision.InstallRequest{ID: id, FastTrack: fast, At: time.Now().UTC().Truncate(time.Second), By: principal}
- err := provision.UpdateRecord(ctx, s.cfg.Releases, next, etag)
+ err := s.updateRecordLocked(ctx, next, etag)
if errors.Is(err, release.ErrCASConflict) {
continue // another writer moved the record: read it again
}
diff --git a/internal/console/view_test.go b/internal/console/view_test.go
index e1d2d7545..a7b1ee9df 100644
--- a/internal/console/view_test.go
+++ b/internal/console/view_test.go
@@ -38,6 +38,9 @@ type deletableStore struct {
// returns fails the read there. Set with setGetHook, safely while the
// server runs.
getHook atomic.Pointer[func(ctx context.Context, key string) error]
+ // putWitness, when set, sees each Put before the hooks above:
+ // newConsoleFixtureWith's app-lock check on record writes (#407).
+ putWitness atomic.Pointer[func(key string)]
}
func (d *deletableStore) setGetHook(h func(ctx context.Context, key string) error) {
@@ -65,6 +68,9 @@ func (d *deletableStore) runDeleteHook(ctx context.Context, key string) error {
}
func (d *deletableStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if w := d.putWitness.Load(); w != nil && *w != nil {
+ (*w)(key)
+ }
if h := d.putHook; h != nil {
h(ctx, key)
}