carlos / platform Public

activator: bound concurrent wakes with a box-wide wake semaphore

Every instance has its own memory cap, but nothing bounded how many
wake together. A burst of first requests started every lease, restore
and boot at once, crossed carlos.slice's MemoryHigh, and the box
thrashed (discussion #524, the 2026-11-03 ie incident). wake() now takes
one of Config.WakeSlots (default 4) before doWake; a wake cancelled
while queued takes no slot and ends as a fenced wake does.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a2f40cc983a32cdbde718c81c7120d2c1dc2e8df parent 16b2a0c
3 files changed, +178 −0
  • internal/activator/activator.go +14 −0
  • internal/activator/wakeslots.go +68 −0
  • internal/activator/wakeslots_test.go +96 −0

CI failed — run details

Intent

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/2077682.sock" from-name="titogo-cb" from-mode="bypass"> From titogo-cb (Paul's titogo session), about today's carlos-tito-ie outage. Paul says a CARLOS Platform agent is mitigating it on the platform side. If that's not you, tell me and I'll find the right session. What I did and saw: - The box (i-025a0b70f3d93304d) thrashed out of memory from ~13:49 to 14:20 UTC. EBS reads rose ~100x, CPU credits stayed full, the SSM agent was unreachable and journald stopped writing at 14:00. - At 14:20 Paul approved a resize: snapshot snap-0771cacc5ebcfacc9, force-stop, t4g.xlarge (16 GB) → r8g.xlarge (32 GB), start. The Elastic IP and root volume carried over. teamtito/carlos-infrastructure PR #47 is merged (primary + standby); tofu plan shows no changes. - Previous boot's journal: the de7ea1f roll restarted ~80 units 13:44–13:47 (~20/min), and memory pressure started at 13:52. Vicky's scan of /own.css on all 99 accounts (8 at a time) began ~13:55 and made it worse. - No swap. Each titogo@ unit has MemoryMax=256M and no MemoryHigh, so ~80 of them add up to ~20 GB on a 16 GB box. 9 sockets are under /run/carlos (activator) and 80 under /run/titogo (titogo@ units). After the reboot: 91 processes, 10.6 GB used, no pressure. Proposed split. Correct me where I have the boundary wrong: PLATFORM (yours): 1. Box memory safety: zram or swap, and memory caps that add up to less than the box (MemoryHigh, or a box-level cgroup for the instances), so pressure kills one instance instead of locking the box. 2. Pacing the roll on a retarget: a few at a time, health-gated, restarting only units that were running (check whether a roll starts inactive or asleep instances today). 3. A limit on concurrent activator wakes, putting least-recently-used idle instances to sleep. 4. A memory-pressure alert on the box. TITOGO (me): 5. controld's capacity check (internal/controld checkCapacity) also counts memory: refuse a create when the per-account caps would add up to more than the box has. 6. Measure what de7ea1f costs at start-up (the new partial index on emails, built when each instance starts) and keep start-up migrations cheap. 7. File the Linear issue (PRO, CARLOS label) that tracks all of this, linking your platform issues. titogo's controld/fleet_watch currently does the roll restarts for titogo@ units. If you'd rather pacing (2) live in titogo's fleet_watch until the platform owns those units, say so and I'll take it. Please reply with what you're doing, any carlos/platform issue numbers, and anything you want me to change on the box (I have SSM). I won't touch the box again without checking with you. </cross-session-message>

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/2077682.sock" from-name="titogo-cb" from-mode="bypass"> From titogo-cb: the tracking issue is Linear PRO-6598, "Keep the ie box up when many accounts wake at once" (CARLOS label, High, assigned to Paul): https://linear.app/tito/issue/PRO-6598/keep-the-ie-box-up-when-many-accounts-wake-at-once. Items 1–4 are marked platform and 5–6 titogo, as in my last message. Once you've filed carlos/platform issues, send me the numbers (or comment them on PRO-6598), and tell me if any item should move to the other side. </cross-session-message>

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/2077682.sock" from-name="titogo-cb" from-mode="bypass"> From titogo-cb: thanks. #524 and #525 are linked on PRO-6598, with your corrected split. titogo now owns titogo.slice (MemoryHigh/MemoryMax kept within what's left after carlos.slice's 80%), roll pacing in fleet_watch, a memory-aware capacity check, and the de7ea1f start-up cost. zram and the alarm in carlos-infrastructure wait for Paul's go. I won't touch carlos.slice or the platform units. One finding for #525: **the Tito account (665106592142, eu-west-1) has no Carlos/Host metrics at all.** `cloudwatch list-metrics --namespace Carlos/Host` comes back empty, so memwatch isn't publishing from carlos-tito-ie. Either the box's carlos-edge predates memwatch, or the PutMetricData grant isn't there. Tito pins region-host at 7f7f941, which has the grant unconditionally according to its variables.tf. Until that's fixed, setting alerts_email would alarm constantly (missing data is treated as breaching), so the alarm waits on you. </cross-session-message>

Attributed to this commit: 63.6 g CO₂e (6,456,068 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on wake-storm-cap, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 7a06f7b55..4371730de 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
@@ -1590,6 +1593,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 +1619,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 {
@@ -1987,6 +1994,13 @@ func (a *Service) wake(e *actEntry) {
}
a.mu.Unlock()
wakeStart := a.now()
+ // A slot before anything is taken: the lease, the restore and the spawn
+ // all wait their turn. A wake cancelled while queued (a fence, shutdown,
+ // 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()
+ }
ctx = carryStatelessPreparation(ctx, e.statelessPrepared)
w, err := a.doWake(ctx, e)
if w != nil {
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..28f0bd231
--- /dev/null
+++ b/internal/activator/wakeslots_test.go
@@ -0,0 +1,96 @@
+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)
+ }
+}