carlos / platform Public

retire-app-lock-407: writes keep their provision call under withRecordLock; witness scoped to follower writes; census overlay; review brief

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev c199aee5a1165388600ca65d0d6cc553bfe89625 parent d66a8ff
11 files changed, +206 −39
  • docs/superpowers/specs/CODEX-REVIEW-BRIEF-RETIRE-APP-LOCK-407.md +101 −0
  • internal/console/apiinstances.go +1 −1
  • internal/console/appsettings.go +2 −2
  • internal/console/channelmove.go +3 −2
  • internal/console/domainattach.go +1 −1
  • internal/console/record_write_lock_test.go +38 −11
  • internal/console/recordlock.go +7 −17
  • internal/console/updatescore.go +2 −2
  • internal/console/view_test.go +2 −2
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/retire_app_lock_407_census_test.go +48 −0
diff --git a/docs/superpowers/specs/CODEX-REVIEW-BRIEF-RETIRE-APP-LOCK-407.md b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-RETIRE-APP-LOCK-407.md
new file mode 100644
index 000000000..cc8584a0c
--- /dev/null
+++ b/docs/superpowers/specs/CODEX-REVIEW-BRIEF-RETIRE-APP-LOCK-407.md
@@ -0,0 +1,101 @@
+# Review brief: branch retire-app-lock-407, round 1 of 3
+
+Repo carlos/platform, branch `retire-app-lock-407`, commit named in the
+prompt (the tip that adds this brief).
+Under review: the diff `origin/main...HEAD` (console-only: internal/console).
+Authorities: discussion #407 (the gap), the canary-retire guard as merged
+on main (`handleRetireCanary` and `channelHosts` in
+`internal/console/server.go`; `retireUnsettled`, `recordStamps` in
+`internal/console/remoteinstances.go`), and the app lock as merged
+(`keyedLocks`, `lockApp` and its lock order in `internal/console/applocks.go`;
+`withAppHost`/`lockAppHost` in `internal/console/lifetimes.go`).
+Do not review against unmerged branches; if this work needs one, say so as
+a P1 and stop. A sibling branch, `retire-window-all-deletes-415`, is NOT an
+authority here.
+
+You are an independent reviewer. Read the diff, then the code it names,
+and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul accepted the canary-retire guard and its 15-minute window on
+ 2026-10-25 (#280), with an app lock to follow (#407). This branch is that
+ lock. Report only mechanisms that fail to honour it.
+- The lock is in-process (`keyedLocks`): "one console per deployment
+ bucket" is the deployment assumption written in `applocks.go`. Do not ask
+ for a bucket-level lock.
+- Box-side record writers are out of scope (boxes do not write instance
+ records except through hostops, which belongs to the shelved claims
+ work and is inert). Say so if you find one that is live.
+- A create or channel change that waits for the retire and lands after the
+ pointer is gone is the accepted outcome (the create door already allows
+ an instance on an unpromoted channel).
+
+## What to check
+
+1. **The claim.** Between the retire's final re-list (`recordStamps`
+ "after") and its `DeleteIfMatch` of the pointer, no console write that
+ could add a follower of a channel can land: a record create (instance
+ or sidecar), or a record write that changes its channel. Writes that
+ leave the channel as it was (moves, seed and run state, asset
+ generations, tombstones, deletes) cannot add a follower and are out of
+ the invariant on purpose. Find any console path that creates a record
+ or sets its channel without holding `s.lockApp` for that record's
+ account and app, with file:line. Lifetime paths hold it through
+ `withAppHost`; the others through `withRecordLock`
+ (`internal/console/recordlock.go`).
+2. **Deadlocks.** `lockApp` is not reentrant. For each newly locked writer
+ (`createRecordMarked`, `createSidecarMarked`, each `withRecordLock`
+ call site, the retire), check every caller chain for a
+ lockApp of the same app already held, and the lock order (account, then
+ app, then hostname) against every other holder. Also check that nothing
+ inside the retire's locked section (`appMutation`, `recordStamps`, the
+ pointer `Get` and `DeleteIfMatch`, `retireBeforeDeleteHook`) can take
+ the same app lock.
+3. **Hold time.** The retire holds the lock across two bucket listings, a
+ Get and a delete; creates hold it across the hostname-history mark and
+ the write. Is any of that unbounded (a context without a deadline)?
+4. **The witness** (`internal/console/record_write_lock_test.go`, installed
+ by `newConsoleFixtureWith`): does it fail a test whose console code
+ creates a record, or changes a record's channel, without the app lock
+ held (`followerWrite` compares the body's channel with the stored one)? Can `consoleCaller`
+ misclassify a console write as the test's own? `held` reports the lock
+ held by anyone: is that a hole in practice?
+5. **The record-write census (9B8).** `internal/provision/retire_app_lock_407_census_test.go`
+ re-pins ten console units with the classes they had; each keeps its own
+ provision call, now inside `withRecordLock`. You decide it (AGENTS.md,
+ "The census", and #280 2026-10-26: the reviewer decides every class).
+ Give a verdict per unit, approve or reject, citing the lines. The
+ root-read census does not apply: `internal/console` is outside its
+ scope since C2 (7c9e9d6a), and `TestPlan14RootReadCensus` passes.
+6. **The test** (`TestRetireSerialisesWithFollowerWrites`): does it fail on
+ main's code for the stated reason, and pass here for the right one?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 7d4ed1275..3b8591a56 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 := s.updateRecordLocked(ctx, *rec, etag); err != nil {
+ if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *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 d03f2f455..77b5532b8 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 := s.updateRecordLocked(ctx, *rec, etag); err != nil {
+ if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *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 := s.updateRecordLocked(ctx, *rec, etag); err != nil {
+ if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *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 fb07f7bd4..f3c73ef70 100644
--- a/internal/console/channelmove.go
+++ b/internal/console/channelmove.go
@@ -28,6 +28,7 @@ import (
"os"
"strings"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
)
@@ -174,7 +175,7 @@ func (s *Server) handleAPIInstanceChannel(w http.ResponseWriter, r *http.Request
return
}
rec.Channel = to
- if err := s.updateRecordLocked(ctx, *rec, etag); err != nil {
+ if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *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
@@ -216,7 +217,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 := s.updateRecordLocked(ctx, *rec, etag); err != nil {
+ if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *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 f73fdec56..8abaeec06 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 := s.createRecordLocked(ctx, rec); err != nil {
+ if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.CreateRecord(ctx, s.cfg.Releases, 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/record_write_lock_test.go b/internal/console/record_write_lock_test.go
index 58241e955..7ad162ce9 100644
--- a/internal/console/record_write_lock_test.go
+++ b/internal/console/record_write_lock_test.go
@@ -1,6 +1,8 @@
package console
import (
+ "context"
+ "encoding/json"
"net/http"
"runtime"
"strings"
@@ -12,13 +14,15 @@ import (
)
// 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
+// the canary retire's final check rests on (#407): every console write that
+// could make a record follow a channel it did not follow before (a create,
+// or a write that changes the record's channel) 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.
+// pointer delete. Other record writes (a move, a seed or run state, a
+// tombstone, a delete) cannot add a follower and are not checked. A write
+// the test itself makes (a frame in a _test.go file calls the store
+// directly) is not checked either. 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)
@@ -30,13 +34,13 @@ func witnessRecordWritesLocked(t *testing.T, srv *Server, rel release.Store) {
done bool
violations []string
)
- w := func(key string) {
+ w := func(key string, body []byte) {
acct, app, ok := recordKeyOwner(key)
if !ok {
return
}
caller, console := consoleCaller()
- if !console || srv.appLocks.held(acct+"/"+app) {
+ if !console || !followerWrite(ds, key, body) || srv.appLocks.held(acct+"/"+app) {
return
}
mu.Lock()
@@ -56,6 +60,28 @@ func witnessRecordWritesLocked(t *testing.T, srv *Server, rel release.Store) {
})
}
+// followerWrite reports whether writing body at key could make the record
+// follow a channel it does not follow now: no record there yet, or another
+// channel. A tombstone (retired) follows nothing. Anything it cannot read
+// counts as one.
+func followerWrite(ds *deletableStore, key string, body []byte) bool {
+ var next, cur struct {
+ Channel string `json:"channel"`
+ Retired bool `json:"retired"`
+ }
+ if json.Unmarshal(body, &next) != nil {
+ return true
+ }
+ if next.Retired {
+ return false
+ }
+ prev, _, err := ds.Store.Get(context.Background(), key)
+ if err != nil || json.Unmarshal(prev, &cur) != nil {
+ return true
+ }
+ return cur.Channel != next.Channel
+}
+
// held reports whether key's mutex is held now, by anyone.
func (l *keyedLocks) held(key string) bool {
l.mu.Lock()
@@ -109,15 +135,16 @@ func consoleCaller() (string, bool) {
}
}
-// writeStoreMethod reports whether fn is a release.Store method of some
-// type (a test's wrapper around the fixture's bucket).
+// writeStoreMethod reports whether fn is a Put method of some type (a
+// test's wrapper around the fixture's bucket). Only Put: a wrapper's Get or
+// List that writes something is the test's own doing.
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":
+ case "Put":
return true
}
return false
diff --git a/internal/console/recordlock.go b/internal/console/recordlock.go
index acf438013..a23e12f9c 100644
--- a/internal/console/recordlock.go
+++ b/internal/console/recordlock.go
@@ -1,11 +1,5 @@
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
@@ -15,17 +9,13 @@ import (
// 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
+// other writers through withRecordLock. 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)
+// withRecordLock runs write, one record write of acct/app, holding that
+// app's lock (s.lockApp). Each writer keeps its provision call in its own
+// body, so the record-write census still sees it there.
+func (s *Server) withRecordLock(acct, app string, write func() error) error {
+ defer s.lockApp(acct, app)()
+ return write()
}
diff --git a/internal/console/updatescore.go b/internal/console/updatescore.go
index fad907ffb..7cfb02b61 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 := s.updateRecordLocked(ctx, next, etag); err != nil {
+ if err := s.withRecordLock(next.Account, next.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, 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 := s.updateRecordLocked(ctx, next, etag)
+ err := s.withRecordLock(next.Account, next.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, 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 a7b1ee9df..856b5ae33 100644
--- a/internal/console/view_test.go
+++ b/internal/console/view_test.go
@@ -40,7 +40,7 @@ type deletableStore struct {
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)]
+ putWitness atomic.Pointer[func(key string, body []byte)]
}
func (d *deletableStore) setGetHook(h func(ctx context.Context, key string) error) {
@@ -69,7 +69,7 @@ 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)
+ (*w)(key, body)
}
if h := d.putHook; h != nil {
h(ctx, key)
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index e3496027a..ded47da0c 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := nearestRegionAWriteCensusInventory()
+ inventory := retireAppLock407WriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/retire_app_lock_407_census_test.go b/internal/provision/retire_app_lock_407_census_test.go
new file mode 100644
index 000000000..2bb0b6eec
--- /dev/null
+++ b/internal/provision/retire_app_lock_407_census_test.go
@@ -0,0 +1,48 @@
+package provision
+
+// Record-write census entries for retire-app-lock-407 (#407: console record
+// writes that can add a follower share the app lock with the canary
+// retire's final section), layered on nearestRegionAWriteCensusInventory
+// (main's newest at f7644a9c). Reviewed by the branch author and the
+// cross-model reviewer (Astra) with the branch.
+// No record write is added, moved or reclassified. Each unit below keeps
+// its own provision call (CreateRecord, CreateSidecarRecord or
+// UpdateRecord, same key, same ETag), now run inside
+// Server.withRecordLock(acct, app, ...), which holds s.lockApp for the
+// record's own account and app around that one call:
+// - Server.createRecordMarked, Server.createSidecarMarked: the lifetimes-off
+// instance create and the sidecar create take the lock for the mark and
+// the create.
+// - Server.attachDomainAs: the lifetimes-off first-route record.
+// - Server.handleAPIInstanceChannel, Server.executePendingRouteChannel:
+// the channel move and a confirmed channel-move proposal.
+// - Server.handleAPIInstanceUpdate, Server.handleAppGate,
+// Server.handleAppRateLimit, Server.applyUpdates,
+// Server.requestInstall: the other record updates.
+func retireAppLock407WriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), nearestRegionAWriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/hostsused.go", "Server.createRecordMarked", "record-writer", "key:CreateRecord,key:RecordKey", "bba49e85274c5feb0b5c878ccc1a415f5951884c36d2a40ceedbc9af121f7b26"},
+ {"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "6e35b29038b60ac6318307e70a323ee9fc2a9eec6d116e832b3e50baaf52b036"},
+ {"internal/console/domainattach.go", "Server.attachDomainAs", "record-writer", "key:CreateRecord", "a9842fe4d774c8667ae357f2b594d47c78c603702b9a8aefac41b833913d2483"},
+ {"internal/console/channelmove.go", "Server.handleAPIInstanceChannel", "record-writer", "key:UpdateRecord", "7027e176c4837eb2555a0809f841e758a3781ef8e782d47171791c6da6762e27"},
+ {"internal/console/channelmove.go", "Server.executePendingRouteChannel", "record-writer", "key:UpdateRecord", "fe42beaeab844b59001bff3701c580e0837e5cedd7c46b7037c743ec16ef023f"},
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceUpdate", "record-writer", "key:UpdateRecord", "ebe33cca7d5aced0d363d9fa0db08566c4a941857180f23494a9466877814869"},
+ {"internal/console/appsettings.go", "Server.handleAppGate", "record-writer", "key:UpdateRecord", "b2157b5190efeac5c25600d0f8808387302b0c253ff156547865ca35750d3e8a"},
+ {"internal/console/appsettings.go", "Server.handleAppRateLimit", "record-writer", "key:UpdateRecord", "466f0d859d9b3fcdb21e56ca463caea929e160e245955b3babc8150704eb8696"},
+ {"internal/console/updatescore.go", "Server.applyUpdates", "record-writer", "key:UpdateRecord", "daf50fce4496999bb13da954c1139930612ae461a1e89bfeed2c2b5178800953"},
+ {"internal/console/updatescore.go", "Server.requestInstall", "record-writer", "key:UpdateRecord", "2e06c79d437fcaf7ccf3b3b5f9b47fe5fe23ebef531705ae40e4016fe4707fcc"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("retire-app-lock-407 replacement of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}