carlos / platform Public

Managed fleets 1b task 2: the console labels at create, behind the activation gate

On a fleet with two or more active boxes the create door stamps FleetBox and
FleetBoxAt (now, UTC) with the fresh, non-draining box at the label floor
holding the fewest records, ties by label, only while labelActive(): the
fleet was read whole, has no sidecars, holds no record failing movable, and
every deployment heartbeat (loadDeploymentBoxesComplete, AND of each
prefix's completeness) and the console are at release.FleetBoxLabelFloor
(v0.33.0). The fleet lock is held from loadFleetView through the record
write; seeded and imported creates release it first and stay unlabelled.

A rootfs create on an active fleet is admitted by the chosen box's
readiness (rule 7), refused with C05 when none is ready. The sidecar create
door refuses a fleet with two or more active boxes (rule 10).

fleetInventoryFor caches each fleet's record and sidecar bodies by ETag, so a
load lists each placed app once and re-reads only changed records; records
are judged through the context's judge each load. Store.AppsPlacedOn lists
placed apps; the registry's routes add legacy placements.

The existing private wire types fleetView/fleetBoxView in fleets.go are
renamed fleetWire/fleetBoxWire to free the plan's names.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 1948cb6f4d4e91877cbb04a0873a11749183cf4d parent dd880e4
10 files changed, +1,310 −15
  • internal/console/apiinstances.go +42 −2
  • internal/console/apisidecars.go +25 −0
  • internal/console/fleetbox.go +549 −0
  • internal/console/fleetbox_test.go +601 −0
  • internal/console/fleets.go +11 −11
  • internal/console/rootfs.go +24 −1
  • internal/console/server.go +9 −1
  • internal/console/store.go +27 −0
  • internal/release/layoutintent.go +12 −0
  • internal/release/layoutintent_test.go +10 −0
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index c0c79ece3..ac83809b8 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -2012,6 +2012,25 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, ref.Status, ref.Msg)
return
}
+ // Managed fleets 1b (rules 1, 7, 8): on a fleet the console labels, the
+ // record names the box that runs it. The fleet's lock is held from this
+ // read until the record is written, so concurrent creates count each
+ // other's records and spread. fleetActive is nil unless the activation
+ // gate is open; a view that cannot be read leaves the record unlabelled,
+ // as on main, and the rootfs admission below asks as it always did. A
+ // one-box fleet reads nothing beyond its registry rows.
+ var fleetActive *fleetView
+ unlockFleet := func() {}
+ defer func() { unlockFleet() }()
+ if fleet, ok := registry.FleetPlacement(placed); ok {
+ unlockFleet = s.lockFleet(fleet)
+ switch v, err := s.loadFleetView(ctx, fleet); {
+ case err != nil:
+ log.Printf("console: api instances create %s/%s: fleet %s view: %v", acct.Sqid, app, fleet, err)
+ case v.labelActive():
+ fleetActive = &v
+ }
+ }
// Rootfs apps (rootfs spec §5.0, §5.6, §5.7; Plan 4 Task 3). Only a
// socket-backed instance is a process the platform starts, so only its
// create asks what the creating release is: a static or addr-backed
@@ -2034,7 +2053,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
ctx = withUnfixedFirstKind(ctx, acct.Sqid, app)
}
if head.Rootfs {
- if ref := s.rootfsCreateRefusal(ctx, reg, acct, app, placed, region, m.Pool, probeRec.Role, seeded); ref != nil {
+ if ref := s.rootfsCreateRefusal(ctx, reg, acct, app, placed, region, m.Pool, probeRec.Role, seeded, fleetActive); ref != nil {
jsonError(w, ref.Status, ref.Msg)
return
}
@@ -2264,7 +2283,15 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
return
}
// Every ordinary check has passed: a seed door takes over from here, and
- // writes its own record (apiinstanceseed.go).
+ // writes its own record (apiinstanceseed.go). A seeded or imported record
+ // is not labelled, and the fleet's lock is let go first, so a long copy
+ // never holds up the fleet's other creates: the record is created
+ // unlabelled, as on main, and the relabel pass labels it by its binding
+ // once it has run (Task 6).
+ if req.From != nil || req.Import != nil {
+ unlockFleet()
+ unlockFleet = func() {}
+ }
if req.From != nil {
s.createFrom(w, r, seedCreate{acct: acct, app: app, principal: principal, message: message, m: m,
rec: rec, placed: placed, regionFrom: regionFrom, siblingLabel: siblingLabel, lifetime: lifetime}, *req.From)
@@ -2278,6 +2305,19 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// Born HA (region HA P1a): only here, after the seed doors above have
// taken their records, so a seed or an import is never stamped.
rec.HA = s.shouldStampHA(rec)
+ // The fleet box (managed fleets 1b, rule 1): on a fleet the gate admits,
+ // the ready box holding the fewest records, stamped with the time it was
+ // assigned, before the claim, lifetime and plain writers below all write
+ // this rec. A record the platform cannot move is left unlabelled (rule
+ // 11). No box to choose leaves it unlabelled too; a rootfs create never
+ // gets here without one (rootfsChosenBoxRefusal).
+ if fleetActive != nil && movable(rec) {
+ if box := fleetActive.chooseDestination(rec.Runtime == provision.RuntimeRootfsV1, ""); box != "" {
+ rec.FleetBox, rec.FleetBoxAt = box, time.Now().UTC().Format(time.RFC3339Nano)
+ } else {
+ log.Printf("console: api instances create %s/%s/%s: fleet %s has no box to label it to; created unlabelled", acct.Sqid, app, host, placed)
+ }
+ }
// A fresh budget for the write and its rollback: validation and the
// rail's listings may have spent most of the original one.
cancel()
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go
index ea26cc629..427b36c0c 100644
--- a/internal/console/apisidecars.go
+++ b/internal/console/apisidecars.go
@@ -52,6 +52,7 @@ import (
"github.com/carlosframework/platform/internal/hostops"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/regionlabel"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -278,6 +279,30 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
// The allow-list then reads the normalized code, as the instance door's
// does.
region := s.homeRegionIn(strings.TrimSpace(req.Region))
+ // Sidecars stay on one-box fleets for now (managed fleets 1b, rule 10):
+ // a fleet with sidecars is never labelled, so a sidecar is refused on a
+ // fleet with two or more active boxes. The fleet's lock is held through
+ // the write, taken before the plan lock as the instance door takes it,
+ // so a sidecar and a labelled create never both pass on the same counts.
+ if fleet, ok := registry.FleetPlacement(placed); ok {
+ defer s.lockFleet(fleet)()
+ boxes, err := reg.ListFleetBoxes(fleet)
+ if err != nil {
+ log.Printf("console: api sidecars create %s/%s: list fleet %s's boxes: %v", acct.Sqid, app, fleet, err)
+ jsonError(w, http.StatusBadGateway, "could not check this app's placement")
+ return
+ }
+ active := 0
+ for _, b := range boxes {
+ if b.Status == "active" {
+ active++
+ }
+ }
+ if active >= 2 {
+ jsonError(w, http.StatusConflict, msgSidecarNeedsSingleBoxFleet(fleet))
+ return
+ }
+ }
if placed != "" {
region = placed
} else if !provision.ValidRegion(region) || !instanceRegionAllowed(m.Regions, region) {
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go
new file mode 100644
index 000000000..1d252921e
--- /dev/null
+++ b/internal/console/fleetbox.go
@@ -0,0 +1,549 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "os"
+ "slices"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+ "github.com/carlosframework/platform/internal/version"
+)
+
+// Managed fleets 1b (spec "1b addendum", rules 1, 7, 8, 10, 11): on a fleet
+// with two or more boxes the console names, at create, the box that runs a
+// new instance (provision.Record.FleetBox). Only behind the activation gate
+// (labelActive): until every box of the deployment and the console run a
+// release that honours the label, and while the fleet holds sidecars or a
+// record the platform cannot move, the fleet stays unlabelled, as on main.
+//
+// The view a decision reads is loadFleetView's: the fleet's registry boxes
+// joined with their heartbeats, the deployment's complete heartbeat listing
+// for the gate, and the fleet's record inventory, cached per fleet so a
+// second read re-reads only the records whose ETag moved (Global
+// Constraints, request budget). The relabel worker (Task 6) reads the same
+// view, the same chooser and the same lock.
+
+// fleetView is one fleet as a labelling decision reads it.
+//
+// Active: the fleet has two or more active boxes (gate a) and every read
+// the view is built from was complete. HasSidecars: some sidecar record is
+// placed on the fleet (gate b). DeploymentCurrent: every heartbeat of the
+// deployment, platform and fleet, and the console itself report a release
+// at or above release.FleetBoxLabelFloor, from a complete listing (gates c
+// and d). Unmovable: some record on the fleet fails movable (rule 11).
+// Load counts the fleet's records by the box they are labelled to.
+type fleetView struct {
+ Boxes []fleetBoxView
+ Active, HasSidecars, DeploymentCurrent bool
+ Unmovable bool
+ Load map[string]int
+}
+
+// fleetBoxView is one active box of the fleet (registry status "active"),
+// with what its newest heartbeat says. A box with no heartbeat is not
+// fresh and has a zero LastSeen. Draining is false until the drain column
+// exists (Task 6).
+type fleetBoxView struct {
+ Label string
+ Fresh, Draining, RootfsReady, AtRootfsFloor, AtLabelFloor bool
+ LastSeen time.Time
+}
+
+// labelActive is the activation gate: the console labels this fleet's
+// records only when it has two or more active boxes and was read whole, has
+// no sidecars, the deployment and the console are at the label floor, and
+// every record on it is one the platform can move.
+func (v fleetView) labelActive() bool {
+ return v.Active && !v.HasSidecars && v.DeploymentCurrent && !v.Unmovable
+}
+
+// chooseDestination is rule 1's choice: among the boxes that are fresh, not
+// draining, at the label floor and not exclude (and, for a rootfs record,
+// rootfs-ready at the rootfs floor), the one holding the fewest records,
+// ties broken by label. "" when there is none. It asks nothing of the other
+// boxes, so a survivor is chosen whatever state its siblings are in.
+func (v fleetView) chooseDestination(rootfs bool, exclude string) string {
+ best, bestLoad := "", 0
+ for _, b := range v.Boxes {
+ if b.Label == exclude || !b.Fresh || b.Draining || !b.AtLabelFloor {
+ continue
+ }
+ if rootfs && !(b.RootfsReady && b.AtRootfsFloor) {
+ continue
+ }
+ load := v.Load[b.Label]
+ if best == "" || load < bestLoad || (load == bestLoad && b.Label < best) {
+ best, bestLoad = b.Label, load
+ }
+ }
+ return best
+}
+
+// movable reports whether rec is a process the platform runs and can stop
+// on one box and start on another by relabelling: no upstream address the
+// platform does not manage (Addr, Addrs), and either a rootfs runtime or a
+// hibernation that is not switched off.
+func movable(rec provision.Record) bool {
+ if rec.Addr != "" || len(rec.Addrs) > 0 {
+ return false
+ }
+ return rec.Runtime == provision.RuntimeRootfsV1 || rec.Hibernate == nil || *rec.Hibernate
+}
+
+// atLabelFloor reports whether a platform release parses at or above
+// release.FleetBoxLabelFloor. Missing or unparseable is false.
+func atLabelFloor(rel string) bool {
+ v, ok := release.ParseReleaseVersion(rel)
+ floor, _ := release.ParseReleaseVersion(release.FleetBoxLabelFloor)
+ return ok && v.Compare(floor) >= 0
+}
+
+// boxAtLabelFloor is atLabelFloor of the release a heartbeat names.
+func boxAtLabelFloor(b status.Box) bool {
+ return b.Metrics != nil && atLabelFloor(b.Metrics.Release)
+}
+
+// consoleAtLabelFloor is gate d: this console's own release.
+func (s *Server) consoleAtLabelFloor() bool {
+ build := s.consoleBuild
+ if build == "" {
+ build = version.Build
+ }
+ return atLabelFloor(build)
+}
+
+// lockFleet takes fleet's mutex: a create holds it from loadFleetView
+// through its record write, so two creates never choose from the same
+// counts, and the relabel worker holds it across a fleet's pass.
+func (s *Server) lockFleet(fleet string) (unlock func()) {
+ m, _ := s.fleetLocks.LoadOrStore(fleet, &sync.Mutex{})
+ mu := m.(*sync.Mutex)
+ mu.Lock()
+ return mu.Unlock
+}
+
+// msgSidecarNeedsSingleBoxFleet is the sidecar create door's refusal on a
+// fleet with two or more active boxes (rule 10).
+func msgSidecarNeedsSingleBoxFleet(fleet string) string {
+ return fmt.Sprintf("sidecars run only on a fleet with one box for now. fleet %s has more than one", fleet)
+}
+
+// loadDeploymentBoxesComplete reads every heartbeat of the deployment: the
+// platform's (status/boxes/, every region and pool) and each fleet's
+// (fleets/<name>/status/boxes/), through loadBoxes, so a request reads each
+// prefix once. complete is the AND of every prefix's own flag: a heartbeat
+// skipped as unreadable, oversize or corrupt, a capped listing, a fleet
+// prefix that would not list, or a fleet set that could not be read makes it
+// false. err is the platform listing's. Unlike systemBoxes, which drops the
+// per-prefix flag, nothing partial reads as whole here.
+func (s *Server) loadDeploymentBoxesComplete(ctx context.Context) (boxes []status.Box, complete bool, err error) {
+ if s.cfg.Releases == nil {
+ return nil, false, errors.New("no release store configured")
+ }
+ _, fleets, fleetsErr := s.systemFleets()
+ prefixes := []string{""}
+ for _, f := range fleets {
+ prefixes = append(prefixes, "fleets/"+f.Name+"/")
+ }
+ type read struct {
+ boxes []status.Box
+ complete bool
+ err error
+ }
+ reads := make([]read, len(prefixes))
+ forEachLimit(len(prefixes), readConcurrency, func(i int) {
+ b, c, err := s.loadBoxes(ctx, s.cfg.Releases, prefixes[i])
+ reads[i] = read{b, c, err}
+ })
+ if reads[0].err != nil {
+ return nil, false, reads[0].err
+ }
+ complete = fleetsErr == nil
+ if fleetsErr != nil {
+ log.Printf("console: deployment boxes: list fleets: %v", fleetsErr)
+ }
+ for i, r := range reads {
+ if r.err != nil {
+ log.Printf("console: deployment boxes: %sstatus/boxes/: %v", prefixes[i], r.err)
+ complete = false
+ continue
+ }
+ complete = complete && r.complete
+ boxes = append(boxes, r.boxes...)
+ }
+ return boxes, complete, nil
+}
+
+// loadFleetView reads fleet as a labelling decision needs it. Only a
+// registry that cannot be read is an error. A fleet with fewer than two
+// active boxes reads nothing more and is not Active; otherwise anything
+// that could not be read whole (the fleet's heartbeats, the deployment's,
+// the inventory) leaves Active false.
+func (s *Server) loadFleetView(ctx context.Context, fleet string) (fleetView, error) {
+ v := fleetView{Load: map[string]int{}}
+ reg, err := s.openPassRegistry()
+ if err != nil {
+ return v, err
+ }
+ regBoxes, err := reg.ListFleetBoxes(fleet)
+ if err != nil {
+ return v, err
+ }
+ for _, b := range regBoxes {
+ if b.Status == "active" {
+ v.Boxes = append(v.Boxes, fleetBoxView{Label: b.Label})
+ }
+ }
+ slices.SortFunc(v.Boxes, func(a, b fleetBoxView) int { return strings.Compare(a.Label, b.Label) })
+ if len(v.Boxes) < 2 || s.cfg.Releases == nil {
+ return v, nil
+ }
+ // The fleet's heartbeats are read twice below, alone and in the
+ // deployment's listing: a caller with no request memo (a background
+ // pass) gets one for the box reports, so each prefix is read once.
+ if memoOf(ctx, boxesMemoKey("")) == nil {
+ ctx = withWriteMemo(ctx)
+ }
+
+ whole := true
+ hbs, hbComplete, err := s.loadBoxes(ctx, s.cfg.Releases, "fleets/"+fleet+"/")
+ if err != nil || !hbComplete {
+ log.Printf("console: fleet %s view: heartbeats: complete %v, %v", fleet, hbComplete, err)
+ whole = false
+ }
+ beat := make(map[string]status.Box, len(hbs))
+ for _, b := range hbs {
+ beat[b.Label] = b
+ }
+ now := time.Now()
+ for i := range v.Boxes {
+ b, ok := beat[v.Boxes[i].Label]
+ if !ok {
+ continue
+ }
+ v.Boxes[i].Fresh = !status.BoxStale(b, now, status.SnapshotPeriod)
+ v.Boxes[i].RootfsReady = boxRootfsReady(b)
+ v.Boxes[i].AtRootfsFloor = boxAtRootfsFloor(b)
+ v.Boxes[i].AtLabelFloor = boxAtLabelFloor(b)
+ v.Boxes[i].LastSeen = b.GeneratedAt
+ }
+
+ deploy, deployComplete, err := s.loadDeploymentBoxesComplete(ctx)
+ if err != nil || !deployComplete {
+ log.Printf("console: fleet %s view: deployment heartbeats: complete %v, %v", fleet, deployComplete, err)
+ whole = false
+ }
+ current := err == nil && deployComplete && s.consoleAtLabelFloor()
+ for _, b := range deploy {
+ current = current && boxAtLabelFloor(b)
+ }
+ v.DeploymentCurrent = current
+
+ recs, sidecars, invComplete, err := s.fleetInventoryFor(ctx, fleet)
+ if err != nil || !invComplete {
+ log.Printf("console: fleet %s view: inventory: complete %v, %v", fleet, invComplete, err)
+ whole = false
+ }
+ for _, rec := range recs {
+ if rec.FleetBox != "" {
+ v.Load[rec.FleetBox]++
+ }
+ if !movable(rec) {
+ v.Unmovable = true
+ }
+ }
+ v.HasSidecars = sidecars > 0
+ v.Active = whole
+ return v, nil
+}
+
+// fleetInventoryMaxPerApp bounds the keys the inventory reads under one
+// app's instances/ or sidecars/; more makes the inventory incomplete.
+const fleetInventoryMaxPerApp = 10000
+
+// fleetInventory is one fleet's record cache (Global Constraints, request
+// budget): per instance record key, the ETag and body last read; per
+// sidecar record key, the ETag listed and the record. A load lists each
+// placed app's instances/ and sidecars/ with their ETags and reads only the
+// keys whose ETag differs from the cached one (or that a store without
+// ETags cannot vouch for). Lifetime validity is never cached: under a judge
+// every record is judged again on each load (the judge reads the slot),
+// with the cached body standing in for the record's own read.
+type fleetInventory struct {
+ mu sync.Mutex
+ records map[string]inventoryObject
+ sidecars map[string]inventorySidecar
+}
+
+type inventoryObject struct {
+ etag string
+ raw []byte
+}
+
+type inventorySidecar struct {
+ etag string
+ rec provision.SidecarRecord
+}
+
+// fleetInventory is fleet's cache, made on first use.
+func (s *Server) fleetInventory(fleet string) *fleetInventory {
+ inv, _ := s.fleetInventories.LoadOrStore(fleet, &fleetInventory{})
+ return inv.(*fleetInventory)
+}
+
+// fleetInventoryFor is fleet's inventory: every instance record placed on
+// it (Region "fleet/<name>") that its lifetime vouches for, as
+// ListRecordsCompleteJudged reads them under the context's judge, and how
+// many sidecar records are placed on it, as ListSidecarRecordsStrict reads
+// them, across every app placed on the fleet. complete is false when a
+// listing failed or was capped, or a record or sidecar could not be read or
+// judged. err is the placed apps' own read.
+func (s *Server) fleetInventoryFor(ctx context.Context, fleet string) (records []provision.Record, sidecars int, complete bool, err error) {
+ st := s.cfg.Releases
+ if st == nil {
+ return nil, 0, false, errors.New("no release store configured")
+ }
+ placement := registry.PlacementTarget(fleet)
+ apps, err := s.fleetInventoryApps(ctx, placement)
+ if err != nil {
+ return nil, 0, false, err
+ }
+ inv := s.fleetInventory(fleet)
+ inv.mu.Lock()
+ defer inv.mu.Unlock()
+ nextRecs := map[string]inventoryObject{}
+ nextSide := map[string]inventorySidecar{}
+ complete = true
+ j := provision.JudgeFrom(ctx)
+ for _, a := range apps {
+ recs, ok := inv.readRecords(ctx, st, j, a, nextRecs)
+ complete = complete && ok
+ for _, rec := range recs {
+ if rec.Region == placement {
+ records = append(records, rec)
+ }
+ }
+ side, ok := inv.readSidecars(ctx, st, a, nextSide)
+ complete = complete && ok
+ for _, rec := range side {
+ if rec.Region == placement {
+ sidecars++
+ }
+ }
+ }
+ inv.records, inv.sidecars = nextRecs, nextSide
+ return records, sidecars, complete, nil
+}
+
+// fleetInventoryApps is every app placed on placement: the store's placement
+// column (AppsPlacedOn), and any app whose instance routes in the registry
+// still carry it from a build older than the column (appPlacement's
+// fallback). No registry, or none yet, adds nothing; a registry that exists
+// and cannot be read is an error.
+func (s *Server) fleetInventoryApps(ctx context.Context, placement string) ([]AppRef, error) {
+ apps, err := s.store.AppsPlacedOn(ctx, placement)
+ if err != nil {
+ return nil, err
+ }
+ seen := map[AppRef]bool{}
+ for _, a := range apps {
+ seen[a] = true
+ }
+ if s.cfg.Registry != "" {
+ reg, err := s.openPassRegistry()
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ case err != nil:
+ return nil, err
+ default:
+ routes, err := reg.List()
+ if err != nil {
+ return nil, err
+ }
+ for _, rt := range routes {
+ if rt.IsForward() || rt.Region != placement || rt.App == "" {
+ continue
+ }
+ if a := (AppRef{Sqid: release.RouteAccount(rt), App: rt.App}); !seen[a] {
+ seen[a] = true
+ apps = append(apps, a)
+ }
+ }
+ }
+ }
+ sort.Slice(apps, func(i, k int) bool {
+ if apps[i].Sqid != apps[k].Sqid {
+ return apps[i].Sqid < apps[k].Sqid
+ }
+ return apps[i].App < apps[k].App
+ })
+ return apps, nil
+}
+
+// listKeyETags lists prefix with each key's ETag. A store without
+// ETagLister, or one whose listing with ETags fails, is listed plainly with
+// no ETags, which only costs the reads the ETags would have saved.
+func listKeyETags(ctx context.Context, st release.Store, prefix string) ([]release.KeyETag, error) {
+ if l, ok := st.(release.ETagLister); ok {
+ if kes, err := l.ListETags(ctx, prefix); err == nil {
+ return kes, nil
+ }
+ }
+ keys, err := st.List(ctx, prefix)
+ if err != nil {
+ return nil, err
+ }
+ kes := make([]release.KeyETag, len(keys))
+ for i, k := range keys {
+ kes[i] = release.KeyETag{Key: k}
+ }
+ return kes, nil
+}
+
+// carry keeps every cached entry under prefix for the next load, for an app
+// whose listing failed: its keys are unknown this time, not gone.
+func carry[T any](from, to map[string]T, prefix string) {
+ for k, v := range from {
+ if strings.HasPrefix(k, prefix) {
+ to[k] = v
+ }
+ }
+}
+
+// readRecords is one placed app's instance records, judged as
+// ListRecordsCompleteJudged judges them, reading a record's body only when
+// its listed ETag is not the cached one. Entries for next are the records
+// read or kept. ok is false when the listing failed or was capped, or a
+// record could not be read or judged.
+func (inv *fleetInventory) readRecords(ctx context.Context, st release.Store, j *provision.LifetimeJudge, a AppRef, next map[string]inventoryObject) ([]provision.Record, bool) {
+ prefix := provision.RecordsPrefix(a.Sqid, a.App)
+ kes, err := listKeyETags(ctx, st, prefix)
+ if err != nil {
+ log.Printf("console: fleet inventory %s/%s: list instances: %v", a.Sqid, a.App, err)
+ carry(inv.records, next, prefix)
+ return nil, false
+ }
+ ok := true
+ type entry struct {
+ key, host, etag string
+ }
+ var entries []entry
+ for _, ke := range kes {
+ if !provision.IsInstanceRecordKeyOf(ke.Key, a.Sqid, a.App) {
+ continue
+ }
+ host := strings.TrimSuffix(strings.TrimPrefix(ke.Key, prefix), ".json")
+ entries = append(entries, entry{ke.Key, host, ke.ETag})
+ }
+ sort.Slice(entries, func(i, k int) bool { return entries[i].host < entries[k].host })
+ if len(entries) > fleetInventoryMaxPerApp {
+ log.Printf("console: fleet inventory %s/%s: %d instance records, reading the first %d", a.Sqid, a.App, len(entries), fleetInventoryMaxPerApp)
+ entries = entries[:fleetInventoryMaxPerApp]
+ ok = false
+ }
+ type read struct {
+ rec *provision.Record
+ keep *inventoryObject
+ whole bool
+ }
+ reads := make([]read, len(entries))
+ forEachLimit(len(entries), readConcurrency, func(i int) {
+ e := entries[i]
+ var obs provision.Observation
+ if prev, hit := inv.records[e.key]; hit && e.etag != "" && prev.etag == e.etag {
+ obs = j.ObserveWith(ctx, st, a.Sqid, a.App, e.host, prev.raw, prev.etag, nil)
+ } else {
+ obs = j.Observe(ctx, st, a.Sqid, a.App, e.host)
+ }
+ r := read{whole: true}
+ switch {
+ case obs.Verdict == provision.LifetimeUnreadable || obs.Verdict == provision.LifetimeCorrupt:
+ log.Printf("console: fleet inventory %s/%s/%s: %v", a.Sqid, a.App, e.host, obs.Err)
+ r.whole = false
+ case !obs.Present:
+ // Gone since the listing.
+ default:
+ r.keep = &inventoryObject{etag: obs.ETag, raw: obs.Raw}
+ if obs.Verdict != provision.LifetimeStale && obs.Rec != nil && !obs.Rec.Retired {
+ r.rec = obs.Rec
+ }
+ }
+ reads[i] = r
+ })
+ var recs []provision.Record
+ for i, r := range reads {
+ ok = ok && r.whole
+ if r.keep != nil {
+ next[entries[i].key] = *r.keep
+ }
+ if r.rec != nil {
+ recs = append(recs, *r.rec)
+ }
+ }
+ return recs, ok
+}
+
+// readSidecars is one placed app's sidecar records, read as
+// ListSidecarRecordsStrict reads them, reading a record only when its
+// listed ETag is not the cached one. ok is false when the listing failed or
+// was capped, or a record could not be read.
+func (inv *fleetInventory) readSidecars(ctx context.Context, st release.Store, a AppRef, next map[string]inventorySidecar) ([]provision.SidecarRecord, bool) {
+ prefix := provision.SidecarsPrefix(a.Sqid, a.App)
+ kes, err := listKeyETags(ctx, st, prefix)
+ if err != nil {
+ log.Printf("console: fleet inventory %s/%s: list sidecars: %v", a.Sqid, a.App, err)
+ carry(inv.sidecars, next, prefix)
+ return nil, false
+ }
+ ok := true
+ type entry struct {
+ key, name, etag string
+ }
+ var entries []entry
+ for _, ke := range kes {
+ rest, found := strings.CutPrefix(ke.Key, prefix)
+ if !found || rest == "" || strings.Contains(rest, "/") {
+ continue
+ }
+ name, found := strings.CutSuffix(rest, ".json")
+ if !found || name == "" {
+ continue
+ }
+ entries = append(entries, entry{ke.Key, name, ke.ETag})
+ }
+ if len(entries) > fleetInventoryMaxPerApp {
+ log.Printf("console: fleet inventory %s/%s: %d sidecar records, reading the first %d", a.Sqid, a.App, len(entries), fleetInventoryMaxPerApp)
+ entries = entries[:fleetInventoryMaxPerApp]
+ ok = false
+ }
+ var recs []provision.SidecarRecord
+ for _, e := range entries {
+ if prev, hit := inv.sidecars[e.key]; hit && e.etag != "" && prev.etag == e.etag {
+ next[e.key] = prev
+ recs = append(recs, prev.rec)
+ continue
+ }
+ rec, err := provision.GetSidecarRecord(ctx, st, a.Sqid, a.App, e.name)
+ if errors.Is(err, os.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ log.Printf("console: fleet inventory %s/%s: sidecar %s: %v", a.Sqid, a.App, e.name, err)
+ ok = false
+ continue
+ }
+ next[e.key] = inventorySidecar{etag: e.etag, rec: *rec}
+ recs = append(recs, *rec)
+ }
+ return recs, ok
+}
diff --git a/internal/console/fleetbox_test.go b/internal/console/fleetbox_test.go
new file mode 100644
index 000000000..cc786630f
--- /dev/null
+++ b/internal/console/fleetbox_test.go
@@ -0,0 +1,601 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// Managed fleets 1b, Task 2: the console names a box for each new instance
+// of a fleet with two or more boxes, behind the activation gate. App shop
+// (and blog) in bab, fleet pi, boxes pi-1, pi-2, ..., hosts under
+// example.com.
+
+// fleetBoxWorld is shop in bab, its instances enabled, placed on fleet pi,
+// with each of boxes registered active and a fresh, rootfs-ready heartbeat
+// at the label floor. The console runs the floor too.
+func fleetBoxWorld(t *testing.T, code string, boxes ...string) (*consoleFixture, string, *registry.Registry) {
+ t.Helper()
+ fx, token := fleetFixture(t, code)
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "shop", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ reg := openTestReg(t, fx)
+ t.Cleanup(func() { reg.Close() })
+ if st, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new",
+ map[string]string{"name": "pi", "bucket": "pi-fleet-data"}, token); st != http.StatusOK {
+ t.Fatalf("create fleet pi = %d %v", st, body)
+ }
+ enableInstances(t, fx, "shop", rootfsShopManifest())
+ placeShop(t, fx, token, "pi")
+ for _, b := range boxes {
+ registerFleetBox(t, reg, "pi", b)
+ piBeat(t, fx, b, true, time.Now(), release.FleetBoxLabelFloor)
+ }
+ fx.srv.consoleBuild = release.FleetBoxLabelFloor
+ return fx, token, reg
+}
+
+// piBeat writes box's heartbeat on fleet pi.
+func piBeat(t *testing.T, fx *consoleFixture, box string, ready bool, at time.Time, rel string) {
+ t.Helper()
+ writeFleetBoxOn(t, fx, "pi", box, "", ready, at, rel)
+}
+
+// createShopAt creates shop's instance at host through the door, and
+// returns the stored record.
+func createShopAt(t *testing.T, fx *consoleFixture, token, host string) *provision.Record {
+ t.Helper()
+ if code, out := createShop(t, fx, token, `{"host":"`+host+`"}`); code != http.StatusCreated {
+ t.Fatalf("create %s = %d %s", host, code, out)
+ }
+ rec, _ := storedShop(t, fx, host)
+ return rec
+}
+
+// putFleetRecord writes a record of app on fleet pi straight to the bucket,
+// with mut applied first.
+func putFleetRecord(t *testing.T, fx *consoleFixture, app, host string, mut func(*provision.Record)) {
+ t.Helper()
+ rec := provision.Record{Schema: 1, Host: host, Slug: strings.TrimSuffix(host, ".example.com"), App: app,
+ Account: fx.sqid, Region: "fleet/pi", Channel: "edge", CreatedAt: time.Now().UTC()}
+ if mut != nil {
+ mut(&rec)
+ }
+ if err := provision.CreateRecord(context.Background(), fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// placeBlog claims app blog in bab and places it on fleet pi in the store.
+func placeBlog(t *testing.T, fx *consoleFixture) {
+ t.Helper()
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "blog", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.SetAppPlacement(OpsAccountID, "blog", "fleet/pi"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func wantNoLabel(t *testing.T, rec *provision.Record) {
+ t.Helper()
+ if rec.FleetBox != "" || rec.FleetBoxAt != "" || rec.FleetBoxMoved {
+ t.Fatalf("record %s labelled %q at %q (moved %v); want no label", rec.Host, rec.FleetBox, rec.FleetBoxAt, rec.FleetBoxMoved)
+ }
+}
+
+func wantLabel(t *testing.T, rec *provision.Record, box string) {
+ t.Helper()
+ if rec.FleetBox != box {
+ t.Fatalf("record %s labelled %q; want %q", rec.Host, rec.FleetBox, box)
+ }
+ at, err := time.Parse(time.RFC3339Nano, rec.FleetBoxAt)
+ if err != nil || time.Since(at) > time.Minute || at.Location() != time.UTC {
+ t.Fatalf("record %s assigned at %q (%v); want now, UTC", rec.Host, rec.FleetBoxAt, err)
+ }
+ if rec.FleetBoxMoved {
+ t.Fatalf("record %s born moved", rec.Host)
+ }
+}
+
+func TestCreateOnASingleBoxFleetLeavesNoLabel(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-single", "pi-1")
+ wantNoLabel(t, createShopAt(t, fx, token, "a.example.com"))
+ v, err := fx.srv.loadFleetView(context.Background(), "pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v.Active || v.labelActive() {
+ t.Fatalf("a one-box fleet's view %+v is active", v)
+ }
+}
+
+func TestCreateLabelsTheLeastLoadedReadyBox(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-least", "pi-1", "pi-2", "pi-3")
+ // Two records already on pi-1 and one on pi-2, from an earlier pass.
+ putFleetRecord(t, fx, "shop", "x1.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "shop", "x2.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "shop", "x3.example.com", func(r *provision.Record) { r.FleetBox = "pi-2" })
+ wantLabel(t, createShopAt(t, fx, token, "a.example.com"), "pi-3")
+ // pi-2 and pi-3 hold one each now: the tie goes by label.
+ wantLabel(t, createShopAt(t, fx, token, "b.example.com"), "pi-2")
+ wantLabel(t, createShopAt(t, fx, token, "c.example.com"), "pi-3")
+ wantLabel(t, createShopAt(t, fx, token, "d.example.com"), "pi-1")
+}
+
+func TestCreateSkipsStaleDrainingAndDetachedBoxes(t *testing.T) {
+ fx, token, reg := fleetBoxWorld(t, "code-fb-skip", "pi-1", "pi-2", "pi-3", "pi-4")
+ piBeat(t, fx, "pi-1", true, time.Now().Add(-time.Hour), release.FleetBoxLabelFloor) // stale
+ if err := reg.SetFleetBoxStatus("pi", "pi-2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ got := map[string]int{}
+ for i := 0; i < 4; i++ {
+ rec := createShopAt(t, fx, token, fmt.Sprintf("s%d.example.com", i))
+ got[rec.FleetBox]++
+ }
+ if got["pi-3"] != 2 || got["pi-4"] != 2 || len(got) != 2 {
+ t.Fatalf("labels %v; want two each on pi-3 and pi-4, none on the stale pi-1 or the detached pi-2", got)
+ }
+
+ // A draining box is never a destination; the choice needs only one
+ // eligible box, whatever the others' freshness; exclude is honoured.
+ ready := fleetBoxView{Fresh: true, RootfsReady: true, AtRootfsFloor: true, AtLabelFloor: true}
+ box := func(label string, mut func(*fleetBoxView)) fleetBoxView {
+ b := ready
+ b.Label = label
+ if mut != nil {
+ mut(&b)
+ }
+ return b
+ }
+ v := fleetView{Boxes: []fleetBoxView{
+ box("pi-1", func(b *fleetBoxView) { b.Draining = true }),
+ box("pi-2", func(b *fleetBoxView) { b.Fresh = false }),
+ box("pi-3", nil),
+ box("pi-4", func(b *fleetBoxView) { b.RootfsReady = false }),
+ }, Load: map[string]int{"pi-3": 5}}
+ for _, tc := range []struct {
+ rootfs bool
+ exclude string
+ want string
+ }{
+ {false, "", "pi-4"},
+ {true, "", "pi-3"},
+ {false, "pi-4", "pi-3"},
+ {true, "pi-3", ""},
+ } {
+ if got := v.chooseDestination(tc.rootfs, tc.exclude); got != tc.want {
+ t.Errorf("chooseDestination(rootfs %v, exclude %q) = %q; want %q", tc.rootfs, tc.exclude, got, tc.want)
+ }
+ }
+ below := fleetView{Boxes: []fleetBoxView{box("pi-1", func(b *fleetBoxView) { b.AtLabelFloor = false })}}
+ if got := below.chooseDestination(false, ""); got != "" {
+ t.Errorf("a box below the label floor was chosen: %q", got)
+ }
+}
+
+func TestGateNeedsEveryDeploymentBoxCurrent(t *testing.T) {
+ fx, token, reg := fleetBoxWorld(t, "code-fb-deploy", "pi-1", "pi-2")
+ // A platform box below the floor.
+ writeFleetBoxOn(t, fx, "", "box-1", "", true, time.Now(), "v0.32.9")
+ wantNoLabel(t, createShopAt(t, fx, token, "a.example.com"))
+ writeFleetBoxOn(t, fx, "", "box-1", "", true, time.Now(), release.FleetBoxLabelFloor)
+
+ // A box of another fleet below the floor.
+ if st, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new",
+ map[string]string{"name": "away", "bucket": "away-fleet-data"}, token); st != http.StatusOK {
+ t.Fatalf("create fleet away = %d %v", st, body)
+ }
+ registerFleetBox(t, reg, "away", "aw-1")
+ writeFleetBoxOn(t, fx, "away", "aw-1", "", true, time.Now(), "v0.31.1")
+ wantNoLabel(t, createShopAt(t, fx, token, "b.example.com"))
+ writeFleetBoxOn(t, fx, "away", "aw-1", "", true, time.Now(), release.FleetBoxLabelFloor)
+
+ // A box of this fleet that names no release.
+ piBeat(t, fx, "pi-2", true, time.Now(), "")
+ wantNoLabel(t, createShopAt(t, fx, token, "c.example.com"))
+ piBeat(t, fx, "pi-2", true, time.Now(), release.FleetBoxLabelFloor)
+
+ // The console itself below the floor.
+ fx.srv.consoleBuild = "dev"
+ wantNoLabel(t, createShopAt(t, fx, token, "d.example.com"))
+ fx.srv.consoleBuild = release.FleetBoxLabelFloor
+
+ // Every box and the console current: labelled.
+ wantLabel(t, createShopAt(t, fx, token, "e.example.com"), "pi-1")
+}
+
+func TestGateClosedForAFleetWithSidecars(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-sidecars", "pi-1", "pi-2")
+ wantLabel(t, createShopAt(t, fx, token, "z.example.com"), "pi-1") // open before the sidecar
+ if err := provision.CreateSidecarRecord(context.Background(), fx.rel, provision.SidecarRecord{Schema: 1, Name: "bot",
+ Host: provision.SidecarHost("bot", "shop", fx.sqid), App: "shop", Account: fx.sqid, Region: "fleet/pi",
+ Channel: "edge", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ wantNoLabel(t, createShopAt(t, fx, token, "a.example.com"))
+ v, err := fx.srv.loadFleetView(context.Background(), "pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !v.HasSidecars || v.labelActive() {
+ t.Fatalf("view %+v; want sidecars seen and the gate closed", v)
+ }
+}
+
+func TestGateClosedForAnUnmanagedRecord(t *testing.T) {
+ off := false
+ for _, tc := range []struct {
+ name string
+ mut func(*provision.Record)
+ }{
+ {"an addr record", func(r *provision.Record) { r.Kind = "instance"; r.Addr = "127.0.0.1:9000" }},
+ {"an addrs record", func(r *provision.Record) { r.Kind = "instance"; r.Addrs = []string{"127.0.0.1:9000"} }},
+ {"a binary that never hibernates", func(r *provision.Record) { r.Hibernate = &off }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-unmanaged", "pi-1", "pi-2")
+ wantLabel(t, createShopAt(t, fx, token, "z.example.com"), "pi-1") // open before it
+ putFleetRecord(t, fx, "shop", "svc.example.com", tc.mut)
+ wantNoLabel(t, createShopAt(t, fx, token, "a.example.com"))
+ wantNoLabel(t, createShopAt(t, fx, token, "b.example.com"))
+ })
+ }
+
+ on := true
+ for _, tc := range []struct {
+ name string
+ rec provision.Record
+ want bool
+ }{
+ {"a binary instance", provision.Record{}, true},
+ {"a binary that hibernates", provision.Record{Hibernate: &on}, true},
+ {"a binary that never hibernates", provision.Record{Hibernate: &off}, false},
+ {"an always-on rootfs instance", provision.Record{Runtime: provision.RuntimeRootfsV1, Hibernate: &off}, true},
+ {"an addr record", provision.Record{Addr: "127.0.0.1:9000"}, false},
+ {"an addrs record", provision.Record{Addrs: []string{"127.0.0.1:9000"}}, false},
+ } {
+ if got := movable(tc.rec); got != tc.want {
+ t.Errorf("movable(%s) = %v; want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestGateClosedOnAnIncompleteListing(t *testing.T) {
+ t.Run("a skipped heartbeat below the floor", func(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-skipped", "pi-1", "pi-2")
+ writeFleetBoxOn(t, fx, "", "box-old", "", true, time.Now(), "v0.30.0")
+ base := fx.srv.cfg.Releases
+ fx.srv.cfg.Releases = &failGetStore{Store: base, key: "status/boxes/box-old.json"}
+ boxes, complete, err := fx.srv.loadDeploymentBoxesComplete(context.Background())
+ if err != nil || complete {
+ t.Fatalf("loadDeploymentBoxesComplete = %d boxes, complete %v, %v; want incomplete", len(boxes), complete, err)
+ }
+ wantNoLabel(t, createShopAt(t, fx, token, "a.example.com"))
+ fx.srv.cfg.Releases = base
+ })
+ t.Run("a capped listing", func(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-capped", "pi-1", "pi-2")
+ for i := 0; i <= 200; i++ {
+ writeFleetBoxOn(t, fx, "", fmt.Sprintf("box-%03d", i), "", true, time.Now(), release.FleetBoxLabelFloor)
+ }
+ if _, complete, err := fx.srv.loadDeploymentBoxesComplete(context.Background()); err != nil || complete {
+ t.Fatalf("a capped listing: complete %v, %v; want incomplete", complete, err)
+ }
+ wantNoLabel(t, createShopAt(t, fx, token, "a.example.com"))
+ })
+ t.Run("everything read", func(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-fb-complete", "pi-1", "pi-2")
+ writeFleetBoxOn(t, fx, "", "box-1", "", true, time.Now(), release.FleetBoxLabelFloor)
+ boxes, complete, err := fx.srv.loadDeploymentBoxesComplete(context.Background())
+ if err != nil || !complete || len(boxes) != 3 {
+ t.Fatalf("loadDeploymentBoxesComplete = %d boxes, complete %v, %v; want the platform box and pi's two", len(boxes), complete, err)
+ }
+ })
+}
+
+func TestSidecarOnlyAppClosesTheGate(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-sidecar-only", "pi-1", "pi-2")
+ placeBlog(t, fx)
+ wantLabel(t, createShopAt(t, fx, token, "z.example.com"), "pi-1") // open before blog's sidecar
+ if err := provision.CreateSidecarRecord(context.Background(), fx.rel, provision.SidecarRecord{Schema: 1, Name: "bot",
+ Host: provision.SidecarHost("bot", "blog", fx.sqid), App: "blog", Account: fx.sqid, Region: "fleet/pi",
+ Channel: "edge", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ _, sidecars, complete, err := fx.srv.fleetInventoryFor(context.Background(), "pi")
+ if err != nil || !complete || sidecars != 1 {
+ t.Fatalf("inventory: %d sidecars, complete %v, %v; want blog's one", sidecars, complete, err)
+ }
+ wantNoLabel(t, createShopAt(t, fx, token, "a.example.com"))
+}
+
+// countStore counts store calls by kind and key, and forwards the listing
+// with ETags the inventory asks for.
+type countStore struct {
+ release.Store
+ mu sync.Mutex
+ gets map[string]int
+ puts map[string]int
+ lists map[string]int
+}
+
+func newCountStore(inner release.Store) *countStore {
+ return &countStore{Store: inner, gets: map[string]int{}, puts: map[string]int{}, lists: map[string]int{}}
+}
+
+func (c *countStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ c.mu.Lock()
+ c.gets[key]++
+ c.mu.Unlock()
+ return c.Store.Get(ctx, key)
+}
+
+func (c *countStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ c.mu.Lock()
+ c.puts[key]++
+ c.mu.Unlock()
+ return c.Store.Put(ctx, key, body, ifMatch)
+}
+
+func (c *countStore) List(ctx context.Context, prefix string) ([]string, error) {
+ c.mu.Lock()
+ c.lists[prefix]++
+ c.mu.Unlock()
+ return c.Store.List(ctx, prefix)
+}
+
+func (c *countStore) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) {
+ c.mu.Lock()
+ c.lists[prefix]++
+ c.mu.Unlock()
+ inner := c.Store
+ if d, ok := inner.(*deletableStore); ok {
+ inner = d.Store // the fixture's wrapper lists no ETags; its DirStore does
+ }
+ return inner.(release.ETagLister).ListETags(ctx, prefix)
+}
+
+func (c *countStore) reset() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.gets, c.puts, c.lists = map[string]int{}, map[string]int{}, map[string]int{}
+}
+
+// recordGets is how many reads of app's instance records were made.
+func (c *countStore) recordGets(sqid, app string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ n := 0
+ for k, v := range c.gets {
+ if provision.IsInstanceRecordKeyOf(k, sqid, app) {
+ n += v
+ }
+ }
+ return n
+}
+
+// recordPuts is how many writes of any instance record were made.
+func (c *countStore) recordPuts() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ n := 0
+ for k, v := range c.puts {
+ if strings.Contains(k, "/instances/") && strings.HasSuffix(k, ".json") {
+ n += v
+ }
+ }
+ return n
+}
+
+// getsOf is how many reads of keys were made.
+func (c *countStore) getsOf(keys ...string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ n := 0
+ for _, k := range keys {
+ n += c.gets[k]
+ }
+ return n
+}
+
+func (c *countStore) listsOf(prefix string) int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.lists[prefix]
+}
+
+func TestInventoryRereadsOnlyChangedRecords(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-fb-reread", "pi-1", "pi-2")
+ for _, h := range []string{"a", "b", "c"} {
+ putFleetRecord(t, fx, "shop", h+".example.com", nil)
+ }
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+ ctx := context.Background()
+ load := func(want int) {
+ t.Helper()
+ recs, _, complete, err := fx.srv.fleetInventoryFor(ctx, "pi")
+ if err != nil || !complete || len(recs) != want {
+ t.Fatalf("inventory: %d records, complete %v, %v; want %d", len(recs), complete, err, want)
+ }
+ }
+ load(3)
+ if n := cs.recordGets(fx.sqid, "shop"); n != 3 {
+ t.Fatalf("the first load read %d records; want 3", n)
+ }
+ cs.reset()
+ load(3)
+ if n := cs.recordGets(fx.sqid, "shop"); n != 0 {
+ t.Fatalf("an unchanged second load read %d records; want none", n)
+ }
+ if n := cs.listsOf(provision.RecordsPrefix(fx.sqid, "shop")); n != 1 {
+ t.Fatalf("the second load listed shop's instances %d times; want once", n)
+ }
+ // One record changes: only it is read again.
+ rec, err := provision.GetRecord(ctx, fx.rel, fx.sqid, "shop", "b.example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.SetRecordFleetBox(ctx, fx.rel, fx.sqid, "shop", "b.example.com",
+ provision.FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt}, "pi-2", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ cs.reset()
+ load(3)
+ if n := cs.recordGets(fx.sqid, "shop"); n != 1 {
+ t.Fatalf("one changed record cost %d reads; want 1", n)
+ }
+ recs, _, _, _ := fx.srv.fleetInventoryFor(ctx, "pi")
+ for _, r := range recs {
+ if r.Host == "b.example.com" && r.FleetBox != "pi-2" {
+ t.Fatalf("the inventory kept b's old body: %+v", r)
+ }
+ }
+ // A record that is gone leaves the inventory.
+ if err := provision.DeleteRecord(ctx, fx.rel, fx.sqid, "shop", "c.example.com"); err != nil {
+ t.Fatal(err)
+ }
+ load(2)
+ // An unreadable record makes it incomplete. (failGetStore lists with no
+ // ETags, so every record is read again.)
+ fx.srv.cfg.Releases = &failGetStore{Store: fx.rel, key: provision.RecordKey(fx.sqid, "shop", "a.example.com")}
+ if _, _, complete, err := fx.srv.fleetInventoryFor(ctx, "pi"); err != nil || complete {
+ t.Fatalf("an unreadable record: complete %v, %v; want incomplete", complete, err)
+ }
+}
+
+func TestConcurrentCreatesSpreadAcrossBoxes(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-concurrent", "pi-1", "pi-2")
+ const n = 6
+ var wg sync.WaitGroup
+ codes := make([]int, n)
+ outs := make([]string, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ codes[i], _, outs[i] = rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "shop"), token,
+ fmt.Sprintf(`{"host":"c%d.example.com"}`, i))
+ }(i)
+ }
+ wg.Wait()
+ got := map[string]int{}
+ for i := 0; i < n; i++ {
+ if codes[i] != http.StatusCreated {
+ t.Fatalf("create %d = %d %s", i, codes[i], outs[i])
+ }
+ rec, _ := storedShop(t, fx, fmt.Sprintf("c%d.example.com", i))
+ got[rec.FleetBox]++
+ }
+ if got["pi-1"] != n/2 || got["pi-2"] != n/2 {
+ t.Fatalf("labels %v; want %d on each box", got, n/2)
+ }
+}
+
+func TestSidecarCreateRefusedOnAMultiBoxFleet(t *testing.T) {
+ sidecarShop := provision.SidecarManifest{Schema: 1, App: "shop", Channel: "edge", Args: []string{"sidecar", "run"}}
+ t.Run("two boxes", func(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-side-multi", "pi-1", "pi-2")
+ enableSidecars(t, fx, "shop", sidecarShop)
+ code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx, fx.sqid, "shop"), token, `{"name":"bot"}`)
+ if code != http.StatusConflict || errorText(out) != msgSidecarNeedsSingleBoxFleet("pi") {
+ t.Fatalf("sidecar create = %d %s; want 409 %q", code, out, msgSidecarNeedsSingleBoxFleet("pi"))
+ }
+ if _, err := provision.GetSidecarRecord(context.Background(), fx.rel, fx.sqid, "shop", "bot"); err == nil {
+ t.Fatal("a refused sidecar create wrote its record")
+ }
+ })
+ t.Run("one box", func(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-side-single", "pi-1")
+ enableSidecars(t, fx, "shop", sidecarShop)
+ if code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx, fx.sqid, "shop"), token, `{"name":"bot"}`); code != http.StatusCreated {
+ t.Fatalf("sidecar create on a one-box fleet = %d %s; want 201", code, out)
+ }
+ })
+}
+
+func TestRootfsAdmissionFollowsTheChosenBox(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-rootfs", "pi-1", "pi-2")
+ piBeat(t, fx, "pi-1", false, time.Now(), release.FleetBoxLabelFloor) // not rootfs-ready
+ shipShop(t, fx, false)
+ rec := createShopAt(t, fx, token, "a.example.com")
+ if rec.Runtime != provision.RuntimeRootfsV1 {
+ t.Fatalf("stored %+v; want a rootfs record", rec)
+ }
+ // pi-1 holds nothing and wins a tie by label, but only pi-2 is ready.
+ wantLabel(t, rec, "pi-2")
+ // A binary record could go to pi-1; a rootfs one still goes to pi-2.
+ wantLabel(t, createShopAt(t, fx, token, "b.example.com"), "pi-2")
+
+ // No ready destination on an active fleet: today's refusal.
+ piBeat(t, fx, "pi-2", false, time.Now(), release.FleetBoxLabelFloor)
+ code, out := createShop(t, fx, token, `{"host":"c.example.com"}`)
+ if code != http.StatusConflict || errorText(out) != fmt.Sprintf(rootfsFleetNotReadyMsg, "pi") {
+ t.Fatalf("create with no ready box = %d %s; want 409 %q", code, out, fmt.Sprintf(rootfsFleetNotReadyMsg, "pi"))
+ }
+ noShopRecord(t, fx, "c.example.com")
+}
+
+func TestCreateOnALabelledFleetCostsOneInventory(t *testing.T) {
+ fx, token, _ := fleetBoxWorld(t, "code-fb-cost", "pi-1", "pi-2")
+ placeBlog(t, fx)
+ putFleetRecord(t, fx, "blog", "blog1.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ putFleetRecord(t, fx, "blog", "blog2.example.com", func(r *provision.Record) { r.FleetBox = "pi-2" })
+ // The create's other checks read blog's key for the new host (hostHolder);
+ // the inventory reads only blog's records.
+ blogRecs := []string{provision.RecordKey(fx.sqid, "blog", "blog1.example.com"), provision.RecordKey(fx.sqid, "blog", "blog2.example.com")}
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+
+ wantLabel(t, createShopAt(t, fx, token, "a.example.com"), "pi-1")
+ if n := cs.getsOf(blogRecs...); n != 2 {
+ t.Fatalf("a cold create read blog's records %d times; want once each", n)
+ }
+ cs.reset()
+ wantLabel(t, createShopAt(t, fx, token, "b.example.com"), "pi-2")
+ blogInstances := provision.RecordsPrefix(fx.sqid, "blog")
+ blogSidecars := provision.SidecarsPrefix(fx.sqid, "blog")
+ if l, s, g := cs.listsOf(blogInstances), cs.listsOf(blogSidecars), cs.getsOf(blogRecs...); l != 1 || s != 1 || g != 0 {
+ t.Fatalf("a warm create cost blog %d instance lists, %d sidecar lists and %d record reads; want 1, 1, 0", l, s, g)
+ }
+ if n := cs.recordPuts(); n != 1 {
+ t.Fatalf("a create wrote %d instance records; want only its own", n)
+ }
+}
+
+// The view's own facts, read from the fleet's heartbeats and the registry.
+func TestFleetViewReadsBoxes(t *testing.T) {
+ fx, _, _ := fleetBoxWorld(t, "code-fb-view", "pi-1", "pi-2")
+ at := time.Now().Add(-time.Minute).UTC().Truncate(time.Second)
+ writeFleetBoxOn(t, fx, "pi", "pi-2", "", false, at, "v0.32.0")
+ putFleetRecord(t, fx, "shop", "a.example.com", func(r *provision.Record) { r.FleetBox = "pi-1" })
+ cs := newCountStore(fx.rel)
+ fx.srv.cfg.Releases = cs
+ v, err := fx.srv.loadFleetView(context.Background(), "pi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // With no request memo, each heartbeat is still read once, though the
+ // fleet's and the deployment's listings both hold it.
+ if n := cs.getsOf("fleets/pi/status/boxes/pi-1.json"); n != 1 {
+ t.Fatalf("pi-1's heartbeat was read %d times; want once", n)
+ }
+ if !v.Active || v.DeploymentCurrent || v.labelActive() || v.Load["pi-1"] != 1 {
+ t.Fatalf("view %+v; want active, a box below the floor, closed, one record on pi-1", v)
+ }
+ if len(v.Boxes) != 2 || v.Boxes[1].Label != "pi-2" || v.Boxes[1].AtLabelFloor || v.Boxes[1].RootfsReady ||
+ !v.Boxes[1].AtRootfsFloor || !v.Boxes[1].Fresh || !v.Boxes[1].LastSeen.Equal(at) {
+ t.Fatalf("boxes %+v", v.Boxes)
+ }
+}
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index e3211ab6b..fafae1c75 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -44,11 +44,11 @@ import (
"github.com/carlosframework/platform/internal/status"
)
-// fleetBoxView and fleetView are the wire shapes for GET .../fleets and the
+// fleetBoxWire and fleetWire are the wire shapes for GET .../fleets and the
// "fleet" field POST .../new returns — deliberately NOT registry.Fleet /
// registry.FleetBox: those carry TokenHash, which this door must never echo
// back (the plaintext is shown once, at mint/rotate, and nowhere else).
-type fleetBoxView struct {
+type fleetBoxWire struct {
Label string `json:"label"`
Status string `json:"status"`
// Tags is additive (2026-08-10, Task 2): omitted entirely for an
@@ -57,10 +57,10 @@ type fleetBoxView struct {
Tags string `json:"tags,omitempty"`
}
-type fleetView struct {
+type fleetWire struct {
Name string `json:"name"`
Bucket string `json:"bucket"`
- Boxes []fleetBoxView `json:"boxes"`
+ Boxes []fleetBoxWire `json:"boxes"`
// SecretsKeyFP is the fleet's registered secrets key fingerprint, and
// StaleSecrets how many sealed values of its apps are not sealed to it
// (fleetStaleValues). Both are omitted for a fleet with no key, and the
@@ -259,7 +259,7 @@ func (s *Server) handleAPIFleetNew(w http.ResponseWriter, r *http.Request) {
return
}
}
- view := fleetView{Name: name, Bucket: bucket, Boxes: []fleetBoxView{}}
+ view := fleetWire{Name: name, Bucket: bucket, Boxes: []fleetBoxWire{}}
if created {
// The fleet owner record (rootfs apps Plan 4 D7): written before the
// door answers. A failed write leaves the row and answers the
@@ -302,7 +302,7 @@ func (s *Server) handleAPIFleetNew(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusInternalServerError, "could not create the fleet — try again")
return
}
- view = fleetView{Name: row.Name, Bucket: row.Bucket, Boxes: fleetBoxViews(boxes)}
+ view = fleetWire{Name: row.Name, Bucket: row.Bucket, Boxes: fleetBoxViews(boxes)}
}
s.audit(acct, name, addr, "fleet-create", "created fleet "+name+" (cli)")
writeJSON(w, http.StatusOK, map[string]any{"fleet": view})
@@ -310,10 +310,10 @@ func (s *Server) handleAPIFleetNew(w http.ResponseWriter, r *http.Request) {
// fleetBoxViews is the wire shape of a fleet's boxes: label, status and
// tags, never a token hash. Always a non-nil slice.
-func fleetBoxViews(boxes []registry.FleetBox) []fleetBoxView {
- bv := make([]fleetBoxView, 0, len(boxes))
+func fleetBoxViews(boxes []registry.FleetBox) []fleetBoxWire {
+ bv := make([]fleetBoxWire, 0, len(boxes))
for _, b := range boxes {
- bv = append(bv, fleetBoxView{Label: b.Label, Status: b.Status, Tags: b.Tags})
+ bv = append(bv, fleetBoxWire{Label: b.Label, Status: b.Status, Tags: b.Tags})
}
return bv
}
@@ -337,7 +337,7 @@ func (s *Server) handleAPIFleetList(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusInternalServerError, "could not list fleets")
return
}
- out := make([]fleetView, 0)
+ out := make([]fleetWire, 0)
for _, f := range all {
if f.Account != acct.Sqid {
continue
@@ -348,7 +348,7 @@ func (s *Server) handleAPIFleetList(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusInternalServerError, "could not list fleets")
return
}
- view := fleetView{Name: f.Name, Bucket: f.Bucket, Boxes: fleetBoxViews(boxes), SecretsKeyFP: f.SecretsKeyFP}
+ view := fleetWire{Name: f.Name, Bucket: f.Bucket, Boxes: fleetBoxViews(boxes), SecretsKeyFP: f.SecretsKeyFP}
if f.SecretsKeyFP != "" {
// The stale count repeats the key door's report until it is
// zero (spec §5.1 B2). A bucket that cannot be read costs the
diff --git a/internal/console/rootfs.go b/internal/console/rootfs.go
index 5b8be5ab3..0d0884c34 100644
--- a/internal/console/rootfs.go
+++ b/internal/console/rootfs.go
@@ -306,7 +306,12 @@ func boxAtRootfsFloor(b status.Box) bool {
// chooser picks a box without asking about rootfs readiness, but a box with
// claim control armed publishes rootfs_ready false, so C05 or C06 refuses
// the create here first.
-func (s *Server) rootfsCreateRefusal(ctx context.Context, reg consoleRegistry, acct *Account, app, placed, region, pool, role string, seeded bool) *doorRefusal {
+//
+// fleetActive is the placed fleet's view when the label gate is open
+// (managed fleets 1b, rule 7): then the box the create will be labelled to
+// decides readiness (rootfsChosenBoxRefusal), not the fleet's other boxes.
+// nil asks as before.
+func (s *Server) rootfsCreateRefusal(ctx context.Context, reg consoleRegistry, acct *Account, app, placed, region, pool, role string, seeded bool, fleetActive *fleetView) *doorRefusal {
switch {
case seeded:
return &doorRefusal{http.StatusUnprocessableEntity, fmt.Sprintf(rootfsSeededMsg, app)}
@@ -316,9 +321,27 @@ func (s *Server) rootfsCreateRefusal(ctx context.Context, reg consoleRegistry, a
if ref := s.rootfsPlacementRefusal(reg, acct, app, placed, pool); ref != nil {
return ref
}
+ if fleetActive != nil {
+ return rootfsChosenBoxRefusal(placed, *fleetActive)
+ }
return s.rootfsReadyRefusal(ctx, reg, placed, region)
}
+// rootfsChosenBoxRefusal is rule 7 of managed fleets 1b: on a fleet the
+// console labels, a rootfs placement is admitted when the box the record
+// will be labelled to is rootfs-ready at the rootfs floor (chooseDestination
+// asks both), which replaces "one fresh box ready and every box on the
+// floor". The gate already holds every box of the deployment at the label
+// floor, which is above the rootfs floor. No such box is today's refusal
+// for a fleet with none ready, C05.
+func rootfsChosenBoxRefusal(placed string, v fleetView) *doorRefusal {
+ if v.chooseDestination(true, "") != "" {
+ return nil
+ }
+ fleet, _ := registry.FleetPlacement(placed)
+ return &doorRefusal{http.StatusConflict, fmt.Sprintf(rootfsFleetNotReadyMsg, fleet)}
+}
+
// The first-kind boundary (Astra R2 finding 2; Plan 4 row 3.2). The create
// door reads the app's kind before any lock. When no release and no kind
// marker fixed it yet (rootfsHead.Unfixed), a first rootfs ship may fix it
diff --git a/internal/console/server.go b/internal/console/server.go
index 016db3b57..8adb77392 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -975,7 +975,15 @@ type Server struct {
// lapseLocks serialises, per account, everything that changes what a
// lapse turns off (plans 4d, Astra finding 1): a plan change, the grace
// pass's convergence and a keep save. Account id to *sync.Mutex.
- lapseLocks sync.Map
+ lapseLocks sync.Map
+ // fleetLocks holds one mutex per fleet name (lockFleet, fleetbox.go),
+ // and fleetInventories each fleet's record inventory cache
+ // (*fleetInventory), both made on first use.
+ fleetLocks sync.Map
+ fleetInventories sync.Map
+ // consoleBuild, when set, is the release this console reports to the
+ // fleet label gate instead of version.Build (tests only).
+ consoleBuild string
claimLossPageMu sync.Mutex
claimLossPageDone chan struct{}
diff --git a/internal/console/store.go b/internal/console/store.go
index 3764cc2d7..8cbe24c69 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -2921,6 +2921,33 @@ FROM audit WHERE account_id = ? AND app = ? ORDER BY id DESC LIMIT ?`, accountID
// AppRef names one app by its account's sqid, as the bucket keys it.
type AppRef struct{ Sqid, App string }
+// AppsPlacedOn lists every app whose stored placement is placement
+// ("fleet/<name>"), by its account's sqid, ordered. Trashed apps and apps of
+// a retired account are listed too: their records stay in the bucket, and
+// the fleet inventory that reads this (fleetbox.go) must see every record
+// that could run on the fleet. Apps placed only through their routes, by a
+// build older than the placement column, are not here (appPlacement's
+// fallback); the inventory adds those from the registry. A plain read.
+func (s *Store) AppsPlacedOn(ctx context.Context, placement string) ([]AppRef, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT accounts.sqid, apps.app
+FROM apps JOIN accounts ON accounts.id = apps.account_id
+WHERE apps.placement = ?
+ORDER BY accounts.sqid, apps.app`, placement)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []AppRef
+ for rows.Next() {
+ var r AppRef
+ if err := rows.Scan(&r.Sqid, &r.App); err != nil {
+ return nil, err
+ }
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
+
// AppsWithActionSince answers, once each, every (account, app) with an audit
// row of action stamped at or after since. The run sweep's orphan
// housekeeping lists runs/ only for apps with a recent run-start (S3
diff --git a/internal/release/layoutintent.go b/internal/release/layoutintent.go
index 403178f30..e7c4edce1 100644
--- a/internal/release/layoutintent.go
+++ b/internal/release/layoutintent.go
@@ -264,6 +264,18 @@ var TeamEnvironmentFloor = SemVer{Major: 0, Minor: 30, Patch: 0}
// later. TestRegionalDomainsFloorIsPinned pins it.
var RegionalDomainsFloor = SemVer{Major: 0, Minor: 31, Patch: 0}
+// FleetBoxLabelFloor is the first platform release whose fleet boxes honour
+// an instance record's box label (managed fleets 1b, rule 8): a box below it
+// ignores the label and mints every record of its fleet. So the console
+// labels a fleet only while every box of the deployment, platform and
+// fleet, and the console itself report a release at or above it
+// (console/fleetbox.go). The latest tag at the time of writing is v0.31.1,
+// so this names a minor bump with room: the first release cut from a main
+// that contains the label rule MUST be v0.33.0 or later, and no release
+// without it may be numbered v0.33.0 or later. A release that is missing
+// or does not parse counts as below. TestFleetBoxLabelFloorIsPinned pins it.
+const FleetBoxLabelFloor = "v0.33.0"
+
// RootfsFloorOverrideFlag is the override's flag name, on `carlos system
// update`, `carlos system rollback` and `carlos system apply`.
const RootfsFloorOverrideFlag = "allow-below-rootfs-floor"
diff --git a/internal/release/layoutintent_test.go b/internal/release/layoutintent_test.go
index f437f102e..d8c59919b 100644
--- a/internal/release/layoutintent_test.go
+++ b/internal/release/layoutintent_test.go
@@ -151,6 +151,16 @@ func TestRootfsLifecycleFloorIsPinned(t *testing.T) {
}
}
+// TestFleetBoxLabelFloorIsPinned pins the first release whose fleet boxes
+// honour a record's box label (managed fleets 1b, rule 8). Moving the
+// constant means re-checking the tags, not editing this test to match.
+func TestFleetBoxLabelFloorIsPinned(t *testing.T) {
+ v, ok := ParseReleaseVersion(FleetBoxLabelFloor)
+ if !ok || v != (SemVer{Major: 0, Minor: 33, Patch: 0}) {
+ t.Fatalf("FleetBoxLabelFloor = %q, want v0.33.0", FleetBoxLabelFloor)
+ }
+}
+
// RootfsFloorAllows is the box-side rule by version alone (Task 15 round
// 3): a box below the floor, or whose own version does not parse, installs
// anything; one at or above it only a parseable candidate at or above it.