carlos / platform Public

host: env-gated startup read measurement over a slow fake door

Plan phase 2 tasks from its numbers (records walk, first pass on arming).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4a96804904be574205152ea0386d219c1790b9fe parent 25c57de
2 files changed, +509 −0
  • docs/superpowers/plans/2026-11-15-fleet-first-reconcile.md +98 −0
  • internal/host/startupmeasure_e2e_test.go +411 −0

Intent

Attributed to this commit: 16.0 g CO₂e (1,961,177 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fleet-first-reconcile-fix, 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/docs/superpowers/plans/2026-11-15-fleet-first-reconcile.md b/docs/superpowers/plans/2026-11-15-fleet-first-reconcile.md
index 890eccf66..281471be1 100644
--- a/docs/superpowers/plans/2026-11-15-fleet-first-reconcile.md
+++ b/docs/superpowers/plans/2026-11-15-fleet-first-reconcile.md
@@ -106,3 +106,101 @@ door reads inside reconcile and the moves pass, with S3 cost flat; mint
already-owned records before the moves stage. Deterministic witnesses:
barrier or fake-clock tests showing the first reconcile is not gated by the
seeds or the moves pass.
+
+## Phase 2 tasks (from Task 2's report, task-2-report.md in the SDD workspace)
+
+Local numbers (60 ms/op fake door): ~2 s of reads before the first mint, so
+the dev 17 s is mostly costs a fixed-latency door cannot show. The prime
+suspects: (a) on the door, `provision.listAppSubtree` cannot use ListDirs
+(`release.HasBucketListDirs` is false for the fleetapi store) and falls back
+to `List("apps/")`, which the door maps to the account's whole `apps/<sqid>/`
+subtree (every artifact and log chunk, paged from S3 at the hub; #231
+measured 60 pages for apps/ on the flagship), and `List("accounts/")`, which
+the door pages across every account and filters. Each runs about 4 times
+before the first pass ends (offline view at arming, reconcile, moves, ...).
+(b) the activator startup latch (sweep + Recover) before the duties start
+(cannot be measured locally; dev numbers after the next release).
+
+### Task 3: door-shaped record walk
+
+Goal: on a fleet box, every record walk lists only what it needs over the
+door: the account's app directories, then each app's `instances/` (or the
+`sub` the caller asks for), never the whole `apps/<sqid>/` subtree, and never
+an unscoped `accounts/` listing that the door pages across the platform.
+
+1. Read `provision.listAppSubtree`, `readAllRecordsJudged` and every caller of
+ `List("apps/")` / `List("accounts/")` on the paths a fleet box runs in its
+ first pass and at arming (offline view, reconcile record scan, moves pass,
+ snapshot build in recordview_store.go). Read the door's `serveListing`,
+ `aclListScope` and `aclDir` (internal/edge/storedoor.go) to learn exactly
+ what `/store/dirs` answers for `apps/`, `apps/<acct>/`,
+ `apps/<acct>/<app>/` and `accounts/` from a fleet box.
+2. Make the walk use the door's delimiter listing in the shape the door
+ really answers. Preferred: a capability the fleetapi store declares (an
+ optional interface in `release`, like `BucketListDirs`) that says "ListDirs
+ works per known account", and a walk branch that lists
+ `apps/<acct>/` for each known account, then `<app>/<sub>` per app, with
+ the existing bounded concurrency (`forEach`). Same for the `accounts/`
+ listing if it is on the path: list only the known accounts' prefixes.
+ Keep the fallback for stores that declare nothing. Do not change the
+ door server unless step 1 shows it cannot answer a needed shape; if it
+ must change, it must stay compatible with old boxes, and a NEW box must
+ work against an OLD hub (the walk runs before any hub upgrade in a roll):
+ prove the old hub already answers what the new box asks.
+3. Results must be identical: the same set of keys/records as the full
+ listing, for records, partial-walk reporting and errors (a failed listing
+ still marks the pass partial, never "no records"). Test with the real
+ fleetapi client against the real door handler (there are door tests in
+ internal/edge and internal/host fleetbind_door_test.go to copy setup
+ from), over a fixture with artifacts and log chunks under the app: assert
+ the key set equals the full listing's and that no listing is made of a
+ whole app subtree (count requests by path and prefix at the handler).
+4. S3 cost: count the hub's S3 listings before and after for the same
+ fixture; the new walk must not cost more S3 list calls than the old one
+ for an account with at least one artifact (report the numbers).
+5. The census (root-read and record-write) will fail for changed units:
+ run `make census-card`, write a CLAIMS file, `make census-propose
+ NAME=fleet-first-reconcile-speed-2 CLAIMS=<file>`; the controller gets
+ it approved.
+
+### Task 4: the first pass runs when the loop arms, seeds off its path
+
+Goal: the first full pass starts as soon as `fastConvergeLoop` has built
+what that pass needs, not after every seed and a tick's sleep.
+
+1. Keep before the first pass, in order: `refreshMovesHolds` (moves spec
+ §9.4: an unbuilt view freezes every host) and `refreshOfflineView`
+ (movesoffline.go: keep answers false only once read), and whatever else
+ the pass's legs read (d.restart, d.passOpts, legs). Every other pre-arm
+ step (`restartSeed`, `armRestartLegs`, `sidecarWakeSeed`,
+ `runRunsBootPass`, `sd.converge`, `systemLeg.observe`, heldHolds'
+ pointer loop) moves after the first pass or runs concurrently, ONLY if
+ its own doc comment's guarantee still holds. In particular restartSeed
+ and sidecarWakeSeed must establish their baseline before the first serial
+ MOVE is acted on (the serial is seeded by the first tick, and the restart
+ and wake legs ride only a serial move), and restartGain must not treat a
+ route minted by the first pass as a request. Read each seed's doc comment
+ and say in the report, per seed, why its guarantee holds in the new order.
+2. Run the boot full pass immediately on arming (the requested boot pass,
+ `requestBootFullPass`, today waits for the first tick's sleep), then
+ enter the tick loop. The pass runs on the loop goroutine as today; no new
+ goroutine may run a pass concurrently with the tick.
+3. Witness tests (deterministic, barriers or a fake clock, no sleeps): (a)
+ the first reconcile starts before restartSeed, sidecarWakeSeed,
+ sd.converge and systemLeg.observe finish (block each on a barrier; the
+ reconcile must still run); (b) the first reconcile does not start before
+ refreshMovesHolds and refreshOfflineView have returned; (c) a restart
+ request already in the store at boot is still not replayed, and one
+ written after the seed is acted on at the next serial move. Use test
+ seams that already exist where possible; a new seam is a package-level
+ func var defaulting to production.
+4. Census as Task 3 (NAME=fleet-first-reconcile-speed-4).
+
+### Parked
+
+- Offline view built from reconcile's own scan (saves one walk, ~0.8 s at
+ 39 records locally): revisit after Task 3, whose fix makes each walk cheap.
+- The activator startup latch: needs the dev numbers from the next release
+ (Task 1's "duties: wait for the activator startup" line). The latch is a
+ safety order (sweep before wakes and before reconcile acts on seeded
+ records); any change gets its own task and review.
diff --git a/internal/host/startupmeasure_e2e_test.go b/internal/host/startupmeasure_e2e_test.go
new file mode 100644
index 000000000..f64ab8d3e
--- /dev/null
+++ b/internal/host/startupmeasure_e2e_test.go
@@ -0,0 +1,411 @@
+//go:build linux
+
+package host
+
+import (
+ "context"
+ "crypto/ed25519"
+ "encoding/base64"
+ "fmt"
+ "io"
+ "os"
+ "regexp"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/appconfig"
+ "github.com/carlosframework/platform/internal/apppolicy"
+ "github.com/carlosframework/platform/internal/hostwrite"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The startup measurement (fleet first reconcile, Task 2): a fleet box's
+// startup store reads over a slow fake store door, step by step, without a
+// dev box. Not a witness: it asserts nothing about timing. It prints, per
+// step, the ops by kind, the wall time, the summed op time and the peak
+// number of ops in flight, then every key each step read, grouped.
+//
+// Skipped unless CARLOS_MEASURE_STARTUP=1. Knobs:
+//
+// CARLOS_MEASURE_STARTUP_LATENCY each op's latency (default 60ms)
+// CARLOS_MEASURE_STARTUP_SIZES instances on the box, comma-separated (default 5,20)
+// CARLOS_MEASURE_STARTUP_OUT a file the tables are also written to
+//
+// The world is the two-box harness's (newFleetWorld): fleet pi, boxes pi-1
+// and pi-2, app shop placed on it, with a signed app policy. For n
+// instances on pi-1, 2(n-1) are created through the console's door (they
+// alternate boxes), pi-1 runs one reconcile (its previous life), then one
+// more is created while it is "stopped" (it lands on pi-1, the witness
+// method). The box then starts: the seeds fastConvergeLoop runs before it
+// arms, then the first tick's reads and the first full pass, in production
+// order, through the production helpers, every store op over the door.
+//
+// Not measured here: the activator startup (systemd sweep and Recover),
+// the runDuties steps, the runs boot pass and the schedule converge (each
+// opens its own store), the moves holds with the Phase 1 switch on (off is
+// the fleet default, and the step is then a no-op), and the first tick's
+// sleep.
+func TestStartupMeasure(t *testing.T) {
+ if os.Getenv("CARLOS_MEASURE_STARTUP") != "1" {
+ t.Skip("a measurement, not a test: set CARLOS_MEASURE_STARTUP=1 to run it")
+ }
+ lat := 60 * time.Millisecond
+ if v := os.Getenv("CARLOS_MEASURE_STARTUP_LATENCY"); v != "" {
+ d, err := time.ParseDuration(v)
+ if err != nil {
+ t.Fatalf("CARLOS_MEASURE_STARTUP_LATENCY=%q: %v", v, err)
+ }
+ lat = d
+ }
+ sizes := []int{5, 20}
+ if v := os.Getenv("CARLOS_MEASURE_STARTUP_SIZES"); v != "" {
+ sizes = nil
+ for _, f := range strings.Split(v, ",") {
+ n, err := strconv.Atoi(strings.TrimSpace(f))
+ if err != nil || n < 1 {
+ t.Fatalf("CARLOS_MEASURE_STARTUP_SIZES=%q: want whole numbers of 1 or more", v)
+ }
+ sizes = append(sizes, n)
+ }
+ }
+ var out strings.Builder
+ for _, n := range sizes {
+ t.Run(fmt.Sprintf("instances=%d", n), func(t *testing.T) {
+ out.WriteString(measureStartup(t, n, lat))
+ })
+ }
+ t.Log("\n" + out.String())
+ if path := os.Getenv("CARLOS_MEASURE_STARTUP_OUT"); path != "" {
+ if err := os.WriteFile(path, []byte(out.String()), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+// slowDoor is the fleet store door's shape (Store, Opener, ETagLister) over
+// a fast store: every op waits lat first, then is noted with its key and
+// how many ops were in flight when it began.
+type slowDoor struct {
+ inner release.Store // a DirStore: Opener and ETagLister both
+ lat time.Duration
+ inflight atomic.Int32
+
+ mu sync.Mutex
+ ops []doorOp
+}
+
+type doorOp struct {
+ op storeOp
+ key string
+ inflight int32 // ops in flight when this one began, itself included
+}
+
+func (d *slowDoor) begin(op storeOp, key string) func() {
+ n := d.inflight.Add(1)
+ time.Sleep(d.lat)
+ d.mu.Lock()
+ d.ops = append(d.ops, doorOp{op: op, key: key, inflight: n})
+ d.mu.Unlock()
+ return func() { d.inflight.Add(-1) }
+}
+
+func (d *slowDoor) mark() int {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return len(d.ops)
+}
+
+func (d *slowDoor) between(from, to int) []doorOp {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return append([]doorOp(nil), d.ops[from:to]...)
+}
+
+func (d *slowDoor) Get(ctx context.Context, key string) ([]byte, string, error) {
+ defer d.begin(opGet, key)()
+ return d.inner.Get(ctx, key)
+}
+
+func (d *slowDoor) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ defer d.begin(opPut, key)()
+ return d.inner.Put(ctx, key, body, ifMatch)
+}
+
+func (d *slowDoor) List(ctx context.Context, prefix string) ([]string, error) {
+ defer d.begin(opList, prefix)()
+ return d.inner.List(ctx, prefix)
+}
+
+func (d *slowDoor) ListDirs(ctx context.Context, prefix string) ([]string, error) {
+ defer d.begin(opDirs, prefix)()
+ return d.inner.ListDirs(ctx, prefix)
+}
+
+func (d *slowDoor) Delete(ctx context.Context, key string) error {
+ defer d.begin(opDelete, key)()
+ return d.inner.Delete(ctx, key)
+}
+
+func (d *slowDoor) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ defer d.begin(opGet, key)()
+ return d.inner.(release.Opener).Open(ctx, key)
+}
+
+func (d *slowDoor) ListETags(ctx context.Context, prefix string) ([]release.KeyETag, error) {
+ defer d.begin(opList, prefix)()
+ return d.inner.(release.ETagLister).ListETags(ctx, prefix)
+}
+
+// measuredLine is one startup timing line and the door ops made since the
+// line before it.
+type measuredLine struct {
+ text string
+ ops []doorOp
+}
+
+// measureStartup builds the world for n instances on pi-1, runs the box's
+// startup reads over a door of latency lat, and returns the report's
+// markdown for this size.
+func measureStartup(t *testing.T, n int, lat time.Duration) string {
+ ctx := context.Background()
+ w := newFleetWorld(t, fleetOpts{})
+ b := w.pi1
+
+ // The release key: the box verifies app policies with it.
+ relPub, relPriv, err := ed25519.GenerateKey(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cfgKey, _, err := appconfig.GenerateKey()
+ if err != nil {
+ t.Fatal(err)
+ }
+ env := map[string]string{
+ "CARLOS_RELEASE_PUBKEY": base64.StdEncoding.EncodeToString(relPub),
+ "CARLOS_SECRETS_KEY": cfgKey,
+ }
+ getenv := func(k string) string {
+ if v, ok := env[k]; ok {
+ return v
+ }
+ return b.getenv(k)
+ }
+ if err := apppolicy.PutIfMatch(ctx, w.store, relPriv, apppolicy.Policy{V: 1, Account: w.acct, App: "shop", Revision: 1,
+ SignedAt: time.Now().UTC()}, ""); err != nil {
+ t.Fatal(err)
+ }
+
+ // n-1 instances on each box, pi-1's previous life, then one more.
+ host := func(i int) string { return fmt.Sprintf("m%02d.example.com", i) }
+ for i := 0; i < 2*(n-1); i++ {
+ w.create(host(i))
+ }
+ b.mustReconcile()
+ last := host(2 * (n - 1))
+ w.create(last)
+ if rec := w.record(last); rec.FleetBox != b.label {
+ t.Fatalf("fixture: %s landed on %q, want %s", last, rec.FleetBox, b.label)
+ }
+
+ // The box starts. Every read from here on is over the door.
+ judge := newBoxJudge(getenv)
+ if judge == nil {
+ t.Fatal("fixture: no lifetime judge, as a claims-off fleet box has")
+ }
+ armMeasuredBox(t, b, getenv, judge)
+ ctx = provision.WithLifetimes(ctx, judge)
+ door := &slowDoor{inner: w.store, lat: lat}
+ if storeExts(door) != doorShape {
+ t.Fatal("fixture: the fake door is not the fleet door's shape")
+ }
+ store, counter := countStore(door)
+
+ var mu sync.Mutex
+ var lines []measuredLine
+ from := 0
+ slog := &startupLog{start: time.Now(), now: time.Now, logf: func(format string, args ...any) {
+ mu.Lock()
+ defer mu.Unlock()
+ to := door.mark()
+ lines = append(lines, measuredLine{text: fmt.Sprintf(format, args...), ops: door.between(from, to)})
+ from = to
+ }}
+ pub, err := release.ParsePublicKey(getenv("CARLOS_RELEASE_PUBKEY"), "CARLOS_RELEASE_PUBKEY")
+ if err != nil {
+ t.Fatal(err)
+ }
+ priv, err := appconfig.ParsePrivateKey(getenv("CARLOS_SECRETS_KEY"), "CARLOS_SECRETS_KEY")
+ if err != nil {
+ t.Fatal(err)
+ }
+ optDir := t.TempDir()
+
+ // fastConvergeLoop's seeds, in its order (the runs boot pass and the
+ // schedule converge open their own stores: left out).
+ arming := slog.steps("arming: ", counter)
+ mem := newRestartMemory()
+ mem.pub = pub
+ restartSeed(ctx, b.reg, store, b.dd, mem)
+ arming.done("restart seed")
+ gain, _ := armRestartLegs(b.reg, store, b.dd, mem, nil, nil)
+ arming.done("restart legs")
+ sidecarWakeSeed(ctx, b.reg, store, newSidecarWakeMemory(false))
+ arming.done("sidecar wake seed")
+ refreshMovesHolds(ctx, store)
+ arming.done("moves holds")
+ refreshOfflineView(ctx, store, armedOfflineView())
+ arming.done("offline view")
+ if leg := newSystemLeg(store, pub, getenv, b.dd, optDir); leg != nil {
+ leg.readers = cachedGroupReaders
+ leg.observe(ctx)
+ }
+ arming.done("system pointer")
+ arming.total("total")
+
+ // The first tick's reads, then the first full pass, which counts
+ // through its own wrapper and logs its own stages.
+ tick := slog.steps("first tick: ", counter)
+ gain(ctx, time.Now())
+ tick.done("restart gain")
+ if _, _, err := release.ReadSerial(ctx, store); err != nil {
+ t.Logf("serial read: %v", err)
+ }
+ tick.done("serial read")
+ legs := &passLegs{store: door, reg: b.reg, pub: pub, optDir: optDir, priv: priv, dd: b.dd, startup: slog,
+ cfg: func() provision.ReconcileConfig {
+ c := BoxProvisionConfig(b.reg, getenv, judge, nil)
+ c.Lifetimes = &provision.LifetimeIndex{}
+ c.Layout = flatLayout
+ return c
+ }}
+ legs.full(ctx)
+ tick.done("full pass")
+ tick.total("total")
+ if rt := b.row(last); rt == nil {
+ t.Fatalf("the first pass did not mint %s", last)
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ return startupReport(n, lat, lines, func(key string) string {
+ key = strings.ReplaceAll(key, w.acct, "<acct>")
+ for i := 0; i <= 2*(n-1); i++ {
+ key = strings.ReplaceAll(key, host(i), "<host>")
+ }
+ return key
+ })
+}
+
+// startupReport is one size's markdown: the step table, then each step's
+// reads grouped by key shape.
+func startupReport(n int, lat time.Duration, lines []measuredLine, shape func(string) string) string {
+ // Reconcile's own stage lines come from its trace hook, when it has
+ // one; without them the reconcile line carries its reads itself.
+ staged := slices.ContainsFunc(lines, func(l measuredLine) bool {
+ return strings.HasPrefix(l.text, "agent: startup: first pass: reconcile: ")
+ })
+ aggregate := func(name string) bool {
+ return strings.HasSuffix(name, "total") || name == "first tick: full pass" || (staged && name == "first pass: reconcile")
+ }
+ var b strings.Builder
+ fmt.Fprintf(&b, "### %d instances on the box, %s per op\n\n", n, lat)
+ b.WriteString("| step | wall | store ops (count/summed time) | ops x latency | peak in flight | began alone |\n")
+ b.WriteString("|---|---|---|---|---|---|\n")
+ for _, l := range lines {
+ m := startupLineRE.FindStringSubmatch(l.text)
+ if m == nil {
+ continue
+ }
+ name, took, ops := m[1], m[2], m[3]
+ total := 0
+ for _, part := range strings.Split(ops, ", ") {
+ if _, rest, ok := strings.Cut(part, " "); ok {
+ c, _, _ := strings.Cut(rest, "/")
+ k, _ := strconv.Atoi(c)
+ total += k
+ }
+ }
+ serialEq := ""
+ if total > 0 {
+ serialEq = (time.Duration(total) * lat).String()
+ }
+ peak, alone := "", ""
+ if aggregate(name) {
+ peak, alone = "(sum of the above)", ""
+ } else if len(l.ops) > 0 {
+ var p int32
+ a := 0
+ for _, o := range l.ops {
+ p = max(p, o.inflight)
+ if o.inflight == 1 {
+ a++
+ }
+ }
+ peak, alone = strconv.Itoa(int(p)), strconv.Itoa(a)
+ }
+ fmt.Fprintf(&b, "| %s | %s | %s | %s | %s | %s |\n", name, took, ops, serialEq, peak, alone)
+ }
+ b.WriteString("\nReads by step (key shape, op, count; listings show their prefix):\n\n")
+ for _, l := range lines {
+ m := startupLineRE.FindStringSubmatch(l.text)
+ if m == nil || len(l.ops) == 0 || aggregate(m[1]) {
+ continue
+ }
+ counts := map[string]int{}
+ for _, o := range l.ops {
+ counts[storeOpNames[o.op]+" "+shape(o.key)]++
+ }
+ keys := make([]string, 0, len(counts))
+ for k := range counts {
+ keys = append(keys, k)
+ }
+ sort.Slice(keys, func(i, j int) bool {
+ if counts[keys[i]] != counts[keys[j]] {
+ return counts[keys[i]] > counts[keys[j]]
+ }
+ return keys[i] < keys[j]
+ })
+ fmt.Fprintf(&b, "- **%s** (%d ops)\n", m[1], len(l.ops))
+ for _, k := range keys {
+ fmt.Fprintf(&b, " - %s x%d\n", k, counts[k])
+ }
+ }
+ b.WriteString("\n")
+ return b.String()
+}
+
+var startupLineRE = regexp.MustCompile(`^agent: startup: (.+?) took (\S+) at \+\S+(?: \(store: (.*)\))?$`)
+
+// armMeasuredBox arms the globals the startup reads through as the agent
+// arms them on a fleet box (claims off, moves switch unset, hibernation
+// configured), and puts them back afterwards.
+func armMeasuredBox(t *testing.T, b *fleetBox, getenv func(string) string, judge *provision.LifetimeJudge) {
+ t.Helper()
+ prevWorker, prevPolicies := armedMovesWorker.Load(), armedPolicyCache.Load()
+ t.Cleanup(func() {
+ armedMovesWorker.Store(prevWorker)
+ armedPolicyCache.Store(prevPolicies)
+ aliasClaimCache.Reset()
+ })
+ aliasClaimCache.Reset()
+ armedPolicyCache.Store(provision.NewPolicyCache(nil))
+ cfg := moveCfg{Judge: judge, Region: getenv("CARLOS_REGION"), OwnBucket: fleetBucket, OwnBucketRegion: fleetRegion,
+ OwnPrefix: fleetPrefix, DataDir: b.dd, Now: time.Now, Box: b.label, OptDir: t.TempDir(),
+ OwnsRoute: func(host string) bool {
+ rt, err := b.reg.Get(host)
+ return err == nil && rt != nil && rt.Provisioned
+ },
+ Route: b.reg.Get, SetStatus: b.reg.SetStatus}
+ armOffline(&cfg, b.dd, b.reg, nil, nil, hostwrite.Config{}, getenv)
+ if !cfg.OfflineCapable {
+ t.Fatal("fixture: the box is not offline capable, as a fleet box with hibernation is")
+ }
+ armedMovesWorker.Store(newMovesWorker(cfg))
+}