carlos / platform Public

Merge remote-tracking branch 'origin/main' into group-capacity-damping

claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 65d02aed1fb0e8dd8589d6e4c9153856c5bf442b parent cae6935parent e6d1f20
6 files changed, +420 −109
  • .amadan/test-gate.sh +69 −12
  • internal/console/policysize.go +123 −51
  • internal/console/policysize_test.go +130 −7
  • internal/console/testdata/demo_claim_layout.mjs +12 −5
  • internal/edge/deadaddr_test.go +82 −0
  • internal/edge/localhold_witness_test.go +4 −34
diff --git a/.amadan/test-gate.sh b/.amadan/test-gate.sh
index 0632a0f37..aca787753 100755
--- a/.amadan/test-gate.sh
+++ b/.amadan/test-gate.sh
@@ -51,8 +51,9 @@
# how long it took, so a slow run says whether it was short of cores.
set -eu
-# Heaviest first: discovery compiles each package's tests in turn, so the
-# packages that dominate the wall clock get their shards started earliest.
+# Heaviest first: shards start in this order once their package's tests
+# have compiled, and the packages that dominate the wall clock should not
+# queue behind the others.
: "${TEST_SPLIT=./internal/console=24 ./internal/edge=4 ./internal/activator=4 ./internal/host=6 .=5 ./internal/grouproll=2}"
weights=$(pwd)/.amadan/test-weights.tsv
gate_t0=$(date +%s)
@@ -168,6 +169,29 @@ start launchctx sh -c 'cd launchctx && go vet ./... && go test ./... -count=1'
start vet go vet ./...
start gofmt sh -c 'fmt_out=$(gofmt -l .); if [ -n "$fmt_out" ]; then echo "gofmt needed:"; echo "$fmt_out"; exit 1; fi; echo "gofmt -l .: clean"'
+# The split packages' test lists, all at once. `go test -list` compiles the
+# test binary, which the shards then reuse from the build cache. One after
+# another the compiles held the last packages' shards back by a minute and
+# a half (host's started at +86 s on 2026-11-11); side by side, each
+# package waits only for its own. The deal below reads each list in turn,
+# as before. Each is its own go command, so a package's list is exactly
+# that package's: the fence counts on it.
+# A package's tag names its files, its shards and a shell variable, so
+# anything but letters, digits and _ becomes _.
+split_tag() { echo "$1" | sed 's|^\./||; s|^\.$|root|; s|[^A-Za-z0-9_]|_|g'; }
+for spec in $TEST_SPLIT; do
+ tag=$(split_tag "${spec%=*}")
+ (
+ set +e
+ t0=$(date +%s)
+ go test -count=1 -list '.*' "${spec%=*}" >"$out/list-$tag.raw" 2>&1
+ echo $? >"$out/list-$tag.rc"
+ echo $(($(date +%s) - t0)) >"$out/list-$tag.secs"
+ ) &
+ started="$started list-$tag:$!"
+ eval "list_pid_$tag=\$!"
+done
+
# Everything not split runs as one ordinary `go test`. Packages are named
# by import path, so match TEST_SPLIT's directories through `go list`.
split_paths=""
@@ -209,26 +233,30 @@ if [ "${GATE_WEIGHTS:-}" = 1 ]; then
shard_json=-json
fi
-for spec in $TEST_SPLIT; do
+# deal_split deals one split package's listed tests onto its shards and
+# starts them.
+deal_split() {
+ spec=$1
dir=${spec%=*}
shards=${spec#*=}
discover go list "$dir" >"$out/go-list"
pkg=$(cat "$out/go-list")
- tag=$(echo "$dir" | sed 's|^\./||; s|^\.$|root|; s|/|_|g')
+ tag=$(split_tag "$dir")
- # -list compiles the test binary, which the shards below then reuse
- # from the build cache. Benchmarks are listed but never run by a plain
- # `go test`, so they are left out of the deal.
- if ! discover go test -count=1 -list '.*' "$dir" >"$out/list-$tag.raw" 2>&1; then
- cp "$out/list-$tag.raw" "$out/$tag.log"
+ # This package's list, started above, has finished. A list with no
+ # status file was killed before it could write one. Benchmarks are
+ # listed but never run by a plain `go test`, so they are left out of
+ # the deal.
+ if [ "$(cat "$out/list-$tag.rc" 2>/dev/null || echo 1)" -ne 0 ]; then
+ cp "$out/list-$tag.raw" "$out/$tag.log" 2>/dev/null || true
fail_job "$tag" "could not list the tests in $pkg"
- continue
+ return
fi
grep -E '^(Test|Example|Fuzz)' "$out/list-$tag.raw" | sort -u >"$out/list-$tag" || true
listed=$(wc -l <"$out/list-$tag")
if [ "$listed" -eq 0 ]; then
fail_job "$tag" "go test -list found no tests in $pkg, which is not believable"
- continue
+ return
fi
# Longest-processing-time first: heaviest test onto the least-loaded
@@ -249,7 +277,7 @@ for spec in $TEST_SPLIT; do
dealt=$(wc -l <"$out/deal-$tag")
if [ "$dealt" -ne "$listed" ]; then
fail_job "$tag" "dealt $dealt of $listed tests in $pkg"
- continue
+ return
fi
i=0
@@ -265,6 +293,26 @@ for spec in $TEST_SPLIT; do
if [ "$launched" -ne "$listed" ]; then
fail_job "$tag-deal" "launched $launched of $listed tests in $pkg"
fi
+}
+
+# Each package's shards start as soon as its own list is ready, whatever
+# order the lists finish in. A list writes its .secs file last.
+pending=$TEST_SPLIT
+while [ -n "$pending" ]; do
+ left=""
+ for spec in $pending; do
+ tag=$(split_tag "${spec%=*}")
+ if [ -e "$out/list-$tag.secs" ]; then
+ eval "wait \$list_pid_$tag" || true
+ deal_split "$spec"
+ else
+ left="$left $spec"
+ fi
+ done
+ pending=$left
+ if [ -n "$pending" ]; then
+ sleep 1
+ fi
done
wait
@@ -307,6 +355,15 @@ for name in $names; do
[ "$rc" -eq 0 ] || failed="$failed $name"
done
+# How long each split package's tests took to compile and list, side by
+# side from the start: a shard cannot start before its package's list.
+lists=""
+for spec in $TEST_SPLIT; do
+ tag=$(split_tag "${spec%=*}")
+ lists="$lists $tag $(cat "$out/list-$tag.secs" 2>/dev/null || echo '?') s,"
+done
+echo "=== lists:${lists%,}"
+
# CPU used against wall clock. The shell's `times` covers every job it
# has waited for, and each job waited for its go test and the test
# binaries under it, so this is the whole gate's CPU. Busy cores well
diff --git a/internal/console/policysize.go b/internal/console/policysize.go
index f634ad1c8..5c3bd1d9c 100644
--- a/internal/console/policysize.go
+++ b/internal/console/policysize.go
@@ -66,8 +66,15 @@ type sizeCommittedBox struct {
// 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
+// A record placed on a fleet (registry.FleetPlacement of its Region) runs
+// on that fleet's boxes and nowhere else (#875): it makes no platform box
+// eligible. With no records, appFleet is the fleet the app is placed on
+// ("" for none) and stands in for them. When every record, or the app, is
+// placed on a fleet, the eligible boxes are the active roster rows of those
+// fleets alone, and no platform listing is read.
+//
+// Otherwise 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) and its known served_pools do not
// exclude that record, or when its edges file lists one of their hosts.
@@ -75,6 +82,9 @@ type sizeCommittedBox struct {
// across regions; nil means the pool is unknown and excludes no box.
// Every active fleet box of the account counts.
//
+// A placed fleet the account does not own, or that is gone, leaves the
+// read incomplete.
+//
// A box's total is, in order: its edges file's box_mem_total_mib; region
// HA's headroom mem_total_mib (ruling C3); its own status report's
// mem_total_bytes, when that report is not stale. None of them is 0.
@@ -83,57 +93,29 @@ type sizeCommittedBox struct {
// 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, defaultPool *string) (boxes []sizeBox, complete bool, err error) {
+func (s *Server) sizeBoxes(ctx context.Context, acct *Account, recs []provision.Record, defaultPool *string, appFleet string) (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 := map[string]bool{}
- regions := map[string][]string{}
+ placed := map[string]bool{}
+ var platformRecs []provision.Record
for _, r := range recs {
- hosts[r.Host] = true
- region := s.homeRegionIn(r.Region)
- regions[region] = append(regions[region], r.Pool)
- }
- now := time.Now()
- seen := map[string]bool{}
- for i, b := range reports {
- if b.Label == "" || seen[b.Label] {
- continue
- }
- stale := status.BoxStale(b, now, status.SnapshotPeriod)
- f := files[b.Label]
- if stale {
- continue
- }
- if len(recs) == 0 {
- if defaultPool != nil && !f.mayServe(*defaultPool) {
- continue
- }
+ if f, ok := registry.FleetPlacement(r.Region); ok {
+ placed[f] = true
} else {
- eligible := f.servesAny(hosts)
- for _, pool := range regions[s.homeRegionIn(b.Region)] {
- eligible = eligible || f.mayServe(pool)
- }
- if !eligible {
- continue
- }
+ platformRecs = append(platformRecs, r)
+ }
+ }
+ if len(recs) == 0 && appFleet != "" {
+ placed[appFleet] = true
+ }
+ fleetOnly := len(placed) > 0 && len(platformRecs) == 0
+ complete = true
+ if !fleetOnly {
+ boxes, complete, err = s.sizePlatformBoxes(ctx, platformRecs, defaultPool)
+ if err != nil {
+ return nil, false, err
}
- seen[b.Label] = true
- boxes = append(boxes, sizeBox{Box: b.Label, Region: b.Region, TotalMiB: f.total, report: &reports[i]})
}
reg, fleets, err := s.systemFleets()
@@ -141,10 +123,12 @@ func (s *Server) sizeBoxes(ctx context.Context, acct *Account, recs []provision.
s.policyLogf("console: size check: fleets: %v", err)
complete = false
}
+ found := map[string]bool{}
for _, f := range fleets {
- if f.Account != acct.Sqid {
+ if f.Account != acct.Sqid || (fleetOnly && !placed[f.Name]) {
continue
}
+ found[f.Name] = true
roster, err := reg.ListFleetBoxes(f.Name)
if err != nil {
s.policyLogf("console: size check: fleet %s roster: %v", f.Name, err)
@@ -179,9 +163,16 @@ func (s *Server) sizeBoxes(ctx context.Context, acct *Account, recs []provision.
boxes = append(boxes, sb)
}
}
+ for f := range placed {
+ if !found[f] && err == nil {
+ s.policyLogf("console: size check: placed fleet %s is not one of the account's fleets", f)
+ complete = false
+ }
+ }
// A box with no total in an edges file falls back to its own status
// report's memory total, when the report is fresh (ruling, Task 9
// review): fleet boxes publish no edges file, so this is their total.
+ now := time.Now()
for i := range boxes {
b := &boxes[i]
if b.TotalMiB > 0 || b.report == nil || status.BoxStale(*b.report, now, status.SnapshotPeriod) {
@@ -195,6 +186,61 @@ func (s *Server) sizeBoxes(ctx context.Context, acct *Account, recs []provision.
return boxes, complete, nil
}
+// sizePlatformBoxes is sizeBoxes's platform half: the eligible platform
+// boxes for recs (none of them fleet-placed), or for defaultPool with no
+// records, each with its edges file total.
+func (s *Server) sizePlatformBoxes(ctx context.Context, recs []provision.Record, defaultPool *string) (boxes []sizeBox, complete bool, err error) {
+ 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 := map[string]bool{}
+ regions := map[string][]string{}
+ for _, r := range recs {
+ hosts[r.Host] = true
+ region := s.homeRegionIn(r.Region)
+ regions[region] = append(regions[region], r.Pool)
+ }
+ now := time.Now()
+ seen := map[string]bool{}
+ for i, b := range reports {
+ if b.Label == "" || seen[b.Label] {
+ continue
+ }
+ stale := status.BoxStale(b, now, status.SnapshotPeriod)
+ f := files[b.Label]
+ if stale {
+ continue
+ }
+ if len(recs) == 0 {
+ if defaultPool != nil && !f.mayServe(*defaultPool) {
+ continue
+ }
+ } else {
+ eligible := f.servesAny(hosts)
+ for _, pool := range regions[s.homeRegionIn(b.Region)] {
+ eligible = eligible || f.mayServe(pool)
+ }
+ if !eligible {
+ continue
+ }
+ }
+ seen[b.Label] = true
+ boxes = append(boxes, sizeBox{Box: b.Label, Region: b.Region, TotalMiB: f.total, report: &reports[i]})
+ }
+ return boxes, complete, nil
+}
+
// sizeEdges is what the size check takes from a box's edges files: its
// total, served pools and the hosts it serves. Two files naming one box
// join conservatively: an unknown total, or the smaller one; either file
@@ -262,8 +308,8 @@ func (e sizeEdges) servesAny(hosts map[string]bool) bool {
// 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, defaultPool *string) ([]sizeBox, *doorRefusal) {
- boxes, complete, err := s.sizeBoxes(ctx, acct, recs, defaultPool)
+func (s *Server) sizeCapacityCheck(ctx context.Context, acct *Account, recs []provision.Record, size cgroup.Size, defaultPool *string, appFleet string) ([]sizeBox, *doorRefusal) {
+ boxes, complete, err := s.sizeBoxes(ctx, acct, recs, defaultPool, appFleet)
if err != nil {
s.policyLogf("console: size check: %v", err)
complete = false
@@ -363,7 +409,20 @@ func (s *Server) policySizeCheck(ctx context.Context, acct *Account, app string,
// Only a complete empty record set may use the app's default pool.
// Unread records or manifests retain the conservative all-box check.
var defaultPool *string
+ appFleet := ""
if ok && len(recs) == 0 {
+ // An app placed on a fleet is sized against that fleet's boxes
+ // alone (#875), whatever its default pool.
+ placement, err := s.sizeAppPlacement(acct, app)
+ switch {
+ case err == nil:
+ appFleet, _ = registry.FleetPlacement(placement)
+ case sizeAboveStandard(c.size):
+ s.policyLogf("console: size check %s/%s: placement: %v", acct.Sqid, app, err)
+ return nil, &doorRefusal{Status: http.StatusServiceUnavailable, Msg: sizeUnreadMsg}
+ }
+ }
+ if ok && len(recs) == 0 && appFleet == "" {
manifest, err := provision.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app)
switch {
case err == nil:
@@ -375,7 +434,7 @@ func (s *Server) policySizeCheck(ctx context.Context, acct *Account, app string,
return nil, &doorRefusal{Status: http.StatusServiceUnavailable, Msg: sizeUnreadMsg}
}
}
- boxes, ref := s.sizeCapacityCheck(ctx, acct, recs, c.size, defaultPool)
+ boxes, ref := s.sizeCapacityCheck(ctx, acct, recs, c.size, defaultPool, appFleet)
if ref != nil {
return nil, ref
}
@@ -409,3 +468,16 @@ func (s *Server) policySizeRecords(ctx context.Context, acct *Account, app, host
}
return recs, true
}
+
+// sizeAppPlacement is the app's placement as the change door reads it
+// (appPlacement); with no registry, the stored column alone.
+func (s *Server) sizeAppPlacement(acct *Account, app string) (string, error) {
+ if s.cfg.Registry == "" {
+ return s.store.AppPlacement(acct.ID, app)
+ }
+ reg, err := openRegistry(s.cfg.Registry)
+ if err != nil {
+ return "", err
+ }
+ return s.appPlacement(reg, acct, app)
+}
diff --git a/internal/console/policysize_test.go b/internal/console/policysize_test.go
index ebdd1a60f..12a69a137 100644
--- a/internal/console/policysize_test.go
+++ b/internal/console/policysize_test.go
@@ -87,7 +87,7 @@ func checkSizes(t *testing.T, s *Server, acct *Account, recs []provision.Record,
t.Helper()
out := map[string]*doorRefusal{}
for _, n := range names {
- _, ref := s.sizeCapacityCheck(context.Background(), acct, recs, mustSize(t, n), nil)
+ _, ref := s.sizeCapacityCheck(context.Background(), acct, recs, mustSize(t, n), nil, "")
out[n] = ref
}
return out
@@ -167,7 +167,7 @@ func TestSizeCapacityRefusesAboveStandardWhenATotalIsMissing(t *testing.T) {
}
putSizeEdges(t, fx.rel, "betty", 0, 16384) // region HA's headroom only
- boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil)
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil, "")
if err != nil || !complete {
t.Fatalf("sizeBoxes = %v, %v", complete, err)
}
@@ -245,7 +245,7 @@ func TestSizeCapacityReadsATotalFromTheBoxsStatusReport(t *testing.T) {
t.Fatalf("large with no report from bx-1 = %+v, want 409 naming bx-1", r)
}
putSizeReport(t, fleet, "bx-1", "", time.Now(), fresh)
- boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil)
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil, "")
if err != nil || !complete {
t.Fatalf("sizeBoxes = %v, %v", complete, err)
}
@@ -295,7 +295,7 @@ func TestSizeBoxesComeFromTheListingsNotTheEdgesFiles(t *testing.T) {
reg.Close()
recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, "")}
- boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil)
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil, "")
if err != nil || !complete {
t.Fatalf("sizeBoxes = %v, %v", complete, err)
}
@@ -306,7 +306,7 @@ func TestSizeBoxesComeFromTheListingsNotTheEdgesFiles(t *testing.T) {
// 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, nil)
+ boxes, complete, err = fx.srv.sizeBoxes(context.Background(), acct, nil, nil, "")
if err != nil || !complete {
t.Fatalf("sizeBoxes with no records = %v, %v", complete, err)
}
@@ -324,7 +324,7 @@ func TestSizeCapacityRefusesAboveStandardWhenTheBoxListingIsIncomplete(t *testin
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, nil); complete {
+ if _, complete, _ := fx.srv.sizeBoxes(context.Background(), acct, recs, nil, ""); complete {
t.Fatal("sizeBoxes says complete with an unreadable status report")
}
got := checkSizes(t, fx.srv, acct, recs, "large", "standard")
@@ -348,7 +348,7 @@ func TestSizeCommittedReportsEachBox(t *testing.T) {
putSizeReport(t, release.NewPrefixStore(fx.rel, "fleets/fx/"), "bx-1", "", time.Now(),
&status.BoxMetrics{SizeCommittedMiB: &fc, MemTotalBytes: &ft, MemAvailBytes: &fa})
- boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, nil, nil)
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, nil, nil, "")
if err != nil || !complete {
t.Fatalf("sizeBoxes = %v, %v", complete, err)
}
@@ -437,3 +437,126 @@ func TestPolicySizeCheckReadsOnlyOnASizeChange(t *testing.T) {
}
}
}
+
+// #875: an app placed on a fleet runs on that fleet's boxes and nowhere
+// else, so its size is judged against them alone. A small platform box and
+// another of the account's fleets do not cap it, and the platform listings
+// are not read (an unreadable platform report leaves the read complete).
+func TestSizeChecksAFleetPlacedAppAgainstItsFleetOnly(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ now := time.Now()
+ putSizeReport(t, fx.rel, "annie", "", now, nil)
+ putSizeEdges(t, fx.rel, "annie", 3847, 0, shopHost)
+ putFixtureObject(t, fx.rel, "status/boxes/zed.json", []byte("{not json"))
+ sizeFleet(t, fx, "classic", fx.sqid, "box-1")
+ sizeFleet(t, fx, "other", fx.sqid, "bo-1")
+ big, small := int64(7990)<<20, int64(2048)<<20
+ putSizeReport(t, release.NewPrefixStore(fx.rel, "fleets/classic/"), "box-1", "", now, &status.BoxMetrics{MemTotalBytes: &big})
+ putSizeReport(t, release.NewPrefixStore(fx.rel, "fleets/other/"), "bo-1", "", now, &status.BoxMetrics{MemTotalBytes: &small})
+ placed := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, registry.PlacementTarget("classic"))}
+
+ want := []sizeBox{{Box: "box-1", TotalMiB: 7990, fleet: "classic"}}
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, placed, nil, "")
+ if err != nil || !complete || !reflect.DeepEqual(noReports(boxes), want) {
+ t.Fatalf("sizeBoxes for a fleet-placed record = %+v, %v, %v, want %+v complete", boxes, complete, err, want)
+ }
+ // No records yet: the app's own placement stands in for them.
+ boxes, complete, err = fx.srv.sizeBoxes(context.Background(), acct, nil, nil, "classic")
+ if err != nil || !complete || !reflect.DeepEqual(noReports(boxes), want) {
+ t.Fatalf("sizeBoxes for a fleet-placed app = %+v, %v, %v, want %+v complete", boxes, complete, err, want)
+ }
+ // The quarter rule still holds on the fleet's own box: 7990 MiB (a
+ // t4g.large) allows 1997 MiB, short of xlarge's 2048.
+ if r := checkSizes(t, fx.srv, acct, placed, "xlarge")["xlarge"]; r == nil || r.Status != http.StatusConflict ||
+ !strings.Contains(r.Msg, "the memory on box-1 (7990 MiB)") {
+ t.Fatalf("xlarge on box-1 (7990 MiB) = %+v, want 409 naming box-1", r)
+ }
+ if r := checkSizes(t, fx.srv, acct, placed, "large")["large"]; r != nil {
+ t.Fatalf("large on box-1 (7990 MiB) = %+v, want it to pass", r)
+ }
+ sixteen := int64(16384) << 20
+ putSizeReport(t, release.NewPrefixStore(fx.rel, "fleets/classic/"), "box-1", "", now, &status.BoxMetrics{MemTotalBytes: &sixteen})
+ if r := checkSizes(t, fx.srv, acct, placed, "xlarge")["xlarge"]; r != nil {
+ t.Fatalf("xlarge on box-1 (16384 MiB) = %+v, want it to pass", r)
+ }
+
+ // The same app unplaced is still judged against every box it may land
+ // on, and the unreadable platform report counts again.
+ unplaced := []provision.Record{placed[0]}
+ unplaced[0].Region = ""
+ if _, complete, _ := fx.srv.sizeBoxes(context.Background(), acct, unplaced, nil, ""); complete {
+ t.Fatal("sizeBoxes for a platform record says complete with an unreadable status report")
+ }
+ if r := checkSizes(t, fx.srv, acct, unplaced, "xlarge")["xlarge"]; r == nil {
+ t.Fatal("xlarge for a platform record passed, want a refusal")
+ }
+}
+
+// A record naming a fleet the account does not own (or no longer has) is
+// not a fleet with no boxes: the read is incomplete, so above standard is
+// refused.
+func TestSizeRefusesAboveStandardForAnUnknownPlacedFleet(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ sizeFleet(t, fx, "fy", "zzz", "by-1")
+ recs := []provision.Record{sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, registry.PlacementTarget("fy"))}
+
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil, "")
+ if err != nil || complete || len(boxes) != 0 {
+ t.Fatalf("sizeBoxes = %+v, %v, %v, want no boxes and incomplete", boxes, complete, err)
+ }
+ got := checkSizes(t, fx.srv, acct, recs, "xlarge", "standard")
+ if r := got["xlarge"]; r == nil || r.Status != http.StatusServiceUnavailable {
+ t.Fatalf("xlarge = %+v, want 503 (string 3)", r)
+ }
+ if got["standard"] != nil {
+ t.Fatalf("standard = %+v, want it to pass", got["standard"])
+ }
+}
+
+// The door, end to end: an app with no instances yet, placed on a fleet,
+// sets a default size its fleet's box can hold even though a platform box
+// could not.
+func TestPolicyDoorSizesAFleetPlacedAppAgainstItsFleet(t *testing.T) {
+ t.Parallel()
+ fx := newPolicyFx(t, "code-policy-fleet-size")
+ now := time.Now()
+ putSizeReport(t, fx.rel, "annie", "", now, nil)
+ putSizeEdges(t, fx.rel, "annie", 3847, 0)
+ sizeFleet(t, fx.consoleFixture, "classic", fx.sqid, "box-1")
+ big := int64(16384) << 20
+ putSizeReport(t, release.NewPrefixStore(fx.rel, "fleets/classic/"), "box-1", "", now, &status.BoxMetrics{MemTotalBytes: &big})
+
+ st, _, out := fx.put(t, "shop", `{"default_size":"xlarge"}`, policyCreate)
+ if st != http.StatusConflict || !strings.Contains(errorOf(t, out), "the memory on annie (3847 MiB)") {
+ t.Fatalf("xlarge unplaced = %d %s, want 409 naming annie", st, out)
+ }
+ if err := fx.st.SetAppPlacement(OpsAccountID, "shop", registry.PlacementTarget("classic")); err != nil {
+ t.Fatal(err)
+ }
+ if st, _, out := fx.put(t, "shop", `{"default_size":"xlarge"}`, policyCreate); st != http.StatusOK {
+ t.Fatalf("xlarge placed on classic = %d %s, want 200", st, out)
+ }
+}
+
+// One platform record among fleet-placed ones keeps the platform boxes it
+// may land on and every fleet of the account in the check.
+func TestSizeChecksMixedRecordsAgainstBothPlatformAndFleets(t *testing.T) {
+ t.Parallel()
+ fx, acct := sizeFx(t)
+ putSizeReport(t, fx.rel, "annie", "", time.Now(), nil)
+ putSizeEdges(t, fx.rel, "annie", 3847, 0, shopHost)
+ sizeFleet(t, fx, "classic", fx.sqid, "box-1")
+ sizeFleet(t, fx, "other", fx.sqid, "bo-1")
+ recs := []provision.Record{
+ sizeRecord(t, fx.rel, fx.sqid, "shop", shopHost, ""),
+ sizeRecord(t, fx.rel, fx.sqid, "shop", "shop-b.example.com", registry.PlacementTarget("classic")),
+ }
+
+ boxes, complete, err := fx.srv.sizeBoxes(context.Background(), acct, recs, nil, "")
+ want := []sizeBox{{Box: "annie", TotalMiB: 3847}, {Box: "bo-1", fleet: "other"}, {Box: "box-1", fleet: "classic"}}
+ if err != nil || !complete || !reflect.DeepEqual(noReports(boxes), want) {
+ t.Fatalf("sizeBoxes = %+v, %v, %v, want %+v complete", boxes, complete, err, want)
+ }
+}
diff --git a/internal/console/testdata/demo_claim_layout.mjs b/internal/console/testdata/demo_claim_layout.mjs
index c742460e0..0d2ae4eeb 100644
--- a/internal/console/testdata/demo_claim_layout.mjs
+++ b/internal/console/testdata/demo_claim_layout.mjs
@@ -77,12 +77,19 @@ export const watchClaimCSP = `
const record = () => {
const stage = claim.dataset.state === 'claimed' ? 4 : Number(progress.dataset.stage);
if (stage === last) return;
- // The server-rendered stage is on screen from the first contentful
- // paint, which a cold or busy browser can reach before this event
- // fires. The page counts its 650 ms from its own paint, so timing the
- // first stage from here would short it (644.9 ms on CI, 2026-11-10).
+ // The first stage is timed from when the document finished parsing
+ // (domInteractive), which is always before the page's script starts
+ // its own 650 ms clock. This event can fire after the page has
+ // already painted and started that clock, and the first-paint entry
+ // may not be posted yet, so timing from here, or from first paint
+ // when it is missing, shorted the stage (644.9 ms and 648.4 ms on CI,
+ // 2026-11-10/11).
let time = performance.now();
- if (last === undefined) time = Math.min(time, performance.getEntriesByName('first-contentful-paint')[0]?.startTime ?? time);
+ if (last === undefined) {
+ const nav = performance.getEntriesByType('navigation')[0];
+ const paint = performance.getEntriesByName('first-contentful-paint')[0];
+ time = Math.min(time, nav?.domInteractive || time, paint?.startTime ?? time);
+ }
window.claimStageTimes.push({stage,time});
last = stage;
};
diff --git a/internal/edge/deadaddr_test.go b/internal/edge/deadaddr_test.go
index ad505358a..6da5525b2 100644
--- a/internal/edge/deadaddr_test.go
+++ b/internal/edge/deadaddr_test.go
@@ -3,6 +3,7 @@
package edge
import (
+ "context"
"errors"
"net"
"os"
@@ -10,6 +11,8 @@ import (
"sync"
"syscall"
"testing"
+
+ "golang.org/x/sys/unix"
)
// deadSockets maps each address deadAddr handed out to the socket holding
@@ -106,6 +109,40 @@ func reviveDeadAddr(addr string) (net.Listener, error) {
// CI gate runs many test processes at once, and a port that was merely
// closed went to another test's server, whose 404 the edge then proxied
// (TestAllUpstreamsDownAnswers503WithRetryAfter, discussion 867).
+func TestHeldTCPPortRestartsWithoutLettingGo(t *testing.T) {
+ addr, listen := heldTCPPort(t)
+ refused := func(when string) {
+ t.Helper()
+ if c, err := net.Dial("tcp", addr); err == nil {
+ c.Close()
+ t.Fatalf("%s: dial %s connected, want refused", when, addr)
+ }
+ if ln, err := net.Listen("tcp", addr); err == nil {
+ ln.Close()
+ t.Fatalf("%s: another listener took %s", when, addr)
+ }
+ }
+ refused("before any listener")
+ for round := 1; round <= 3; round++ {
+ ln, err := listen()
+ if err != nil {
+ t.Fatalf("round %d: listen: %v", round, err)
+ }
+ go func() {
+ if c, err := ln.Accept(); err == nil {
+ c.Close()
+ }
+ }()
+ c, err := net.Dial("tcp", addr)
+ if err != nil {
+ t.Fatalf("round %d: dial while listening: %v", round, err)
+ }
+ c.Close()
+ ln.Close()
+ refused("after round " + strconv.Itoa(round))
+ }
+}
+
func TestDeadAddrStaysDeadForTheTest(t *testing.T) {
addr := deadAddr(t)
if ln, err := net.Listen("tcp", addr); err == nil {
@@ -138,3 +175,48 @@ func TestDeadAddrStaysDeadForTheTest(t *testing.T) {
t.Fatal("revived the same address twice")
}
}
+
+// heldTCPPort is a loopback address whose upstream a test can start, stop
+// and start again, with the port kept from everyone else the whole time.
+// A socket bound with SO_REUSEPORT and never listening holds it; each call
+// to listen binds a listener beside it with SO_REUSEPORT, which only this
+// process can do (the kernel matches the user, and a listener without the
+// option is refused). While no listener is open, connections are refused
+// at once, as for deadAddr. Reserving a port and closing it, as the restart
+// witness did until 2026-11-11, let another test process take it between
+// restarts ("bind: address already in use" on CI).
+func heldTCPPort(t *testing.T) (addr string, listen func() (net.Listener, error)) {
+ t.Helper()
+ syscall.ForkLock.RLock()
+ fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
+ if err == nil {
+ syscall.CloseOnExec(fd)
+ }
+ syscall.ForkLock.RUnlock()
+ if err != nil {
+ t.Fatalf("socket: %v", err)
+ }
+ t.Cleanup(func() { syscall.Close(fd) })
+ if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil {
+ t.Fatalf("SO_REUSEPORT: %v", err)
+ }
+ if err := syscall.Bind(fd, &syscall.SockaddrInet4{Addr: [4]byte{127, 0, 0, 1}}); err != nil {
+ t.Fatalf("bind 127.0.0.1:0: %v", err)
+ }
+ sa, err := syscall.Getsockname(fd)
+ in4, ok := sa.(*syscall.SockaddrInet4)
+ if err != nil || !ok {
+ t.Fatalf("getsockname: %T, %v; want an IPv4 address", sa, err)
+ }
+ addr = net.JoinHostPort("127.0.0.1", strconv.Itoa(in4.Port))
+ lc := net.ListenConfig{Control: func(_, _ string, c syscall.RawConn) error {
+ var serr error
+ if err := c.Control(func(fd uintptr) {
+ serr = syscall.SetsockoptInt(int(fd), syscall.SOL_SOCKET, unix.SO_REUSEPORT, 1)
+ }); err != nil {
+ return err
+ }
+ return serr
+ }}
+ return addr, func() (net.Listener, error) { return lc.Listen(context.Background(), "tcp", addr) }
+}
diff --git a/internal/edge/localhold_witness_test.go b/internal/edge/localhold_witness_test.go
index 3c941e96e..1f069c0c0 100644
--- a/internal/edge/localhold_witness_test.go
+++ b/internal/edge/localhold_witness_test.go
@@ -277,44 +277,14 @@ func witnessEdge(t *testing.T, reg *registry.Registry, hold localHold) *Edge {
return e
}
-// reserveLoopbackAddr picks a free 127.0.0.1 port and releases it, so the
-// route can name an address the upstream binds later.
-func reserveLoopbackAddr(t *testing.T) string {
- t.Helper()
- l, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- t.Fatalf("reserve port: %v", err)
- }
- addr := l.Addr().String()
- l.Close()
- return addr
-}
-
-// listenTCPFixed binds addr, retrying briefly in case the kernel has not yet
-// released it.
-func listenTCPFixed(addr string) func() (net.Listener, error) {
- return func() (net.Listener, error) {
- var lastErr error
- for i := 0; i < 50; i++ {
- l, err := net.Listen("tcp", addr)
- if err == nil {
- return l, nil
- }
- lastErr = err
- time.Sleep(20 * time.Millisecond)
- }
- return nil, lastErr
- }
-}
-
func witnessTCPEdge(t *testing.T, hold localHold) (*Edge, func() (net.Listener, error)) {
t.Helper()
- addr := reserveLoopbackAddr(t)
+ addr, listen := heldTCPPort(t)
reg := openReg(t)
if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "service", Addr: addr, Status: "ready"}); err != nil {
t.Fatalf("upsert: %v", err)
}
- return witnessEdge(t, reg, hold), listenTCPFixed(addr)
+ return witnessEdge(t, reg, hold), listen
}
// TestLocalUpstreamRestartWitness restarts a local upstream under load and
@@ -353,7 +323,7 @@ func TestLocalUpstreamRestartWitness(t *testing.T) {
// requests wait for its readmission, and readmission takes up to R.
t.Run("probed", func(t *testing.T) {
t.Parallel()
- addr := reserveLoopbackAddr(t)
+ addr, listen := heldTCPPort(t)
h := provision.Health{Path: "/healthz", IntervalMS: 100, FailAfter: 1, RiseAfter: 2}
reg := openReg(t)
if err := reg.Upsert(registry.Route{Host: witnessHost, Kind: "service", Addrs: addr, Health: healthJSON(t, h), Status: "ready"}); err != nil {
@@ -365,7 +335,7 @@ func TestLocalUpstreamRestartWitness(t *testing.T) {
if got, ok := e.probers.Hold(witnessHost); !ok || got != min(hold.dial+r, hold.cap) {
t.Fatalf("Hold = (%v, %v), want (%v, true)", got, ok, min(hold.dial+r, hold.cap))
}
- st := runRestartWitness(t, e, listenTCPFixed(addr))
+ st := runRestartWitness(t, e, listen)
logWitness(t, "probed", st)
checkWitness(t, st, r)
})