retire-window-all-deletes-415: every console record delete marks the canary-retire window
The canary-retire guard refuses for 15 minutes after a record of the app is deleted, but learns of deletions only from noteRecordDeletion and the audit log. Lifetime paths skipped both: a domain detach (detachRetireLocked -> retireRecordWithLifetimeLocked), recovery (retirementStepsLocked directly), and the previous owner's stale body in allocCleanLocked and allocPrevOwnerCleanLocked. - retirementStepsLocked notes the deletion at entry: N1 makes the record a tombstone, and detach and recovery both reach it. - deleteRecordIfMatch notes, then deletes on the ETag. Every lifetime delete of a record goes through it: the stale-body delete, both allocation cleanups (the previous owner's under its own app), deleteUnderRetiredSlot and the migration's corrupt-body delete. - recentRecordDeletion reads domain-detach audit rows too, for a second console process, which has none of the first one's notes. Tests: TestRetireWaitsAfterLifetimeDetach (no audit row) and ...OnAnotherConsole (audit only) both failed on the old code. Every console fixture now carries a deletion-evidence witness: a record delete that reaches the bucket from console code without a fresh note for its account and app fails the test, naming the function.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+231
−12
internal/console/deletion_evidence_test.go+195 −0internal/console/lifetimes_create.go+4 −6internal/console/lifetimes_migrate.go+1 −1internal/console/lifetimes_retire.go+5 −1internal/console/remoteinstances.go+19 −4internal/console/server_test.go+1 −0internal/console/view_test.go+6 −0
diff --git a/internal/console/deletion_evidence_test.go b/internal/console/deletion_evidence_test.go| new file mode 100644 |
| index 000000000..a2cac9b74 |
| --- /dev/null |
| +++ b/internal/console/deletion_evidence_test.go |
| @@ -0,0 +1,195 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// witnessDeletionEvidence checks, in every console fixture, the invariant |
| +// the canary-retire guard rests on (#415): the console notes the deletion |
| +// of an instance or sidecar record (noteRecordDeletion) before the delete |
| +// reaches the bucket, whichever path deletes it. A delete the test itself |
| +// makes (a frame in a _test.go file calls the store directly) is a delete |
| +// behind the console's back and is not checked. A violation fails the test |
| +// when it ends, naming the key and the console function that deleted it. |
| +func witnessDeletionEvidence(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 := recordOwnerOfKey(key) |
| + if !ok { |
| + return |
| + } |
| + caller, console := deletingCaller() |
| + if !console { |
| + return |
| + } |
| + if srv.recentlyDeleted(acct, app, time.Now()) { |
| + return |
| + } |
| + mu.Lock() |
| + defer mu.Unlock() |
| + if !done { |
| + violations = append(violations, key+" deleted by "+caller+" with no deletion evidence for "+acct+"/"+app) |
| + } |
| + } |
| + ds.witness.Store(&w) |
| + t.Cleanup(func() { |
| + mu.Lock() |
| + defer mu.Unlock() |
| + done = true |
| + for _, v := range violations { |
| + t.Errorf("deletion evidence (#415): %s", v) |
| + } |
| + }) |
| +} |
| + |
| +// recordOwnerOfKey is the account and app of an instance or sidecar record |
| +// key: apps/<acct>/<app>/{instances,sidecars}/<name>.json. |
| +func recordOwnerOfKey(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 |
| +} |
| + |
| +// deletingCaller walks the delete's stack, past the store doubles and any |
| +// other package (release, provision, hostops), 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 deleting behind the console's |
| +// back. |
| +func deletingCaller() (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/deletion_evidence_test.go"), |
| + strings.HasSuffix(f.File, "/internal/console/view_test.go"): |
| + case strings.HasSuffix(f.File, "_test.go") && isStoreMethod(f.Function): |
| + // A test's store wrapper passing the console's delete 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 |
| + } |
| + } |
| +} |
| + |
| +// isStoreMethod reports whether fn is a release.Store method of some type |
| +// (a test's wrapper around the fixture's bucket). |
| +func isStoreMethod(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 "Delete", "DeleteIfMatch", "Put", "Get", "List", "ListMod": |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// lifetimeDetachedApp attaches ltDomain to shop as a first route with |
| +// lifetimes on (a record of its own), ages every record past the window, |
| +// forgets the console's deletion notes, checks the app reads as settled, |
| +// then detaches the domain through the API door. |
| +func lifetimeDetachedApp(t *testing.T) ltOn { |
| + t.Helper() |
| + l := newLtOn(t) |
| + l.fx.srv.cfg.Releases = ltModStore{l.bucket} |
| + ctx := context.Background() |
| + code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.member, |
| + `{"host":"`+ltDomain+`","kind":"static","channel":"stable"}`) |
| + if code != http.StatusOK { |
| + t.Fatalf("attach = %d %s", code, body) |
| + } |
| + root := l.fx.rel.(*deletableStore).root |
| + old := time.Now().Add(-channelSettle - time.Minute) |
| + keys, err := l.fx.rel.List(ctx, provision.RecordsPrefix("bab", ltApp)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, k := range keys { |
| + if err := os.Chtimes(filepath.Join(root, k), old, old); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + l.fx.srv.deletionsMu.Lock() |
| + l.fx.srv.deletions = nil |
| + l.fx.srv.deletionsMu.Unlock() |
| + if _, err := l.fx.srv.channelHosts(ctx, "bab", ltApp, "canary/x"); err != nil { |
| + t.Fatalf("fixture: a still app = %v", err) |
| + } |
| + if code, _, body := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.member, ""); code != http.StatusOK { |
| + t.Fatalf("detach = %d %s", code, body) |
| + } |
| + if raw, _ := rawOf(t, l.fx.rel, ltApp, ltDomain); raw != nil { |
| + t.Fatal("the record outlived the detach") |
| + } |
| + return l |
| +} |
| + |
| +// #415: a domain detach with lifetimes on removes its record through the |
| +// lifetime retirement steps, not retireHostRecord. The canary-retire guard |
| +// still waits out the window afterwards, with no audit row to lean on and |
| +// nothing left in the bucket to date the deletion. |
| +func TestRetireWaitsAfterLifetimeDetach(t *testing.T) { |
| + l := lifetimeDetachedApp(t) |
| + if _, err := l.fx.st.db.Exec(`DELETE FROM audit`); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err := l.fx.srv.channelHosts(context.Background(), "bab", ltApp, "canary/x") |
| + if !errorsIsUnsettled(err) || !strings.Contains(err.Error(), "deleted") { |
| + t.Fatalf("right after a lifetime detach = %v, want unsettled (deleted)", err) |
| + } |
| +} |
| + |
| +// #415: another console process over the same database has no notes in |
| +// memory; the detach's audit row dates the deletion for it. |
| +func TestRetireWaitsAfterLifetimeDetachOnAnotherConsole(t *testing.T) { |
| + l := lifetimeDetachedApp(t) |
| + srv := l.restart(t) |
| + srv.startedAt = time.Now().Add(-24 * time.Hour) |
| + _, err := srv.channelHosts(context.Background(), "bab", ltApp, "canary/x") |
| + if !errorsIsUnsettled(err) || !strings.Contains(err.Error(), "deleted") { |
| + t.Fatalf("a second console right after a lifetime detach = %v, want unsettled (deleted)", err) |
| + } |
| +} |
| + |
| +// ltModStore is the lifetimes bucket with the modification-time listing |
| +// every production store offers, which the canary-retire guard needs. |
| +type ltModStore struct{ *ltStore } |
| + |
| +func (s ltModStore) ListMod(ctx context.Context, prefix string) ([]release.KeyMod, error) { |
| + ml, ok := s.ltStore.Store.(release.ModLister) |
| + if !ok { |
| + return nil, errors.New("ltModStore: the wrapped store has no ListMod") |
| + } |
| + return ml.ListMod(ctx, prefix) |
| +} |
diff --git a/internal/console/lifetimes_create.go b/internal/console/lifetimes_create.go| index b7921bb0b..b615a7f0d 100644 |
| --- a/internal/console/lifetimes_create.go |
| +++ b/internal/console/lifetimes_create.go |
| @@ -10,7 +10,6 @@ import ( |
| "net/http" |
| "os" |
| "strings" |
| - "time" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| @@ -322,15 +321,14 @@ func (s *Server) allocSlotLocked(ctx context.Context, a Allocation) error { |
| // Any failure, a conflict included, leaves the allocation pending. |
| func (s *Server) allocCleanLocked(ctx context.Context, a Allocation, staleETag string, plan createPlan) error { |
| if staleETag != "" { |
| - s.noteRecordDeletion(a.Account, a.App, time.Now()) // the canary-retire guard's evidence, first |
| - if err := release.DeleteIfMatch(ctx, s.cfg.Releases, provision.RecordKey(a.Account, a.App, a.Host), staleETag); err != nil { |
| + if err := s.deleteRecordIfMatch(ctx, a.Account, a.App, provision.RecordKey(a.Account, a.App, a.Host), staleETag); err != nil { |
| log.Printf("console: lifetimes: allocation %s of %s: remove the stale record: %v (pending)", a.OpID, a.Host, err) |
| return errLifetimePending |
| } |
| } |
| if plan.ownerStaleETag != "" { |
| key := provision.RecordKey(plan.ownerAccount, plan.ownerApp, a.Host) |
| - if err := release.DeleteIfMatch(ctx, s.cfg.Releases, key, plan.ownerStaleETag); err != nil { |
| + if err := s.deleteRecordIfMatch(ctx, plan.ownerAccount, plan.ownerApp, key, plan.ownerStaleETag); err != nil { |
| log.Printf("console: lifetimes: allocation %s of %s: remove the stale record under %s/%s: %v (pending)", |
| a.OpID, a.Host, plan.ownerAccount, plan.ownerApp, err) |
| return errLifetimePending |
| @@ -369,7 +367,7 @@ func (s *Server) allocPrevOwnerCleanLocked(ctx context.Context, a Allocation) er |
| s.lifetimeLogHourly(logKey, "console: lifetime recovery: allocation %s of %s: the slot moved while removing the previous owner's record (pending)", a.OpID, a.Host) |
| return errLifetimePending |
| } |
| - if err := release.DeleteIfMatch(ctx, s.cfg.Releases, a.PrevOwnerKey, prev.ETag); err != nil { |
| + if err := s.deleteRecordIfMatch(ctx, acct, app, a.PrevOwnerKey, prev.ETag); err != nil { |
| s.lifetimeLogHourly(logKey, "console: lifetime recovery: allocation %s of %s: remove the stale record %s: %v (pending)", a.OpID, a.Host, a.PrevOwnerKey, err) |
| return errLifetimePending |
| } |
| @@ -546,7 +544,7 @@ func (s *Server) deleteUnderRetiredSlot(ctx context.Context, r Retirement, again |
| log.Printf("console: lifetimes: retirement %s of %s: the slot moved on (%+v); the body under %s is not this retirement's to remove", r.OpID, r.Host, slot, key) |
| return nil |
| } |
| - err = release.DeleteIfMatch(ctx, s.cfg.Releases, key, obs.ETag) |
| + err = s.deleteRecordIfMatch(ctx, r.Account, r.App, key, obs.ETag) |
| switch { |
| case err == nil, !errors.Is(err, release.ErrCASConflict): |
| return err |
diff --git a/internal/console/lifetimes_migrate.go b/internal/console/lifetimes_migrate.go| index 100197505..fcc70d134 100644 |
| --- a/internal/console/lifetimes_migrate.go |
| +++ b/internal/console/lifetimes_migrate.go |
| @@ -221,7 +221,7 @@ func (s *Server) migrationStepsLocked(ctx context.Context, m Migration) (*provis |
| logf("quarantine the corrupt body: %v (pending)", err) |
| return migrationPending() |
| } |
| - err := release.DeleteIfMatch(ctx, s.cfg.Releases, key, obs.ETag) |
| + err := s.deleteRecordIfMatch(ctx, m.Account, m.App, key, obs.ETag) |
| if errors.Is(err, release.ErrCASConflict) { |
| continue |
| } |
diff --git a/internal/console/lifetimes_retire.go b/internal/console/lifetimes_retire.go| index 8bb2c3165..d8399e549 100644 |
| --- a/internal/console/lifetimes_retire.go |
| +++ b/internal/console/lifetimes_retire.go |
| @@ -199,7 +199,7 @@ func (s *Server) retireStaleLocked(ctx context.Context, acct, app, host string, |
| } |
| return s.retirementStepsLocked(ctx, r) |
| } |
| - switch err := release.DeleteIfMatch(ctx, s.cfg.Releases, key, obs.ETag); { |
| + switch err := s.deleteRecordIfMatch(ctx, acct, app, key, obs.ETag); { |
| case err == nil: |
| return nil |
| case errors.Is(err, release.ErrCASConflict): |
| @@ -227,6 +227,10 @@ func (s *Server) retireStaleLocked(ctx context.Context, acct, app, host string, |
| // |
| // A failed write or re-read is pending, never a terminal branch. |
| func (s *Server) retirementStepsLocked(ctx context.Context, r Retirement) error { |
| + // The canary-retire guard's evidence, first: N1 turns the record into |
| + // its tombstone, which every reader takes as gone, and recovery enters |
| + // here with no wrapper of its own (#415). |
| + s.noteRecordDeletion(r.Account, r.App, time.Now()) |
| key := provision.RecordKey(r.Account, r.App, r.Host) |
| logf := func(format string, args ...any) { |
| log.Printf("console: lifetimes: retirement %s (%s) of %s: "+format, append([]any{r.OpID, r.Kind, r.Host}, args...)...) |
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go| index 60bf9f849..6fe36b5be 100644 |
| --- a/internal/console/remoteinstances.go |
| +++ b/internal/console/remoteinstances.go |
| @@ -558,9 +558,11 @@ var errRetireUnsettled = errors.New("the app's instances have not settled") |
| // every console path that deletes a record notes the app in memory |
| // before deleting (noteRecordDeletion: retireHostRecord, |
| // retireClaimHostRecord, deleteRead, finishSeedOnce, the owner's purge, |
| -// the claim purge and the expiry purge), |
| -// and the console refuses for channelSettle after it starts; the audit |
| -// log is read too; |
| +// the claim purge, the expiry purge, every lifetime retirement step |
| +// (retirementStepsLocked, which detach and recovery reach too) and |
| +// every lifetime delete of a stale body, the previous owner's included |
| +// (deleteRecordIfMatch)), and the console refuses for channelSettle |
| +// after it starts; the audit log is read too; |
| // - the box reports cannot all be read; or |
| // - a fresh box report names this account and app (its rollout entry) for |
| // a host no record names: a route still up after its record was |
| @@ -691,6 +693,16 @@ func (s *Server) noteRecordDeletion(acct, app string, at time.Time) { |
| s.boxReports.invalidate() |
| } |
| +// deleteRecordIfMatch is the conditional delete of an instance record |
| +// (key, a record key of acct/app) for every path that removes one: the |
| +// deletion is noted for the canary-retire guard first (noteRecordDeletion), |
| +// then the key is deleted on its ETag. A note for a delete that then fails |
| +// costs at most one refused retire for channelSettle. |
| +func (s *Server) deleteRecordIfMatch(ctx context.Context, acct, app, key, etag string) error { |
| + s.noteRecordDeletion(acct, app, time.Now()) |
| + return release.DeleteIfMatch(ctx, s.cfg.Releases, key, etag) |
| +} |
| + |
| // recentlyDeleted reports whether the console began deleting a record of |
| // acct/app within channelSettle. |
| func (s *Server) recentlyDeleted(acct, app string, now time.Time) bool { |
| @@ -732,7 +744,10 @@ func (s *Server) recentRecordDeletion(acct, app string, now time.Time) error { |
| if now.Sub(e.CreatedAt) >= channelSettle { |
| return nil // newest first: nothing older can be recent |
| } |
| - if e.Action == "instance-delete" || e.Action == "sidecar-delete" { |
| + // domain-detach: a detach of a first-route domain retires that |
| + // route's record (#415). Not every detach does, so this can hold a |
| + // retire that had nothing to wait for; it never lets one through. |
| + if e.Action == "instance-delete" || e.Action == "sidecar-delete" || e.Action == "domain-detach" { |
| return fmt.Errorf("%w: %s deleted %s ago", errRetireUnsettled, e.Target, now.Sub(e.CreatedAt).Round(time.Second)) |
| } |
| } |
diff --git a/internal/console/server_test.go b/internal/console/server_test.go| index 8cdddaf20..705927f56 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) |
| } |
| + witnessDeletionEvidence(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/view_test.go b/internal/console/view_test.go| index e1d2d7545..9336bc05c 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] |
| + // witness, when set, sees each Delete and DeleteIfMatch before the hook |
| + // above: newConsoleFixtureWith's deletion-evidence check (#415). |
| + witness atomic.Pointer[func(key string)] |
| } |
| func (d *deletableStore) setGetHook(h func(ctx context.Context, key string) error) { |
| @@ -58,6 +61,9 @@ func (d *deletableStore) setDeleteHook(h func(ctx context.Context, key string) e |
| } |
| func (d *deletableStore) runDeleteHook(ctx context.Context, key string) error { |
| + if w := d.witness.Load(); w != nil && *w != nil { |
| + (*w)(key) |
| + } |
| if h := d.deleteHook.Load(); h != nil && *h != nil { |
| return (*h)(ctx, key) |
| } |