carlos / platform Public

activator: box-wide wake slots so a wake burst can't thrash a box (#524)

A burst of first requests started every lease, restore and boot at
once and pushed carlos.slice past MemoryHigh. wake() now takes one of
Config.WakeSlots (default 4) before doWake. A queued wake takes nothing;
fence/shutdown/retired/disabled refusals are asked again at admission;
RetireExcept cancels a queued wake; the first-wake health window starts
at admission. Astra R1+R2; census-ruling-wake-storm-cap (#280).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from wake-storm-cap into main.
claude agent, operated by paul@keymail.dev e44476a1cec2804aba38b870aca453c751dfcdf5 parent 56940c8
6 files changed, +394 −16
  • docs/superpowers/notes/census-proposal-wake-storm-cap.md +25 −0
  • internal/activator/activator.go +55 −16
  • internal/activator/wakeslots.go +68 −0
  • internal/activator/wakeslots_test.go +236 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-wake-storm-cap.tsv +9 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-wake-storm-cap.md b/docs/superpowers/notes/census-proposal-wake-storm-cap.md
new file mode 100644
index 000000000..46c05c959
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-wake-storm-cap.md
@@ -0,0 +1,25 @@
+# Census approval: wake-storm-cap
+
+Ruling `census-ruling-wake-storm-cap`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/activator.go` `type Service` | body | unchanged (0) | the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read. |
+| `internal/activator/activator.go` `Service.wake` | sites | -whole:Route | the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): waits for a box-wide wake slot (acquireWakeSlot, an in-memory buffered channel) before doWake; the fence/shutdown/retired/disabled refusals move into refuseWakeLocked and are asked again after admission (one fewer direct whole-Route read here: a.disabled(e.route) now runs inside refuseWakeLocked, same value); e.wakeStart is set at admission and e.admitted marks it. Only waits and refuses more; no new read. |
+
+Envelopes re-pinned: `internal/activator`.
+
+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:
+
+- `internal/activator/activator.go` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.
+- `internal/activator/activator.go` `Service.wake`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=logs that timer's breakdown to the journal after a successful wake (w.steps.String(), e.host, w.wakeTook); no read added;rev3=census-ruling-plans-4d-lapse;basis=cancels a wake whose row the turned-off hook names, like a fence, unless it is a move's active probe (plans 4d). One more whole-row read: the row handed to the hook (a.disabled). Only refuses.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: a refusal before the lease is reported once per change (noteRootfsRefusal) instead of a wake-failure event; the proc, generation and replica are installed through installProcLocked (which puts a resident under its lease watch before the fence); residency notes the outcome (noteResidentWakeLocked); same generation values;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R [pf R3.5]: the wake's context ceiling is wakeCeilingFor(e.route): the old 5 minutes for a binary row, 5 minutes plus runs.MaxTimeout for a rootfs row (room for a release inside the wake); new site +whole:Route (e.route to wakeCeilingFor, which reads Runtime only); no other change;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (branch review R1 P1-1): the wake's context is also cancelled before doWake when RetireExcept has marked the entry retired (e.retired, in memory under a.mu), as it is for a fence or a shutdown. Read sites unchanged (13). Agent, not root; it only refuses more.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry successful hold preparation into its wake, preserve actual mode in the generation and OnWake projection, and project serving version/mode through the narrow registry writer before releasing wake waiters. Final review I1: SetServingMode only for non-worker successful wakes with a nonempty spawned version and either a stateless generation or a mode transition from the route. Ordinary stateful wakes leave rollout status and the wake critical path unchanged.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds a.cancelHeldLegsLocked(e, 0) on the failed-wake path before the entry is deleted, and after close(e.ready) on success calls a.noteHeldAdmissible(e.host), the non-blocking held wake callback, outside a.mu. No read added.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/activator.go:Service.refuseWakeLocked`: reads +whole:Route; written legacy, accepted-legacy, frozen
+
+Seal: `09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6` → `b0fc198c53bb0dacba33a54c3d8bf8fe5ac07d94b76a31b8a69e9411115ecd85`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-wake-storm-cap.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 7a06f7b55..cb8ef6e50 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -101,6 +101,9 @@ type Config struct {
Region string // CARLOS_HIBERNATE_REGION (optional; AWS default chain resolves "")
Prefix string // CARLOS_HIBERNATE_PREFIX (optional key prefix inside the bucket)
Idle time.Duration // CARLOS_HIBERNATE_IDLE (default 15m; seconds-granular, e.g. "90s")
+ // WakeSlots bounds how many wakes run at once on this box (wakeslots.go).
+ // Zero means defaultWakeSlots.
+ WakeSlots int
// AgentSocket is the unix socket a worker child dials to reach back —
// the direction that makes a sidecar possible at all: the agent listens,
// children call in; the platform never dials a sidecar. Handed to every
@@ -757,9 +760,12 @@ type actEntry struct {
// that observation's context, both registered in the awake transition
// (armFirstWatchLocked) and read by watchFirstWake's goroutine. All but
// plan are written under a.mu.
- plan WakePlan
- firstWake bool
- wakeStart time.Time
+ plan WakePlan
+ firstWake bool
+ wakeStart time.Time
+ // admitted is set, under a.mu, once the wake holds a wake slot
+ // (wakeslots.go). RetireExcept cancels a wake that is still queued.
+ admitted bool
unexpectedExit bool
firstWatch context.CancelFunc
firstWatchCtx context.Context
@@ -1590,6 +1596,9 @@ type Service struct {
// seam: a test that removes the generations file's directory waits on
// it first (fix wave 1, item 6). Set before the wake; nil in production.
wakeEnded func(host string)
+ // wakeSlots is the box-wide wake semaphore (wakeslots.go): a buffered
+ // channel with one token per running wake.
+ wakeSlots chan struct{}
// genHealth, when set, replaces a generation's health check. It is a
// test seam. Nil is waitHealthyCtx on the generation's own socket (spec
// §7.1: health uses the handle, never AppSocket).
@@ -1613,6 +1622,7 @@ func New(cfg Config, backend Backend, due DueStore) *Service {
entries: make(map[string]*actEntry),
gens: GenerationsEnabled(),
}
+ a.wakeSlots = make(chan struct{}, wakeSlotCount(cfg.WakeSlots))
// The resident listing (Plan 3 Task 8): the registry in production. A
// DueStore without it (a test double) has no residents.
if l, ok := due.(ResidentLister); ok {
@@ -1951,6 +1961,23 @@ func (a *Service) consumeDueTime(e *actEntry) {
}
}
+// refuseWakeLocked cancels a wake that must not go on: its host fenced, the
+// agent shutting down, the entry retired, or its route turned off. wake asks
+// at its start and again once it holds a wake slot.
+func (a *Service) refuseWakeLocked(e *actEntry, cancel context.CancelFunc) {
+ // A wake that starts after Shutdown began is cancelled before its
+ // lease, whatever CARLOS_SWAP says (#292): with swaps off it used to run
+ // on, and take a lease the exiting agent never gave back.
+ if a.fences[e.host] != 0 || a.shuttingDown || e.retired {
+ cancel()
+ }
+ // A route a lapse turned off is refused like a fence (plans 4d); a
+ // move's probe wake still runs, so moves keep working.
+ if !activeProbe(e) && a.disabled(e.route) {
+ cancel()
+ }
+}
+
// wake drives asleep→awake: lease, restore-if-missing, spawn, replicate,
// co-spawn the sidecar. It runs on the first requester's goroutine but under
// its own generous timeout, detached from that request's context — queued
@@ -1971,22 +1998,27 @@ func (a *Service) wake(e *actEntry) {
defer cancel()
a.mu.Lock()
e.wakeCancel = cancel
+ a.refuseWakeLocked(e, cancel)
+ a.mu.Unlock()
+ wakeStart := a.now()
+ // A slot before anything is taken: the lease, the restore and the spawn
+ // all wait their turn (wakeslots.go). A wake cancelled while queued (a
+ // fence, shutdown, retirement, its ceiling) gets no slot and runs doWake
+ // on the cancelled context, which is how a fenced wake already ends.
+ if releaseSlot := a.acquireWakeSlot(ctx, e.host); releaseSlot != nil {
+ defer releaseSlot()
+ }
+ a.mu.Lock()
+ // Admitted: from here a retirement leaves the wake to wakeGoesOn's
+ // checks, as before the queue existed. The refusals are asked again
+ // because the queue can be long enough for any of them to change.
+ e.admitted = true
// Real time, not a.now: it anchors a first wake's real health deadline
- // (spawnPlanned, doClaimWake).
+ // (spawnPlanned, doClaimWake). Set at admission, not at the wake's start,
+ // so time spent queued never shortens a candidate build's health window.
e.wakeStart = time.Now()
- // A wake that starts after Shutdown began is cancelled before its
- // lease, whatever CARLOS_SWAP says (#292): with swaps off it used to run
- // on, and take a lease the exiting agent never gave back.
- if a.fences[e.host] != 0 || a.shuttingDown || e.retired {
- cancel()
- }
- // A route a lapse turned off is refused like a fence (plans 4d); a
- // move's probe wake still runs, so moves keep working.
- if !activeProbe(e) && a.disabled(e.route) {
- cancel()
- }
+ a.refuseWakeLocked(e, cancel)
a.mu.Unlock()
- wakeStart := a.now()
ctx = carryStatelessPreparation(ctx, e.statelessPrepared)
w, err := a.doWake(ctx, e)
if w != nil {
@@ -5882,6 +5914,13 @@ func (a *Service) RetireExcept(keep map[string]bool) {
// never boots the copy it kept. One past its spawn finishes and
// is stopped below, as before.
e.retired = true
+ // A wake still queued for a slot holds nothing yet: cancel it,
+ // so it ends now rather than when a slot opens (#524). Its
+ // wake goroutine sets wakeCancel before it queues, and one that
+ // has not got that far reads e.retired itself.
+ if !e.admitted && e.wakeCancel != nil {
+ e.wakeCancel()
+ }
waking = append(waking, e)
case actStopping:
// Already on its way out.
diff --git a/internal/activator/wakeslots.go b/internal/activator/wakeslots.go
new file mode 100644
index 000000000..cfef35768
--- /dev/null
+++ b/internal/activator/wakeslots.go
@@ -0,0 +1,68 @@
+package activator
+
+import (
+ "context"
+ "log"
+ "time"
+)
+
+// defaultWakeSlots is how many wakes run at once on one box (discussion
+// #524). Every instance has its own memory cap, but nothing else bounded how
+// many wake together: a burst of first requests (a crawler, a schedule firing
+// on the hour, a restart) started every lease claim, restore and boot at
+// once, and the box's combined charge crossed carlos.slice's MemoryHigh before
+// any single tenant reached its own cap. Past that line the kernel reclaims
+// the whole slice, the agent included, and the box thrashes instead of
+// killing anyone. Queueing the wakes caps the start-up spike: the restore and
+// the boot are the expensive part, and once an instance is up its working
+// set is smaller.
+//
+// Four, under workerBootConcurrency's eight: that bound is a boot pass over
+// sidecars on a box nobody is visiting yet, and this one has to hold while
+// the box is serving. The boot pass's wakes take these slots too, so in
+// effect it now starts four at a time. A wake that waits longer than
+// wakeWaitBound for its slot answers its requester with the usual wake
+// timeout; the wake itself carries on and the next request finds it.
+//
+// The cost: a slot is held for the whole wake, so four slow wakes (a rootfs
+// release inside its ceiling) hold every other wake on the box behind them.
+// That is the trade for a box that stays up; memory-aware admission (#524's
+// spec) replaces the fixed count.
+const defaultWakeSlots = 4
+
+// wakeSlotCount is n, or the default for zero or less.
+func wakeSlotCount(n int) int {
+ if n <= 0 {
+ return defaultWakeSlots
+ }
+ return n
+}
+
+// acquireWakeSlot waits for one of the box's wake slots. It returns the
+// release, or nil when ctx ended first: a wake cancelled while queued (a
+// fence, shutdown, its ceiling) takes no slot, so it cannot hold one up for
+// the wakes behind it. A wait worth noticing is logged with the queue it
+// waited behind, because "woke in 9s (spawn 400ms)" is otherwise
+// indistinguishable from a slow restore.
+func (a *Service) acquireWakeSlot(ctx context.Context, host string) func() {
+ if a.wakeSlots == nil {
+ // A Service built without New (a test literal) has no limit.
+ return func() {}
+ }
+ release := func() { <-a.wakeSlots }
+ select {
+ case a.wakeSlots <- struct{}{}:
+ return release
+ default:
+ }
+ start := time.Now()
+ select {
+ case a.wakeSlots <- struct{}{}:
+ if waited := time.Since(start); waited >= time.Second {
+ log.Printf("activator: %s: waited %s for a wake slot (%d at once on this box)", host, waited.Round(time.Millisecond), cap(a.wakeSlots))
+ }
+ return release
+ case <-ctx.Done():
+ return nil
+ }
+}
diff --git a/internal/activator/wakeslots_test.go b/internal/activator/wakeslots_test.go
new file mode 100644
index 000000000..cddc0b409
--- /dev/null
+++ b/internal/activator/wakeslots_test.go
@@ -0,0 +1,236 @@
+package activator
+
+import (
+ "context"
+ "fmt"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// testActivatorSlots is testActivator with a wake-slot count of its own.
+func testActivatorSlots(t *testing.T, slots int) (*Service, *fakeBackend) {
+ t.Helper()
+ b := &fakeBackend{}
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatalf("open registry: %v", err)
+ }
+ return New(Config{Bucket: "test-bucket", Idle: time.Minute, WakeSlots: slots}, b, reg), b
+}
+
+// A burst of first requests to different hosts (#524) wakes at most
+// WakeSlots of them at once; the rest queue for a slot and every request is
+// still served once the running wakes finish.
+func TestWakeSlotsBoundConcurrentWakes(t *testing.T) {
+ t.Parallel()
+ a, b := testActivatorSlots(t, 2)
+ b.startGate = make(chan struct{})
+
+ const n = 5
+ var wg sync.WaitGroup
+ errs := make(chan error, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ release, err := a.beginRequest(context.Background(), testRoute(fmt.Sprintf("h%d.example.com", i)))
+ if err != nil {
+ errs <- err
+ return
+ }
+ release()
+ }(i)
+ }
+ waitFor(t, "two wakes to reach the spawn", func() bool { _, _, s := b.counts(); return s == 2 })
+ time.Sleep(100 * time.Millisecond)
+ if acquires, _, starts := b.counts(); acquires != 2 || starts != 2 {
+ t.Fatalf("with 2 slots: acquires=%d starts=%d, want 2 each (queued wakes must take nothing)", acquires, starts)
+ }
+ close(b.startGate)
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ t.Errorf("beginRequest: %v", err)
+ }
+ if _, _, starts := b.counts(); starts != n {
+ t.Fatalf("starts=%d after the gate opened, want %d", starts, n)
+ }
+}
+
+// A wake whose context ends while it queues gets no slot, and leaves the
+// slots it found exactly as full as they were.
+func TestWakeSlotCancelledWhileQueuedTakesNone(t *testing.T) {
+ t.Parallel()
+ a, _ := testActivatorSlots(t, 1)
+ hold := a.acquireWakeSlot(context.Background(), "a.example.com")
+ if hold == nil {
+ t.Fatal("first slot refused")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ if got := a.acquireWakeSlot(ctx, "b.example.com"); got != nil {
+ t.Fatal("a queued wake whose context ended was given a slot")
+ }
+ if len(a.wakeSlots) != 1 {
+ t.Fatalf("slots in use = %d, want 1", len(a.wakeSlots))
+ }
+ hold()
+ if len(a.wakeSlots) != 0 {
+ t.Fatalf("slots in use after release = %d, want 0", len(a.wakeSlots))
+ }
+}
+
+func TestWakeSlotCountDefault(t *testing.T) {
+ for _, n := range []int{0, -3} {
+ if got := wakeSlotCount(n); got != defaultWakeSlots {
+ t.Errorf("wakeSlotCount(%d) = %d, want %d", n, got, defaultWakeSlots)
+ }
+ }
+ if got := wakeSlotCount(6); got != 6 {
+ t.Errorf("wakeSlotCount(6) = %d", got)
+ }
+}
+
+// queuedBehindOne fills a one-slot service with a gated wake of
+// a.example.com, then starts a wake of b.example.com that queues behind it.
+// It returns the second request's outcome channel.
+func queuedBehindOne(t *testing.T, a *Service, b *fakeBackend) <-chan error {
+ t.Helper()
+ b.startGate = make(chan struct{})
+ go func() {
+ if release, err := a.beginRequest(context.Background(), testRoute("a.example.com")); err == nil {
+ release()
+ }
+ }()
+ waitFor(t, "a.example.com to hold the slot", func() bool { _, _, s := b.counts(); return s == 1 })
+ out := make(chan error, 1)
+ go func() {
+ release, err := a.beginRequest(context.Background(), testRoute("b.example.com"))
+ if err == nil {
+ release()
+ }
+ out <- err
+ }()
+ waitFor(t, "b.example.com to queue", func() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries["b.example.com"]
+ return e != nil && e.wakeCancel != nil
+ })
+ return out
+}
+
+func startedHost(b *fakeBackend, host string) bool {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ for _, rt := range b.startedRoutes {
+ if rt.Host == host {
+ return true
+ }
+ }
+ return false
+}
+
+// A route turned off while its wake queues for a slot takes nothing once
+// it is admitted: no lease, no start (Astra R1 P2).
+func TestWakeSlotDisabledWhileQueuedStartsNothing(t *testing.T) {
+ t.Parallel()
+ a, b := testActivatorSlots(t, 1)
+ out := queuedBehindOne(t, a, b)
+ a.SetDisabledFor(disabledFor("b.example.com"))
+ close(b.startGate)
+ if err := <-out; err == nil {
+ t.Fatal("the disabled route's request was served")
+ }
+ if acquires, _, _ := b.counts(); acquires != 1 {
+ t.Fatalf("acquires = %d, want 1 (a.example.com only)", acquires)
+ }
+ if startedHost(b, "b.example.com") {
+ t.Fatal("b.example.com was started after it was turned off")
+ }
+}
+
+// Retiring a host whose wake is still queued ends that wake straight away,
+// while every slot is still held, and it takes nothing (Astra R1 P2).
+func TestWakeSlotRetiredWhileQueuedEndsNow(t *testing.T) {
+ t.Parallel()
+ a, b := testActivatorSlots(t, 1)
+ out := queuedBehindOne(t, a, b)
+ a.RetireExcept(map[string]bool{"a.example.com": true})
+ select {
+ case err := <-out:
+ if err == nil {
+ t.Fatal("the retired host's request was served")
+ }
+ case <-time.After(5 * time.Second):
+ t.Fatal("the retired queued wake still waits for a slot")
+ }
+ close(b.startGate)
+ if acquires, _, _ := b.counts(); acquires != 1 {
+ t.Fatalf("acquires = %d, want 1 (a.example.com only)", acquires)
+ }
+ if startedHost(b, "b.example.com") {
+ t.Fatal("b.example.com was started after it was retired")
+ }
+}
+
+// A queued wake's health window starts when it is admitted, not when it
+// was asked for: time in the queue never shortens it (Astra R1 P2).
+func TestWakeSlotHealthWindowStartsAtAdmission(t *testing.T) {
+ t.Parallel()
+ a, b := testActivatorSlots(t, 1)
+ out := queuedBehindOne(t, a, b)
+ time.Sleep(100 * time.Millisecond)
+ admittedAfter := time.Now()
+ close(b.startGate)
+ if err := <-out; err != nil {
+ t.Fatalf("b.example.com: %v", err)
+ }
+ a.mu.Lock()
+ got := a.entries["b.example.com"].wakeStart
+ a.mu.Unlock()
+ if got.Before(admittedAfter) {
+ t.Fatalf("wakeStart %v is before admission %v: the queue ate the health window", got, admittedAfter)
+ }
+}
+
+// A planned first wake that queues for a slot longer than B's whole health
+// window still execs B once admitted: the window is counted from admission,
+// so the queue never decides which build boots (Astra R2 P2). Counted from
+// the request, 2.5 s queued against a 2 s window would leave B under the
+// 1 s verdict floor and boot the good build instead.
+func TestWakeSlotQueuedFirstWakeStillExecsTheCandidate(t *testing.T) {
+ shrinkFirstWake(t, 3*time.Second, time.Second, 50*time.Millisecond)
+ shrinkVerdictFloor(t, time.Second)
+ dir := t.TempDir()
+ good, next := stagedID(t, dir, "v1"), stagedID(t, dir, "v2")
+ a, b, evs := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good, Check: slowFirstCheck(0)})
+ a.wakeSlots = make(chan struct{}, 1)
+ hold := a.acquireWakeSlot(context.Background(), "other.example.com")
+ out := make(chan error, 1)
+ go func() {
+ done, err := a.beginRequest(context.Background(), testRoute("one.example.com"))
+ if err == nil {
+ done()
+ }
+ out <- err
+ }()
+ time.Sleep(2500 * time.Millisecond)
+ if gens := b.started(); len(gens) != 0 {
+ t.Fatalf("spawned %+v while every slot was held", gens)
+ }
+ hold()
+ if err := <-out; err != nil {
+ t.Fatalf("the queued first wake: %v", err)
+ }
+ if gens := b.started(); len(gens) != 1 || gens[0].Build != "v2" {
+ t.Fatalf("spawned %+v, want the candidate v2: queue time must not spend its health window", gens)
+ }
+ if ev := evs.wait(t, GenHealthy); !ev.FirstWake || ev.Gen.Build != "v2" {
+ t.Fatalf("healthy event = %+v, want v2's first wake", ev)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index eae19e409..2e49aa73e 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -70,3 +70,4 @@ plan14-root-reads-storedoor-stream-get.tsv 7e30dee4fb52370555ad173512d7f03782f0f
plan14-root-reads-design-pdf-service.tsv 09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6
plan14-root-reads-region-ha-placement-survivor.tsv 09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6
plan14-root-reads-domains-buy-nosub.tsv 09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6
+plan14-root-reads-wake-storm-cap.tsv b0fc198c53bb0dacba33a54c3d8bf8fe5ac07d94b76a31b8a69e9411115ecd85
diff --git a/internal/provision/testdata/plan14-root-reads-wake-storm-cap.tsv b/internal/provision/testdata/plan14-root-reads-wake-storm-cap.tsv
new file mode 100644
index 000000000..5b56a983b
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-wake-storm-cap.tsv
@@ -0,0 +1,9 @@
+# Census overlay wake-storm-cap, written by census-propose (#369). census-ruling-wake-storm-cap, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-wake-storm-cap.md.
+# 1 body, 1 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy b3f8cb9d012e779847f5abdb3fdf8755aedd60820202af06e602569547043fa1 internal/activator/activator.go Service.refuseWakeLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-wake-storm-cap;basis=new, the agent as carlos: the refusals Service.wake already made at its start, moved verbatim (fences, shuttingDown, e.retired, then !activeProbe(e) && a.disabled(e.route)) so wake can ask them twice; reads only in-memory state and the route already in hand (whole Route to the disabled hook). Only cancels. whole:Route@515 80a66fed561a404a0c58c6f76d919970ce4f3d73717210c3f7d378609a78e028
+@legacy cee477ff4ffd517760c41e5b47dcfc2f7cb7ebf64563933d906d2ad8ffb24262 internal/activator/activator.go Service.wake legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=logs that timer's breakdown to the journal after a successful wake (w.steps.String(), e.host, w.wakeTook); no read added;rev3=census-ruling-plans-4d-lapse;basis=cancels a wake whose row the turned-off hook names, like a fence, unless it is a move's active probe (plans 4d). One more whole-row read: the row handed to the hook (a.disabled). Only refuses.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: a refusal before the lease is reported once per change (noteRootfsRefusal) instead of a wake-failure event; the proc, generation and replica are installed through installProcLocked (which puts a resident under its lease watch before the fence); residency notes the outcome (noteResidentWakeLocked); same generation values;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R [pf R3.5]: the wake's context ceiling is wakeCeilingFor(e.route): the old 5 minutes for a binary row, 5 minutes plus runs.MaxTimeout for a rootfs row (room for a release inside the wake); new site +whole:Route (e.route to wakeCeilingFor, which reads Runtime only); no other change;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (branch review R1 P1-1): the wake's context is also cancelled before doWake when RetireExcept has marked the entry retired (e.retired, in memory under a.mu), as it is for a fence or a shutdown. Read sites unchanged (13). Agent, not root; it only refuses more.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry successful hold preparation into its wake, preserve actual mode in the generation and OnWake projection, and project serving version/mode through the narrow registry writer before releasing wake waiters. Final review I1: SetServingMode only for non-worker successful wakes with a nonempty spawned version and either a stateless generation or a mode transition from the route. Ordinary stateful wakes leave rollout status and the wake critical path unchanged.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds a.cancelHeldLegsLocked(e, 0) on the failed-wake path before the entry is deleted, and after close(e.ready) on success calls a.noteHeldAdmissible(e.host), the non-blocking held wake callback, outside a.mu. No read added.;rev3=census-ruling-wake-storm-cap;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): waits for a box-wide wake slot (acquireWakeSlot, an in-memory buffered channel) before doWake; the fence/shutdown/retired/disabled refusals move into refuseWakeLocked and are asked again after admission (one fewer direct whole-Route read here: a.disabled(e.route) now runs inside refuseWakeLocked, same value); e.wakeStart is set at admission and e.admitted marks it. Only waits and refuses more; no new read. registry:Socket@8171,registry:Socket@8332,registry:Stateless@10414,registry:Stateless@9666,whole:Route@10416,whole:Route@2921,whole:Route@3012,whole:Route@3069,whole:Route@417,whole:Route@6419,whole:Route@8124,whole:Route@8173,whole:Route@8334,whole:Route@9657,whole:Route@9712 db8062c178ac05479edb5e9765942868e0bd5f214ffcaa9bb044876f4a96521d
+internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read. f6d09bc7a18c2eb32a36168a9153047495dc2bcf18fb35a5b978b98d7496ded1
+internal/activator/activator.go Service.refuseWakeLocked legacy accepted-legacy accepted-legacy;rev3=census-ruling-wake-storm-cap;basis=new, the agent as carlos: the refusals Service.wake already made at its start, moved verbatim (fences, shuttingDown, e.retired, then !activeProbe(e) && a.disabled(e.route)) so wake can ask them twice; reads only in-memory state and the route already in hand (whole Route to the disabled hook). Only cancels. whole:Route@515 80a66fed561a404a0c58c6f76d919970ce4f3d73717210c3f7d378609a78e028
+internal/activator/activator.go Service.wake legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=logs that timer's breakdown to the journal after a successful wake (w.steps.String(), e.host, w.wakeTook); no read added;rev3=census-ruling-plans-4d-lapse;basis=cancels a wake whose row the turned-off hook names, like a fence, unless it is a move's active probe (plans 4d). One more whole-row read: the row handed to the hook (a.disabled). Only refuses.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: a refusal before the lease is reported once per change (noteRootfsRefusal) instead of a wake-failure event; the proc, generation and replica are installed through installProcLocked (which puts a resident under its lease watch before the fence); residency notes the outcome (noteResidentWakeLocked); same generation values;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R [pf R3.5]: the wake's context ceiling is wakeCeilingFor(e.route): the old 5 minutes for a binary row, 5 minutes plus runs.MaxTimeout for a rootfs row (room for a release inside the wake); new site +whole:Route (e.route to wakeCeilingFor, which reads Runtime only); no other change;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (branch review R1 P1-1): the wake's context is also cancelled before doWake when RetireExcept has marked the entry retired (e.retired, in memory under a.mu), as it is for a fence or a shutdown. Read sites unchanged (13). Agent, not root; it only refuses more.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry successful hold preparation into its wake, preserve actual mode in the generation and OnWake projection, and project serving version/mode through the narrow registry writer before releasing wake waiters. Final review I1: SetServingMode only for non-worker successful wakes with a nonempty spawned version and either a stateless generation or a mode transition from the route. Ordinary stateful wakes leave rollout status and the wake critical path unchanged.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds a.cancelHeldLegsLocked(e, 0) on the failed-wake path before the entry is deleted, and after close(e.ready) on success calls a.noteHeldAdmissible(e.host), the non-blocking held wake callback, outside a.mu. No read added.;rev3=census-ruling-wake-storm-cap;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): waits for a box-wide wake slot (acquireWakeSlot, an in-memory buffered channel) before doWake; the fence/shutdown/retired/disabled refusals move into refuseWakeLocked and are asked again after admission (one fewer direct whole-Route read here: a.disabled(e.route) now runs inside refuseWakeLocked, same value); e.wakeStart is set at admission and e.admitted marks it. Only waits and refuses more; no new read. registry:Socket@8171,registry:Socket@8332,registry:Stateless@10414,registry:Stateless@9666,whole:Route@10416,whole:Route@2921,whole:Route@3012,whole:Route@3069,whole:Route@417,whole:Route@6419,whole:Route@8124,whole:Route@8173,whole:Route@8334,whole:Route@9657,whole:Route@9712 db8062c178ac05479edb5e9765942868e0bd5f214ffcaa9bb044876f4a96521d
+@coverage internal/activator 75e3d5e5cca5c68250f77305f24477a6d2a2d4591277cf7c97aff046a3496eb9