carlos / platform Public

console: a born-HA app has no fleet placement, decided in one place

Branch review R1 P1 (stopping rule 2, option 3). effectivePlacement is
the one rule: a row with ha_pool has no fleet placement, whatever its
column or a stale legacy route says; other apps keep the column, then
the route fallback. appPlacement, Store.AppPlacement, fleetPlacedApps,
regionFactsFor and fleetAppRegions all go through it, and
TestEffectivePlacementIsTheOnlyRouteFallback refuses a route fold or a
placement SELECT anywhere else. TestStaleRouteNeverPlacesHAApp creates
an instance and a sidecar in the stale-route world: HA in us, pool ha;
a plain legacy app still inherits its fleet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev c2e4ab43e1fecaa10a292793b2dbb748cacb92ba parent 221bca3
6 files changed, +328 −29
  • internal/console/apiinstances_haenable_test.go +102 −0
  • internal/console/fleets.go +32 −8
  • internal/console/fleetsecretskey.go +8 −5
  • internal/console/placement_census_test.go +146 −0
  • internal/console/regionfacts.go +19 −9
  • internal/console/store.go +21 −7
diff --git a/internal/console/apiinstances_haenable_test.go b/internal/console/apiinstances_haenable_test.go
index 38e822f4f..194eb681b 100644
--- a/internal/console/apiinstances_haenable_test.go
+++ b/internal/console/apiinstances_haenable_test.go
@@ -22,6 +22,7 @@ import (
lsfile "github.com/benbjohnson/litestream/file"
"github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
)
// haEnableAppsDomain is the Task 3 worlds' PLATFORM_APPS_DOMAIN: the enable
@@ -492,3 +493,104 @@ func TestEnableHAManifestForBrowser(t *testing.T) {
m, _ = w.manifestOf(t, "ukapp")
wantManifest(t, "browser enable in us", m, "ha", []string{"us"})
}
+
+// TestStaleRouteNeverPlacesHAApp (branch review R1 P1, stopping rule 2
+// option 3): nothing deletes a purged app's routes, so a legacy fleet/pi
+// route left by a purged plain haapp names the born-HA haapp recreated
+// under that name. appPlacement (effectivePlacement) answers "" for it, so
+// its instance and its sidecar are born HA in us, pool ha, not placed on
+// the fleet. Control: a plain legacy app with the same kind of route still
+// inherits fleet/pi at both doors.
+//
+// The mutation that makes it fail: drop the haPool check in
+// effectivePlacement; haapp's placement reads fleet/pi and both creates
+// land on the fleet, not HA.
+func TestStaleRouteNeverPlacesHAApp(t *testing.T) {
+ w := haEnableWorld(t, "us", nil)
+ ctx := context.Background()
+ // The console's own registry handle (no second connection).
+ cached, err := openRegistry(w.srv.cfg.Registry)
+ if err != nil {
+ t.Fatal(err)
+ }
+ reg := cached.(*registry.Registry)
+ if _, err := reg.CreateFleet(registry.Fleet{Name: "pi", Account: "bab", Bucket: "pi-data"}); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ for _, app := range []string{"haapp", "legacy"} {
+ if _, err := w.st.CreateAppIn(OpsAccountID, app, "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.Upsert(registry.Route{Host: app + ".example.com", Kind: "instance", App: app, Account: "bab", Region: "fleet/pi"}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The plain haapp is purged; its route stays. The name comes back born HA.
+ if err := w.st.TrashAppRow(OpsAccountID, "haapp", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.st.PurgeAppRow(OpsAccountID, "haapp"); err != nil {
+ t.Fatal(err)
+ }
+ w.haApp(t, "haapp", "us")
+ if rt, err := reg.Get("haapp.example.com"); err != nil || rt == nil || rt.Region != "fleet/pi" {
+ t.Fatalf("fixture: the stale route = %+v %v, want fleet/pi", rt, err)
+ }
+ acct := &Account{ID: OpsAccountID, Sqid: "bab"}
+ for app, want := range map[string]string{"haapp": "", "legacy": "fleet/pi"} {
+ if got, err := w.srv.appPlacement(reg, acct, app); err != nil || got != want {
+ t.Errorf("appPlacement(%s) = %q %v, want %q", app, got, err, want)
+ }
+ }
+
+ // The instance door.
+ code, res := w.enable(t, "haapp", `{}`)
+ wantBody(t, "haapp enable", code, res, "ha", []string{"us"})
+ if code, res := w.enable(t, "legacy", `{}`); code != http.StatusOK {
+ t.Fatalf("legacy enable = %d %v", code, res)
+ }
+ create := func(app string) *provision.Record {
+ t.Helper()
+ host := haEnableHost(app)
+ if code, _, out := rawReq(t, http.MethodPost, instancesURL(w.consoleFixture, "bab", app), w.token,
+ fmt.Sprintf(`{"host":%q}`, host)); code != http.StatusCreated {
+ t.Fatalf("%s instance create = %d %s, want 201", app, code, out)
+ }
+ rec, err := provision.GetRecord(ctx, w.evidence, "bab", app, host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rec
+ }
+ if rec := create("haapp"); !rec.HA || rec.Pool != "ha" || rec.Region != "us" {
+ t.Errorf("haapp record = %+v, want HA in pool ha at us", rec)
+ }
+ if rec := create("legacy"); rec.HA || rec.Region != "fleet/pi" {
+ t.Errorf("control: legacy record = %+v, want legacy at fleet/pi", rec)
+ }
+
+ // The sidecar door.
+ for app, pool := range map[string]string{"haapp": "ha", "legacy": ""} {
+ sm := titoSidecarManifest()
+ sm.App, sm.Pool, sm.Regions = app, pool, nil
+ enableSidecars(t, w.consoleFixture, app, sm)
+ }
+ sidecar := func(app, body string) *provision.SidecarRecord {
+ t.Helper()
+ if code, _, out := rawReq(t, http.MethodPost, sidecarsURL(w.consoleFixture, "bab", app), w.token, body); code != http.StatusCreated {
+ t.Fatalf("%s sidecar create = %d %s, want 201", app, code, out)
+ }
+ rec, err := provision.GetSidecarRecord(ctx, w.evidence, "bab", app, "bot")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return rec
+ }
+ if rec := sidecar("haapp", `{"name":"bot","region":"us"}`); !rec.HA || rec.Pool != "ha" || rec.Region != "us" {
+ t.Errorf("haapp sidecar record = %+v, want HA in pool ha at us", rec)
+ }
+ if rec := sidecar("legacy", `{"name":"bot"}`); rec.HA || rec.Region != "fleet/pi" {
+ t.Errorf("control: legacy sidecar record = %+v, want legacy at fleet/pi", rec)
+ }
+}
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index 5ede5465c..14f23a00c 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -720,21 +720,45 @@ func (s *Server) handleAPIFleetDrainBox(w http.ResponseWriter, r *http.Request)
// happens to send — see placeAppTarget's doc comment for why that
// inheritance has to be a separate mechanism from the route/record stamping
// below, not the same one.
+//
+// A born-HA app has NO fleet placement (G6, branch review R1): its region
+// is its pool's. Nothing deletes a purged app's routes, so a legacy
+// fleet/<f> route can outlive its app and name a born-HA app recreated
+// under the same name; effectivePlacement answers "" for that row whatever
+// its column or its routes say.
func (s *Server) appPlacement(reg consoleRegistry, acct *Account, app string) (string, error) {
- stored, err := s.store.AppPlacement(acct.ID, app)
+ stored, haPool, err := s.store.appPlacementRow(acct.ID, app)
if err != nil {
return "", err
}
- if stored != "" {
- return stored, nil
- }
// Fallback: route-derived placement, for an app placed before the store
// column existed (see the doc comment above).
- routes, err := reg.List()
- if err != nil {
- return "", err
+ return effectivePlacement(stored, haPool, func() (string, error) {
+ routes, err := reg.List()
+ if err != nil {
+ return "", err
+ }
+ return legacyFleetFromRoutes(routes, acct.Sqid, app), nil
+ })
+}
+
+// effectivePlacement is the ONE rule for an app's effective fleet
+// placement, from its row's placement column (stored) and HA pool, and a
+// route fold the caller supplies: a born-HA app (haPool set) has none, and
+// fold is never run for it; otherwise the column, and when the column is
+// empty, fold's route-derived placement for an app placed by an older
+// build. fold nil is "no route fallback" (Store.AppPlacement's column-only
+// reading). Every reader of placement reaches it: appPlacement,
+// Store.AppPlacement, fleetPlacedApps, regionFactsFor and fleetAppRegions
+// (TestEffectivePlacementIsTheOnlyRouteFallback keeps it so).
+func effectivePlacement(stored, haPool string, fold func() (string, error)) (string, error) {
+ if haPool != "" {
+ return "", nil
+ }
+ if stored != "" || fold == nil {
+ return stored, nil
}
- return legacyFleetFromRoutes(routes, acct.Sqid, app), nil
+ return fold()
}
// staleSealedRefusal is FSK-C47: a move refused because the app has sealed
diff --git a/internal/console/fleetsecretskey.go b/internal/console/fleetsecretskey.go
index eff499d8a..4ddd2806b 100644
--- a/internal/console/fleetsecretskey.go
+++ b/internal/console/fleetsecretskey.go
@@ -378,22 +378,25 @@ func (s *Server) fleetPlacedAppsIn(acct *Account, fleet string, includeTrash boo
listed := false
var out []string
for _, app := range apps {
- placed, err := s.store.AppPlacement(acct.ID, app)
+ stored, haPool, err := s.store.appPlacementRow(acct.ID, app)
if err != nil {
return nil, err
}
- if placed == "" {
+ placed, err := effectivePlacement(stored, haPool, func() (string, error) {
if !listed {
reg, err := openRegistry(s.cfg.Registry)
if err != nil {
- return nil, err
+ return "", err
}
if routes, err = reg.List(); err != nil {
- return nil, err
+ return "", err
}
listed = true
}
- placed = legacyFleetFromRoutes(routes, acct.Sqid, app)
+ return legacyFleetFromRoutes(routes, acct.Sqid, app), nil
+ })
+ if err != nil {
+ return nil, err
}
if placed == target {
out = append(out, app)
diff --git a/internal/console/placement_census_test.go b/internal/console/placement_census_test.go
new file mode 100644
index 000000000..411f7a7f4
--- /dev/null
+++ b/internal/console/placement_census_test.go
@@ -0,0 +1,146 @@
+package console
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// TestEffectivePlacementIsTheOnlyRouteFallback keeps "a born-HA app has no
+// fleet placement" in one place (G6 branch review R1, stopping rule 2
+// option 3): effectivePlacement. Two ways round it fail here.
+//
+// - A route fold (legacyFleetFromRoutes, fleetFromRoutes) whose answer
+// becomes an app's placement must run inside a func literal handed to
+// effectivePlacement, which never runs it for a born-HA row. The few
+// functions allowed to fold elsewhere are listed with the reason their
+// answer cannot place a born-HA app.
+// - A SQL statement that SELECTs the apps placement column must be one
+// of the listed reads: appPlacementRow and LivePlacesNamed return
+// ha_pool beside it for effectivePlacement; the others are named with
+// their reason.
+//
+// A new reader fails here before it can ship.
+func TestEffectivePlacementIsTheOnlyRouteFallback(t *testing.T) {
+ folds := map[string]bool{"legacyFleetFromRoutes": true, "fleetFromRoutes": true}
+ foldOK := map[string]string{
+ "sealkey.go:backfillAppPlacements": "picks backfill candidates; the write is SetAppPlacementIfContext, which never places a born-HA row",
+ "sealkey.go:backfillApp": "the backfill's decision under its locks; same guarded write",
+ "view.go:assembleViews": "routeFleet is display input; regionFactsFor runs it through effectivePlacement",
+ "apitemporary.go:handleAPIAppList": "routeFleet for regionFactsFor, which runs it through effectivePlacement",
+ }
+ selectOK := map[string]string{
+ "store.go:appPlacementRow": "returns ha_pool beside placement for effectivePlacement",
+ "store.go:LivePlacesNamed": "returns ha_pool beside placement; fleetAppRegions applies effectivePlacement",
+ "store.go:migrateAppsKey": "the table rebuild copies the column",
+ "store.go:AppsPlacedOn": "matches a fleet target; a born-HA row's column is never one (every writer refuses or skips it)",
+ "replicaplacement.go:replicaFleetState": "matches a fleet target; a born-HA row's column is never one (every writer refuses or skips it)",
+ }
+ used := map[string]bool{}
+ selectPlacement := regexp.MustCompile(`(?is)\bSELECT\b.*\bplacement\b`)
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ var bad []string
+ for _, name := range files {
+ if strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := parser.ParseFile(fset, name, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, decl := range f.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ where := name + ":" + fn.Name.Name
+ // The func literals handed to effectivePlacement.
+ var inside []*ast.FuncLit
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ if call, ok := n.(*ast.CallExpr); ok && calleeName(call) == "effectivePlacement" {
+ for _, arg := range call.Args {
+ if lit, ok := arg.(*ast.FuncLit); ok {
+ inside = append(inside, lit)
+ }
+ }
+ }
+ return true
+ })
+ within := func(p token.Pos) bool {
+ for _, lit := range inside {
+ if p >= lit.Pos() && p < lit.End() {
+ return true
+ }
+ }
+ return false
+ }
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.CallExpr:
+ if folds[calleeName(x)] && !within(x.Pos()) {
+ if foldOK[where] == "" {
+ bad = append(bad, fset.Position(x.Pos()).String()+": "+calleeName(x)+" outside effectivePlacement in "+where)
+ }
+ used["fold "+where] = true
+ }
+ case *ast.BasicLit:
+ if x.Kind != token.STRING {
+ return true
+ }
+ v, err := strconv.Unquote(x.Value)
+ if err != nil {
+ return true
+ }
+ if selectPlacement.MatchString(v) {
+ if selectOK[where] == "" {
+ bad = append(bad, fset.Position(x.Pos()).String()+": a SELECT of the placement column in "+where)
+ }
+ used["select "+where] = true
+ }
+ }
+ return true
+ })
+ }
+ }
+ // A listed exception that no longer happens is stale: drop it.
+ for where := range foldOK {
+ if !used["fold "+where] {
+ bad = append(bad, "stale fold exception "+where)
+ }
+ }
+ for where := range selectOK {
+ if !used["select "+where] {
+ bad = append(bad, "stale SELECT exception "+where)
+ }
+ }
+ sort.Strings(bad)
+ for _, b := range bad {
+ t.Error(b)
+ }
+}
+
+// calleeName is a call's function or method name.
+func calleeName(call *ast.CallExpr) string {
+ switch f := call.Fun.(type) {
+ case *ast.Ident:
+ return f.Name
+ case *ast.SelectorExpr:
+ return f.Sel.Name
+ }
+ return ""
+}
diff --git a/internal/console/regionfacts.go b/internal/console/regionfacts.go
index 9bedc4f54..fa937cc31 100644
--- a/internal/console/regionfacts.go
+++ b/internal/console/regionfacts.go
@@ -1,6 +1,7 @@
package console
import (
+ "errors"
"fmt"
"log"
"sort"
@@ -107,6 +108,10 @@ func (f appRegionFacts) SourceSentence() string {
return ""
}
+// errRoutesUnread is a route fold's answer when the caller's registry
+// listing failed: the placement is unknown.
+var errRoutesUnread = errors.New("the registry's routes could not be read")
+
// legacyFleetFromRoutes is the placement an app placed by an older build
// carries only in its rows: the first fleet placement among sqid/app's rows
// that can carry one. A forward row is skipped (fleet public routes,
@@ -176,16 +181,19 @@ func (s *Server) registryRoutes() ([]registry.Route, bool) {
// listed (routeFleet, with routesOK false when that listing failed). An
// unread fact is unknown: never the home by default.
func (s *Server) regionFactsFor(acct *Account, app, routeFleet string, routesOK bool) appRegionFacts {
- placed, err := s.store.AppPlacement(acct.ID, app)
+ stored, haPool, err := s.store.appPlacementRow(acct.ID, app)
if err != nil {
log.Printf("console: region labels %s/%s: placement: %v", acct.Sqid, app, err)
return appRegionFacts{}
}
- if placed == "" {
+ placed, err := effectivePlacement(stored, haPool, func() (string, error) {
if !routesOK {
- return appRegionFacts{}
+ return "", errRoutesUnread
}
- placed = routeFleet
+ return routeFleet, nil
+ })
+ if err != nil {
+ return appRegionFacts{}
}
if name, ok := registry.FleetPlacement(placed); ok {
return appRegionFacts{Known: true, Fleet: name, Label: regionlabel.ForCode(placed, s.regionHome(), s.regionNames())}
@@ -283,13 +291,15 @@ func (s *Server) fleetAppRegions(names []string) map[string]string {
home, n := s.regionHome(), s.regionNames()
seen := map[string]map[string]bool{}
for _, r := range rows {
- placed := r.Placement
- if placed == "" {
+ placed, err := effectivePlacement(r.Placement, r.HAPool, func() (string, error) {
if !routesOK {
- seen[r.App] = map[string]bool{"": true, "?": true} // unknown: ambiguous by construction
- continue
+ return "", errRoutesUnread
}
- placed = fleetFromRoutes(routes, r.Sqid, r.App)
+ return fleetFromRoutes(routes, r.Sqid, r.App), nil
+ })
+ if err != nil {
+ seen[r.App] = map[string]bool{"": true, "?": true} // unknown: ambiguous by construction
+ continue
}
text := regionlabel.ForCode(r.Region, home, n).Text
if _, ok := registry.FleetPlacement(placed); ok {
diff --git a/internal/console/store.go b/internal/console/store.go
index 6ceb71599..737cd97db 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -2120,14 +2120,26 @@ func (s *Store) claimRawSetAppBuildProbe(accountID int64, app, path string) erro
// about that this store has no claim for at all) also reads as "", not an
// error — the same "absence is un-placed" answer, for a caller that has
// already proven the row exists as much as one that hasn't.
+//
+// A born-HA row reads "" whatever its column says (effectivePlacement, the
+// one placement rule).
func (s *Store) AppPlacement(accountID int64, app string) (string, error) {
- var placement string
- err := s.db.QueryRow(`SELECT placement FROM apps WHERE account_id = ? AND app = ?`, accountID, app).
- Scan(&placement)
+ placement, haPool, err := s.appPlacementRow(accountID, app)
+ if err != nil {
+ return "", err
+ }
+ return effectivePlacement(placement, haPool, nil)
+}
+
+// appPlacementRow is the row's raw placement column and HA pool, for
+// effectivePlacement; a missing row reads "", "".
+func (s *Store) appPlacementRow(accountID int64, app string) (placement, haPool string, err error) {
+ err = s.db.QueryRow(`SELECT placement, ha_pool FROM apps WHERE account_id = ? AND app = ?`, accountID, app).
+ Scan(&placement, &haPool)
if errors.Is(err, sql.ErrNoRows) {
- return "", nil
+ return "", "", nil
}
- return placement, err
+ return placement, haPool, err
}
// TrashAppRow marks an app trashed. Trashing twice keeps the FIRST timestamp
@@ -2362,6 +2374,8 @@ WHERE a.deleted_at = 0 ORDER BY a.sqid, p.app`)
type namedAppPlace struct {
AccountID int64
Sqid, App, Region, Placement string
+ // HAPool is the row's HA pool, for effectivePlacement.
+ HAPool string
}
// LivePlacesNamed lists every live app holding one of names, across
@@ -2374,7 +2388,7 @@ func (s *Store) LivePlacesNamed(names []string) ([]namedAppPlace, error) {
for i, n := range names {
args[i] = n
}
- rows, err := s.db.Query(`SELECT a.id, a.sqid, p.app, p.region, p.placement FROM apps p
+ rows, err := s.db.Query(`SELECT a.id, a.sqid, p.app, p.region, p.placement, p.ha_pool FROM apps p
JOIN accounts a ON a.id = p.account_id
WHERE p.deleted_at = 0 AND p.app IN (?`+strings.Repeat(",?", len(names)-1)+`) ORDER BY a.sqid, p.app`, args...)
if err != nil {
@@ -2384,7 +2398,7 @@ WHERE p.deleted_at = 0 AND p.app IN (?`+strings.Repeat(",?", len(names)-1)+`) OR
var out []namedAppPlace
for rows.Next() {
var r namedAppPlace
- if err := rows.Scan(&r.AccountID, &r.Sqid, &r.App, &r.Region, &r.Placement); err != nil {
+ if err := rows.Scan(&r.AccountID, &r.Sqid, &r.App, &r.Region, &r.Placement, &r.HAPool); err != nil {
return nil, err
}
out = append(out, r)