carlos / platform Public

console-slow-writes: the slow CLI writes read less, and at once. Ship's wrong-program rule reads its 20 manifests ten at a time, streamed and capped at 1 MiB each, and an over-cap manifest fails the check closed (975 -> ~410 ms after the upload). Instance create reads the live edges snapshot once per request, prefetched under the door's 15 s deadline in a write memo that holds only box-written objects; memo readers honour their own context and a panicked load panics again in every reader, so a failed read never becomes a write; holder, claim and cap reads are narrowed and run together (70 -> 51 S3, 2,050 -> ~590 ms). App create gets the same changes (~1,200 -> ~410 ms); promote reads manifest and pipeline at once. No write moved or reordered. TestPerfWriteRoutesMeetTheBudget locks each write door's S3 count and its time after the body, stamped server-side. Astra round 1 NOT READY (2 P1, 2 P2) fixed with witnesses; round 2 READY AFTER FIXES, the P2 fixed; census census-ruling-console-slow-writes (runningThings 9B8, internal/release and internal/edgesfile envelopes, new unit readProgramManifest) approved by Astra on #280 at 54233a0a. Not released.

Squashed from console-slow-writes into main.
claude agent, operated by paul@keymail.dev de23fa5ec21dddbae95a6be44867abd2652baa81 parent bb7d095
19 files changed, +1,229 −81
  • docs/superpowers/notes/census-proposal-console-slow-writes.md +55 −0
  • internal/console/apex.go +19 −5
  • internal/console/apicli.go +44 −13
  • internal/console/apiinstances.go +22 −3
  • internal/console/authcli.go +3 −0
  • internal/console/instancesplacement.go +24 −1
  • internal/console/perfquickwins_test.go +36 −7
  • internal/console/perfwrites_test.go +377 −0
  • internal/console/plancaps.go +25 −7
  • internal/console/reqmemo.go +127 −12
  • internal/console/reqmemo_prefetch_test.go +154 −0
  • internal/console/server.go +4 −0
  • internal/edgesfile/snapshot.go +12 −3
  • internal/provision/console_slow_writes_census_test.go +38 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv +7 −0
  • internal/release/program.go +132 −29
  • internal/release/program_bound_test.go +148 −0

CI passed — run details

landed from console-slow-writes

diff --git a/docs/superpowers/notes/census-proposal-console-slow-writes.md b/docs/superpowers/notes/census-proposal-console-slow-writes.md
new file mode 100644
index 000000000..ad11ebe9e
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-console-slow-writes.md
@@ -0,0 +1,55 @@
+# Census approval: console-slow-writes
+
+Ruling `census-ruling-console-slow-writes`. 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).
+
+Envelopes re-pinned: `internal/edgesfile`, `internal/release`.
+
+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.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/release/program.go:readProgramManifest`: reads +file:ReadAll; written legacy, accepted-legacy, frozen
+
+Seal: `886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f` → `fe61ef9b2ecbb7d3d2049b8e6c9746ee08d3ea32dc1e65455e126771447f403f`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
+
+## Branch context
+
+Branch `console-slow-writes` makes the console's slow CLI writes faster
+(ship, instance create, app create, promote). The two envelopes move
+because two functions in root-binary packages changed shape. One new unit
+appears, from Astra's round 1 memory finding.
+
+- `internal/release`, `PreviousProgram` (program.go): the wrong-program
+ rule reads the 20 newest manifests ten at a time instead of one after
+ another, then judges them in the listing's order exactly as before. The
+ first store error in that order still fails the check closed; missing
+ and unparseable manifests are still skipped and logged with the same
+ text. New helpers `readProgramManifest` (one manifest's read and
+ verdict) and `forEachBounded` (a bounded worker pool). Callers: both
+ ship doors (the console's API ship and the direct-bucket `carlos ship`).
+ Root does not call it.
+- New unit `readProgramManifest` (`+file:ReadAll`): after round 1 it opens
+ the same key with `OpenQualified` (the streaming twin of `GetQualified`:
+ same key, same not-found answer) and reads at most
+ `maxProgramManifestBytes` (1 MiB) and one byte with
+ `io.ReadAll(io.LimitReader(...))`. The ReadAll is over that capped
+ object-store body, not a file path. A manifest over the cap is skipped as
+ one that does not validate; a worker keeps only program, built-at and
+ version once judged. Before, the whole body came through `GetQualified`
+ with no cap.
+- `internal/edgesfile`, `ReadLiveSnapshot` (snapshot.go): its join half
+ is split out as `JoinLive(snap, boxes, complete, loadErr, now)`, and
+ `ReadLiveSnapshot` now calls it with the same two reads in the same
+ order. The rulings, the completeness flags and the once-said logs are
+ the same lines. The console calls `JoinLive` after reading the edges
+ files and the box reports at once.
+
+The record-write census (9B8) gains a layer on main's newest inventory
+(`consoleSlowWritesWriteCensusInventory`, on
+`teamScopedCredentialsWriteCensusInventory`): `Server.runningThings` is
+re-pinned, still key-site, now naming `RecordsPrefix` beside
+`ParseRecordKey` because it lists each counted app's records prefix
+instead of the account's whole prefix. It writes nothing. Astra approved
+this row, and both envelopes, in round 1 at d38e5827.
diff --git a/internal/console/apex.go b/internal/console/apex.go
index a838e70b3..c35156769 100644
--- a/internal/console/apex.go
+++ b/internal/console/apex.go
@@ -18,9 +18,11 @@ import (
"fmt"
"log"
"os"
+ "slices"
"strings"
"github.com/carlosframework/platform/internal/domains"
+ "github.com/carlosframework/platform/internal/provision"
)
// apexHost is the platform apex app would have in the account with this
@@ -143,14 +145,26 @@ func (s *Server) hostHolder(ctx context.Context, acct *Account, host, own string
for _, t := range trashed {
apps = append(apps, candidate{app: t.App, trashed: true})
}
- for _, c := range apps {
- if c.app == name {
- continue
- }
+ apps = slices.DeleteFunc(apps, func(c candidate) bool { return c.app == name })
+ // Every other app's record at host is read at once, readConcurrency at a
+ // time (console-slow-writes), and judged in the order above, exactly as
+ // when each was judged as it was read: the first app holding the host
+ // answers, and the first read error before any holder fails closed.
+ // Each read is its own record then its slot (readRecord), in that order.
+ type read struct {
+ rec *provision.Record
+ err error
+ }
+ reads := make([]read, len(apps))
+ forEachLimit(len(apps), readConcurrency, func(i int) {
// Judged when the request was admitted with lifetimes on (a nil
// judge is GetRecord): a body its slot no longer vouches for holds
// nothing.
- rec, _, err := s.readRecord(ctx, acct.Sqid, c.app, host)
+ rec, _, err := s.readRecord(ctx, acct.Sqid, apps[i].app, host)
+ reads[i] = read{rec, err}
+ })
+ for i, c := range apps {
+ rec, err := reads[i].rec, reads[i].err
if errors.Is(err, os.ErrNotExist) {
continue
}
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index c4ca4b72d..d9d338192 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -18,6 +18,7 @@ import (
"fmt"
"io"
"log"
+ "maps"
"net/http"
"net/url"
"regexp"
@@ -503,6 +504,10 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
jsonError(w, http.StatusInternalServerError, "could not create the app — try again")
return
}
+ // The answer's region lines read the live edges snapshot, which nothing
+ // the claim writes can change: it is read while the claim runs
+ // (console-slow-writes).
+ defer s.prefetchLiveEdges(r.Context())()
outcome, placed, held := s.claimApp(r.Context(), acct, name, addr, place, ownerClaim, rq)
switch outcome {
case claimInvalid:
@@ -564,17 +569,32 @@ func (s *Server) handleAPICreateApp(w http.ResponseWriter, r *http.Request) {
"control_plane": gotCP,
"build_probe": gotProbe,
}
- s.echoCreatedRegion(r.Context(), acct, name, out)
- // "analytics" and "analytics_from" echo what the app now resolves to,
- // read back after the write, so the CLI compares that with what it
- // asked for. A failed write leaves the app following the account.
- if err := s.applyNewAppAnalytics(r.Context(), acct, name, addr, req.Analytics, analyticsOwner); err != nil {
- log.Printf("console: api create %s/%s: analytics setting: %v", acct.Sqid, name, err)
- }
- if res, err := telemetry.Resolve(r.Context(), s.cfg.Releases, acct.Sqid, name); err != nil {
- log.Printf("console: api create %s/%s: read back analytics: %v", acct.Sqid, name, err)
- } else {
- out["analytics"], out["analytics_from"] = res.Count, res.CountFrom
+ // The region lines and the analytics setting are independent (the
+ // one reads the edges snapshot and the app's row, the other writes
+ // and reads back the app's telemetry), so they run at once
+ // (console-slow-writes), each into its own map.
+ region := map[string]any{}
+ var analytics *telemetry.Resolved
+ runConcurrently(
+ func() { s.echoCreatedRegion(r.Context(), acct, name, region) },
+ func() {
+ // "analytics" and "analytics_from" echo what the app now
+ // resolves to, read back after the write, so the CLI
+ // compares that with what it asked for. A failed write
+ // leaves the app following the account.
+ if err := s.applyNewAppAnalytics(r.Context(), acct, name, addr, req.Analytics, analyticsOwner); err != nil {
+ log.Printf("console: api create %s/%s: analytics setting: %v", acct.Sqid, name, err)
+ }
+ if res, err := telemetry.Resolve(r.Context(), s.cfg.Releases, acct.Sqid, name); err != nil {
+ log.Printf("console: api create %s/%s: read back analytics: %v", acct.Sqid, name, err)
+ } else {
+ analytics = &res
+ }
+ },
+ )
+ maps.Copy(out, region)
+ if analytics != nil {
+ out["analytics"], out["analytics_from"] = analytics.Count, analytics.CountFrom
}
writeJSON(w, http.StatusOK, out)
default:
@@ -902,7 +922,19 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
- man, err := release.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app, version)
+ // The version's manifest and the app's pipeline are read at once
+ // (console-slow-writes); each answer is judged where it always was, so
+ // an unshipped version is still refused before the pipeline's error.
+ var (
+ man *release.Manifest
+ err error
+ pipe *release.Pipeline
+ perr error
+ )
+ runConcurrently(
+ func() { man, err = release.GetManifest(ctx, s.cfg.Releases, acct.Sqid, app, version) },
+ func() { pipe, perr = release.GetPipeline(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app) },
+ )
if err != nil {
jsonError(w, http.StatusNotFound, "Version "+version+" is not a shipped release of "+app+".")
return
@@ -921,7 +953,6 @@ func (s *Server) handleAPIPromote(w http.ResponseWriter, r *http.Request) {
// means "not safely nil", and treating it as "no pipeline" would drop
// this door back to the legacy ladder under exactly the app that opted
// out of it — the same line PromoteOnLadder itself takes.
- pipe, perr := release.GetPipeline(ctx, s.cfg.Releases, s.cfg.ReleasePub, acct.Sqid, app)
if perr != nil {
log.Printf("console: api promote %s/%s: read pipeline: %v", acct.Sqid, app, perr)
jsonError(w, http.StatusBadGateway, "could not read the pipeline for "+app)
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index e641874d7..bbba6063a 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -1277,6 +1277,12 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
}
ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
defer cancel()
+ // The live edges snapshot (the edges files and the box reports) is read
+ // while the checks before its first use run: the placement gate, R9 and
+ // the answer's region name all ask it, and nothing they ask depends on
+ // anything read before it (console-slow-writes). It runs under the
+ // door's deadline (ctx), as the checks that ask for it do.
+ defer s.prefetchLiveEdges(ctx)()
m, ok := s.instanceManifest(ctx, w, acct, app)
if !ok {
return
@@ -1460,7 +1466,20 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
// needs host-scoped atomic ownership, which is a gap in the instance door
// that predates the flat canary host and is not built here. The
// sequential case, the common one, is closed.
- switch hold, err := s.hostHolder(ctx, acct, host, app); {
+ //
+ // The holder check and the claim check below are two reads of
+ // different objects, made at once (console-slow-writes); their answers
+ // are judged in the order they always were, so the holder's refusal
+ // still comes first.
+ var (
+ hold, claimHold *apexHold
+ holdErr, claimErr error
+ )
+ runConcurrently(
+ func() { hold, holdErr = s.hostHolder(ctx, acct, host, app) },
+ func() { claimHold, claimErr = s.hostClaimHolder(ctx, acct, host, app) },
+ )
+ switch hold, err := hold, holdErr; {
case err != nil:
log.Printf("console: api instances create %s/%s: host holder check %s: %v", acct.Sqid, app, host, err)
jsonError(w, http.StatusInternalServerError, "could not check the host — try again")
@@ -1471,7 +1490,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
}
// An attached alias has no record and may have no route yet, so the
// holder check cannot see it; its authoritative claim is one read.
- switch hold, err := s.hostClaimHolder(ctx, acct, host, app); {
+ switch hold, err := claimHold, claimErr; {
case err != nil:
log.Printf("console: api instances create %s/%s: host claim check %s: %v", acct.Sqid, app, host, err)
jsonError(w, http.StatusInternalServerError, "could not check the host — try again")
@@ -1649,7 +1668,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request)
return
}
probe := provision.Record{Kind: strings.TrimSpace(req.Kind), Addrs: req.Addrs, Role: probeRec.Role}
- caps, published := placements(ctx, s.cfg.Releases)
+ caps, published := s.placementsIn(ctx)
// The replica placement rides the same gate as the record's own
// region (#162): a replica named into a placement no box announces
// is a mirror nothing will ever provision — an order ledger in a
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index dfc98cb08..ceb8daa3b 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -457,6 +457,9 @@ func (s *Server) cliRoute(pattern string, allow svcrole.Set, h http.HandlerFunc)
// request context.
func (s *Server) cliGate(allow svcrole.Set, h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
+ if s.cliBodyWrap != nil && r.Body != nil {
+ r.Body = s.cliBodyWrap(r)
+ }
now := time.Now()
p, ok := s.store.CLIPrincipal(bearer(r), now)
if !ok {
diff --git a/internal/console/instancesplacement.go b/internal/console/instancesplacement.go
index 74e714648..5ebd5a19f 100644
--- a/internal/console/instancesplacement.go
+++ b/internal/console/instancesplacement.go
@@ -156,8 +156,13 @@ type placementCapability struct {
// wrong, publishes hibernation_configured true and fails every lease. This
// is configuration, which is all an edges file can honestly carry.
func placements(ctx context.Context, s release.Store) (caps map[string]placementCapability, published bool) {
+ return foldPlacements(readEdgesFiles(ctx, s))
+}
+
+// foldPlacements is placements' fold over files already read.
+func foldPlacements(files []edgesFilePlacementView) (caps map[string]placementCapability, published bool) {
caps = map[string]placementCapability{}
- for _, f := range readEdgesFiles(ctx, s) {
+ for _, f := range files {
if f.Placement == "" {
continue
}
@@ -167,6 +172,24 @@ func placements(ctx context.Context, s release.Store) (caps map[string]placement
return caps, published
}
+// placementsIn is placements over the request's live edges snapshot
+// (liveEdges), for a door that reads that snapshot anyway: the edges files
+// are then read once, not once for each (console-slow-writes). The files
+// are the same bytes, read by the same reader; a failed read is
+// readEdgesFiles' answer, no files, logged as it logs it. With no memo
+// holding the snapshot it is placements.
+func (s *Server) placementsIn(ctx context.Context) (caps map[string]placementCapability, published bool) {
+ if s.cfg.Releases == nil || memoOf(ctx, "edges") == nil {
+ return placements(ctx, s.cfg.Releases)
+ }
+ snap, err := s.liveEdges(ctx)
+ if err != nil {
+ log.Printf("console: api instances: could not list %s for the placement join: %v", edgesFilePrefix, err)
+ return foldPlacements(nil)
+ }
+ return foldPlacements(snap.Files)
+}
+
// foldCapability adds one box's edges file to its code's capability.
func foldCapability(c placementCapability, f edgesFilePlacementView) placementCapability {
// Every capability below is gated on reachability: a box with no dial
diff --git a/internal/console/perfquickwins_test.go b/internal/console/perfquickwins_test.go
index 7b900bb20..4028c3bb1 100644
--- a/internal/console/perfquickwins_test.go
+++ b/internal/console/perfquickwins_test.go
@@ -112,6 +112,8 @@ type s3Req struct {
Token string // a listing's continuation token: "" on its first page
// IfNoneMatch is a conditional read's ETag, "" for a plain one.
IfNoneMatch string
+ // At is when the fake answered it, after its delay.
+ At time.Time
}
// recordS3 installs the recorder as the fake's request hook; fail, when
@@ -121,7 +123,7 @@ func recordS3(lat *perfLatency, fail func(s3Req) bool) *s3Recorder {
rec := &s3Recorder{}
lat.Fake().OnRequest(func(r *http.Request) (int, <-chan struct{}) {
_, key, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/")
- q := s3Req{Method: r.Method, Key: key, IfNoneMatch: r.Header.Get("If-None-Match")}
+ q := s3Req{Method: r.Method, Key: key, IfNoneMatch: r.Header.Get("If-None-Match"), At: time.Now()}
if key == "" {
q.Prefix = r.URL.Query().Get("prefix")
q.Token = r.URL.Query().Get("continuation-token")
@@ -303,7 +305,8 @@ func TestLogsHostPickerReadsNoRecords(t *testing.T) {
}
// TestReqMemoOnlyOnViews: memoize with no memo in the context loads every
-// time; registerRoute installs a memo for GET and HEAD requests only.
+// time; registerRoute installs a whole memo for GET and HEAD requests only,
+// and a write door's memo holds the edges snapshot and box reports alone.
func TestReqMemoOnlyOnViews(t *testing.T) {
loads := 0
load := func() (int, error) { loads++; return loads, nil }
@@ -330,9 +333,13 @@ func TestReqMemoOnlyOnViews(t *testing.T) {
t.Errorf("a failed load: %d loads, errors %v and %v; want 1 load and its error twice", errs, e1, e2)
}
+ // A view holds every key; a write door holds only the live edges
+ // snapshot and the box reports (withWriteMemo, console-slow-writes),
+ // which boxes write and the console never does: a record, a manifest
+ // or anything else a door may write is read afresh each time it asks.
for _, tc := range []struct {
pattern, method string
- memo bool
+ view bool
}{
{"POST /x", http.MethodPost, false},
{"GET /x", http.MethodGet, true},
@@ -343,16 +350,38 @@ func TestReqMemoOnlyOnViews(t *testing.T) {
} {
t.Run(tc.method+" "+tc.pattern, func(t *testing.T) {
s := &Server{mux: http.NewServeMux()}
- seen := false
+ held := map[string]bool{}
s.registerRoute(tc.pattern, func(w http.ResponseWriter, r *http.Request) {
- seen = r.Context().Value(reqMemoKey{}) != nil
+ for _, key := range []string{"edges", boxesMemoKey(""), boxesMemoKey("fleets/f/"), "instances-manifest:bab/kass", "k"} {
+ held[key] = memoOf(r.Context(), key) != nil
+ }
})
s.mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(tc.method, "/x", nil))
- if seen != tc.memo {
- t.Errorf("memo in the request context: %v, want %v", seen, tc.memo)
+ for key, got := range held {
+ want := tc.view || key == "edges" || strings.HasPrefix(key, "boxes:")
+ if got != want {
+ t.Errorf("memo holds %q: %v, want %v", key, got, want)
+ }
+ }
+ if len(held) != 5 {
+ t.Errorf("the handler saw %d keys, want 5", len(held))
}
})
}
+ // A write door's memo loads a key it does not hold every time.
+ wctx := withWriteMemo(context.Background())
+ loads = 0
+ memoize(wctx, "instances-manifest:bab/kass", load)
+ memoize(wctx, "instances-manifest:bab/kass", load)
+ if loads != 2 {
+ t.Errorf("a write memo loaded a key it does not hold %d times in two asks, want 2", loads)
+ }
+ loads = 0
+ memoize(wctx, "edges", load)
+ memoize(wctx, "edges", load)
+ if loads != 1 {
+ t.Errorf("a write memo loaded the edges snapshot %d times in two asks, want 1", loads)
+ }
}
// settingsGroup names which settings read a request belongs to, from the
diff --git a/internal/console/perfwrites_test.go b/internal/console/perfwrites_test.go
new file mode 100644
index 000000000..bb9e4ae8f
--- /dev/null
+++ b/internal/console/perfwrites_test.go
@@ -0,0 +1,377 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptrace"
+ "os"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// The console's slow CLI writes (console-slow-writes): the write doors
+// flagship's speed table put slowest, and the instance list's cold path,
+// measured over newPerfFixture shaped further toward flagship: lifetimes
+// on, the many-instance app grown to perfWritesInstances, and a release
+// history of perfWritesReleases versions, each a Go program, which is what
+// the ship door's wrong-program rule reads.
+
+const (
+ perfWritesInstances = 100
+ perfWritesReleases = 20
+ perfWritesProgram = "example.com/shopfront"
+)
+
+// perfWritesFx is the fixture the write measurements run on.
+type perfWritesFx struct {
+ fx *consoleFixture
+ lat *perfLatency
+ token string
+ prog []byte // a linux/arm64 Go binary whose main package is perfWritesProgram
+ // bodyEnd is when the console read the last request's body to its end.
+ bodyEnd *atomic.Pointer[time.Time]
+}
+
+// newPerfWritesFx is newPerfFixture with lifetimes on, every CLI budget
+// lifted, perfFlagshipApp grown to perfWritesInstances instances and
+// perfWritesReleases releases, and Paul's CLI token.
+func newPerfWritesFx(t *testing.T) perfWritesFx {
+ t.Helper()
+ perfCaptureLogs(t)
+ clock := useLifetimesClock(t)
+ fx, lat := newPerfFixture(t)
+ token := cliToken(t, fx, "paul@keymail.dev", "code-perf-writes")
+ turnLifetimesOn(t, fx.srv, clock)
+ liftShipBudget(fx)
+ // Flagship serves apps under its platform apps domain.
+ fx.srv.cfg.AppsDomain = "oncarlos.test"
+ fx.srv.cli.write = newRateLimiter(1<<20, time.Minute)
+ fx.srv.cli.create = newRateLimiter(1<<20, time.Minute)
+ fx.srv.cli.instances = newRateLimiter(1<<20, time.Minute)
+
+ ctx := context.Background()
+ now := time.Now()
+ // The account is on a plan, as flagship's are, with room for what the
+ // doors create: the cap checks run and pass.
+ acct, err := fx.st.AccountBySqid(fx.sqid)
+ if err != nil || acct == nil {
+ t.Fatalf("account %s: %v", fx.sqid, err)
+ }
+ applyPlan(t, fx, acct, "free", nil, &plans.Limits{RunningThings: 10000, SidecarsPerApp: 10}, now)
+ codes := []string{"ie", "uk", "us"}
+ for i := perfFlagshipInstances; i < perfWritesInstances; i++ {
+ rec := provision.Record{Schema: 1, Host: fmt.Sprintf("s%02d.shopfront.example.com", i), Slug: fmt.Sprintf("s%02d", i),
+ App: perfFlagshipApp, Account: fx.sqid, Channel: "stable", Region: codes[i%len(codes)],
+ CreatedAt: now.Add(-2 * time.Hour), CreatedBy: "paul@keymail.dev"}
+ if err := provision.CreateRecord(ctx, fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ }
+ prog := tinyProgramForConsole(t, perfWritesProgram)
+ for i := 0; i < perfWritesReleases; i++ {
+ v := fmt.Sprintf("r%02d", i)
+ m := release.Manifest{Schema: 1, App: perfFlagshipApp, Version: v, Kind: "binary", Program: perfWritesProgram,
+ BuiltAt: now.Add(time.Duration(i-perfWritesReleases) * time.Hour).UTC().Format(time.RFC3339),
+ Artifacts: map[string]release.Artifact{"linux-arm64": {File: "linux-arm64"}}}
+ if err := release.Ship(ctx, fx.rel, release.OpsAccount, m, map[string][]byte{"linux-arm64": prog}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // Aged as perfSeed ages its objects, and the gone boxes' reports put
+ // back past the listing horizon.
+ perfAgeObjects(t, fx, 30*time.Second)
+ perfSeedGoneBoxes(t, fx, 1100)
+ bodyEnd := new(atomic.Pointer[time.Time])
+ fx.srv.cliBodyWrap = func(r *http.Request) io.ReadCloser {
+ return &bodyEndStamp{ReadCloser: r.Body, want: r.ContentLength, at: bodyEnd}
+ }
+ t.Cleanup(func() { fx.srv.cliBodyWrap = nil })
+ return perfWritesFx{fx: fx, lat: lat, token: token, prog: prog, bodyEnd: bodyEnd}
+}
+
+// perfWriteResult is one measured request.
+type perfWriteResult struct {
+ status int
+ body string
+ // total is from the request's start to its last response byte;
+ // afterBody from when the console read the request body's last byte
+ // (perfWritesFx.bodyEnd) to the first response byte: the console's own
+ // work once the body is in, for a ship's upload and a JSON door's small
+ // body alike. A bodiless request's is from when the client sent it.
+ total, afterBody time.Duration
+ reqs []s3Req
+ start time.Time
+}
+
+// perfWriteDo makes one request with the CLI's bearer and records every S3
+// request the fake answers for it.
+func (w perfWritesFx) do(t *testing.T, method, path, contentType string, body []byte) perfWriteResult {
+ t.Helper()
+ rec := recordS3(w.lat, nil)
+ var wrote, first time.Time
+ ctx := httptrace.WithClientTrace(context.Background(), &httptrace.ClientTrace{
+ WroteRequest: func(httptrace.WroteRequestInfo) { wrote = time.Now() },
+ GotFirstResponseByte: func() { first = time.Now() },
+ })
+ req, err := http.NewRequestWithContext(ctx, method, w.fx.ts.URL+path, bytes.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if contentType != "" {
+ req.Header.Set("Content-Type", contentType)
+ }
+ req.Header.Set("Authorization", "Bearer "+w.token)
+ start := time.Now()
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ total := time.Since(start)
+ if !perfIdle(perfSeedsOf(w.fx).inflight, 2*time.Second) {
+ t.Fatalf("%s %s: a handler was still running 2s after its response", method, path)
+ }
+ // A request with a body is timed from the console's read of its end,
+ // and must have one; a bodiless one (the GET) from the client's send.
+ if end := w.bodyEnd.Swap(nil); end != nil {
+ wrote = *end
+ } else if len(body) > 0 {
+ t.Fatalf("%s %s: the console never read the request body to its end (%d bytes); nothing to time from", method, path, len(body))
+ }
+ return perfWriteResult{status: resp.StatusCode, body: string(raw), total: total, afterBody: first.Sub(wrote),
+ reqs: rec.all(), start: start}
+}
+
+// bodyEndStamp notes when the console has read a request body to its end:
+// the read that answers io.EOF, or that brings what was read to the
+// request's Content-Length, whichever comes first. A JSON decoder may stop
+// at the closing brace without asking for io.EOF, so the length is what
+// marks a small body's end.
+type bodyEndStamp struct {
+ io.ReadCloser
+ want, n int64
+ at *atomic.Pointer[time.Time]
+}
+
+func (b *bodyEndStamp) Read(p []byte) (int, error) {
+ n, err := b.ReadCloser.Read(p)
+ b.n += int64(n)
+ if err == io.EOF || (b.want > 0 && b.n >= b.want) {
+ now := time.Now()
+ b.at.CompareAndSwap(nil, &now)
+ }
+ return n, err
+}
+
+func (w perfWritesFx) json(t *testing.T, method, path string, v any) perfWriteResult {
+ t.Helper()
+ raw, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return w.do(t, method, path, "application/json", raw)
+}
+
+// ship is `carlos ship` of version with the fixture's program as its one
+// linux-arm64 artifact.
+func (w perfWritesFx) ship(t *testing.T, version string) perfWriteResult {
+ t.Helper()
+ var buf bytes.Buffer
+ mw := multipart.NewWriter(&buf)
+ for _, p := range []shipPart{metaPart(t, version, "binary"), {name: "linux-arm64", body: w.prog}} {
+ fw, err := mw.CreateFormFile(p.name, p.name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fw.Write(p.body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := mw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return w.do(t, http.MethodPost, "/api/cli/apps/"+w.fx.sqid+"/"+perfFlagshipApp+"/releases", mw.FormDataContentType(), buf.Bytes())
+}
+
+// trace is one result's S3 requests in the order the fake answered them,
+// each with its offset from the request's start, for reading which run one
+// after another.
+func (r perfWriteResult) trace() string {
+ var b strings.Builder
+ for _, q := range r.reqs {
+ fmt.Fprintf(&b, " +%4dms %s\n", q.At.Sub(r.start).Milliseconds(), s3ReqName(q))
+ }
+ return b.String()
+}
+
+// perfWriteRoute is one measured door: what it is, and one request of it
+// (n numbers the request, so each can name a fresh version, host or app).
+type perfWriteRoute struct {
+ Name string
+ Do func(t *testing.T, w perfWritesFx, n int) perfWriteResult
+ Want int
+}
+
+func perfWriteRoutes() []perfWriteRoute {
+ return []perfWriteRoute{
+ {"ship", func(t *testing.T, w perfWritesFx, n int) perfWriteResult {
+ return w.ship(t, fmt.Sprintf("v%d", 100+n))
+ }, http.StatusCreated},
+ {"instance create", func(t *testing.T, w perfWritesFx, n int) perfWriteResult {
+ return w.json(t, http.MethodPost, "/api/cli/apps/"+w.fx.sqid+"/"+perfFlagshipApp+"/instances",
+ map[string]string{"host": fmt.Sprintf("n%02d.shopfront.example.com", n), "region": "uk"})
+ }, http.StatusCreated},
+ {"app create", func(t *testing.T, w perfWritesFx, n int) perfWriteResult {
+ return w.json(t, http.MethodPost, "/api/cli/apps/"+w.fx.sqid+"/new", map[string]string{"name": fmt.Sprintf("made-%d", n)})
+ }, http.StatusOK},
+ {"promote", func(t *testing.T, w perfWritesFx, n int) perfWriteResult {
+ v := "r19"
+ if n%2 == 1 {
+ v = "r18"
+ }
+ return w.json(t, http.MethodPost, "/api/cli/apps/"+w.fx.sqid+"/"+perfFlagshipApp+"/promote",
+ map[string]string{"version": v, "channel": "canary/perf"})
+ }, http.StatusOK},
+ {"config put", func(t *testing.T, w perfWritesFx, n int) perfWriteResult {
+ return w.json(t, http.MethodPut, "/api/cli/apps/"+w.fx.sqid+"/"+perfFlagshipApp+"/config",
+ map[string]any{"set": map[string]any{"GREETING": map[string]string{"kind": "env", "value": fmt.Sprintf("hello %d", n)}}})
+ }, http.StatusOK},
+ {"instances-manifest put", func(t *testing.T, w perfWritesFx, n int) perfWriteResult {
+ ch := "stable"
+ if n%2 == 1 {
+ ch = "beta"
+ }
+ return w.json(t, http.MethodPut, "/api/cli/apps/"+w.fx.sqid+"/blog/instances-manifest", map[string]any{"channel": ch})
+ }, http.StatusOK},
+ {"instance list", func(t *testing.T, w perfWritesFx, n int) perfWriteResult {
+ if n == 0 {
+ perfFullyCold(w.fx)
+ }
+ return w.do(t, http.MethodGet, "/api/cli/apps/"+w.fx.sqid+"/"+perfFlagshipApp+"/instances", "", nil)
+ }, http.StatusOK},
+ }
+}
+
+// TestPerfWriteRoutesTrace prints each route's S3 requests and timings,
+// one cold request and three after it, with the walk's 25 ms per S3
+// request. It asserts nothing beyond the answers' statuses: it is the
+// measurement the speed table's rows were fixed from. PERF_WRITES_TRACE=1
+// prints every request's trace.
+func TestPerfWriteRoutesTrace(t *testing.T) {
+ if os.Getenv("PERF_WRITES_TRACE") == "" {
+ t.Skip("set PERF_WRITES_TRACE=1 to print the write doors' traces")
+ }
+ w := newPerfWritesFx(t)
+ for _, rt := range perfWriteRoutes() {
+ for n := 0; n < 4; n++ {
+ w.lat.Enable(true)
+ r := rt.Do(t, w, n)
+ w.lat.Enable(false)
+ if r.status != rt.Want {
+ t.Fatalf("%s #%d = %d, want %d:\n%s", rt.Name, n, r.status, rt.Want, r.body)
+ }
+ summary, _ := s3Summary(r.reqs)
+ t.Logf("%s #%d: %d S3, total %dms, after body %dms\n%s\nsummary:\n%s", rt.Name, n, len(r.reqs),
+ r.total.Milliseconds(), r.afterBody.Milliseconds(), r.trace(), summary)
+ }
+ }
+}
+
+// perfWriteLimit is one write door's lock: the most S3 requests any of its
+// measured requests may make, and the most its median may take after the
+// body, with the walk's 25 ms per S3 request. Budget is perfWriteBudget
+// unless Over says why the door is still above it.
+type perfWriteLimit struct {
+ Calls int
+ Budget time.Duration
+ Over string
+}
+
+// perfWriteLimits are the write doors' locks on newPerfWritesFx, measured
+// on 2026-10-28 (console-slow-writes). Before that branch, and after it:
+//
+// - ship: 32 S3 requests both; 975 ms of console work after the upload
+// before, about 450 ms after. The wrong-program rule's 20 manifests
+// are read ten at a time rather than one after another.
+// - instance create: 70 S3 requests and 2,050 ms before; 51 and about
+// 590 ms after. The edges files and box reports are read once, at
+// once, while the door's other checks run; the host holder reads every
+// other app's record at once; the plan cap lists each app's records
+// rather than the account's whole prefix.
+// - app create: 40 to 44 S3 requests and 1,200 ms before; 44 to 50
+// (one records listing per app now, at once, in place of the
+// account's whole prefix) and about 410 ms after.
+// - promote: 18 S3 requests both; 540 ms before, about 510 ms after
+// (the version's manifest and the pipeline are read at once).
+// - config put (10, about 320 ms) and instances-manifest put (6, about
+// 195 ms): unchanged, every request a write or the read its CAS needs.
+func perfWriteLimits() map[string]perfWriteLimit {
+ return map[string]perfWriteLimit{
+ "ship": {Calls: 32, Budget: perfWriteBudget},
+ "instance create": {Calls: 51, Budget: 700 * time.Millisecond, Over: "23 requests one after another: the manifest, the host holder (record then slot), the channel head (pointer then manifest), the plan cap's listings, then under the record lock the app's tombstone, this key's record and slot, every other app's, three writes in the lifetime protocol's order, the change index and the serial"},
+ "app create": {Calls: 50, Budget: perfWriteBudget},
+ "promote": {Calls: 18, Budget: 600 * time.Millisecond, Over: "the signed promote's own reads and writes, one after another, inside release.PromoteOnLadder: on flagship 470 ms before this branch, one read fewer after it"},
+ "config put": {Calls: 10, Budget: perfWriteBudget},
+ "instances-manifest put": {Calls: 6, Budget: perfWriteBudget},
+ }
+}
+
+// TestPerfWriteRoutesMeetTheBudget: each write door makes at most its
+// recorded S3 requests on every request, and (in CI, as the walk's timing
+// is) its median over three requests answers within its budget after the
+// body is read. A first request runs before the three, since a door's
+// first use in a process can read a remembered object once.
+func TestPerfWriteRoutesMeetTheBudget(t *testing.T) {
+ w := newPerfWritesFx(t)
+ limits := perfWriteLimits()
+ enforce := perfEnforce()
+ var table []string
+ for _, rt := range perfWriteRoutes() {
+ lim, ok := limits[rt.Name]
+ if !ok {
+ continue // the instance list is the walk's
+ }
+ var times []time.Duration
+ most := 0
+ for n := 0; n < 4; n++ {
+ w.lat.Enable(true)
+ r := rt.Do(t, w, n)
+ w.lat.Enable(false)
+ if r.status != rt.Want {
+ t.Fatalf("%s #%d = %d, want %d:\n%s", rt.Name, n, r.status, rt.Want, r.body)
+ }
+ if len(r.reqs) > lim.Calls {
+ summary, _ := s3Summary(r.reqs)
+ t.Errorf("%s #%d: %d S3 requests, the lock is %d:\n%s", rt.Name, n, len(r.reqs), lim.Calls, summary)
+ }
+ most = max(most, len(r.reqs))
+ if n > 0 {
+ times = append(times, r.afterBody)
+ }
+ }
+ slices.Sort(times)
+ median := times[len(times)/2]
+ table = append(table, fmt.Sprintf("%s\t%d S3 at most\tmedian %s ms after the body\tbudget %v", rt.Name, most, ms(median), lim.Budget))
+ if median > lim.Budget {
+ if enforce {
+ t.Errorf("%s: median %s ms after the body, over its budget of %v", rt.Name, ms(median), lim.Budget)
+ } else {
+ t.Logf("(not enforced locally) %s: median %s ms after the body, over its budget of %v", rt.Name, ms(median), lim.Budget)
+ }
+ }
+ }
+ t.Logf("door\tS3\ttime\tbudget\n%s", strings.Join(table, "\n"))
+}
diff --git a/internal/console/plancaps.go b/internal/console/plancaps.go
index 996e381e7..2324afbfe 100644
--- a/internal/console/plancaps.go
+++ b/internal/console/plancaps.go
@@ -4,7 +4,9 @@ import (
"context"
"errors"
"fmt"
+ "maps"
"net/http"
+ "slices"
"strings"
"time"
@@ -46,7 +48,10 @@ func capMessage(id string, args ...any) string {
// runningThings is the account's live apps (temporary and restoring
// included) plus the instance records of those apps. Trashed apps and their
-// instances do not count. One key-only list of the account's prefix.
+// instances do not count. One key-only list of each counted app's records
+// prefix, all at once, readConcurrency at a time (console-slow-writes): the
+// account's whole prefix, which it listed before, holds every release,
+// channel and data object too, and its pages came one after another.
func (s *Server) runningThings(ctx context.Context, acct *Account) (int, error) {
apps, err := s.store.LiveAppCount(acct.ID)
if err != nil {
@@ -67,15 +72,28 @@ func (s *Server) runningThings(ctx context.Context, acct *Account) (int, error)
if s.cfg.Releases == nil {
return apps, nil
}
- keys, err := s.cfg.Releases.List(ctx, "apps/"+acct.Sqid+"/")
- if err != nil {
- return 0, err
+ counted := slices.Sorted(maps.Keys(liveSet))
+ type listed struct {
+ keys []string
+ err error
}
+ lists := make([]listed, len(counted))
+ forEachLimit(len(counted), readConcurrency, func(i int) {
+ keys, err := s.cfg.Releases.List(ctx, provision.RecordsPrefix(acct.Sqid, counted[i]))
+ lists[i] = listed{keys, err}
+ })
known := map[string]bool{acct.Sqid: true}
instances := 0
- for _, k := range keys {
- if _, app, _, ok := provision.ParseRecordKey(k, known); ok && liveSet[app] {
- instances++
+ for i, app := range counted {
+ if lists[i].err != nil {
+ return 0, lists[i].err
+ }
+ // The same parse the whole-prefix count made, so a key is counted
+ // exactly when it was: a record of this app, one level down.
+ for _, k := range lists[i].keys {
+ if _, keyApp, _, ok := provision.ParseRecordKey(k, known); ok && keyApp == app {
+ instances++
+ }
}
}
return apps + instances, nil
diff --git a/internal/console/reqmemo.go b/internal/console/reqmemo.go
index 842e9f4f3..2eaf9bbf6 100644
--- a/internal/console/reqmemo.go
+++ b/internal/console/reqmemo.go
@@ -3,10 +3,13 @@ package console
import (
"context"
"errors"
+ "log"
"net/http"
+ "strings"
"sync"
"time"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/status"
@@ -17,9 +20,15 @@ import (
// app's instances.json). It lives in the request's context and dies with the
// request: nothing is shared between requests, so nothing here can go stale.
//
-// registerRoute installs it on GET and HEAD requests only. A write door's
-// request has none, so every read a door decides on (liveEdges for
-// placement, the strict box loads) is its own, made when it asks.
+// registerRoute installs it on GET and HEAD requests. A write door's
+// request gets a narrower one (withWriteMemo): only the live edges snapshot
+// and the box reports, which boxes write and the console never does, so no
+// write the door makes can change them under its own request. Every other
+// read a door decides on (a record, a manifest, a pointer) is still its own,
+// made when it asks: a door may write the very object it read a moment ago.
+// Before console-slow-writes a write door had no memo at all, and one
+// instance create read the edges files three times and the box reports
+// twice.
//
// A memoized value is shared by every reader in the request: callers treat
// these results as read-only, as they always have. A failed load is
@@ -32,16 +41,24 @@ type reqMemoKey struct{}
type reqMemo struct {
mu sync.Mutex
entries map[string]*reqMemoEntry
+ // only, when set, is the keys this memo holds: any other key loads
+ // every time, as with no memo (withWriteMemo).
+ only func(key string) bool
}
type reqMemoEntry struct {
done chan struct{}
val any
err error
+ // panicked and panicVal are set when the load panicked: every reader
+ // waiting on it panics with the same value, as the loader did, so a
+ // panic is never a failed read that a caller could answer as "none".
+ panicked bool
+ panicVal any
}
-// errMemoLoadPanicked is what a reader waiting on a load sees when that
-// load panicked.
+// errMemoLoadPanicked is a panicked load's memoized error, for readers
+// that look without waiting (memoFinished).
var errMemoLoadPanicked = errors.New("console: request memo: the load panicked")
// withReqMemo returns ctx with a fresh, empty memo.
@@ -49,11 +66,38 @@ func withReqMemo(ctx context.Context) context.Context {
return context.WithValue(ctx, reqMemoKey{}, &reqMemo{entries: map[string]*reqMemoEntry{}})
}
+// withWriteMemo returns ctx with a fresh, empty memo that holds only the
+// keys writeMemoKey names.
+func withWriteMemo(ctx context.Context) context.Context {
+ return context.WithValue(ctx, reqMemoKey{}, &reqMemo{entries: map[string]*reqMemoEntry{}, only: writeMemoKey})
+}
+
+// writeMemoKey is the keys a write door's memo holds: the live edges
+// snapshot (liveEdges) and the box reports (loadBoxes), objects that boxes
+// write and the console never does.
+func writeMemoKey(key string) bool {
+ return key == "edges" || strings.HasPrefix(key, "boxes:")
+}
+
+// memoOf is ctx's memo when it holds key, nil otherwise.
+func memoOf(ctx context.Context, key string) *reqMemo {
+ m, _ := ctx.Value(reqMemoKey{}).(*reqMemo)
+ if m == nil || (m.only != nil && !m.only(key)) {
+ return nil
+ }
+ return m
+}
+
// memoize is load's answer for key, made at most once per memo. With no
-// memo in ctx, load runs every time. Concurrent readers of one key in one
-// request wait for the first one's load.
+// memo in ctx, or one that does not hold key, load runs every time.
+// Concurrent readers of one key in one request wait for the first one's
+// load, each for no longer than its own ctx allows: a reader whose ctx
+// ends first gets ctx's error, and the load carries on for the others.
+// When the load panics, the loader and every reader waiting on it panic
+// with the same value. Every goroutine that calls memoize could have been
+// the loader, so each already answers a panic from it.
func memoize[T any](ctx context.Context, key string, load func() (T, error)) (T, error) {
- m, _ := ctx.Value(reqMemoKey{}).(*reqMemo)
+ m := memoOf(ctx, key)
if m == nil {
return load()
}
@@ -65,11 +109,25 @@ func memoize[T any](ctx context.Context, key string, load func() (T, error)) (T,
}
m.mu.Unlock()
if ok {
- <-e.done
+ select {
+ case <-e.done:
+ case <-ctx.Done():
+ var zero T
+ return zero, ctx.Err()
+ }
+ if e.panicked {
+ panic(e.panicVal)
+ }
v, _ := e.val.(T)
return v, e.err
}
defer close(e.done)
+ defer func() {
+ if v := recover(); v != nil {
+ e.panicked, e.panicVal = true, v
+ panic(v)
+ }
+ }()
v, err := load()
e.val, e.err = v, err
return v, err
@@ -80,7 +138,7 @@ func memoize[T any](ctx context.Context, key string, load func() (T, error)) (T,
// such load, one still running, or one that failed). It never loads and
// never waits.
func memoFinished[T any](ctx context.Context, key string) (v T, ok bool) {
- m, _ := ctx.Value(reqMemoKey{}).(*reqMemo)
+ m := memoOf(ctx, key)
if m == nil {
return v, false
}
@@ -102,11 +160,14 @@ func memoFinished[T any](ctx context.Context, key string) (v T, ok bool) {
return v, ok
}
-// withReqMemoOnViews gives each GET and HEAD request a memo of its own.
+// withReqMemoOnViews gives each GET and HEAD request a memo of its own,
+// and every other request a write door's (withWriteMemo).
func withReqMemoOnViews(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if readOnlyMethod(r.Method) {
r = r.WithContext(withReqMemo(r.Context()))
+ } else {
+ r = r.WithContext(withWriteMemo(r.Context()))
}
h(w, r)
}
@@ -148,9 +209,30 @@ func (s *Server) loadBoxes(ctx context.Context, st release.Store, prefix string)
// liveEdges is the one read every automatic-eligibility caller makes: the
// edges files joined with box liveness as of now (F1), once per request.
+// The edges files and the box reports are read at once, each fan-out
+// concurrent (readEdgesSnapshotConcurrently, loadBoxes), and joined by
+// edgesfile.JoinLive: the reads and the answer are readLiveEdgesSnapshot's
+// (console-slow-writes). Only the box reports are read when the edges
+// files would not list, as that read made them after; the answer is still
+// the listing's error.
func (s *Server) liveEdges(ctx context.Context) (edgesSnapshot, error) {
return memoize(ctx, "edges", func() (edgesSnapshot, error) {
- return readLiveEdgesSnapshot(ctx, s.cfg.Releases, time.Now())
+ now := time.Now()
+ var (
+ snap edgesSnapshot
+ snapErr error
+ boxes []status.Box
+ complete bool
+ boxesErr error
+ )
+ runConcurrently(
+ func() { snap, snapErr = readEdgesSnapshotConcurrently(ctx, s.cfg.Releases) },
+ func() { boxes, complete, boxesErr = s.loadBoxes(ctx, s.cfg.Releases, "") },
+ )
+ if snapErr != nil {
+ return snap, snapErr
+ }
+ return edgesfile.JoinLive(snap, boxes, complete, boxesErr, now), nil
})
}
@@ -161,3 +243,36 @@ func (s *Server) instancesManifest(ctx context.Context, sqid, app string) (*prov
return provision.GetManifest(ctx, s.cfg.Releases, sqid, app)
})
}
+
+// prefetchLiveEdges starts the request's liveEdges read in the background,
+// for a door that will ask for it later and has independent work to do
+// first (console-slow-writes): the answer lands in the request's memo,
+// where the later ask finds it, or waits for it. With no memo holding the
+// snapshot it does nothing, since a read nobody could find would be
+// wasted. ctx bounds the read: pass the door's own deadline, so a stalled
+// read ends when the door's work would. The returned stop cancels the read
+// if it is still running and waits for it, so nothing the prefetch began
+// outlives the handler: call it before returning. A panic in the read is
+// logged here and kept in the memo, and the later ask panics with it in
+// the handler, as it did when the handler made the read itself: a panic
+// never becomes a failed read that a gate could answer as "no files".
+func (s *Server) prefetchLiveEdges(ctx context.Context) (stop func()) {
+ if s.cfg.Releases == nil || memoOf(ctx, "edges") == nil {
+ return func() {}
+ }
+ pctx, cancel := context.WithCancel(ctx)
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ defer func() {
+ if v := recover(); v != nil {
+ log.Printf("console: prefetch of the live edges snapshot panicked: %v", v)
+ }
+ }()
+ _, _ = s.liveEdges(pctx)
+ }()
+ return func() {
+ cancel()
+ <-done
+ }
+}
diff --git a/internal/console/reqmemo_prefetch_test.go b/internal/console/reqmemo_prefetch_test.go
new file mode 100644
index 000000000..f93584f68
--- /dev/null
+++ b/internal/console/reqmemo_prefetch_test.go
@@ -0,0 +1,154 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// edgesFaultStore is the console's release store with a fault on the edges
+// files' listing, armed only while a test asks: panic panics there, stall
+// waits there until the read's context ends.
+type edgesFaultStore struct {
+ release.Store
+ panic, stall atomic.Bool
+}
+
+func (s *edgesFaultStore) List(ctx context.Context, prefix string) ([]string, error) {
+ if prefix == edgesFilePrefix {
+ if s.panic.Load() {
+ panic("injected: the edges listing panicked")
+ }
+ if s.stall.Load() {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ }
+ return s.Store.List(ctx, prefix)
+}
+
+func edgesFaultFixture(t *testing.T) (*consoleFixture, *edgesFaultStore) {
+ t.Helper()
+ faults := &edgesFaultStore{}
+ fx := newConsoleFixtureWith(t, consoleFixtureOptions{WithKey: true, WrapReleases: func(s release.Store) release.Store {
+ faults.Store = s
+ return faults
+ }})
+ return fx, faults
+}
+
+// TestInstanceCreatePrefetchPanicWritesNothing: when the live edges read
+// that instance create starts early (prefetchLiveEdges) panics, the create
+// fails as it did when the door made that read itself, and no record is
+// written. A recovered panic must never read as "no edges files", which
+// for a named region skips the placement gate (Astra, console-slow-writes
+// round 1, P1).
+func TestInstanceCreatePrefetchPanicWritesNothing(t *testing.T) {
+ perfCaptureLogs(t)
+ fx, faults := edgesFaultFixture(t)
+ now := time.Now()
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ token := cliToken(t, fx, "alice@keymail.dev", "code-prefetch-panic")
+ m := titoManifest()
+ m.Regions = []string{"ie", "uk"}
+ enableInstances(t, fx, "titogo", m)
+
+ faults.panic.Store(true)
+ req, err := http.NewRequest(http.MethodPost, instancesURL(fx, "bab", "titogo"), strings.NewReader(`{"host":"acme.go.tito.io","region":"uk"}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+token)
+ resp, err := http.DefaultClient.Do(req)
+ if err == nil {
+ resp.Body.Close()
+ if resp.StatusCode/100 == 2 {
+ t.Fatalf("create = %d with the edges read panicking, want a failed request", resp.StatusCode)
+ }
+ }
+ faults.panic.Store(false)
+ rec, err := provision.GetRecord(context.Background(), fx.rel, release.OpsAccount, "titogo", "acme.go.tito.io")
+ if err == nil && rec != nil {
+ t.Fatalf("a record was written for acme.go.tito.io although the edges read panicked: %+v", rec)
+ }
+}
+
+// TestMemoWaiterHonoursItsDeadline: a reader waiting on a memoized load that
+// will not finish returns when its own context ends, and the prefetch's
+// stop cancels that load and returns (Astra, console-slow-writes round 1,
+// P1: a stalled prefetch held instance create past its deadline).
+func TestMemoWaiterHonoursItsDeadline(t *testing.T) {
+ fx, faults := edgesFaultFixture(t)
+ faults.stall.Store(true)
+ memo := withWriteMemo(context.Background())
+ stop := fx.srv.prefetchLiveEdges(memo) // the load: no deadline of its own
+ // Let the prefetch become the loader, so the read below waits on it.
+ time.Sleep(20 * time.Millisecond)
+ ctx, cancel := context.WithTimeout(memo, 100*time.Millisecond)
+ defer cancel()
+ start := time.Now()
+ _, err := fx.srv.liveEdges(ctx)
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("liveEdges = %v, want the waiter's own deadline", err)
+ }
+ if waited := time.Since(start); waited > 2*time.Second {
+ t.Fatalf("the waiter returned after %v, want about its 100 ms deadline", waited)
+ }
+ done := make(chan struct{})
+ go func() { stop(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("stop did not return: the stalled prefetch outlived its cancel")
+ }
+}
+
+// TestMemoPanicReachesEveryReader: a load that panicked panics again for a
+// reader that waited on it and for one that asks after it finished.
+func TestMemoPanicReachesEveryReader(t *testing.T) {
+ ctx := withWriteMemo(context.Background())
+ unblock := make(chan struct{})
+ loaderDone := make(chan any, 1)
+ go func() {
+ defer func() { loaderDone <- recover() }()
+ memoize(ctx, "edges", func() (int, error) {
+ <-unblock
+ panic("boom")
+ })
+ }()
+ time.Sleep(20 * time.Millisecond)
+ waiter := make(chan any, 1)
+ go func() {
+ defer func() { waiter <- recover() }()
+ memoize(ctx, "edges", func() (int, error) { return 1, nil })
+ }()
+ time.Sleep(20 * time.Millisecond)
+ close(unblock)
+ if v := <-loaderDone; v != "boom" {
+ t.Errorf("loader recovered %v, want boom", v)
+ }
+ if v := <-waiter; v != "boom" {
+ t.Errorf("waiting reader recovered %v, want boom", v)
+ }
+ func() {
+ defer func() {
+ if v := recover(); v != "boom" {
+ t.Errorf("later reader recovered %v, want boom", v)
+ }
+ }()
+ memoize(ctx, "edges", func() (int, error) { return 1, nil })
+ }()
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index 8526f61e2..fbb878fca 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -1250,6 +1250,10 @@ type Server struct {
// door reads any of it. Tests only: it counts what the door read
// before it answered (rootfs Plan 1 preflight 3.2).
shipBodyWrap func(io.ReadCloser) io.ReadCloser
+ // cliBodyWrap, when non-nil, wraps every CLI door's request body before
+ // its gate runs. Tests only: the write measurements stamp the moment
+ // the console has read a body's last byte (console-slow-writes).
+ cliBodyWrap func(*http.Request) io.ReadCloser
// delegationZone and lookupCNAME are the wildcard-capability door's two
// seams (apidomains.go). delegationZone is cfg.DelegationZone, shape-
// validated and normalized once here (normalizeDelegationZone);
diff --git a/internal/edgesfile/snapshot.go b/internal/edgesfile/snapshot.go
index 9f0273fcb..e8f4a5435 100644
--- a/internal/edgesfile/snapshot.go
+++ b/internal/edgesfile/snapshot.go
@@ -149,11 +149,20 @@ func ReadLiveSnapshot(ctx context.Context, s release.Store, now time.Time) (Snap
// actually read. A skipped read leaves that box's liveness UNKNOWN,
// and unknown is never "stale".
boxes, boxesComplete, err := status.LoadBoxesComplete(ctx, s)
- if err != nil {
+ return JoinLive(snap, boxes, boxesComplete, err, now), nil
+}
+
+// JoinLive is ReadLiveSnapshot's join, for a reader that made its two reads
+// itself: snap is ReadSnapshot's answer (read without error), and boxes,
+// boxesComplete and loadErr are status.LoadBoxesComplete's. The console
+// makes both reads at once (console-slow-writes); the join, its rulings
+// and its once-said diagnostics are this one.
+func JoinLive(snap Snapshot, boxes []status.Box, boxesComplete bool, loadErr error, now time.Time) Snapshot {
+ if err := loadErr; err != nil {
if _, said := livenessSaid.LoadOrStore("load", true); !said {
log.Printf("edges: could not load box snapshots (%v), so no box outside the home counts for automatic region placement until they load", err)
}
- return snap, nil
+ return snap
}
snap.BoxesComplete = boxesComplete
// known is every box with a status object at all; live is the fresh
@@ -206,7 +215,7 @@ func ReadLiveSnapshot(ctx context.Context, s release.Store, now time.Time) (Snap
log.Printf("edges: %d edges file(s) under %s but no fresh box snapshot matched any of them, so automatic region placement sees the home alone (are edges and status in different buckets? see CARLOS_STATUS_BUCKET/CARLOS_STATUS_PREFIX)", len(snap.Files), Prefix)
}
}
- return snap, nil
+ return snap
}
// Snapshot is one read of control/edges/. Complete is false when any
diff --git a/internal/provision/console_slow_writes_census_test.go b/internal/provision/console_slow_writes_census_test.go
new file mode 100644
index 000000000..ab15caf2f
--- /dev/null
+++ b/internal/provision/console_slow_writes_census_test.go
@@ -0,0 +1,38 @@
+package provision
+
+// Record-write census entries for console-slow-writes (the console's slow
+// CLI writes), layered on teamScopedCredentialsWriteCensusInventory (main's
+// newest at 9bcbab0f). Reviewed by the branch author; no record write is
+// added, removed or reclassified, and no write call, key, body or CAS
+// changes.
+//
+// Re-pinned:
+// - Server.runningThings (plan caps): the instance records it counts are
+// listed under each counted app's own records prefix
+// (provision.RecordsPrefix(acct, app), apps/<acct>/<app>/instances/),
+// all at once, instead of under the account's whole prefix
+// (apps/<acct>/). Each listed key passes the same ParseRecordKey, and
+// is counted only when it names the listed app, so the count is the
+// same set of keys. It reads; it writes nothing: key-site, as before,
+// now naming RecordsPrefix beside ParseRecordKey.
+func consoleSlowWritesWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), teamScopedCredentialsWriteCensusInventory()...)
+ replacements := []censusEntry{
+ {"internal/console/plancaps.go", "Server.runningThings", "key-site", "key:ParseRecordKey,key:RecordsPrefix", "dbbc39ec3c46b538f445a5a2920bef22dab3b25eaec51dd1c7f83b0afa75922f"},
+ }
+ for _, r := range replacements {
+ found := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class {
+ panic("console-slow-writes reclassifies " + r.File + ":" + r.Unit)
+ }
+ entries[i], found = r, true
+ }
+ }
+ if !found {
+ panic("console-slow-writes re-pins an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 8ea25dc1b..d4a0bdf29 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := teamScopedCredentialsWriteCensusInventory()
+ inventory := consoleSlowWritesWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 99d370c0f..2373f96be 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -25,3 +25,4 @@ plan14-root-reads-rootfs-overlap-demand.tsv 2cced1b359b64855bacc94c64e0370e6b78c
plan14-root-reads-edge-roll-blip.tsv 886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f
plan14-root-reads-cert-warm-propagation-443.tsv 886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f
plan14-root-reads-console-budget-cold-warm.tsv 886863e79986b005cf52aa11445a49c1bbc3fb9b55bce25915fc21d0e65f1b7f
+plan14-root-reads-console-slow-writes.tsv fe61ef9b2ecbb7d3d2049b8e6c9746ee08d3ea32dc1e65455e126771447f403f
diff --git a/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv b/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv
new file mode 100644
index 000000000..9a8ed87fe
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv
@@ -0,0 +1,7 @@
+# Census overlay console-slow-writes, written by census-propose (#369). census-ruling-console-slow-writes, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-console-slow-writes.md.
+# 0 body, 0 sites, 2 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 ed8f5d8741b31e602b74ed5bc1f91320ae01db4e52fd5ecabfe59a631a61caf0 internal/release/program.go readProgramManifest legacy accepted-legacy accepted-legacy;rev3=census-ruling-console-slow-writes;basis=the wrong-program check reads a release manifest (ManifestKey under the account's own app prefix, the key GetManifest reads) as a stream and stops at maxProgramManifestBytes+1 bytes; the ReadAll is over that capped object-store body, not a file path, and replaces the uncapped GetQualified read; an over-cap manifest fails the check closed like a store error file:ReadAll@302 99903230a8397bb8d35ebf1342109ddb6aef03124d13699b056e1f4c1f1ad8c6
+internal/release/program.go readProgramManifest legacy accepted-legacy accepted-legacy;rev3=census-ruling-console-slow-writes;basis=the wrong-program check reads a release manifest (ManifestKey under the account's own app prefix, the key GetManifest reads) as a stream and stops at maxProgramManifestBytes+1 bytes; the ReadAll is over that capped object-store body, not a file path, and replaces the uncapped GetQualified read; an over-cap manifest fails the check closed like a store error file:ReadAll@302 99903230a8397bb8d35ebf1342109ddb6aef03124d13699b056e1f4c1f1ad8c6
+@coverage internal/edgesfile 208247056835a351b28b1890430de339fd16edc57b2240740a9725958380ee4f
+@coverage internal/release e95c4786456d29b4f5f7100c5a1e994d77627869da655b00deb82e19ee12b7dc
diff --git a/internal/release/program.go b/internal/release/program.go
index 3a0abc570..acb26ac43 100644
--- a/internal/release/program.go
+++ b/internal/release/program.go
@@ -16,10 +16,13 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"log"
"os"
"sort"
"strings"
+ "sync"
+ "sync/atomic"
)
// ArtifactProgram extracts the Go main package path from a binary's debug/buildinfo,
@@ -118,51 +121,151 @@ func ReleaseProgram(files map[string][]byte) (string, error) {
// whose manifest declares one, and that release's version. It skips missing
// manifests (os.ErrNotExist) and manifests that don't parse or validate
// (logging each), returning store errors to fail the check closed.
+//
+// The manifests are read previousProgramReads at a time (console-slow-writes:
+// one after another they were most of a ship's console time), and then
+// judged in the listing's order, exactly as when each was judged as it was
+// read: the first store error in that order fails the check, and the skips
+// before it are logged as they were. Only the waiting overlaps.
+//
+// What is held is bounded, not only the requests: each manifest is
+// streamed and read no further than maxProgramManifestBytes and one byte,
+// so at most previousProgramReads bodies of that size are in memory at
+// once, and once a manifest is judged its worker keeps only the three
+// fields the comparison reads (program, built-at and version). A manifest
+// over the cap fails the check closed, as a store error does: nothing in
+// validateManifest limits a manifest's size, so one too large to read may
+// be a valid release declaring a program, and skipping it would let a
+// mismatched ship through. No ship door writes one within a hundredth of
+// the cap.
func PreviousProgram(ctx context.Context, s Store, acct, app string) (string, string, error) {
vers, _, err := VersionCandidates(ctx, s, acct, app, 20)
if err != nil {
return "", "", err
}
- var best *Manifest
- for _, v := range vers {
- // Read the manifest using GetQualified, exactly as GetManifest does.
- raw, _, err := GetQualified(ctx, s, ManifestKey(acct, app, v))
- if err != nil {
- if errors.Is(err, os.ErrNotExist) {
- // In-flight release with no manifest yet; skip it.
- continue
- }
+ reads := make([]programRead, len(vers))
+ forEachBounded(len(vers), previousProgramReads, func(i int) {
+ reads[i] = readProgramManifest(ctx, s, acct, app, vers[i])
+ })
+ var best *programRead
+ for i, v := range vers {
+ r := &reads[i]
+ switch {
+ case r.storeErr != nil:
// Store error; fail closed.
- return "", "", err
- }
-
- // Decode and validate the manifest ourselves, separating parse errors
- // (which we skip) from store errors (which fail closed).
- var m Manifest
- if err := json.Unmarshal(raw, &m); err != nil {
- log.Printf("program check: manifest %s/%s: decode error: %v", app, v, err)
+ return "", "", r.storeErr
+ case r.missing:
+ // In-flight release with no manifest yet; skip it.
continue
- }
- if err := validateManifest(&m); err != nil {
- log.Printf("program check: manifest %s/%s: validation error: %v", app, v, err)
+ case r.skip != "":
+ log.Printf("program check: manifest %s/%s: %s", app, v, r.skip)
continue
}
- if m.App != app || m.Version != v {
- log.Printf("program check: manifest %s/%s: declares wrong app/version", app, v)
+ if r.program == "" {
continue
}
-
- if m.Program == "" {
- continue
- }
- if best == nil || m.BuiltAt > best.BuiltAt {
- best = &m
+ if best == nil || r.builtAt > best.builtAt {
+ best = r
}
}
if best == nil {
return "", "", nil
}
- return best.Program, best.Version, nil
+ return best.program, best.version, nil
+}
+
+// previousProgramReads bounds how many manifests PreviousProgram has in
+// flight at once: the console's own fan-out width (its readConcurrency),
+// which is the AWS SDK's idle connections per host.
+const previousProgramReads = 10
+
+// maxProgramManifestBytes is the most of one manifest PreviousProgram
+// reads. A ship door's manifest is a few kilobytes: its largest field,
+// Notes, is capped at MaxNotesLen, and the console's meta part at
+// MaxNotesLen and 8 KiB.
+const maxProgramManifestBytes = 1 << 20
+
+// programRead is one manifest PreviousProgram read: a store error, a
+// missing manifest, a skip (the log line's tail), or the three fields of a
+// valid manifest that the comparison reads.
+type programRead struct {
+ storeErr error
+ missing bool
+ skip string
+ program, builtAt, version string
+}
+
+// readProgramManifest reads and judges one version's manifest for
+// PreviousProgram, separating parse errors (skipped) from store errors
+// and over-cap manifests (which fail closed). It opens the manifest with
+// OpenQualified, the same key and the same not-found answer GetManifest's
+// GetQualified gives, and reads no further than maxProgramManifestBytes
+// and one byte.
+func readProgramManifest(ctx context.Context, s Store, acct, app, v string) programRead {
+ rc, _, err := OpenQualified(ctx, s, ManifestKey(acct, app, v))
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return programRead{missing: true}
+ }
+ return programRead{storeErr: err}
+ }
+ raw, err := io.ReadAll(io.LimitReader(rc, maxProgramManifestBytes+1))
+ rc.Close()
+ if err != nil {
+ return programRead{storeErr: err}
+ }
+ if len(raw) > maxProgramManifestBytes {
+ return programRead{storeErr: fmt.Errorf("manifest %s/%s is over %d bytes, more than the program check reads", app, v, maxProgramManifestBytes)}
+ }
+ var m Manifest
+ if err := json.Unmarshal(raw, &m); err != nil {
+ return programRead{skip: fmt.Sprintf("decode error: %v", err)}
+ }
+ if err := validateManifest(&m); err != nil {
+ return programRead{skip: fmt.Sprintf("validation error: %v", err)}
+ }
+ if m.App != app || m.Version != v {
+ return programRead{skip: "declares wrong app/version"}
+ }
+ return programRead{program: m.Program, builtAt: m.BuiltAt, version: m.Version}
+}
+
+// forEachBounded runs fn(i) for every i in [0, n), at most limit at a time,
+// and returns when all have. A panic in one is raised again on the caller's
+// goroutine once all have returned, as it would have been had the calls run
+// in sequence.
+func forEachBounded(n, limit int, fn func(i int)) {
+ if n <= 0 {
+ return
+ }
+ limit = max(1, min(limit, n))
+ var (
+ next atomic.Int64
+ wg sync.WaitGroup
+ panicked atomic.Pointer[any]
+ )
+ for range limit {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ defer func() {
+ if v := recover(); v != nil {
+ panicked.CompareAndSwap(nil, &v)
+ }
+ }()
+ for {
+ i := int(next.Add(1) - 1)
+ if i >= n {
+ return
+ }
+ fn(i)
+ }
+ }()
+ }
+ wg.Wait()
+ if v := panicked.Load(); v != nil {
+ panic(*v)
+ }
}
// ProgramMismatchError is returned when a release attempts to ship a different program
diff --git a/internal/release/program_bound_test.go b/internal/release/program_bound_test.go
new file mode 100644
index 000000000..4b9e5040b
--- /dev/null
+++ b/internal/release/program_bound_test.go
@@ -0,0 +1,148 @@
+package release
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "strings"
+ "sync"
+ "testing"
+)
+
+// boundStore serves the manifests of the versions in huge as endless
+// bodies (spaces, which json reads as whitespace forever) and records how
+// many bytes were taken from each, and the most bytes taken by readers open
+// at the same time.
+type boundStore struct {
+ Store
+ huge map[string]bool
+
+ mu sync.Mutex
+ open, peakOpen int
+ inFlight, peak int64
+ read map[string]int64
+}
+
+type endless struct{}
+
+func (endless) Read(p []byte) (int, error) {
+ for i := range p {
+ p[i] = ' '
+ }
+ return len(p), nil
+}
+
+type countedBody struct {
+ r io.Reader
+ s *boundStore
+ key string
+ n int64
+}
+
+func (c *countedBody) Read(p []byte) (int, error) {
+ n, err := c.r.Read(p)
+ c.s.mu.Lock()
+ c.n += int64(n)
+ c.s.read[c.key] += int64(n)
+ c.s.inFlight += int64(n)
+ c.s.peak = max(c.s.peak, c.s.inFlight)
+ c.s.mu.Unlock()
+ return n, err
+}
+
+func (c *countedBody) Close() error {
+ c.s.mu.Lock()
+ c.s.inFlight -= c.n
+ c.s.open--
+ c.s.mu.Unlock()
+ return nil
+}
+
+func (s *boundStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ var r io.Reader
+ for v := range s.huge {
+ if key == ManifestKey("bab", "console", v) {
+ r = endless{}
+ }
+ }
+ if r == nil {
+ rc, _, err := OpenObject(ctx, s.Store, key)
+ if err != nil {
+ return nil, "", err
+ }
+ defer rc.Close()
+ b, err := io.ReadAll(rc)
+ if err != nil {
+ return nil, "", err
+ }
+ r = strings.NewReader(string(b))
+ }
+ s.mu.Lock()
+ s.open++
+ s.peakOpen = max(s.peakOpen, s.open)
+ s.mu.Unlock()
+ return &countedBody{r: r, s: s, key: key}, "", nil
+}
+
+func (s *boundStore) Get(ctx context.Context, key string) ([]byte, string, error) {
+ if strings.HasSuffix(key, "/manifest.json") {
+ panic("PreviousProgram read a whole manifest through Get: " + key)
+ }
+ return s.Store.Get(ctx, key)
+}
+
+// TestPreviousProgramBoundsWhatItHolds: a manifest that never ends is read
+// no further than the cap and one byte and fails the check closed, at most
+// previousProgramReads are open at once, and the bytes held by open readers
+// never pass that many caps.
+func TestPreviousProgramBoundsWhatItHolds(t *testing.T) {
+ dir := NewDirStore(t.TempDir())
+ art := map[string]Artifact{adoptPlatform: {File: adoptPlatform, SHA256: strings.Repeat("a", 64), Size: 1}}
+ huge := map[string]bool{}
+ for i := 0; i < 20; i++ {
+ v := fmt.Sprintf("v%02d", i)
+ putManifest(t, dir, v, Manifest{Schema: 1, App: "console", Version: v, Kind: "binary",
+ BuiltAt: fmt.Sprintf("2026-01-%02dT00:00:00Z", i+1), Artifacts: art, Program: "example.com/console"})
+ if i%2 == 1 {
+ huge[v] = true // v01, v03, ... v19: v19 is the newest, and endless
+ }
+ }
+ s := &boundStore{Store: dir, huge: huge, read: map[string]int64{}}
+ got, ver, err := PreviousProgram(context.Background(), s, "bab", "console")
+ if err == nil || !strings.Contains(err.Error(), "more than the program check reads") {
+ t.Fatalf("PreviousProgram = %q %q %v, want the over-cap manifest to fail the check", got, ver, err)
+ }
+ for v := range huge {
+ if n := s.read[ManifestKey("bab", "console", v)]; n > maxProgramManifestBytes+1 {
+ t.Errorf("%s: read %d bytes of an endless manifest, want at most %d", v, n, maxProgramManifestBytes+1)
+ }
+ }
+ if s.peakOpen > previousProgramReads {
+ t.Errorf("%d manifests open at once, want at most %d", s.peakOpen, previousProgramReads)
+ }
+ if limit := int64(previousProgramReads) * (maxProgramManifestBytes + 1); s.peak > limit {
+ t.Errorf("open readers held %d bytes at once, want at most %d", s.peak, limit)
+ }
+ if s.open != 0 {
+ t.Errorf("%d manifest readers left open", s.open)
+ }
+}
+
+// TestOversizedValidManifestStillRefusesAProgramChange: the app's only
+// previous release declares its program in a manifest that validates but is
+// over the cap (a long commit field). A ship of another program without
+// --program-change is refused, not let through as if there were no previous
+// program (Astra, console-slow-writes round 2, P2).
+func TestOversizedValidManifestStillRefusesAProgramChange(t *testing.T) {
+ s := NewDirStore(t.TempDir())
+ art := map[string]Artifact{adoptPlatform: {File: adoptPlatform, SHA256: strings.Repeat("a", 64), Size: 1}}
+ putManifest(t, s, "v1", Manifest{Schema: 1, App: "console", Version: "v1", Kind: "binary",
+ BuiltAt: "2026-01-01T00:00:00Z", Artifacts: art, Program: "example.com/console",
+ Commit: strings.Repeat("a", maxProgramManifestBytes)})
+ if _, err := GetManifest(context.Background(), s, "bab", "console", "v1"); err != nil {
+ t.Fatalf("the oversized manifest should still validate: %v", err)
+ }
+ if err := shipWithProgram(t, s, "v2", tinyProgram(t, "example.com/carlos"), false); err == nil {
+ t.Fatal("a ship of another program was let through past an oversized previous manifest")
+ }
+}