carlos / platform Public

backfillAppPlacements decides each candidate again under the account lock and then the app lock (placeAppTarget's lock), from a fresh read of the column and the routes, so a place or an unplace that commits after the listing is never overwritten (Task 5 review, Important 1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 174a39720b7807c63f7c0b4bdba0d77366c3b0b4 parent e2b7e42
2 files changed, +192 −8
  • internal/console/sealkey.go +55 −8
  • internal/console/sealkey_test.go +137 −0

Intent

Human

<task-notification> <task-id>a769dfc11bbfdf41e</task-id> <tool-use-id>toolu_019awisS937VgecmYSDthN86</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/a769dfc11bbfdf41e.output</output-file> <status>completed</status> <summary>Agent "Implement Task 5: sealKeyFor and config" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>Status: DONE_WITH_CONCERNS Commit: e2b7e424 on `design-fleet-secrets-key`. Tests: 16 new console tests, 2 new CLI tests and 1 new appconfig test, all passing, along with the wider `Config|Secret|Place|Fleet` runs, the copy gate and the cross-builds. Each was shown failing before the change. Both required mutations make their tests fail (deployment-key fallback on a keyless fleet; owner check removed), and so do three more: no PUT lock, the account lock taken twice with plans on, and the CLI dropping `sealed_to`. Concerns: 1. The copy gate lets a placeholder match any text, so the C41 line also passes the gate as C40. A change to C40 alone would go unnoticed; the tests pin both sentences exactly. 2. The PUT reads `chooseSealKey`, not `sealKeyFor`, because it needs the fleet name for its refusals. `sealKeyFor` is `chooseSealKey` plus the one `NewSealer` call, so both use the same key. 3. I added one helper outside the brief's file list, `appconfig.EnvelopeBound`, so the PUT can refuse v1 envelopes on fleet apps. 4. The new 502 answers reuse the door's existing "could not read the config โ€” try again", which has an em dash. 5. For Task 6: team-environment minting now runs under the PUT's account lock, so Task 6 must not take that lock inside the mail or relay hooks. Report: /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-5-report.md</result> <usage><subagent_tokens>246577</subagent_tokens><tool_uses>103</tool_uses><duration_ms>1537896</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>a7d55619dcd5681e9</task-id> <tool-use-id>toolu_013Jj2y9ZjYkhU1us8fKEcBk</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/2d812478-ae68-44f2-8075-b2330abd5939/tasks/a7d55619dcd5681e9.output</output-file> <status>completed</status> <summary>Agent "Review Task 5 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Spec compliance:** โœ… Compliant. Two items can't be confirmed from this diff alone: - **Task 6:** the team-environment mail mint still seals to the deployment key, and it now runs under the PUT's account lock. Task 6 should pass the sealer through, not take `lockAccount` there. - **Placement race:** a place onto a fleet can land between a platform app's PUT check and its Apply. I1 still holds and the box refuses the value (an I2 miss). The later placement-refusal task should close it. **Task quality:** Needs fixes. **Critical:** none. **Important:** - `internal/console/sealkey.go:206-231`: `backfillAppPlacements` lists the routes once at the start, then reads each app's placement and writes it with a plain UPDATE, holding no lock. `placeAppTarget` writes placements under the app lock, so a place that lands mid-pass can be overwritten (risk e). A legacy app unplaced after the listing gets its old fleet written back. Fix: take `lockApp` per app and re-read the placement and routes under it. **Review:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-fleet-secrets-key/.superpowers/sdd/2026-10-29-fleet-secrets-key/task-5-review.md</result> <usage><subagent_tokens>121137</subagent_tokens><tool_uses>22</tool_uses><duration_ms>255242</duration_ms></usage> </task-notification>

Attributed to this commit: 20.9 g CO₂e (2,656,378 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-fleet-secrets-key, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/console/sealkey.go b/internal/console/sealkey.go
index 3d726ac09..e8d113f3a 100644
--- a/internal/console/sealkey.go
+++ b/internal/console/sealkey.go
@@ -187,8 +187,14 @@ func (s *Server) deploymentSealKey() (*ecdh.PublicKey, error) {
// (fleetFromRoutes), so the column becomes the one authority (spec ยง5.2 step
// 2). It does not change any answer appPlacement gives: appPlacement already
// falls back to the same routes for those apps. That is why it need not
-// finish before the first seal (plan ruling R-1). One route listing for the
-// whole pass; every app is tried, and the failures are joined.
+// finish before the first seal (plan ruling R-1).
+//
+// One route listing picks the candidates. Each candidate is then decided
+// again under the account lock and its app lock, the lock placeAppTarget
+// writes the column and the routes under, from a fresh read of both: a place
+// or an unplace that committed after the listing is never overwritten, and a
+// legacy app unplaced since never gets its old fleet back (backfillApp).
+// Every app is tried, and the failures are joined.
func (s *Server) backfillAppPlacements(ctx context.Context) error {
if s.cfg.Registry == "" {
return nil
@@ -221,23 +227,64 @@ func (s *Server) backfillAppPlacements(ctx context.Context) error {
errs = append(errs, fmt.Errorf("%s/%s: %w", acct.Sqid, app, err))
continue
}
- if placed != "" {
+ if placed != "" || fleetFromRoutes(routes, acct.Sqid, app) == "" {
continue
}
- target := fleetFromRoutes(routes, acct.Sqid, app)
- if target == "" {
- continue
+ if backfillPlacementBeforeWrite != nil {
+ backfillPlacementBeforeWrite(acct.Sqid, app)
}
- if err := s.store.SetAppPlacementContext(ctx, acct.ID, app, target); err != nil {
+ target, err := s.backfillApp(ctx, reg, acct, app)
+ if err != nil {
errs = append(errs, fmt.Errorf("%s/%s: %w", acct.Sqid, app, err))
continue
}
- log.Printf("console: app placement backfill: %s/%s placed on %s, from its routes", acct.Sqid, app, target)
+ if target != "" {
+ log.Printf("console: app placement backfill: %s/%s placed on %s, from its routes", acct.Sqid, app, target)
+ }
}
}
return errors.Join(errs...)
}
+// backfillApp is one candidate of the backfill, decided under the account
+// lock and then the app lock (the lock order of applocks.go), from the
+// column and the routes as they are now. It writes, and returns, the fleet
+// placement only if the column is still empty and the routes still say
+// fleet/<f>; "" means it wrote nothing. The background goroutine holds no
+// other lock, so neither is taken twice.
+func (s *Server) backfillApp(ctx context.Context, reg consoleRegistry, acct Account, app string) (string, error) {
+ defer s.lockAccount(acct.Sqid)()
+ defer s.lockApp(acct.Sqid, app)()
+ placed, err := s.store.AppPlacement(acct.ID, app)
+ if err != nil || placed != "" {
+ return "", err
+ }
+ routes, err := reg.List()
+ if err != nil {
+ return "", err
+ }
+ target := fleetFromRoutes(routes, acct.Sqid, app)
+ if target == "" {
+ return "", nil
+ }
+ if backfillPlacementLocked != nil {
+ backfillPlacementLocked(acct.Sqid, app)
+ }
+ if err := s.store.SetAppPlacementContext(ctx, acct.ID, app, target); err != nil {
+ return "", err
+ }
+ return target, nil
+}
+
+// backfillPlacementBeforeWrite runs between the backfill's route listing
+// and an app's locked decision. Test-only (TestBackfillAppPlacementsKeepsAConcurrentPlace);
+// nil in production.
+var backfillPlacementBeforeWrite func(sqid, app string)
+
+// backfillPlacementLocked runs inside backfillApp's locks, after its reads
+// and before its write. Test-only; nil in production.
+var backfillPlacementLocked func(sqid, app string)
+
// RunAppPlacementBackfill is backfillAppPlacements for cmd/console, run in
// the goroutine that runs the fleet owner backfill, never holding up
// serving. It logs the outcome; the next start tries again.
diff --git a/internal/console/sealkey_test.go b/internal/console/sealkey_test.go
index e4b80072a..4242a430d 100644
--- a/internal/console/sealkey_test.go
+++ b/internal/console/sealkey_test.go
@@ -16,6 +16,7 @@ import (
"fmt"
"net/http"
"os"
+ "strings"
"testing"
"time"
@@ -548,3 +549,139 @@ func TestBackfillAppPlacementsFromRoutes(t *testing.T) {
}
}
}
+
+// TestBackfillAppPlacementsKeepsAConcurrentPlace: a place or an unplace that
+// commits after the backfill listed the routes, and before it writes, is not
+// overwritten. The hook runs the place through its door at that point.
+func TestBackfillAppPlacementsKeepsAConcurrentPlace(t *testing.T) {
+ for _, c := range []struct {
+ name, target, want string
+ }{
+ {"a place onto another fleet", "fleet/away", "fleet/away"},
+ {"an unplace", "", ""},
+ // A place whose column landed and whose route stamping did not
+ // (placeAppTarget writes the column first): the column wins.
+ {"a column written without its routes", "column:fleet/away", "fleet/away"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-sk-backfill-race")
+ if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "away", "bucket": "away-data"}, token); status != http.StatusOK {
+ t.Fatalf("create away = %d %v", status, body)
+ }
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ // A legacy app: placed on home in its routes only, column empty.
+ reg := openTestReg(t, fx)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Account: fx.sqid, Region: "fleet/home"}); err != nil {
+ t.Fatal(err)
+ }
+ placed := false
+ backfillPlacementBeforeWrite = func(sqid, app string) {
+ if app != "shop" || placed {
+ return
+ }
+ placed = true
+ if col, ok := strings.CutPrefix(c.target, "column:"); ok {
+ if err := fx.st.SetAppPlacement(OpsAccountID, "shop", col); err != nil {
+ t.Fatal(err)
+ }
+ return
+ }
+ if status, body := postJSON(t, placeURL(fx, "shop"), map[string]string{"target": c.target}, token); status != http.StatusOK {
+ t.Fatalf("place shop on %q = %d %v", c.target, status, body)
+ }
+ }
+ t.Cleanup(func() { backfillPlacementBeforeWrite = nil })
+
+ if err := fx.srv.backfillAppPlacements(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if !placed {
+ t.Fatal("the hook never ran: shop was not a backfill candidate")
+ }
+ if got, err := fx.st.AppPlacement(OpsAccountID, "shop"); err != nil || got != c.want {
+ t.Fatalf("shop placement = %q %v, want %q: the backfill overwrote the place", got, err, c.want)
+ }
+ })
+ }
+}
+
+// skAppLockHolders is how many requests hold or wait on sqid/app's app lock.
+func skAppLockHolders(s *Server, sqid, app string) int {
+ s.appLocks.mu.Lock()
+ defer s.appLocks.mu.Unlock()
+ if e := s.appLocks.m[sqid+"/"+app]; e != nil {
+ return e.refs
+ }
+ return 0
+}
+
+// TestBackfillAppPlacementsHoldsTheAppLock: a place that arrives while the
+// backfill is deciding shop waits on the app lock, and lands after the
+// backfill's write, so the place wins. Deterministic: the hook inside the
+// backfill's locks, after its reads and before its write, starts the place
+// and returns only once it is waiting on the app lock (or, were the lock
+// missing, has finished, and the backfill would then write its stale read
+// over it).
+func TestBackfillAppPlacementsHoldsTheAppLock(t *testing.T) {
+ fx, token, _ := fskFixture(t, "code-sk-backfill-lock")
+ if status, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "away", "bucket": "away-data"}, token); status != http.StatusOK {
+ t.Fatalf("create away = %d %v", status, body)
+ }
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ reg := openTestReg(t, fx)
+ if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "instance", App: "shop", Account: fx.sqid, Region: "fleet/home"}); err != nil {
+ t.Fatal(err)
+ }
+ place := make(chan skAnswer, 1)
+ backfillPlacementLocked = func(sqid, app string) {
+ go func() {
+ place <- skPostAsync(placeURL(fx, "shop"), map[string]string{"target": "fleet/away"}, token)
+ }()
+ deadline := time.Now().Add(5 * time.Second)
+ for skAppLockHolders(fx.srv, sqid, app) < 2 && len(place) == 0 && time.Now().Before(deadline) {
+ time.Sleep(time.Millisecond)
+ }
+ }
+ t.Cleanup(func() { backfillPlacementLocked = nil })
+
+ if err := fx.srv.backfillAppPlacements(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case got := <-place:
+ if got.err != nil || got.status != http.StatusOK {
+ t.Fatalf("place = %d %v %v", got.status, got.body, got.err)
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("the place never answered")
+ }
+ if got, err := fx.st.AppPlacement(OpsAccountID, "shop"); err != nil || got != "fleet/away" {
+ t.Fatalf("shop placement = %q %v, want fleet/away: the backfill wrote over a place that had already committed", got, err)
+ }
+}
+
+// skPostAsync is skPutAsync for a POST.
+func skPostAsync(u string, body any, bearer string) skAnswer {
+ raw, err := json.Marshal(body)
+ if err != nil {
+ return skAnswer{err: err}
+ }
+ req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(raw))
+ if err != nil {
+ return skAnswer{err: err}
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ res, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return skAnswer{err: err}
+ }
+ defer res.Body.Close()
+ out := map[string]any{}
+ err = json.NewDecoder(res.Body).Decode(&out)
+ return skAnswer{status: res.StatusCode, body: out, err: err}
+}