carlos / platform Public

console: refuse a size above a quarter of the smallest box; report each box's committed figure

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev d04b86aa7ec8709553c76ab62eeba7b2e8421d08 parent 79057a5
5 files changed, +723 −20
  • internal/console/apipolicy.go +9 −0
  • internal/console/apisystemupdate.go +29 −16
  • internal/console/egressfleet_test.go +8 −4
  • internal/console/policysize.go +330 −0
  • internal/console/policysize_test.go +347 −0
diff --git a/internal/console/apipolicy.go b/internal/console/apipolicy.go
index 3a806fb4c..dff055678 100644
--- a/internal/console/apipolicy.go
+++ b/internal/console/apipolicy.go
@@ -102,6 +102,9 @@ type policyReply struct {
// EgressConflicts (GET only) is the policy's allowed addresses that the
// fleet-address report last found on a fleet box (#328).
EgressConflicts []string `json:"egress_conflicts,omitempty"`
+ // Committed (PUT only) is each box's committed figure after a size
+ // change (policysize.go): information, never a gate.
+ Committed []sizeCommittedBox `json:"committed,omitempty"`
}
// policyLock is the app's policy mutex, the store's (Store.AppPolicyLock), so
@@ -524,6 +527,11 @@ func (s *Server) handleAPIPolicyPut(w http.ResponseWriter, r *http.Request) {
if s.cfg.HostClaim {
pol.AppID = cur
}
+ committed, ref := s.policySizeCheck(ctx, acct, app, old, pol, req)
+ if ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
notChecked := []string{}
if req.EgressAllow != nil {
nc, status, msg := s.checkEgressGrant(ctx, acct, app, old.EgressAllow, pol.EgressAllow)
@@ -569,6 +577,7 @@ func (s *Server) handleAPIPolicyPut(w http.ResponseWriter, r *http.Request) {
}
s.bumpSerial(ctx)
reply.NotChecked = notChecked
+ reply.Committed = committed
w.Header().Set("ETag", reply.ETag)
writeJSON(w, http.StatusOK, reply)
}
diff --git a/internal/console/apisystemupdate.go b/internal/console/apisystemupdate.go
index f3f3dd9b5..382c7973b 100644
--- a/internal/console/apisystemupdate.go
+++ b/internal/console/apisystemupdate.go
@@ -18,6 +18,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/publicrelease"
+ "github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
)
@@ -271,22 +272,7 @@ func (s *Server) systemBoxes(ctx context.Context, strict bool) ([]status.Box, bo
if err != nil {
return nil, false, err
}
- if s.cfg.Registry == "" {
- return boxes, false, nil // this console serves no route registry: no fleets
- }
- // openPassRegistry reports the not-yet-created case by wrapping os.Stat's
- // error, so errors.Is reaches it; the unconfigured case is the guard
- // above, since that one is a plain message. Distinguished here rather
- // than in openPassRegistry so its other callers keep the answers they
- // already expect.
- reg, err := s.openPassRegistry()
- switch {
- case errors.Is(err, os.ErrNotExist):
- return boxes, false, nil // no registry file yet: no fleets
- case err != nil:
- return s.systemFleetsUnreadable(boxes, strict, err)
- }
- fleets, err := reg.ListFleets()
+ _, fleets, err := s.systemFleets()
if err != nil {
return s.systemFleetsUnreadable(boxes, strict, err)
}
@@ -306,6 +292,33 @@ func (s *Server) systemBoxes(ctx context.Context, strict bool) ([]status.Box, bo
return boxes, partial, nil
}
+// systemFleets is systemBoxes' fleet rule, shared with the size check
+// (policysize.go): no registry configured, or no registry file yet, is no
+// fleets (nil, nil, nil); a registry that exists and cannot be opened, or
+// whose fleets cannot be listed, is the error.
+func (s *Server) systemFleets() (consoleRegistry, []registry.Fleet, error) {
+ if s.cfg.Registry == "" {
+ return nil, nil, nil // this console serves no route registry: no fleets
+ }
+ // openPassRegistry reports the not-yet-created case by wrapping os.Stat's
+ // error, so errors.Is reaches it; the unconfigured case is the guard
+ // above, since that one is a plain message. Distinguished here rather
+ // than in openPassRegistry so its other callers keep the answers they
+ // already expect.
+ reg, err := s.openPassRegistry()
+ switch {
+ case errors.Is(err, os.ErrNotExist):
+ return nil, nil, nil // no registry file yet: no fleets
+ case err != nil:
+ return nil, nil, err
+ }
+ fleets, err := reg.ListFleets()
+ if err != nil {
+ return nil, nil, err
+ }
+ return reg, fleets, nil
+}
+
// systemFleetsUnreadable is the shared answer to "this console cannot say
// what fleets exist": a refusal under strict, a logged degradation otherwise.
func (s *Server) systemFleetsUnreadable(boxes []status.Box, strict bool, err error) ([]status.Box, bool, error) {
diff --git a/internal/console/egressfleet_test.go b/internal/console/egressfleet_test.go
index 327382cad..28a1c049e 100644
--- a/internal/console/egressfleet_test.go
+++ b/internal/console/egressfleet_test.go
@@ -316,8 +316,9 @@ func TestPolicyDoorReplyCarriesNotChecked(t *testing.T) {
}
// Through the door, with control/edges/ and the status snapshots down: a
-// revoke and a size-only change go through and read neither, and only an
-// addition is refused (ruling C5).
+// revoke goes through and reads neither (ruling C5). A size change reads
+// them for the size check (plan 3 Task 9): standard still goes through,
+// large is refused with 503. Only an egress addition is refused.
func TestPolicyDoorRevokeGoesThroughAnEdgesOutage(t *testing.T) {
t.Parallel()
fx := newPolicyFx(t, "code-policy-revoke-outage")
@@ -330,10 +331,13 @@ func TestPolicyDoorRevokeGoesThroughAnEdgesOutage(t *testing.T) {
if !slices.Equal(revoked.Policy.EgressAllow, []string{"10.0.5.21"}) || revoked.NotChecked == nil || len(revoked.NotChecked) != 0 {
t.Fatalf("revoke reply %+v", revoked)
}
- sized := fx.mustPut(t, "shop", `{"default_size":"large"}`, policyIfMatch(revoked.ETag))
if l, le, g := cs.requests(); l+le+g != 0 {
- t.Fatalf("a revoke and a size change made %d lists, %d ETag lists and %d gets of edges or status, want none", l, le, g)
+ t.Fatalf("a revoke made %d lists, %d ETag lists and %d gets of edges or status, want none", l, le, g)
}
+ if st, _, out := fx.put(t, "shop", `{"default_size":"large"}`, policyIfMatch(revoked.ETag)); st != http.StatusServiceUnavailable {
+ t.Fatalf("large with edges and status down = %d %s, want 503", st, out)
+ }
+ sized := fx.mustPut(t, "shop", `{"default_size":"standard"}`, policyIfMatch(revoked.ETag))
if st, _, out := fx.put(t, "shop", `{"egress_allow":["10.0.5.21","10.0.5.22"]}`, policyIfMatch(sized.ETag)); st != http.StatusServiceUnavailable {
t.Fatalf("an addition with edges down = %d %s, want 503", st, out)
}
diff --git a/internal/console/policysize.go b/internal/console/policysize.go
new file mode 100644
index 000000000..5768b9570
--- /dev/null
+++ b/internal/console/policysize.go
@@ -0,0 +1,330 @@
+// The console's size check (instance sizes and egress spec §5.5, #329,
+// plan 3 Task 9): a size may not exceed a quarter of the memory of the
+// smallest box the app or instance can be placed on, and a size above
+// standard needs every such box's memory total to be known.
+//
+// The boxes come from the box listings, not from edges files (Astra plan
+// R2-5): the platform's status reports and the account's fleet rosters.
+// The totals come from the edges files, joined on the file's box. Fleet
+// boxes publish no edges file, so their totals are unknown and only small
+// and standard can be set while one can take the app.
+//
+// Request budget (spec §3a, ruling 11): everything here is read only by a
+// policy PUT that changes a size, never on an egress-only change and never
+// on a timer.
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/apppolicy"
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// Door copy (drafts, plan 3 Task 14 strings 1-3).
+const (
+ sizeQuarterMsg = "%s is more than a quarter of the memory on %s (%d MiB). Choose a smaller size."
+ sizeNoTotalMsg = "%s does not publish its memory total, so only small and standard can be set. Upgrade the box, then try again."
+ sizeUnreadMsg = "Could not read every box's memory total, so only small and standard can be set. Try again in a minute."
+)
+
+// sizeBox is one box a size may land on. TotalMiB 0 is unknown.
+type sizeBox struct {
+ Box, Region string
+ TotalMiB int64
+}
+
+// sizeCommittedBox is one box's committed figure for the door's reply:
+// information, never a gate.
+type sizeCommittedBox struct {
+ Box string `json:"box"`
+ CommittedMiB int64 `json:"committed_mib"`
+ TotalMiB int64 `json:"total_mib"`
+ FreeMiB int64 `json:"free_mib"`
+}
+
+// sizeBoxes is the boxes recs can be placed on, sorted by label, with each
+// one's memory total.
+//
+// Eligible are the platform boxes of status.LoadBoxesComplete and the
+// active roster rows of every fleet the account owns. With records, a
+// platform box counts when it is not stale and in the region of one of
+// them (homeRegionIn on both sides), or when its edges file lists one of
+// their hosts, stale or not; a fleet box of the account always counts.
+// With no records (an app default before any instance), every non-stale
+// platform box and every active fleet box of the account.
+//
+// A box's total is its edges file's box_mem_total_mib, else region HA's
+// headroom mem_total_mib (ruling C3); no file, or neither field, is 0.
+//
+// complete is false when a status report could not be read, the registry
+// or a fleet's roster could not be read, or an edges file could not be read
+// or parsed. A failed listing of the status reports or of control/edges/ is
+// the error, and no boxes.
+func (s *Server) sizeBoxes(ctx context.Context, acct *Account, recs []provision.Record) (boxes []sizeBox, complete bool, err error) {
+ if s.cfg.Releases == nil {
+ return nil, false, errors.New("no deployment bucket")
+ }
+ reports, complete, err := status.LoadBoxesComplete(ctx, s.cfg.Releases)
+ if err != nil {
+ return nil, false, fmt.Errorf("status reports: %w", err)
+ }
+ snap, err := readEdgesSnapshot(ctx, s.cfg.Releases)
+ if err != nil {
+ return nil, false, fmt.Errorf("list %s: %w", edgesfile.Prefix, err)
+ }
+ complete = complete && snap.Complete
+
+ files := map[string]sizeEdges{}
+ for _, f := range snap.Files {
+ files[f.Box] = files[f.Box].join(f)
+ }
+ hosts, regions := map[string]bool{}, map[string]bool{}
+ for _, r := range recs {
+ hosts[r.Host] = true
+ regions[s.homeRegionIn(r.Region)] = true
+ }
+ now := time.Now()
+ seen := map[string]bool{}
+ for _, b := range reports {
+ if b.Label == "" || seen[b.Label] {
+ continue
+ }
+ stale := status.BoxStale(b, now, status.SnapshotPeriod)
+ f := files[b.Label]
+ if len(recs) == 0 {
+ if stale {
+ continue
+ }
+ } else if !(!stale && regions[s.homeRegionIn(b.Region)]) && !f.servesAny(hosts) {
+ continue
+ }
+ seen[b.Label] = true
+ boxes = append(boxes, sizeBox{Box: b.Label, Region: b.Region, TotalMiB: f.total})
+ }
+
+ reg, fleets, err := s.systemFleets()
+ if err != nil {
+ s.policyLogf("console: size check: fleets: %v", err)
+ complete = false
+ }
+ for _, f := range fleets {
+ if f.Account != acct.Sqid {
+ continue
+ }
+ roster, err := reg.ListFleetBoxes(f.Name)
+ if err != nil {
+ s.policyLogf("console: size check: fleet %s roster: %v", f.Name, err)
+ complete = false
+ continue
+ }
+ for _, fb := range roster {
+ if fb.Status == "active" {
+ boxes = append(boxes, sizeBox{Box: fb.Label})
+ }
+ }
+ }
+ slices.SortStableFunc(boxes, func(a, b sizeBox) int { return strings.Compare(a.Box, b.Box) })
+ return boxes, complete, nil
+}
+
+// sizeEdges is what the size check takes from a box's edges files: its
+// total and the hosts it serves. Two files naming one box (a stray copy)
+// join conservatively: an unknown total, or the smaller one.
+type sizeEdges struct {
+ listed bool
+ total int64
+ hosts map[string]bool
+}
+
+func (e sizeEdges) join(f edgesfile.PlacementView) sizeEdges {
+ t := f.BoxMemTotalMiB
+ if t <= 0 && f.Headroom != nil {
+ t = f.Headroom.MemTotalMiB
+ }
+ t = max(t, 0)
+ switch {
+ case !e.listed:
+ e.total = t
+ case e.total == 0 || t == 0:
+ e.total = 0
+ default:
+ e.total = min(e.total, t)
+ }
+ e.listed = true
+ if e.hosts == nil {
+ e.hosts = map[string]bool{}
+ }
+ for h := range f.Hosts {
+ e.hosts[h] = true
+ }
+ return e
+}
+
+func (e sizeEdges) servesAny(hosts map[string]bool) bool {
+ for h := range e.hosts {
+ if hosts[h] {
+ return true
+ }
+ }
+ return false
+}
+
+// sizeCapacityCheck refuses size for recs's boxes (sizeBoxes), and returns
+// the boxes it checked. Above standard: 503 (string 3) when the read is not
+// complete, as plan 2's egressFleetBoxesMsg path does (ruling C7), then 409
+// (string 2) naming the first box, by label, whose total is unknown. For
+// any size: 409 (string 1) when the size's MemoryMax is more than a quarter
+// of the smallest known total, naming that box. small and standard are
+// never refused for an unknown total or an incomplete read.
+func (s *Server) sizeCapacityCheck(ctx context.Context, acct *Account, recs []provision.Record, size cgroup.Size) ([]sizeBox, *doorRefusal) {
+ boxes, complete, err := s.sizeBoxes(ctx, acct, recs)
+ if err != nil {
+ s.policyLogf("console: size check: %v", err)
+ complete = false
+ }
+ return boxes, sizeRefusal(boxes, complete, size)
+}
+
+// sizeRefusal is sizeCapacityCheck's rule over one read; boxes are sorted
+// by label.
+func sizeRefusal(boxes []sizeBox, complete bool, size cgroup.Size) *doorRefusal {
+ if sizeAboveStandard(size) {
+ if !complete {
+ return &doorRefusal{http.StatusServiceUnavailable, sizeUnreadMsg}
+ }
+ for _, b := range boxes {
+ if b.TotalMiB == 0 {
+ return &doorRefusal{http.StatusConflict, fmt.Sprintf(sizeNoTotalMsg, b.Box)}
+ }
+ }
+ }
+ var smallest *sizeBox
+ for i := range boxes {
+ if b := &boxes[i]; b.TotalMiB > 0 && (smallest == nil || b.TotalMiB < smallest.TotalMiB) {
+ smallest = b
+ }
+ }
+ if smallest != nil && size.Limit.MemoryMax>>20 > smallest.TotalMiB/4 {
+ return &doorRefusal{http.StatusConflict, fmt.Sprintf(sizeQuarterMsg, size.Name, smallest.Box, smallest.TotalMiB)}
+ }
+ return nil
+}
+
+func sizeAboveStandard(size cgroup.Size) bool {
+ std, _ := cgroup.SizeByName("standard")
+ return size.Limit.MemoryMax > std.Limit.MemoryMax
+}
+
+// sizeCommitted is each box's committed figure from its status report
+// (status/boxes/<box>.json): the sum of its awake instances' sizes, its
+// memory total and its available memory, in MiB. A box whose report cannot
+// be read or lacks one of the three is left out. A fleet box's report is
+// under its fleet's prefix, so a fleet box is left out too.
+func (s *Server) sizeCommitted(ctx context.Context, boxes []string) []sizeCommittedBox {
+ if s.cfg.Releases == nil {
+ return nil
+ }
+ var out []sizeCommittedBox
+ for _, box := range boxes {
+ if box == "" || strings.ContainsAny(box, "/\\") || strings.Contains(box, "..") {
+ continue
+ }
+ body, _, err := s.cfg.Releases.Get(ctx, "status/boxes/"+box+".json")
+ if err != nil {
+ continue
+ }
+ var b status.Box
+ if json.Unmarshal(body, &b) != nil || b.Label != box {
+ continue
+ }
+ m := b.Metrics
+ if m == nil || m.SizeCommittedMiB == nil || m.MemTotalBytes == nil || m.MemAvailBytes == nil {
+ continue
+ }
+ out = append(out, sizeCommittedBox{Box: box, CommittedMiB: *m.SizeCommittedMiB,
+ TotalMiB: *m.MemTotalBytes >> 20, FreeMiB: *m.MemAvailBytes >> 20})
+ }
+ return out
+}
+
+// policySizeCheck is the door's size check (handleAPIPolicyPut, after
+// applyPolicyChange and before checkEgressGrant and the audit). It runs only
+// for a PUT that changes a size: a default_size set to a size other than
+// the stored one, checked against every record of the app; a size override
+// set or replaced on a host, checked against that host's record. Clearing a
+// size, re-sending the one in force and an egress-only change read nothing.
+// On success it answers each checked box's committed figure.
+func (s *Server) policySizeCheck(ctx context.Context, acct *Account, app string, old, next apppolicy.Policy, req policyPutReq) ([]sizeCommittedBox, *doorRefusal) {
+ type check struct {
+ size cgroup.Size
+ host string // "" is the whole app
+ }
+ var checks []check
+ if req.DefaultSize != nil && next.DefaultSize != "" && next.DefaultSize != old.DefaultSize {
+ if sz, ok := cgroup.SizeByName(next.DefaultSize); ok {
+ checks = append(checks, check{size: sz})
+ }
+ }
+ if req.Size != nil && req.Size.Value != policySizeValueDefault {
+ host := strings.ToLower(req.Size.Host)
+ o, had := old.Sizes[host]
+ n, has := next.Sizes[host]
+ if has && (!had || o.Size != n.Size || !o.CreatedAt.Equal(n.CreatedAt)) {
+ if sz, ok := cgroup.SizeByName(n.Size); ok {
+ checks = append(checks, check{size: sz, host: host})
+ }
+ }
+ }
+ if len(checks) == 0 {
+ return nil, nil
+ }
+ var labels []string
+ for _, c := range checks {
+ recs, ok := s.policySizeRecords(ctx, acct, app, c.host)
+ if !ok && sizeAboveStandard(c.size) {
+ return nil, &doorRefusal{http.StatusServiceUnavailable, sizeUnreadMsg}
+ }
+ // An unread record set is checked against every box (recs nil):
+ // more boxes, never fewer.
+ boxes, ref := s.sizeCapacityCheck(ctx, acct, recs, c.size)
+ if ref != nil {
+ return nil, ref
+ }
+ for _, b := range boxes {
+ labels = append(labels, b.Box)
+ }
+ }
+ slices.Sort(labels)
+ return s.sizeCommitted(ctx, slices.Compact(labels)), nil
+}
+
+// policySizeRecords is the records a size check covers: host's own, or
+// every record of the app for host "". ok is false when they could not all
+// be read (a failed read, too many, or one that does not decode).
+func (s *Server) policySizeRecords(ctx context.Context, acct *Account, app, host string) ([]provision.Record, bool) {
+ if host != "" {
+ rec, _, err := s.readRecord(ctx, acct.Sqid, app, host)
+ if err != nil {
+ s.policyLogf("console: size check %s/%s: record %s: %v", acct.Sqid, app, host, err)
+ return nil, false
+ }
+ return []provision.Record{*rec}, true
+ }
+ recs, unreadable, err := s.listRecordsStrict(ctx, acct.Sqid, app, instanceListMax)
+ if err != nil || len(unreadable) > 0 {
+ s.policyLogf("console: size check %s/%s: records (%d unreadable): %v", acct.Sqid, app, len(unreadable), err)
+ return nil, false
+ }
+ return recs, true
+}
diff --git a/internal/console/policysize_test.go b/internal/console/policysize_test.go
new file mode 100644
index 000000000..fba16b591
--- /dev/null
+++ b/internal/console/policysize_test.go
@@ -0,0 +1,347 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/status"
+)
+
+// sizeFx is the console fixture and its account, for the size checks
+// called directly. The fixture names no home region, so a record's ""
+// matches a box reporting region "".
+func sizeFx(t *testing.T) (*consoleFixture, *Account) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ acct, err := fx.st.AccountBySqid(fx.sqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account %s: %v", fx.sqid, err)
+ }
+ return fx, acct
+}
+
+// putSizeReport writes status/boxes/<label>.json generated at at.
+func putSizeReport(t *testing.T, s release.Store, label, region string, at time.Time, m *status.BoxMetrics) {
+ t.Helper()
+ if err := status.WriteBox(context.Background(), s, status.Box{Label: label, Region: region, GeneratedAt: at, Metrics: m}); err != nil {
+ t.Fatalf("report %s: %v", label, err)
+ }
+}
+
+// putSizeEdges writes control/edges/<box>.json serving hosts, with the
+// top-level box_mem_total_mib when total is not 0 and the region HA
+// headroom's nested mem_total_mib when headroom is not 0.
+func putSizeEdges(t *testing.T, s release.Store, box string, total, headroom int64, hosts ...string) {
+ t.Helper()
+ h := map[string]any{}
+ for _, host := range hosts {
+ h[host] = map[string]any{}
+ }
+ f := map[string]any{"v": 1, "box": box, "eip": "192.0.2.1", "hosts": h}
+ if total != 0 {
+ f["box_mem_total_mib"] = total
+ }
+ if headroom != 0 {
+ f["headroom"] = map[string]any{"mem_total_mib": headroom, "mem_free_mib": 100}
+ }
+ body, err := json.Marshal(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ putFixtureObject(t, s, edgesfile.Key(box), body)
+}
+
+func sizeRecord(t *testing.T, rel release.Store, sqid, app, host, region string) provision.Record {
+ t.Helper()
+ rec := provision.Record{Schema: 1, Host: host, Slug: strings.Split(host, ".")[0], App: app, Account: sqid,
+ Region: region, Channel: "stable", CreatedAt: time.Now().UTC().Truncate(time.Second)}
+ if err := provision.CreateRecord(context.Background(), rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ return rec
+}
+
+func mustSize(t *testing.T, name string) cgroup.Size {
+ t.Helper()
+ sz, ok := cgroup.SizeByName(name)
+ if !ok {
+ t.Fatalf("no size %s", name)
+ }
+ return sz
+}
+
+// checkSizes runs sizeCapacityCheck for each size and returns the refusal
+// of each, nil where it passes.
+func checkSizes(t *testing.T, s *Server, acct *Account, recs []provision.Record, names ...string) map[string]*doorRefusal {
+ t.Helper()
+ out := map[string]*doorRefusal{}
+ for _, n := range names {
+ _, ref := s.sizeCapacityCheck(context.Background(), acct, recs, mustSize(t, n))
+ out[n] = ref
+ }
+ return out
+}
+
+const shopHost = "shop-a.example.com"
+
+func TestSizeCapacityRefusesAboveAQuarterOfTheSmallestBox(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ now := time.Now()
+ putSizeReport(t, fx.rel, "annie", "", now, nil)
+ putSizeEdges(t, fx.rel, "annie", 3884, 0)
+ putSizeReport(t, fx.rel, "betty", "", now, nil)
+ putSizeEdges(t, fx.rel, "betty", 7820, 0, shopHost)
+ recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")}
+
+ got := checkSizes(t, fx.srv, acct, recs, "xlarge", "large", "standard", "small")
+ want := "xlarge is more than a quarter of the memory on annie (3884 MiB). Choose a smaller size."
+ if r := got["xlarge"]; r == nil || r.Status != http.StatusConflict || r.Msg != want {
+ t.Fatalf("xlarge = %+v, want 409 %q", r, want)
+ }
+ if r := got["large"]; r == nil || r.Status != http.StatusConflict || !strings.Contains(r.Msg, "annie (3884 MiB)") {
+ t.Fatalf("large (1024 > 971) = %+v, want 409 naming annie", r)
+ }
+ if got["standard"] != nil || got["small"] != nil {
+ t.Fatalf("standard = %+v, small = %+v, want both to pass", got["standard"], got["small"])
+ }
+}
+
+// A total is the top-level box_mem_total_mib, else region HA's nested
+// headroom total (ruling C3); a box with neither is unknown.
+func TestSizeCapacityRefusesAboveStandardWhenATotalIsMissing(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ now := time.Now()
+ putSizeReport(t, fx.rel, "annie", "", now, nil)
+ putSizeEdges(t, fx.rel, "annie", 65536, 0)
+ putSizeReport(t, fx.rel, "betty", "", now, nil)
+ putSizeEdges(t, fx.rel, "betty", 0, 0) // an older box: neither total
+ recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")}
+
+ got := checkSizes(t, fx.srv, acct, recs, "large", "standard", "small")
+ want := "betty does not publish its memory total, so only small and standard can be set. Upgrade the box, then try again."
+ if r := got["large"]; r == nil || r.Status != http.StatusConflict || r.Msg != want {
+ t.Fatalf("large = %+v, want 409 %q", r, want)
+ }
+ if got["standard"] != nil || got["small"] != nil {
+ t.Fatalf("standard = %+v, small = %+v, want both to pass", got["standard"], got["small"])
+ }
+
+ putSizeEdges(t, fx.rel, "betty", 0, 16384) // region HA's headroom only
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs)
+ if err != nil || !complete {
+ t.Fatalf("sizeBoxes = %v, %v", complete, err)
+ }
+ if want := []sizeBox{{Box: "annie", TotalMiB: 65536}, {Box: "betty", TotalMiB: 16384}}; !reflect.DeepEqual(boxes, want) {
+ t.Fatalf("boxes = %+v, want %+v", boxes, want)
+ }
+ if r := checkSizes(t, fx.srv, acct, recs, "large")["large"]; r != nil {
+ t.Fatalf("large with betty's headroom total = %+v, want it to pass", r)
+ }
+ putSizeEdges(t, fx.rel, "betty", 2048, 16384) // the top-level total wins
+ if r := checkSizes(t, fx.srv, acct, recs, "large")["large"]; r == nil || !strings.Contains(r.Msg, "betty (2048 MiB)") {
+ t.Fatalf("large with betty's top-level 2048 = %+v, want 409 naming betty", r)
+ }
+}
+
+func TestSizeCapacityRefusesAboveStandardOnAnIncompleteSnapshot(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ putSizeReport(t, fx.rel, "annie", "", time.Now(), nil)
+ putSizeEdges(t, fx.rel, "annie", 65536, 0)
+ putFixtureObject(t, fx.rel, edgesfile.Key("zed"), []byte("{not json"))
+ recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")}
+
+ got := checkSizes(t, fx.srv, acct, recs, "large", "standard")
+ want := "Could not read every box's memory total, so only small and standard can be set. Try again in a minute."
+ if r := got["large"]; r == nil || r.Status != http.StatusServiceUnavailable || r.Msg != want {
+ t.Fatalf("large = %+v, want 503 %q", r, want)
+ }
+ if got["standard"] != nil {
+ t.Fatalf("standard = %+v, want it to pass", got["standard"])
+ }
+}
+
+// Astra plan R2-5: a box in the app's region that publishes no edges file
+// at all is still a box the app may land on.
+func TestSizeCapacityRefusesForAnEligibleBoxWithNoEdgesFile(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ putSizeReport(t, fx.rel, "box-a", "", time.Now(), nil)
+ putSizeReport(t, fx.rel, "box-b", "", time.Now(), nil)
+ putSizeEdges(t, fx.rel, "box-b", 65536, 0)
+ recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")}
+
+ got := checkSizes(t, fx.srv, acct, recs, "large", "standard", "small")
+ if r := got["large"]; r == nil || r.Status != http.StatusConflict || !strings.HasPrefix(r.Msg, "box-a does not publish its memory total") {
+ t.Fatalf("large = %+v, want 409 naming box-a", r)
+ }
+ if got["standard"] != nil || got["small"] != nil {
+ t.Fatalf("standard = %+v, small = %+v, want both to pass", got["standard"], got["small"])
+ }
+
+ putSizeReport(t, fx.rel, "box-a", "", time.Now().Add(-time.Hour), nil) // stale, serving nothing
+ if r := checkSizes(t, fx.srv, acct, recs, "large")["large"]; r != nil {
+ t.Fatalf("large with box-a stale = %+v, want it to pass (box-b: 1024 <= 16384)", r)
+ }
+}
+
+func TestSizeBoxesComeFromTheListingsNotTheEdgesFiles(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ now := time.Now()
+ putSizeReport(t, fx.rel, "annie", "", now, nil) // the app's region
+ putSizeEdges(t, fx.rel, "annie", 3884, 0)
+ putSizeReport(t, fx.rel, "ivy", "ie", now, nil) // another region, serving nothing
+ putSizeEdges(t, fx.rel, "ivy", 3884, 0)
+ putSizeReport(t, fx.rel, "iris", "ie", now.Add(-time.Hour), nil) // stale, but serving the host
+ putSizeEdges(t, fx.rel, "iris", 7820, 0, shopHost)
+ putSizeEdges(t, fx.rel, "ghost", 1024, 0, shopHost) // an edges file with no box listing
+ reg, err := registry.Open(fx.regPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tok := strings.Repeat("a", 64)
+ for _, f := range []registry.Fleet{{Name: "fx", Account: fx.sqid, Bucket: "fx-data"}, {Name: "fy", Account: "zzz", Bucket: "fy-data"}} {
+ if _, err := reg.CreateFleet(f); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, b := range []registry.FleetBox{{Fleet: "fx", Label: "bx-1", TokenHash: tok}, {Fleet: "fx", Label: "bx-2", TokenHash: tok},
+ {Fleet: "fy", Label: "by-1", TokenHash: tok}} {
+ if err := reg.AddFleetBox(b); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := reg.SetFleetBoxStatus("fx", "bx-2", "detached"); err != nil {
+ t.Fatal(err)
+ }
+ reg.Close()
+ recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")}
+
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs)
+ if err != nil || !complete {
+ t.Fatalf("sizeBoxes = %v, %v", complete, err)
+ }
+ want := []sizeBox{{Box: "annie", TotalMiB: 3884}, {Box: "bx-1"}, {Box: "iris", Region: "ie", TotalMiB: 7820}}
+ if !reflect.DeepEqual(boxes, want) {
+ t.Fatalf("boxes = %+v, want %+v", boxes, want)
+ }
+
+ // With no records (an app default before any instance), every
+ // non-stale platform box and the account's active fleet boxes.
+ boxes, complete, err = fx.srv.sizeBoxes(context.Background(), acct, nil)
+ if err != nil || !complete {
+ t.Fatalf("sizeBoxes with no records = %v, %v", complete, err)
+ }
+ want = []sizeBox{{Box: "annie", TotalMiB: 3884}, {Box: "bx-1"}, {Box: "ivy", Region: "ie", TotalMiB: 3884}}
+ if !reflect.DeepEqual(boxes, want) {
+ t.Fatalf("boxes with no records = %+v, want %+v", boxes, want)
+ }
+}
+
+func TestSizeCapacityRefusesAboveStandardWhenTheBoxListingIsIncomplete(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ putSizeReport(t, fx.rel, "annie", "", time.Now(), nil)
+ putSizeEdges(t, fx.rel, "annie", 65536, 0)
+ putFixtureObject(t, fx.rel, "status/boxes/zed.json", []byte("{not json"))
+ recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")}
+
+ if _, complete, _ := fx.srv.sizeBoxes(context.Background(), acct, recs); complete {
+ t.Fatal("sizeBoxes says complete with an unreadable status report")
+ }
+ got := checkSizes(t, fx.srv, acct, recs, "large", "standard")
+ if r := got["large"]; r == nil || r.Status != http.StatusServiceUnavailable || !strings.HasPrefix(r.Msg, "Could not read every box's memory total") {
+ t.Fatalf("large = %+v, want 503 (string 3)", r)
+ }
+ if got["standard"] != nil {
+ t.Fatalf("standard = %+v, want it to pass", got["standard"])
+ }
+}
+
+func TestSizeCommittedReportsEachBox(t *testing.T) {
+ t.Parallel()
+ fx, _ := sizeFx(t)
+ committed, total, avail := int64(2304), int64(3884)<<20, int64(1200)<<20
+ putSizeReport(t, fx.rel, "annie", "", time.Now(), &status.BoxMetrics{SizeCommittedMiB: &committed, MemTotalBytes: &total, MemAvailBytes: &avail})
+ putSizeReport(t, fx.rel, "betty", "", time.Now(), &status.BoxMetrics{MemTotalBytes: &total, MemAvailBytes: &avail}) // an older box
+ got := fx.srv.sizeCommitted(context.Background(), []string{"annie", "betty", "nobody"})
+ want := []sizeCommittedBox{{Box: "annie", CommittedMiB: 2304, TotalMiB: 3884, FreeMiB: 1200}}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("committed = %+v, want %+v", got, want)
+ }
+}
+
+// Through plan 1's door: a refused size writes no audit event, no policy
+// object and no row; a size that passes answers with each box's committed
+// figure.
+func TestPolicyDoorRefusesAnOversizeBeforeTheAuditWrite(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-policy-oversize")
+ committed, total, avail := int64(512), int64(3884)<<20, int64(1200)<<20
+ putSizeReport(t, fx.rel, "annie", "", time.Now(), &status.BoxMetrics{SizeCommittedMiB: &committed, MemTotalBytes: &total, MemAvailBytes: &avail})
+ putSizeEdges(t, fx.rel, "annie", 3884, 0, shopHost)
+ sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")
+ before := fx.serial(t)
+
+ for _, body := range []string{`{"size":{"host":"shop-a.example.com","value":"xlarge"}}`, `{"default_size":"large"}`} {
+ st, _, out := fx.put(t, "shop", body, policyCreate)
+ if st != http.StatusConflict || !strings.Contains(errorOf(t, out), "the memory on annie (3884 MiB)") {
+ t.Fatalf("%s = %d %s, want 409 naming annie", body, st, out)
+ }
+ }
+ fx.noObject(t, "shop")
+ if evs := fx.policyEvents(t, "shop"); len(evs) != 0 {
+ t.Fatalf("a refused size recorded events: %+v", evs)
+ }
+ if row := fx.row(t, "shop"); row.Revision != 0 {
+ t.Fatalf("a refused size recorded a row: %+v", row)
+ }
+ if got := fx.serial(t); got != before {
+ t.Fatalf("serial %d, want %d", got, before)
+ }
+
+ st, _, out := policyReq(t, fx.consoleFixture, http.MethodPut, "shop", fx.owner, `{"size":{"host":"shop-a.example.com","value":"standard"}}`, policyCreate)
+ if st != http.StatusOK || !strings.Contains(out, `"committed":[{"box":"annie","committed_mib":512,"total_mib":3884,"free_mib":1200}]`) {
+ t.Fatalf("standard = %d %s, want 200 with annie's committed figure", st, out)
+ }
+}
+
+// The request budget (spec §3a, ruling 11): the size check reads boxes and
+// edges files only on a PUT that changes a size. An egress-only change and
+// a re-send of the size in force read neither.
+func TestPolicySizeCheckReadsOnlyOnASizeChange(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-policy-size-budget")
+ putSizeReport(t, fx.rel, "annie", "", time.Now(), nil)
+ putSizeEdges(t, fx.rel, "annie", 65536, 0)
+ cs := newEdgesCountingStore(fx.srv.cfg.Releases)
+ fx.srv.cfg.Releases = cs
+
+ r := fx.mustPut(t, "shop", `{"egress_allow":[]}`, policyCreate)
+ if l, le, g := cs.requests(); l+le+g != 0 {
+ t.Fatalf("an egress-only change made %d lists, %d ETag lists and %d gets of edges or status, want none", l, le, g)
+ }
+ r = fx.mustPut(t, "shop", `{"default_size":"large"}`, policyIfMatch(r.ETag))
+ if l, _, g := cs.requests(); l == 0 || g == 0 {
+ t.Fatalf("a size change made %d lists and %d gets of edges or status, want the size check's reads", l, g)
+ }
+ for _, body := range []string{`{"default_size":"large"}`, `{"egress_allow":[],"default_size":"large"}`, `{"default_size":""}`} {
+ r = fx.mustPut(t, "shop", body, policyIfMatch(r.ETag))
+ if l, le, g := cs.requests(); l+le+g != 0 {
+ t.Fatalf("%s made %d lists, %d ETag lists and %d gets of edges or status, want none", body, l, le, g)
+ }
+ }
+}