Merge remote-tracking branch 'origin/main' into nearest-region-b
retire-app-lock-407: the app lock is taken before gateDataCreate in the two marked create writers; record-write overlay layered on retireAppLock407 and the two writers re-pinned.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+601
−24
docs/superpowers/specs/CODEX-FINDINGS-RETIRE-APP-LOCK-407.md+40 −0docs/superpowers/specs/CODEX-REVIEW-BRIEF-RETIRE-APP-LOCK-407.md+101 −0internal/console/apiinstances.go+1 −1internal/console/appsettings.go+2 −2internal/console/channelmove.go+2 −2internal/console/domainattach.go+1 −1internal/console/hostsused.go+2 −0internal/console/record_write_lock_test.go+340 −0internal/console/recordlock.go+21 −0internal/console/remoteinstances.go+3 −2internal/console/server.go+18 −10internal/console/server_test.go+1 −0internal/console/updatescore.go+2 −2internal/console/view_test.go+12 −0internal/provision/nearest_region_b_census_test.go+4 −4internal/provision/retire_app_lock_407_census_test.go+51 −0
diff --git a/docs/superpowers/specs/CODEX-FINDINGS-RETIRE-APP-LOCK-407.md b/docs/superpowers/specs/CODEX-FINDINGS-RETIRE-APP-LOCK-407.md| new file mode 100644 |
| index 000000000..46e808b06 |
| --- /dev/null |
| +++ b/docs/superpowers/specs/CODEX-FINDINGS-RETIRE-APP-LOCK-407.md |
| @@ -0,0 +1,40 @@ |
| +Reviewed `origin/main...9eba959e78c3c83c24956e0e12eb80199afb9d41`, including merged #415. Later working-tree edits are excluded. |
| + |
| +All ten record-write census entries are **approved**. Their digests match the pinned function bodies, their `record-writer` classes are unchanged, and each retains its original provision call and write arguments. |
| + |
| +| Unit | Verdict | Evidence | |
| +|---|---|---| |
| +| `createRecordMarked` | Approve | `internal/console/hostsused.go:168–174`: lock covers mark and create | |
| +| `createSidecarMarked` | Approve | `internal/console/hostsused.go:180–185`: lock covers mark and create | |
| +| `attachDomainAs` | Approve | `internal/console/domainattach.go:259`: create under record’s app lock | |
| +| `handleAPIInstanceChannel` | Approve | `internal/console/channelmove.go:177–178`: channel update locked | |
| +| `executePendingRouteChannel` | Approve | `internal/console/channelmove.go:215–220`: proposal checks retained; update locked | |
| +| `handleAPIInstanceUpdate` | Approve | `internal/console/apiinstances.go:2427`: update locked | |
| +| `handleAppGate` | Approve | `internal/console/appsettings.go:1122`: update locked | |
| +| `handleAppRateLimit` | Approve | `internal/console/appsettings.go:1249`: update locked | |
| +| `applyUpdates` | Approve | `internal/console/updatescore.go:178`: update locked | |
| +| `requestInstall` | Approve | `internal/console/updatescore.go:218`: each conditional update locked | |
| + |
| +**P1: None found.** |
| + |
| +**P2 — The witness can accept an unlocked follower write.** |
| +Evidence: `internal/console/record_write_lock_test.go:43,95–97,104–115`. `witnessLockHeld` accepts a lock held by any goroutine on any registered server. While retirement holds the app lock, an unlocked sidecar create or another omitted writer would therefore pass this check—the exact overlap it should reject. The dedicated concurrency test covers only ordinary instance creation and direct channel changes (`:171–180`). |
| + |
| +Fix: check ownership by the writing goroutine, using the existing test-only tracking pattern in `internal/console/lifetimes_create_test.go:2310–2350`. Add a negative probe with another goroutine holding the same app lock. |
| +Fault family: **lock-ownership evidence**. |
| + |
| +**P2 — Rejected conditional writes can produce false violations.** |
| +Evidence: `internal/console/view_test.go:76–83` invokes the witness before knowing whether the store accepts the write; `internal/console/record_write_lock_test.go:78–82` compares its body against independently read current bytes. |
| + |
| +For example, a permitted region-only update (`internal/console/fleets.go:694`) reads channel A, then a locked channel change writes B. The region update attempts its old body with its old ETag. The witness reports an unlocked channel change, although the store rejects that stale write and the update retries (`internal/provision/provision.go:1097–1110`). No follower was added. |
| + |
| +Fix: evaluate accepted writes against the predecessor they actually replaced, and add a regression covering this losing-write interleaving. |
| +Fault family: **committed-write evidence**. |
| + |
| +**P3: None.** |
| + |
| +I found no live follower-writing bypass or newly introduced lock-order inversion in the production paths inspected. Retirement holds the app lock through its final listings and pointer deletion; the newly locked store operations receive deadline-bound contexts. The root-read census has no production-source change in scope. |
| + |
| +By source inspection, the concurrency test distinguishes main’s unlocked writers from this implementation. Execution remains unverified: the focused Go test could not start because the sandbox denied its build directory. No full suites ran, and I edited no files. |
| + |
| +READY AFTER FIXES |
| \ No newline at end of file |
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 d5c0731fd..692e8de16 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -2441,7 +2441,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.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 fbbe08ab9..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 := provision.UpdateRecord(ctx, s.cfg.Releases, *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 := provision.UpdateRecord(ctx, s.cfg.Releases, *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 c41024a4a..f3c73ef70 100644 |
| --- a/internal/console/channelmove.go |
| +++ b/internal/console/channelmove.go |
| @@ -175,7 +175,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.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 |
| @@ -217,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 := provision.UpdateRecord(ctx, s.cfg.Releases, *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 9daca8d73..bb45e48f5 100644 |
| --- a/internal/console/domainattach.go |
| +++ b/internal/console/domainattach.go |
| @@ -257,7 +257,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.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/hostsused.go b/internal/console/hostsused.go| index 98da5834f..be863ada7 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -556,6 +556,7 @@ func recordUse(rec provision.Record) provision.HostUse { |
| // (gateDataCreate) and its mark, 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 ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil { |
| return &hostsUsedError{*ref} |
| @@ -571,6 +572,7 @@ func (s *Server) createRecordMarked(ctx context.Context, rec provision.Record) e |
| // data kind, admitted (gateDataCreate) and 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) |
| if ref := s.gateDataCreate(ctx, rec.Host, rec.Region); ref != nil { |
| return &hostsUsedError{*ref} |
| } |
diff --git a/internal/console/record_write_lock_test.go b/internal/console/record_write_lock_test.go| new file mode 100644 |
| index 000000000..d01c5190c |
| --- /dev/null |
| +++ b/internal/console/record_write_lock_test.go |
| @@ -0,0 +1,340 @@ |
| +package console |
| + |
| +import ( |
| + "encoding/json" |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "net/http" |
| + "path/filepath" |
| + "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): 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. 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) |
| + if !ok { |
| + return |
| + } |
| + var ( |
| + mu sync.Mutex |
| + done bool |
| + violations []string |
| + ) |
| + w := func(key string, body, prev []byte) { |
| + acct, app, ok := recordOwnerOfKey(key) |
| + if !ok { |
| + return |
| + } |
| + caller, console := consoleCaller() |
| + if !console || !followerWrite(body, prev) || (witnessLockHeld(ds, acct+"/"+app) && stackHoldsAppLock(t)) { |
| + 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) |
| + } |
| + }) |
| +} |
| + |
| +// followerWrite reports whether a write that replaced prev (nil: no record |
| +// there) with body could make the record follow a channel it did not |
| +// follow before: no record there yet, or another channel. A tombstone |
| +// (retired) follows nothing. Anything it cannot read counts as one. |
| +func followerWrite(body, prev []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 |
| + } |
| + if prev == nil || json.Unmarshal(prev, &cur) != nil || cur.Retired { |
| + return true |
| + } |
| + return cur.Channel != next.Channel |
| +} |
| + |
| +// stackHoldsAppLock reports whether the calling goroutine is inside a |
| +// function that holds an app lock for its whole body: one that defers |
| +// s.lockApp or s.lockAppHost, or withAppHost and withRecordLock. With |
| +// witnessLockHeld, that is the writing goroutine's own lock, not one some |
| +// other goroutine (a retire) happens to hold. |
| +func stackHoldsAppLock(t *testing.T) bool { |
| + holders := appLockHolders(t) |
| + pcs := make([]uintptr, 128) |
| + n := runtime.Callers(2, pcs) |
| + frames := runtime.CallersFrames(pcs[:n]) |
| + for { |
| + f, more := frames.Next() |
| + name := f.Function[strings.LastIndex(f.Function, ".")+1:] |
| + if strings.Contains(f.Function, "/internal/console.") && holders[name] { |
| + return true |
| + } |
| + if !more { |
| + return false |
| + } |
| + } |
| +} |
| + |
| +var ( |
| + appLockHoldersOnce sync.Once |
| + appLockHoldersSet map[string]bool |
| +) |
| + |
| +// appLockHolders is the console's functions that hold an app lock for their |
| +// whole body, by name, parsed from the package source once. |
| +func appLockHolders(t *testing.T) map[string]bool { |
| + appLockHoldersOnce.Do(func() { |
| + set := map[string]bool{"withAppHost": true, "withRecordLock": true} |
| + fset := token.NewFileSet() |
| + files, err := filepath.Glob("*.go") |
| + if err != nil { |
| + panic(err) |
| + } |
| + for _, file := range files { |
| + if strings.HasSuffix(file, "_test.go") { |
| + continue |
| + } |
| + f, err := parser.ParseFile(fset, file, nil, 0) |
| + if err != nil { |
| + panic(err) |
| + } |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + for _, st := range fd.Body.List { |
| + ds, ok := st.(*ast.DeferStmt) |
| + if !ok { |
| + continue |
| + } |
| + inner, ok := ds.Call.Fun.(*ast.CallExpr) |
| + if !ok { |
| + continue |
| + } |
| + if sel, ok := inner.Fun.(*ast.SelectorExpr); ok && (sel.Sel.Name == "lockApp" || sel.Sel.Name == "lockAppHost") { |
| + set[fd.Name.Name] = true |
| + } |
| + } |
| + } |
| + } |
| + appLockHoldersSet = set |
| + }) |
| + return appLockHoldersSet |
| +} |
| + |
| +// witnessLockHeld reports whether the app lock key is held on any console |
| +// the test built over ds (witnessServer: the fixture's own, and a restarted |
| +// one), since the witness cannot tell which server made the write. |
| +func witnessLockHeld(ds *deletableStore, key string) bool { |
| + witnessServersMu.Lock() |
| + defer witnessServersMu.Unlock() |
| + v, ok := witnessServers.Load(ds) |
| + if !ok { |
| + return false |
| + } |
| + for _, srv := range *v.(*[]*Server) { |
| + if srv.appLocks.held(key) { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// 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 |
| +} |
| + |
| +// 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 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": |
| + 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) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// #407 review (Astra round 1, P2 1): the witness takes the lock as held only |
| +// when the writing goroutine itself is inside a lock holder. A lock another |
| +// goroutine holds (a retire in flight) does not vouch for an unlocked write. |
| +func TestRecordWriteWitnessNeedsTheWritersOwnLock(t *testing.T) { |
| + srv := &Server{} |
| + if h := appLockHolders(t); !h["createRecordMarked"] || !h["createSidecarMarked"] || !h["sweepTrashedApp"] { |
| + t.Fatalf("the holder set misses known holders: %v", appLockHolders(t)) |
| + } |
| + held := make(chan struct{}) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + _ = srv.withRecordLock("abc", "shop", func() error { |
| + if !stackHoldsAppLock(t) { |
| + t.Error("inside withRecordLock the writer's own lock is not seen") |
| + } |
| + close(held) |
| + <-done |
| + return nil |
| + }) |
| + }() |
| + <-held |
| + if !srv.appLocks.held("abc/shop") { |
| + t.Fatal("the probe's lock is not held") |
| + } |
| + if stackHoldsAppLock(t) { |
| + t.Fatal("a goroutine outside every lock holder counted another goroutine's lock as its own") |
| + } |
| + done <- struct{}{} |
| +} |
diff --git a/internal/console/recordlock.go b/internal/console/recordlock.go| new file mode 100644 |
| index 000000000..a23e12f9c |
| --- /dev/null |
| +++ b/internal/console/recordlock.go |
| @@ -0,0 +1,21 @@ |
| +package console |
| + |
| +// 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 |
| +// other writers through withRecordLock. The witness in |
| +// record_write_lock_test.go checks every write in every console test. |
| + |
| +// 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/remoteinstances.go b/internal/console/remoteinstances.go| index 129af891d..2b3a4c77b 100644 |
| --- a/internal/console/remoteinstances.go |
| +++ b/internal/console/remoteinstances.go |
| @@ -647,8 +647,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 3eb1c2fd4..a1c8be99d 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1313,7 +1313,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 |
| @@ -5913,8 +5914,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 { |
| @@ -5954,6 +5956,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() |
| @@ -5982,15 +5989,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 74dfa038f..611f58623 100644 |
| --- a/internal/console/server_test.go |
| +++ b/internal/console/server_test.go |
| @@ -163,6 +163,7 @@ func newConsoleFixtureWith(t *testing.T, o consoleFixtureOptions) *consoleFixtur |
| t.Fatal(err) |
| } |
| witnessDeletionEvidence(t, srv, relStore) |
| + 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..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 := provision.UpdateRecord(ctx, s.cfg.Releases, 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 := provision.UpdateRecord(ctx, s.cfg.Releases, 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 9336bc05c..b70331db1 100644 |
| --- a/internal/console/view_test.go |
| +++ b/internal/console/view_test.go |
| @@ -41,6 +41,10 @@ type deletableStore struct { |
| // witness, when set, sees each Delete and DeleteIfMatch before the hook |
| // above: newConsoleFixtureWith's deletion-evidence check (#415). |
| witness atomic.Pointer[func(key string)] |
| + // putWitness, when set, sees each Put the store accepted, with the body |
| + // that was at the key just before (nil for none): |
| + // newConsoleFixtureWith's app-lock check on record writes (#407). |
| + putWitness atomic.Pointer[func(key string, body, prev []byte)] |
| } |
| func (d *deletableStore) setGetHook(h func(ctx context.Context, key string) error) { |
| @@ -74,7 +78,15 @@ func (d *deletableStore) Put(ctx context.Context, key string, body []byte, ifMat |
| if h := d.putHook; h != nil { |
| h(ctx, key) |
| } |
| + var witnessPrev []byte |
| + w := d.putWitness.Load() |
| + if w != nil && *w != nil { |
| + witnessPrev, _, _ = d.Store.Get(ctx, key) |
| + } |
| etag, err := d.Store.Put(ctx, key, body, ifMatch) |
| + if w != nil && *w != nil && err == nil { |
| + (*w)(key, body, witnessPrev) |
| + } |
| if h := d.afterPut; h != nil && err == nil { |
| h(ctx, key) |
| } |
diff --git a/internal/provision/nearest_region_b_census_test.go b/internal/provision/nearest_region_b_census_test.go| index e4de205a7..1e796b26c 100644 |
| --- a/internal/provision/nearest_region_b_census_test.go |
| +++ b/internal/provision/nearest_region_b_census_test.go |
| @@ -2,7 +2,7 @@ package provision |
| // Record-write census entries for nearest-region never-reuse merge B (branch |
| // nearest-region-b, reworked to offline activation on Paul's cut, #404), |
| -// layered on regionHAP1aWriteCensusInventory (main's chain tip). Reviewed by the branch |
| +// layered on retireAppLock407WriteCensusInventory (main's chain tip). Reviewed by the branch |
| // author; the census approval is recorded on #280. |
| // - WriteHostsState (provision), new: the one Put of control/hosts-used/@mode. |
| // No record key or body: nonrecord. WriteHostsMode writes through it. |
| @@ -33,7 +33,7 @@ package provision |
| // - Server.registerCLIRoutes, re-pinned (merge A's status door's |
| // neighbourhood only). Same literals: key-site. |
| func nearestRegionBWriteCensusInventory() []censusEntry { |
| - entries := append([]censusEntry(nil), regionHAP1aWriteCensusInventory()...) |
| + entries := append([]censusEntry(nil), retireAppLock407WriteCensusInventory()...) |
| for _, r := range []struct{ file, unit string }{ |
| {"internal/provision/hostsused.go", "WriteHostsMode"}, |
| } { |
| @@ -59,8 +59,8 @@ func nearestRegionBWriteCensusInventory() []censusEntry { |
| {"internal/console/hostsused_tripwire.go", "Server.hostsTripwire", "key-site", "key:IsRecordKey,lit:instances,lit:sidecars", "6a503a4b29f7909c45ec6a3e52a33a2e5a8b8b37a816942cabba9fa6f80faeba"}, |
| {"accounts_hostsused.go", "beforeRecord", "key-site", "key:IsRecordKey", "73e989d07dfde038fd917d004c16d2119afcedf5f76a26e85a6800cf0a950a58"}, |
| {"accounts_hostsused.go", "refuseDataRecords", "key-site", "key:IsRecordKey", "c7aee0366810562cd3bda840fac75533ec420ce76b277d267216e963f8415114"}, |
| - {"internal/console/hostsused.go", "Server.createRecordMarked", "record-writer", "key:CreateRecord,key:RecordKey", "4a8cc22bd98a187e7b5e263e8ead2f0b0a962ae644996af582e8cd9e6915052d"}, |
| - {"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "197fba9ee8949f7e61caef81800cb6bb9a4374497884f229312216d0ef8056cf"}, |
| + {"internal/console/hostsused.go", "Server.createRecordMarked", "record-writer", "key:CreateRecord,key:RecordKey", "1c2b1885e944a631a1a7af9bbc3133ff0dbef66cef09eaa8ffaf87519337f3e8"}, |
| + {"internal/console/hostsused.go", "Server.createSidecarMarked", "record-writer", "key:CreateSidecarRecord,key:SidecarRecordKey", "316c654471b9048f246c046b88432f4b679c66249bb1d3fd88b15ea4406474e0"}, |
| {"accounts_hostsused.go", "migrationRecordHost", "key-site", "lit:sidecars", "709eb800cebb6e9a9fa6ba40caf9bed51ab4ecc81b22676270aab28eefeddbb3"}, |
| {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "25cb2b7d4f7d264d8a45e5b9306f8f7f95fe886237fd88b9e4a492d7e66e90e3"}, |
| } |
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..096c635ba |
| --- /dev/null |
| +++ b/internal/provision/retire_app_lock_407_census_test.go |
| @@ -0,0 +1,51 @@ |
| +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 regionHAP1aWriteCensusInventory |
| +// (main's newest at fd93024a). 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. Re-pinned |
| +// after merging region-ha-p1a (fd93024a), whose own approved line |
| +// (rec.HA = s.shouldStampHA(rec)) sits in the same body; this branch's |
| +// change there is only the lock around the CreateRecord call. |
| +// - 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), regionHAP1aWriteCensusInventory()...) |
| + 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", "626663b0f9307d33b391b12800341e822bfa855ecb1ba3e08feb6196fa061378"}, |
| + {"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 |
| +} |