carlos / platform Public

Merge remote-tracking branch 'origin/main' into group-verb-followups

# Conflicts:
#	internal/provision/testdata/plan14-root-reads-chain.tsv
claude pushed by paul@keymail.dev 6891713b926eaac80e768073f08caeb1848d9dfe parent ef855cfparent 4fe1230
14 files changed, +476 −115
  • .amadan/test-gate.sh +69 −12
  • docs/superpowers/notes/census-proposal-group-capacity-damping.md +21 −0
  • docs/superpowers/notes/census-proposal-group-verb-followups.md +1 −1
  • docs/superpowers/plans/2026-11-01-region-ha-p3-group.md +3 −0
  • docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md +3 −0
  • infra/modules/region-host/group_alarms.tf +16 −2
  • infra/modules/region-host/tests/group_alarms.tftest.hcl +2 −2
  • 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
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • internal/provision/testdata/plan14-root-reads-group-capacity-damping.tsv +8 −0

CI passed — run details

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/docs/superpowers/notes/census-proposal-group-capacity-damping.md b/docs/superpowers/notes/census-proposal-group-capacity-damping.md
new file mode 100644
index 000000000..aa97a508d
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-group-capacity-damping.md
@@ -0,0 +1,21 @@
+# Census approval: group-capacity-damping
+
+Ruling `census-ruling-group-capacity-damping`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `infra/modules/region-host/group_alarms.tf` `external` | body | unchanged (1) | group_capacity alarm: evaluation_periods and datapoints_to_alarm 1 -> 5 (alarms after 5 of 5 one-minute periods breaching), comment updated, description unchanged; same metric math, threshold, missing-data handling and actions. tofu only, run on an operator machine; no read is added and nothing on a box reads the file. |
+| `infra/modules/region-host/tests/group_alarms.tftest.hcl` `external` | body | unchanged (1) | Assert the group capacity alarm window is 5 of 5 (was 1 of 1) and update its message. Mock-provider test only, no root runtime read. |
+
+Envelopes re-pinned: `infra/modules/region-host`, `infra/modules/region-host/tests`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `infra/modules/region-host/group_alarms.tf` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. Copy sweep 1: apply approved variable and alarm descriptions verbatim; no resource, threshold, action or read changes.;rev3=census-ruling-region-ha-p3b;basis=Add group capacity, memory, clock, missing-clock and launch-failure notifications; preserve account-owner SNS rights and scope CloudWatch/EventBridge publishers by source account/ARN. Operator-applied Terraform, no box file read; notifications grant no replacement authority.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: add one group-mode SuspectHolderHosts Maximum alarm, 60 seconds, 1 of 1, threshold greater than zero, missing data notBreaching, existing regional SNS actions and ASG dimension. No replacement, scale, IAM, storage or root runtime authority.;rev3=census-ruling-region-ha-g3-fixes;basis=Send existing queue, group and launch-failure notifications to the selected regional SNS topic. Keep externally owned topic policy and subscriptions outside this module; no replacement or scale authority and no new root runtime read.
+- `infra/modules/region-host/tests/group_alarms.tftest.hcl` `external`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions.;rev3=census-ruling-region-ha-p3b;basis=Mock group metric producers, alarm dimensions/windows/missing data and complete scoped SNS policy; retain fixed alarm expectations. Test-only Terraform input, no root runtime read.;rev3=census-ruling-region-ha-p3b1-fixes;basis=Supply the real-shape group queue URL in the group alarm mock so the launch URL equality guard is exercised. Mock plans only; no runtime reads.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: pin fixed-mode zero count, group shape, regional SNS actions and non-breaching missing data for the new alarm; mock-provider test only, no root runtime read.
+
+Seal: `43260792034a1a20791d14c4e4476e762b40d7bcca64257ef2e9899da6af5df0` → `0c649af234a7b89a75479e59e705307e3293a59439b7b251dd4558bd46ef2100`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-group-capacity-damping.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-group-verb-followups.md b/docs/superpowers/notes/census-proposal-group-verb-followups.md
index 60f1b1c9b..79b1cfe71 100644
--- a/docs/superpowers/notes/census-proposal-group-verb-followups.md
+++ b/docs/superpowers/notes/census-proposal-group-verb-followups.md
@@ -18,6 +18,6 @@ Recorded dispositions, which each change must still satisfy:
- `internal/grouprollaws/group.go` `Adapter.TemplateRelease`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-group-roll-verb;basis=reads the launch template's user data from the EC2 answer (in memory, 4 MiB cap)
- `system_group.go` `runSystemGroup`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-group-roll-verb;basis=lstats /etc/carlos/host.env to refuse running on a carlos box (euid 0 is refused first); routes the roll, replace, remove, cancel-drain and probe verbs to the engine after refusing missing arguments
-Seal: `43260792034a1a20791d14c4e4476e762b40d7bcca64257ef2e9899da6af5df0` → `a53b2aed26da8e8a46974ad982376e373762399e6cc92b43d7907ddc53f3971f`.
+Seal: `0c649af234a7b89a75479e59e705307e3293a59439b7b251dd4558bd46ef2100` → `9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af`.
Overlay: `internal/provision/testdata/plan14-root-reads-group-verb-followups.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md b/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md
index b1bd581fe..91f2eb17b 100644
--- a/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md
+++ b/docs/superpowers/plans/2026-11-01-region-ha-p3-group.md
@@ -272,6 +272,9 @@ The admitted check refuses startup/shutdown; the start callback additionally pro
| Local set-aside / files / migration | Reason counts; oldest continuous unpublished >300s, snapshot >2 configured intervals, partial/backfill failure and migration refusal; existing runtime producers, migration slice owns its signal; **I2**. |
| Wake without eligible capacity | Existing per-region/hour notification from placement, not a new per-box alarm sender; **A20/H4**. |
+> **Superseded 2026-11-11 (branch group-capacity-damping, Paul via 8a3d302):** the group-capacity alarm is now 5 of 5 one-minute periods, not 1 of 1, because planned member launches (1-2 min short) fired it on every launch. See the comment on `group_capacity` in `infra/modules/region-host/group_alarms.tf`.
+
+
- [ ] **Step 4 — verify sources and routing.** PASS local/mock tests; exercise every threshold/recovery/missing-data case with fake time. At integration, each non-P3 row must cite the actual merged producer or remain a named G2 blocker; writing an alarm with no stream does not complete §20. Migration/backfill signals are conditional on that later feature, not a requirement to build migration before G2. Add no migration feature just to produce its alarm. Verify subscriptions before live faults; alarm lag is recorded separately from failover time.
- [ ] **Step 5 — commit**, bundled with its visible slice; deferred producers are not implemented against branch previews.
diff --git a/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md b/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md
index 3b5d85838..eb3f8802d 100644
--- a/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md
+++ b/docs/superpowers/plans/2026-11-04-region-ha-p3b-group.md
@@ -193,6 +193,9 @@ The first **live** step of P3b-2 is one approved disposable Enter/ExitStandby ob
- [ ] Extend actual simulation with boot/hook/response-loss/admission/first-direct-service hang, pre-admission departure delivery/redelivery/failed boot, and both no-hook and Pending:Wait maintenance-return actions; retain I1–I6 and merged production predicates. Mutation pre-admission service and failed-health completion must fail; one serial nice-19 3,000-seed sweep per implementation revision. Do not model unmerged drain as complete. Run named metrics/budget/mock tests; no extra task review solely for metrics.
- [ ] Complete census/whole-branch review and Task 8's first-service subsection under a dated scoped go. Reuse dev ingress or separately approved group ingress, set console full ingress **before** group publication, roll all readers first, verify exact SSM path reads with the actual box role, and show signed release/version and hapair service. No empty NLB acceptance. N-HA19 settles D1/D2; the dated execution card remains required before build; P2b merge is **not** a prerequisite for this limited observation. Only then land P3b-1 through amadan with exact-tip green CI; read main CI afterward.
+> **Superseded 2026-11-11 (branch group-capacity-damping, Paul via 8a3d302):** the group-capacity alarm is now 5 of 5 one-minute periods, not 1 of 1, because planned member launches (1-2 min short) fired it on every launch. See the comment on `group_capacity` in `infra/modules/region-host/group_alarms.tf`.
+
+
### Task 7: Operator Standby roll and T1/I4 witness [own review: root/termination]
**Files:** later, separate `platform-infrastructure` branch: proposed `scripts/roll-region-group.sh`, proposed `scripts/tests/roll-region-group-test.sh` for fake-AWS/transport tests, `dev/region-ha-group.tf`, and `docs/superpowers/notes/2026-11-04-region-ha-p3b-dev-drill.md`. These are proposed private paths, not existing interfaces. This planning commission writes none of them. Platform changes, if needed by testing, remain in Task 4's reviewed guard.
diff --git a/infra/modules/region-host/group_alarms.tf b/infra/modules/region-host/group_alarms.tf
index f177b6863..606d6907b 100644
--- a/infra/modules/region-host/group_alarms.tf
+++ b/infra/modules/region-host/group_alarms.tf
@@ -31,14 +31,28 @@ locals {
group_alarm_actions = local.alerts_actions
}
+# Five of five minutes, not one. A planned member launch (roll, Standby
+# return, replacement) leaves the group one short for one to two minutes:
+# 76 such ALARM/OK pairs on the dev IE and flagship US groups between
+# 2026-11-04 and 11-11, none longer than two minutes, which taught people
+# to ignore this alarm. It now needs five consecutive breaching periods
+# instead of one, about four periods later for the same data. A period
+# breaches when the group is short OR an ASG input is missing (FILL makes
+# a late sample breach), so five periods mixing the two also alarm, and a
+# late sample can delay the clear. A member that never comes back still
+# pages. An observed non-breaching period (full membership reported)
+# breaks the sequence, so a dip that reports recovered within five
+# periods does not page here; a recovery whose sample is missing still
+# counts as breaching. Launch failures notify separately through the
+# EventBridge rule below (best effort, no added window).
resource "aws_cloudwatch_metric_alarm" "group_capacity" {
count = var.mode == "group" ? 1 : 0
alarm_name = "${var.name}-group-capacity"
alarm_description = "Fewer group members are in service than the current desired capacity. Check launch failures and member health."
comparison_operator = "LessThanThreshold"
threshold = 0
- evaluation_periods = 1
- datapoints_to_alarm = 1
+ evaluation_periods = 5
+ datapoints_to_alarm = 5
treat_missing_data = "breaching"
alarm_actions = local.group_alarm_actions
ok_actions = local.group_alarm_actions
diff --git a/infra/modules/region-host/tests/group_alarms.tftest.hcl b/infra/modules/region-host/tests/group_alarms.tftest.hcl
index f2f3eb2a6..06b1b8c9d 100644
--- a/infra/modules/region-host/tests/group_alarms.tftest.hcl
+++ b/infra/modules/region-host/tests/group_alarms.tftest.hcl
@@ -224,8 +224,8 @@ run "group_alarm_producers" {
error_message = "suspect-holder missing data or actions changed"
}
assert {
- condition = aws_cloudwatch_metric_alarm.group_capacity[0].threshold == 0 && aws_cloudwatch_metric_alarm.group_capacity[0].comparison_operator == "LessThanThreshold" && aws_cloudwatch_metric_alarm.group_capacity[0].evaluation_periods == 1 && aws_cloudwatch_metric_alarm.group_capacity[0].datapoints_to_alarm == 1 && one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.expression if q.id == "deficit"]) == "IF(FILL(desired, -1) < 0, -1, FILL(inservice, -1) - desired)" && alltrue([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : length(q.metric) == 0 ? true : q.metric[0].period == 60 && q.metric[0].namespace == "AWS/AutoScaling" && q.metric[0].dimensions == tomap({ AutoScalingGroupName = aws_autoscaling_group.group[0].name })])
- error_message = "capacity uses actual desired membership including approved Standby"
+ condition = aws_cloudwatch_metric_alarm.group_capacity[0].threshold == 0 && aws_cloudwatch_metric_alarm.group_capacity[0].comparison_operator == "LessThanThreshold" && aws_cloudwatch_metric_alarm.group_capacity[0].evaluation_periods == 5 && aws_cloudwatch_metric_alarm.group_capacity[0].datapoints_to_alarm == 5 && one([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : q.expression if q.id == "deficit"]) == "IF(FILL(desired, -1) < 0, -1, FILL(inservice, -1) - desired)" && alltrue([for q in aws_cloudwatch_metric_alarm.group_capacity[0].metric_query : length(q.metric) == 0 ? true : q.metric[0].period == 60 && q.metric[0].namespace == "AWS/AutoScaling" && q.metric[0].dimensions == tomap({ AutoScalingGroupName = aws_autoscaling_group.group[0].name })])
+ error_message = "capacity uses actual desired membership including approved Standby, and alarms only after five consecutive breaching one-minute periods"
}
assert {
condition = aws_cloudwatch_metric_alarm.group_memory[0].metric_name == "MemAvailablePercent" && aws_cloudwatch_metric_alarm.group_memory[0].statistic == "Minimum" && aws_cloudwatch_metric_alarm.group_memory[0].period == 60 && aws_cloudwatch_metric_alarm.group_memory[0].threshold == 15 && aws_cloudwatch_metric_alarm.group_memory[0].evaluation_periods == 3 && aws_cloudwatch_metric_alarm.group_memory[0].datapoints_to_alarm == 3 && aws_cloudwatch_metric_alarm.group_memory[0].comparison_operator == "LessThanThreshold"
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)
})
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index e351bed39..5bd6fdb67 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -165,4 +165,5 @@ plan14-root-reads-demo-terms-links.tsv c8e2c7ed3850823a8e379d880738982772b870ad8
plan14-root-reads-fix-silent-start-kill-861.tsv 733204d61bea49fe418d8ff0f1bfa20d77bdffb1f08a216d9de92923eea22557
plan14-root-reads-group-bucket-region.tsv 733204d61bea49fe418d8ff0f1bfa20d77bdffb1f08a216d9de92923eea22557
plan14-root-reads-w6-ingress-drain.tsv 43260792034a1a20791d14c4e4476e762b40d7bcca64257ef2e9899da6af5df0
-plan14-root-reads-group-verb-followups.tsv a53b2aed26da8e8a46974ad982376e373762399e6cc92b43d7907ddc53f3971f
+plan14-root-reads-group-capacity-damping.tsv 0c649af234a7b89a75479e59e705307e3293a59439b7b251dd4558bd46ef2100
+plan14-root-reads-group-verb-followups.tsv 9c74b9876a13a3a3802860fe44406898c8bcbfd3bd22e8172a59a02674c3b4af
diff --git a/internal/provision/testdata/plan14-root-reads-group-capacity-damping.tsv b/internal/provision/testdata/plan14-root-reads-group-capacity-damping.tsv
new file mode 100644
index 000000000..7e42926a7
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-group-capacity-damping.tsv
@@ -0,0 +1,8 @@
+# Census overlay group-capacity-damping, written by census-propose (#369). census-ruling-group-capacity-damping, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-group-capacity-damping.md.
+# 2 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@legacy cf36c0ea936437db75d8cee8bbba1531638c4104cee4813e7078934f57643470 infra/modules/region-host/group_alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. Copy sweep 1: apply approved variable and alarm descriptions verbatim; no resource, threshold, action or read changes.;rev3=census-ruling-region-ha-p3b;basis=Add group capacity, memory, clock, missing-clock and launch-failure notifications; preserve account-owner SNS rights and scope CloudWatch/EventBridge publishers by source account/ARN. Operator-applied Terraform, no box file read; notifications grant no replacement authority.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: add one group-mode SuspectHolderHosts Maximum alarm, 60 seconds, 1 of 1, threshold greater than zero, missing data notBreaching, existing regional SNS actions and ASG dimension. No replacement, scale, IAM, storage or root runtime authority.;rev3=census-ruling-region-ha-g3-fixes;basis=Send existing queue, group and launch-failure notifications to the selected regional SNS topic. Keep externally owned topic policy and subscriptions outside this module; no replacement or scale authority and no new root runtime read.;rev3=census-ruling-group-capacity-damping;basis=group_capacity alarm: evaluation_periods and datapoints_to_alarm 1 -> 5 (alarms after 5 of 5 one-minute periods breaching), comment updated, description unchanged; same metric math, threshold, missing-data handling and actions. tofu only, run on an operator machine; no read is added and nothing on a box reads the file. file:external@0 00bb28311d50c48cde502ca7c7400764b7797c88c291a4ed0179bec7a4681480
+@legacy 6305d3c6c54f8df28bf3b39c3226f3addf94257db34346dea5f85e6dd58268b3 infra/modules/region-host/tests/group_alarms.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions.;rev3=census-ruling-region-ha-p3b;basis=Mock group metric producers, alarm dimensions/windows/missing data and complete scoped SNS policy; retain fixed alarm expectations. Test-only Terraform input, no root runtime read.;rev3=census-ruling-region-ha-p3b1-fixes;basis=Supply the real-shape group queue URL in the group alarm mock so the launch URL equality guard is exercised. Mock plans only; no runtime reads.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: pin fixed-mode zero count, group shape, regional SNS actions and non-breaching missing data for the new alarm; mock-provider test only, no root runtime read.;rev3=census-ruling-group-capacity-damping;basis=Assert the group capacity alarm window is 5 of 5 (was 1 of 1) and update its message. Mock-provider test only, no root runtime read. file:external@0 6865c7786c25abe0d0ec308b1e90f229cd754127165fb553ee81d6134ddba972
+infra/modules/region-host/group_alarms.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add default-off termination queue age alarm, using existing queue name and regional SNS topic; no IAM, queue, consumer or instance changes. Copy sweep 1: apply approved variable and alarm descriptions verbatim; no resource, threshold, action or read changes.;rev3=census-ruling-region-ha-p3b;basis=Add group capacity, memory, clock, missing-clock and launch-failure notifications; preserve account-owner SNS rights and scope CloudWatch/EventBridge publishers by source account/ARN. Operator-applied Terraform, no box file read; notifications grant no replacement authority.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: add one group-mode SuspectHolderHosts Maximum alarm, 60 seconds, 1 of 1, threshold greater than zero, missing data notBreaching, existing regional SNS actions and ASG dimension. No replacement, scale, IAM, storage or root runtime authority.;rev3=census-ruling-region-ha-g3-fixes;basis=Send existing queue, group and launch-failure notifications to the selected regional SNS topic. Keep externally owned topic policy and subscriptions outside this module; no replacement or scale authority and no new root runtime read.;rev3=census-ruling-group-capacity-damping;basis=group_capacity alarm: evaluation_periods and datapoints_to_alarm 1 -> 5 (alarms after 5 of 5 one-minute periods breaching), comment updated, description unchanged; same metric math, threshold, missing-data handling and actions. tofu only, run on an operator machine; no read is added and nothing on a box reads the file. file:external@0 00bb28311d50c48cde502ca7c7400764b7797c88c291a4ed0179bec7a4681480
+infra/modules/region-host/tests/group_alarms.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock queue alarm defaults, thresholds, missing-data and regional notification assertions.;rev3=census-ruling-region-ha-p3b;basis=Mock group metric producers, alarm dimensions/windows/missing data and complete scoped SNS policy; retain fixed alarm expectations. Test-only Terraform input, no root runtime read.;rev3=census-ruling-region-ha-p3b1-fixes;basis=Supply the real-shape group queue URL in the group alarm mock so the launch URL equality guard is exercised. Mock plans only; no runtime reads.;rev3=census-ruling-region-ha-g2-t3;basis=T3b: pin fixed-mode zero count, group shape, regional SNS actions and non-breaching missing data for the new alarm; mock-provider test only, no root runtime read.;rev3=census-ruling-group-capacity-damping;basis=Assert the group capacity alarm window is 5 of 5 (was 1 of 1) and update its message. Mock-provider test only, no root runtime read. file:external@0 6865c7786c25abe0d0ec308b1e90f229cd754127165fb553ee81d6134ddba972
+@coverage infra/modules/region-host 852b117804e6635ade13c313db7b57580678c8e81706fa3fb56c382c0d9aa251
+@coverage infra/modules/region-host/tests 5c232284952d1bcc228804b757a560fb19289f63f6d479583c706bd294ce0971