console-slow-writes: the slow CLI writes read less, and at once
Measured on newPerfFixture grown toward flagship (lifetimes on, 100 instances across three regions, 20 Go-program releases, 25 ms per S3 request), then fixed in the console's own work: - ship: the wrong-program rule's 20 manifests are read ten at a time (release.PreviousProgram), judged in the listing's order as before. Console work after the upload 975 ms -> ~410 ms; 32 S3 requests. - instance create: the live edges snapshot (edges files and box reports) is read once per write request, concurrently, and while the door's other checks run (a write memo holding only objects boxes write); the host holder reads every other app's record at once; holder and claim checks run together; the plan cap lists each app's records prefix instead of the account's whole prefix. 70 -> 51 S3, 2,050 -> ~590 ms. - app create: the same holder, cap and snapshot changes, and the answer's region lines beside the analytics write-back. ~1,200 -> ~410 ms. - promote: the version's manifest and the pipeline read at once. No write moved or reordered. edgesfile.ReadLiveSnapshot's join is split out as JoinLive (same reads, same rulings). TestPerfWriteRoutesMeetTheBudget locks each write door's S3 count and (in CI) its time after the body. Record-write census: runningThings re-pinned in a branch layer. Root-read census: envelopes internal/release and internal/edgesfile re-pinned, overlay proposed for review, not approved.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+837
−74
docs/superpowers/notes/census-proposal-console-slow-writes.md+42 −0internal/console/apex.go+19 −5internal/console/apicli.go+44 −13internal/console/apiinstances.go+21 −3internal/console/instancesplacement.go+24 −1internal/console/perfquickwins_test.go+36 −7internal/console/perfwrites_test.go+371 −0internal/console/plancaps.go+25 −7internal/console/reqmemo.go+98 −9internal/edgesfile/snapshot.go+12 −3internal/provision/console_slow_writes_census_test.go+38 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv+4 −0internal/release/program.go+101 −25
CI passed — run details
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..bf2d8e2c3 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-console-slow-writes.md |
| @@ -0,0 +1,42 @@ |
| +# Census approval: console-slow-writes |
| + |
| +Ruling `census-ruling-console-slow-writes`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +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. Escalate 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. An escalation goes to the census owner as a decision. |
| + |
| +Seal: `b6f3a369ca91563f1d28a9855b242125fab0e3215066c0fd88a93d731459e43b` → `b6f3a369ca91563f1d28a9855b242125fab0e3215066c0fd88a93d731459e43b`. |
| + |
| +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). It changes no root read and |
| +no census unit: the two envelopes move because two functions in root-binary |
| +packages changed shape, not what they read. |
| + |
| +- `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 |
| + same keys are read with the same `GetQualified`; 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. |
| +- `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. |
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..b75ec13f3 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -1277,6 +1277,11 @@ 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). |
| + defer s.prefetchLiveEdges(r.Context())() |
| m, ok := s.instanceManifest(ctx, w, acct, app) |
| if !ok { |
| return |
| @@ -1460,7 +1465,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 +1489,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 +1667,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/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..7a74d076f |
| --- /dev/null |
| +++ b/internal/console/perfwrites_test.go |
| @@ -0,0 +1,371 @@ |
| +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 ship'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.shipBodyWrap = func(rc io.ReadCloser) io.ReadCloser { return bodyEndStamp{rc, bodyEnd} } |
| + t.Cleanup(func() { fx.srv.shipBodyWrap = 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 the request body's last byte to the first response |
| + // byte, the console's own work once the body is in: for a ship, from |
| + // when the console read the upload's end (perfWritesFx.bodyEnd), for |
| + // the JSON doors, which read their small bodies first, from when the |
| + // client wrote 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) |
| + } |
| + if end := w.bodyEnd.Swap(nil); end != nil { |
| + wrote = *end |
| + } |
| + return perfWriteResult{status: resp.StatusCode, body: string(raw), total: total, afterBody: first.Sub(wrote), |
| + reqs: rec.all(), start: start} |
| +} |
| + |
| +// bodyEndStamp notes when a ship body's reader first answers io.EOF: the |
| +// moment the console has read the whole upload. |
| +type bodyEndStamp struct { |
| + io.ReadCloser |
| + at *atomic.Pointer[time.Time] |
| +} |
| + |
| +func (b bodyEndStamp) Read(p []byte) (int, error) { |
| + n, err := b.ReadCloser.Read(p) |
| + if err == io.EOF { |
| + 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) |
| + } |
| + } |
| +} |
| + |
| +// perfWriteBudget is the write rule (console-budget-cold-warm): a write |
| +// answers within 500 ms of its request body being read. |
| +const perfWriteBudget = 500 * time.Millisecond |
| + |
| +// 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..ce3eed7b7 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,6 +41,9 @@ 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 { |
| @@ -49,11 +61,34 @@ 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. |
| 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() |
| } |
| @@ -80,7 +115,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 +137,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 +186,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 +220,33 @@ 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. 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 and leaves the memo's |
| +// errMemoLoadPanicked for the later ask, which answers it as a failed read. |
| +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/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 982442bca..6bbae64a2 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -20,3 +20,4 @@ plan14-root-reads-region-ha-p1b1.tsv 185170fe393cb565d18a3359dee5ace12676b3e1ade |
| plan14-root-reads-rootfs-apps-3.tsv 4337475617b84cadf26e62a31387b7de1b6e9174bf5e6fa4d191f2d2a024e930 |
| plan14-root-reads-retire-join-units-on-adopt.tsv 9e0c4a0c3c5299f68a046e989f49f35cfd2af82dbc76f2e5f00d15512f101a9d |
| plan14-root-reads-team-scoped-credentials.tsv b6f3a369ca91563f1d28a9855b242125fab0e3215066c0fd88a93d731459e43b |
| +plan14-root-reads-console-slow-writes.tsv b6f3a369ca91563f1d28a9855b242125fab0e3215066c0fd88a93d731459e43b |
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..8bdf82343 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv |
| @@ -0,0 +1,4 @@ |
| +# 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. |
| +@coverage internal/edgesfile 208247056835a351b28b1890430de339fd16edc57b2240740a9725958380ee4f |
| +@coverage internal/release d76e3c9c8117fcf62899480b1370da4dc23599321c59195fd0bda9984dd3d261 |
diff --git a/internal/release/program.go b/internal/release/program.go| index 3a0abc570..7270e5db2 100644 |
| --- a/internal/release/program.go |
| +++ b/internal/release/program.go |
| @@ -20,6 +20,8 @@ import ( |
| "os" |
| "sort" |
| "strings" |
| + "sync" |
| + "sync/atomic" |
| ) |
| // ArtifactProgram extracts the Go main package path from a binary's debug/buildinfo, |
| @@ -118,45 +120,42 @@ 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. A worker |
| +// keeps only the decoded manifest, never its bytes. |
| 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 |
| } |
| + reads := make([]programRead, len(vers)) |
| + forEachBounded(len(vers), previousProgramReads, func(i int) { |
| + reads[i] = readProgramManifest(ctx, s, acct, app, vers[i]) |
| + }) |
| 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 |
| - } |
| + 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) |
| - continue |
| - } |
| - if m.App != app || m.Version != v { |
| - log.Printf("program check: manifest %s/%s: declares wrong app/version", app, v) |
| + case r.skip != "": |
| + log.Printf("program check: manifest %s/%s: %s", app, v, r.skip) |
| continue |
| } |
| - |
| + m := r.m |
| if m.Program == "" { |
| continue |
| } |
| if best == nil || m.BuiltAt > best.BuiltAt { |
| - best = &m |
| + best = m |
| } |
| } |
| if best == nil { |
| @@ -165,6 +164,83 @@ func PreviousProgram(ctx context.Context, s Store, acct, app string) (string, st |
| 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 |
| + |
| +// programRead is one manifest PreviousProgram read: a store error, a |
| +// missing manifest, a skip (the log line's tail), or the decoded manifest. |
| +type programRead struct { |
| + storeErr error |
| + missing bool |
| + skip string |
| + m *Manifest |
| +} |
| + |
| +// readProgramManifest reads and judges one version's manifest for |
| +// PreviousProgram, separating parse errors (skipped) from store errors |
| +// (which fail closed). It reads the manifest with GetQualified, exactly as |
| +// GetManifest does. |
| +func readProgramManifest(ctx context.Context, s Store, acct, app, v string) programRead { |
| + raw, _, err := GetQualified(ctx, s, ManifestKey(acct, app, v)) |
| + if err != nil { |
| + if errors.Is(err, os.ErrNotExist) { |
| + return programRead{missing: true} |
| + } |
| + return programRead{storeErr: err} |
| + } |
| + 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{m: &m} |
| +} |
| + |
| +// 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 |
| // than the app's previous releases without the --program-change override. |
| // |