console-slow-writes: review fixes (Astra round 1: two P1s, two P2s)
1. P1, the prefetch outlived the instance-create deadline. The prefetch now runs under the door's 15 s context, and a memo reader waiting on another's load returns when its own context ends (the load carries on for the others). TestMemoWaiterHonoursItsDeadline: a stalled edges listing; the waiter returns at its 100 ms deadline and stop() returns. On the old memo it hangs. 2. P1, a prefetch panic could become permission to write. A memoized load that panics now panics again in every reader that waited on it or asks after it, so the handler fails as it did when it made the read itself; the prefetch goroutine still recovers and logs as the loader. Every goroutine that calls memoize could have been the loader, so each already answers a panic from it. TestInstanceCreatePrefetchPanicWrites Nothing drives the registered create route with the edges listing panicking, for a named non-home region: 201 and a record on the old memo, a failed request and no record now. TestMemoPanicReachesEvery Reader covers the memo alone. 3. P2, manifest reads bounded only by workers. readProgramManifest opens the manifest with OpenQualified and reads at most 1 MiB and one byte; an over-cap manifest is skipped as invalid, and a judged read keeps only program, built-at and version. TestPreviousProgramBoundsWhatItHolds: endless manifests read no further than the cap, at most ten open, held bytes within ten caps. 4. P2, JSON write timings started at the client's send. A test-only seam (Server.cliBodyWrap, in cliGate) stamps when the console has read a CLI request body to EOF or its Content-Length, for JSON doors and ship alike; a request with a body and no stamp fails the measurement. Census: readProgramManifest is a new unit (+file:ReadAll over the capped object-store body); overlay re-proposed with its claim, seal b6f3a369 -> ff94c448; card's branch context restored and updated. Not approved here.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
11 files changed,
+422
−56
docs/superpowers/notes/census-proposal-console-slow-writes.md+26 −13internal/console/apiinstances.go+3 −2internal/console/authcli.go+3 −0internal/console/perfwrites_test.go+23 −13internal/console/reqmemo.go+34 −8internal/console/reqmemo_prefetch_test.go+154 −0internal/console/server.go+4 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −1internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv+4 −1internal/release/program.go+41 −18internal/release/program_bound_test.go+129 −0
diff --git a/docs/superpowers/notes/census-proposal-console-slow-writes.md b/docs/superpowers/notes/census-proposal-console-slow-writes.md| index bf2d8e2c3..4cc2ccee1 100644 |
| --- a/docs/superpowers/notes/census-proposal-console-slow-writes.md |
| +++ b/docs/superpowers/notes/census-proposal-console-slow-writes.md |
| @@ -1,32 +1,44 @@ |
| # 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). |
| +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. 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`. |
| +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: `b6f3a369ca91563f1d28a9855b242125fab0e3215066c0fd88a93d731459e43b` → `ff94c4484dff88e5c0583827bdbb900a8f7d1ee35a23a2f7507c244af094195c`. |
| 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. |
| +(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 |
| - 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. |
| + 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 |
| @@ -39,4 +51,5 @@ The record-write census (9B8) gains a layer on main's newest inventory |
| `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. |
| +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/apiinstances.go b/internal/console/apiinstances.go| index b75ec13f3..bbba6063a 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -1280,8 +1280,9 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| // 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())() |
| + // 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 |
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/perfwrites_test.go b/internal/console/perfwrites_test.go| index 7a74d076f..3108d6afb 100644 |
| --- a/internal/console/perfwrites_test.go |
| +++ b/internal/console/perfwrites_test.go |
| @@ -40,7 +40,7 @@ type perfWritesFx struct { |
| 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 is when the console read the last request's body to its end. |
| bodyEnd *atomic.Pointer[time.Time] |
| } |
| @@ -94,8 +94,10 @@ func newPerfWritesFx(t *testing.T) perfWritesFx { |
| 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 }) |
| + 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} |
| } |
| @@ -104,11 +106,10 @@ 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. |
| + // 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 |
| @@ -143,23 +144,32 @@ func (w perfWritesFx) do(t *testing.T, method, path, contentType string, body [] |
| 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 a ship body's reader first answers io.EOF: the |
| -// moment the console has read the whole upload. |
| +// 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 |
| - at *atomic.Pointer[time.Time] |
| + want, n int64 |
| + at *atomic.Pointer[time.Time] |
| } |
| -func (b bodyEndStamp) Read(p []byte) (int, error) { |
| +func (b *bodyEndStamp) Read(p []byte) (int, error) { |
| n, err := b.ReadCloser.Read(p) |
| - if err == io.EOF { |
| + b.n += int64(n) |
| + if err == io.EOF || (b.want > 0 && b.n >= b.want) { |
| now := time.Now() |
| b.at.CompareAndSwap(nil, &now) |
| } |
diff --git a/internal/console/reqmemo.go b/internal/console/reqmemo.go| index ce3eed7b7..2eaf9bbf6 100644 |
| --- a/internal/console/reqmemo.go |
| +++ b/internal/console/reqmemo.go |
| @@ -50,10 +50,15 @@ 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. |
| @@ -86,7 +91,11 @@ func memoOf(ctx context.Context, key string) *reqMemo { |
| // memoize is load's answer for key, made at most once per memo. With no |
| // 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. |
| +// 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 := memoOf(ctx, key) |
| if m == nil { |
| @@ -100,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 |
| @@ -226,10 +249,13 @@ func (s *Server) instancesManifest(ctx context.Context, sqid, app string) (*prov |
| // 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. |
| +// 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() {} |
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 2d8d88c22..2c579ef44 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/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 6bbae64a2..8c11079e0 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -20,4 +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 |
| +plan14-root-reads-console-slow-writes.tsv ff94c4484dff88e5c0583827bdbb900a8f7d1ee35a23a2f7507c244af094195c |
diff --git a/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv b/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv| index 8bdf82343..b941f4cc0 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-console-slow-writes.tsv |
| @@ -1,4 +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 a1032342d51bd566935f47c3fc0076f3dc599a7ffdc888034c42402868ed0a91 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 is skipped as invalid file:ReadAll@302 952fbed30d3b6ebd8c42417fa5388c2d10b992b2b3e27a03de7cd8efd530e63d |
| +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 is skipped as invalid file:ReadAll@302 952fbed30d3b6ebd8c42417fa5388c2d10b992b2b3e27a03de7cd8efd530e63d |
| @coverage internal/edgesfile 208247056835a351b28b1890430de339fd16edc57b2240740a9725958380ee4f |
| -@coverage internal/release d76e3c9c8117fcf62899480b1370da4dc23599321c59195fd0bda9984dd3d261 |
| +@coverage internal/release 6d6fd048ef4ffb0ff7639fb6295db1f976d01f833243f731b5bc8d3c7ae99056 |
diff --git a/internal/release/program.go b/internal/release/program.go| index 7270e5db2..ed7c703f8 100644 |
| --- a/internal/release/program.go |
| +++ b/internal/release/program.go |
| @@ -16,6 +16,7 @@ import ( |
| "encoding/json" |
| "errors" |
| "fmt" |
| + "io" |
| "log" |
| "os" |
| "sort" |
| @@ -125,8 +126,15 @@ func ReleaseProgram(files map[string][]byte) (string, error) { |
| // 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. |
| +// 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 is skipped as one that does not validate: no ship door |
| +// writes one within a hundredth of it. |
| func PreviousProgram(ctx context.Context, s Store, acct, app string) (string, string, error) { |
| vers, _, err := VersionCandidates(ctx, s, acct, app, 20) |
| if err != nil { |
| @@ -136,9 +144,9 @@ func PreviousProgram(ctx context.Context, s Store, acct, app string) (string, st |
| forEachBounded(len(vers), previousProgramReads, func(i int) { |
| reads[i] = readProgramManifest(ctx, s, acct, app, vers[i]) |
| }) |
| - var best *Manifest |
| + var best *programRead |
| for i, v := range vers { |
| - r := reads[i] |
| + r := &reads[i] |
| switch { |
| case r.storeErr != nil: |
| // Store error; fail closed. |
| @@ -150,18 +158,17 @@ func PreviousProgram(ctx context.Context, s Store, acct, app string) (string, st |
| log.Printf("program check: manifest %s/%s: %s", app, v, r.skip) |
| continue |
| } |
| - m := r.m |
| - if m.Program == "" { |
| + if r.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 |
| @@ -169,27 +176,43 @@ func PreviousProgram(ctx context.Context, s Store, acct, app string) (string, st |
| // 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 decoded manifest. |
| +// 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 |
| - m *Manifest |
| + 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 |
| -// (which fail closed). It reads the manifest with GetQualified, exactly as |
| -// GetManifest does. |
| +// (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 { |
| - raw, _, err := GetQualified(ctx, s, ManifestKey(acct, app, v)) |
| + 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{skip: fmt.Sprintf("validation error: manifest is over %d bytes", maxProgramManifestBytes)} |
| + } |
| var m Manifest |
| if err := json.Unmarshal(raw, &m); err != nil { |
| return programRead{skip: fmt.Sprintf("decode error: %v", err)} |
| @@ -200,7 +223,7 @@ func readProgramManifest(ctx context.Context, s Store, acct, app, v string) prog |
| if m.App != app || m.Version != v { |
| return programRead{skip: "declares wrong app/version"} |
| } |
| - return programRead{m: &m} |
| + 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, |
diff --git a/internal/release/program_bound_test.go b/internal/release/program_bound_test.go| new file mode 100644 |
| index 000000000..051058d67 |
| --- /dev/null |
| +++ b/internal/release/program_bound_test.go |
| @@ -0,0 +1,129 @@ |
| +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 skipped, the valid ones still |
| +// answer, 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 || got != "example.com/console" || ver != "v18" { |
| + t.Fatalf("PreviousProgram = %q %q %v, want example.com/console from v18 (v19 is endless and skipped)", 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) |
| + } |
| +} |