| index c8dbc4b76..60c90f567 100644 |
| --- a/docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md |
| +++ b/docs/superpowers/plans/2026-10-25-console-perf-2-fixes.md |
| @@ -29,13 +29,14 @@ Every task's requirements include this section. |
| - **S3 requests cost money.** Total S3 requests go down, not just warm-page counts: `TestPerfSessionS3Requests`' ceiling falls (Task 17) and the Console speed table's per-route and background counts fall on flagship. Refresh happens only when someone views the screen (a page GET, a part fetch) or inside a mutation's own request. No timers, no tickers, no per-app or per-box polling, no warm-up at start. A background load is one goroutine per key, started by a view, ended within `viewLoadTimeout`. |
| - **Freshness, verbatim from the spec.** About 30 s for live data (instance health, observed versions, box snapshots, edges, app self-reports, logs, errors and analytics windows): `liveWindow = 30 * time.Second`. About 5 min for data only console writes change (manifests, channels, pipeline, account manifest, settings records): `writtenWindow = 5 * time.Minute`. |
| - **Cached values are immutable.** `viewGet` hands every caller its own copy (`viewClone`). No consumer can change what the next request sees. Pointer fields inside a cached value are never written through. |
| -- **Read your own writes.** A mutation marks its effect after admission (session, CSRF, owner, confirmation, fresh auth, its own validation) and after its write succeeded, before it writes its response. The effect names the entries it changed, across scopes (an app delete also changes the account's Trash). Invalidation bumps each entry's generation, which also covers a load already in flight, so a load that started before the write can never publish. Then only the declared entries are re-read, inside the request. If the re-read fails the mutation still succeeds and the entries stay invalidated: the next GET is a miss. The pre-write value is never served after the user's own write. |
| +- **Read your own writes, by read set** (Task 8). Every cache entry records the object keys its load read and the prefixes it listed. Every acknowledged object-store write invalidates, at once, every entry whose read set covers its key, bumping its generation, which also covers a load already in flight; such a load can never publish. The writing request re-reads those entries before it answers. If the re-read fails, the write still stands and the entries stay invalidated: the next GET is a miss. A refused request writes nothing and so touches nothing. The pre-write value is never served after the user's own write. Two rules keep read sets complete: a cached value holds only object-store facts (routes, SQLite rows and the clock are joined per request), and a load whose key set comes from local state caches one entry per key. A server with no store tracker caches nothing. |
| - **Deferred parts.** The page arrives within 150 ms. A part the cache does not hold renders as a placeholder that a `fetch()` fills, following the Logs tab's pattern (`templates/app_logs.html:66-196`: inline script, an `AbortController` with a 20 s timeout, an `Accept` header). Parts are HTML fragments rendered by the same templates as the page. No new JS framework. With JavaScript off the page is still usable minus that part, and its placeholder says how to see it. A part endpoint runs its page's own full authorization before it touches the cache. Independent reads that remain on a request path run concurrently; removing them is the goal. |
| - **Console security gate order is unchanged:** session, then CSRF, then owner (byte-identical 404), then `requireFreshAuth`. A request the gate refuses starts no load and makes no remote call. |
| - **New routes pass the existing route gates.** Every registration this plan adds gets its line in `internal/console/testdata/claim-routes.txt`, a classification in `claimFixtures` (`claim_invariant_fixtures_test.go:722`) and a probe in `claimReadProbes` (`claim_invariant_probes_read_test.go:112`), in the task that adds it. |
| - **Copy goes through a Luna pass before it is written into a template** (Task 1). House voice: no em dashes (a full stop and a new sentence, continuing in lower case); human text only. No tenant names: neutral names in code, tests and fixtures (`shop`, `example.com`; the existing fixture app `kass`, the claim world's `bab` and `titogo`, and account `ops` may be reused, never newly introduced). |
| - **`over:` records.** Each task deletes the `over:` records of the screens it makes fast, in the same commit, and the walk passes with `CI=1` before that commit. A screen that needs a remote call on a warm GET gets a `calls <n>: <reason>` record only with a reason a reviewer accepts; the target is none. |
| -- **Tests that read a converted page see what a browser sees.** A test that asserts on a screen's body after this plan converts it reads it with `getAssembled` (Task 7), which follows the page's deferred parts the way the loader script does. The task that converts a screen converts that screen's tests and claim probes. |
| +- **Tests that read a converted page see what a browser sees.** The default fixtures (no tracker) read inline, so existing tests keep working unchanged. Tests on a cached server (`newPerfFixture`, the claim world) read bodies with `getAssembled` (Task 7), which follows deferred parts the way the loader script does. The task that converts a screen runs that screen's existing acceptance tests on `newPerfFixture` too: the nav plan's Releases tests at least, as Task 10 lists. Claim probes splice parts. |
| +- **No script inside a deferred fragment** (Task 7). Page behaviour lives in the frame, as an initializer run on load and on `carlos:part`. |
| - **Commit per task.** Every commit message ends with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. |
| - **Amadan tasks:** one per plan task on the branch, advanced as each closes. **Test weights:** a new top-level `internal/console` test of a second or more gets a row in `.amadan/test-weights.tsv`. **Merge main first** before review and before merging, re-run the census card, wait for CI on that tip, merge with `amadan branch merge carlos/platform console-perf-2 -expect <tip> -message "..."`. Never a bare `amadan branch merge`. |
| |
| @@ -45,7 +46,7 @@ Every task's requirements include this section. |
| 2. **A refresh, or a first load, that started before the user's write and finishes after it.** It read the pre-write state and must never publish. Test: Task 6, `TestLoadInFlightAtAWriteNeverPublishes` (both a first load and a refresh); Task 10, `TestPromoteDuringABackgroundRefreshShowsTheNewVersion`. |
| 3. **Two people viewing the same app at once.** The cache shares values across requests; one page decorating channels or versions must not leak into another's or race it. Test: Task 9, `TestConcurrentViewsShareNoState` (run with `-race`). |
| 4. **A refresh that hangs.** S3 stalls for a minute while people keep opening the app. They expect the last reading with its "as of" age, not a pile of goroutines, and the next view after the hang ends to try again. Test: Task 6, `TestHungLoadIsBoundedAndRetried`. |
| -5. **A write whose effect reaches another screen.** Deleting an app changes Trash; an operator's storage approval changes that account's settings page; a CLI promote changes the browser's Releases. A person expects each to show at once. Test: Task 8, `TestWriteEffectsReachOtherScopes`; Task 14, `TestDeletedAppShowsInTrash`; Task 10, `TestCLIPromoteShowsInTheBrowser`. |
| +5. **A write whose effect reaches another screen.** Deleting an app changes Trash; an operator's storage approval changes that account's settings page; a CLI promote changes the browser's Releases. A person expects each to show at once. Test: Task 8, the coverage check in `TestClaimConsoleMutationInvariant` and the warm-before-write cases; Task 14, `TestDeletedAppShowsInTrash` and `TestStoreDecisionShowsOnTheAccount`; Task 10, `TestCLIPromoteShowsInTheBrowser`. |
| |
| --- |
| |
| @@ -56,10 +57,11 @@ Every task's requirements include this section. |
| | `internal/console/pagememo.go` (create) | per-request memo: `withPageMemo`, `memoOnce`. | |
| | `internal/console/viewcache.go` (create) | the view cache: keys, windows, generations, single-flight loads, `wrote`, eviction, quiesce. | |
| | `internal/console/viewparts.go` (create) | `viewMode`, `errViewPending`, `viewGet`, the part tables and handlers, `renderView`, `asOfText`. | |
| -| `internal/console/viewwrites.go` (create) | `viewEffect`, the rule constructors, `viewWrites` (route pattern to effect), `wroteView`. | |
| +| `internal/console/viewtrack.go` (create), `internal/release/store.go` and the `DirStore` file (modify) | the store observer, `StoreTracker`, write sets and the re-read writer. | |
| +| `internal/console/bgwork.go` (create) | `bgWork`: every request-triggered goroutine, so tests can wait for all of them. | |
| | `internal/console/templates/parts.html` (create) | `deferred`, `asof`, `partfailed`, `partloader`, `part_text`. | |
| | `internal/console/claim_routes.go` (modify `:59-69`) | `registerRoute` installs the request memo. | |
| -| `internal/console/server.go`, `view.go`, `appsettings.go`, `deployments.go`, `instancepage.go`, `errorsview.go`, `analyticsview.go`, `accountfleet.go`, `fleets.go`, `ownership.go`, `storepage.go`, `archpage.go`, `pipelinepage.go`, `pendinghandlers.go`, `regiondefault.go`, `regioncandidates.go`, `apisystemupdate.go`, `apiinstances.go`, `accountreview.go`, `instances.go`, `apidomains.go`, `appdomains.go`, `controlplane.go`, `appswap.go`, `apitemporary.go`, `apicli.go` and the other write doors (modify) | screens read through the memo and the cache; mutations call `wroteView`. | |
| +| `internal/console/server.go`, `view.go`, `appsettings.go`, `deployments.go`, `instancepage.go`, `errorsview.go`, `analyticsview.go`, `accountfleet.go`, `fleets.go`, `ownership.go`, `storepage.go`, `archpage.go`, `pipelinepage.go`, `pendinghandlers.go`, `regiondefault.go`, `regioncandidates.go`, `apisystemupdate.go`, `apiinstances.go`, `accountreview.go`, `instances.go`, `apidomains.go`, `appdomains.go`, `controlplane.go`, `appswap.go`, `apitemporary.go`, `apicli.go` and the other write doors (modify) | screens read through the memo and the cache. | |
| | `internal/console/templates/*.html` (modify) | each converted screen's body wrapped in `{{define "<name>_body"}}`, an `asof` line, a placeholder branch. Operator templates are not touched. | |
| | `internal/console/store.go` (modify, Task 16 only if the measurement calls for it) | a read-only pool for the gate's reads. | |
| | `internal/provision/provision.go` (modify) | export `ListRecordHosts` over `recordHosts` (`:2859`). | |
| @@ -101,6 +103,7 @@ Spec §2.4 C rows 1 to 3: `ensureAccountManifest` re-reads on every app tab; `Se |
| |
| **Files:** |
| - Create: `internal/console/pagememo.go`; Test: `internal/console/pagememo_test.go` |
| +- Create: `internal/console/bgwork.go`: `type bgWork struct{…}` with `Go(f func())` and `Wait()`; `Server.bg bgWork`. Every goroutine a request starts runs through `s.bg.Go`: this task's account-manifest check, Task 3's edge-fold refresh, Task 6's view loads and the inner metrics and economics sweeps, so a test can wait for all of them (Task 6's `waitBackground`). |
| - Modify: `internal/console/claim_routes.go:59-69` (`registerRoute`) |
| - Modify: `internal/console/server.go`: `account` (`:2426`), `accountPage` (`:3344`, `:3353`), `memberAccount` (`:2361`), `ensureAccountManifest` (`:4087-4103`), `appPage` (`:3406`, `:3424`) |
| - Modify: `internal/console/accountreview.go:37`, `:41` (`appAccountReview` gains `ctx context.Context` as its first parameter) |
| @@ -113,9 +116,9 @@ Spec §2.4 C rows 1 to 3: `ensureAccountManifest` re-reads on every app tab; `Se |
| - `func memoOnce[T any](ctx context.Context, key string, f func() (T, error)) (T, error)`: the first call per key per request runs `f`; later calls return its result (error included); with no memo in `ctx` it just runs `f`. |
| - `var pageMemoHits atomic.Int64`: incremented on every memo hit (read by tests). |
| - `func (s *Server) accountsFor(ctx context.Context, addr string) ([]Account, error)` (memo key `accounts:<addr>`) and the package-level `func memoRoutes(ctx context.Context, regPath string) ([]registry.Route, error)` (memo key `routes:<regPath>`, through `openRegistry`), so `Assemble` and `appAccountReview` share one route read. Every page-path caller of `s.store.AccountsFor` and of `reg.List()` with a request context uses these. Callers copy before sorting or appending. |
| - - `func (s *Server) ensureAccountManifestLater(acct *Account)`: replaces the synchronous call at `server.go:3406`. It returns at once. When `Server.manifestSeen` (a `sync.Map`, sqid to `struct{}`) does not hold the sqid and no check is running for it, it starts one goroutine that runs today's `ensureAccountManifest` body on `context.WithTimeout(context.Background(), viewLoadTimeout)` and records the sqid on success. The check is still triggered only by a view. *(My call: the backfill is best-effort today; moving it off the response path keeps that and removes the only remote read left in the gates.)* |
| + - `func (s *Server) ensureAccountManifestLater(acct *Account)`: replaces the synchronous call at `server.go:3406`. It returns at once. When `Server.manifestSeen` (a `sync.Map`, sqid to `struct{}`) does not hold the sqid and no check is running for it, it starts one goroutine (through `s.bg.Go`, Task 6) that runs today's `ensureAccountManifest` body on `context.WithTimeout(context.Background(), viewLoadTimeout)` and records the sqid on success. The check is still triggered only by a view. *(My call: the backfill is best-effort today; moving it off the response path keeps that and removes the only remote read left in the gates.)* |
| - `func (s *Server) noteLastAccount(addr string, id int64) (wrote bool)`: writes `SetLastAccount` only when `Server.lastAccount` (a `sync.Map` addr to id, filled on write and by `memberAccount`'s `LastAccount` read) differs from `id`. |
| - - test-only, on plan 1's `perfLatency`, all built on the S3 fake's `OnRequest` hook so they act on real HTTP requests: `Keys() []string` (the object key of every `GetObject`, `PutObject` and `DeleteObject` and the prefix of every `ListObjectsV2`, in order); `ResetKeys()`; `SetFail(match func(key string) bool)` (a matching request answers 500 after counting; nil clears it); `HoldNext(op string, match func(key string) bool) (held <-chan struct{}, release func())` with `op` `"get"` or `"list"` (the next matching request, and only that one, is read by the fake, then closes `held` and waits for `release` before its response is written, so it returns what was read before the hold); `OnPut(f func(key string))` (runs after each `PutObject` has been stored). Later tasks use these by name. |
| + - test-only, on plan 1's `perfLatency`, all built on the S3 fake's `OnRequest` hook so they act on real HTTP requests: `Keys() []string` (the object key of every `GetObject`, `PutObject` and `DeleteObject` and the prefix of every `ListObjectsV2`, in order); `Writes() []string` (the keys of the `PutObject` and `DeleteObject` requests alone, in order: the write oracle Task 8 checks against); `ResetKeys()` (clears both logs); `SetFail(match func(key string) bool)` (a matching request answers 500 after counting; nil clears it); `HoldNext(op string, match func(key string) bool) (held <-chan struct{}, release func())` with `op` `"get"` or `"list"` (the next matching request, and only that one, is read by the fake, then closes `held` and waits for `release` before its response is written, so it returns what was read before the hold); `OnPut(f func(key string))` (runs after each `PutObject` has been stored). Later tasks use these by name. |
| |
| `registerRoute` wraps every handler with `withPageMemo` inside the mux (the mux has already set the pattern for plan 1's perf middleware) and keeps its existing claim-entry wrapping and order. |
| |
| @@ -144,7 +147,7 @@ Spec §2.4 C rows 5 to 7, plus two wasted reads the 2026-10-25 inventory found. |
| |
| **Interfaces:** |
| - Produces: |
| - - `foldedEdgeIPs` never waits on a fold: it returns the last fold (or nothing before the first) and, when the fold is older than `edgeFoldTTL` and none is running, starts one in a goroutine. The empty-fold rule (`:1281-1286`) is kept. The fold is still triggered only by a request. |
| + - `foldedEdgeIPs` never waits on a fold: it returns the last fold (or nothing before the first) and, when the fold is older than `edgeFoldTTL` and none is running, starts one in a goroutine (through `s.bg.Go`, Task 6). The empty-fold rule (`:1281-1286`) is kept. The fold is still triggered only by a request. |
| - `AppView.PipelineErr error`: set by `applyPipelineView` when the read fails, so `Pipeline == nil && PipelineErr == nil` means "no pipeline". `func pipelineOf(view *AppView) (*release.Pipeline, error)` replaces the second `GetPipeline` in `pendingPipeline`'s callers (the Overview and the Releases page's pending section) and in `handlePipelineSettingsPage`. |
| - `var versionsTimeout = instanceStoreTimeout`: `Versions` and the nav plan's `VersionsPage` wrap their `ctx` with it. |
| - Account settings resolve the account level only: `telemetry.Read(ctx, s.cfg.Releases, telemetry.AccountKey(sqid))` folded with `telemetry.Fold(acct, telemetry.Settings{})`, instead of `telemetry.Resolve(…, "")`, which reads `apps/<sqid>//telemetry.json`, a key nothing writes. |
| @@ -233,26 +236,29 @@ Spec §2.4 C rows "Settings, `populateAppSettings`", "`appDeployEmpty`" and "`en |
| **Files:** |
| - Create: `internal/console/viewcache.go`; Test: `internal/console/viewcache_test.go` |
| - Modify: `internal/console/server.go` (`Server.views *viewCache`, set in `NewServer` to `newViewCache(s.now, viewCacheMax)`; `Server.now func() time.Time`, `time.Now` by default, the clock every request-time derivation in Tasks 9 to 14 reads) |
| -- Modify: `internal/console/perfwalk_test.go` (`perfQuiesce = func(fx *consoleFixture) { fx.srv.views.quiesce() }`; `perfColdReset = func(fx *consoleFixture) { fx.srv.resetForColdView() }`; `newPerfFixture` sets `fx.clock` and points `fx.srv.now` at it) |
| -- Create: `internal/console/viewreset_test.go`: `func (s *Server) resetForColdView()` (test-only) gives the server what a restart would: a fresh `newViewCache(s.now, viewCacheMax)`, an empty `manifestSeen`, an unset edge fold, and empty inner caches in `LoadMetrics` and `LoadEconomics`. |
| +- Modify: `internal/console/perfwalk_test.go` (`perfQuiesce = func(fx *consoleFixture) { fx.srv.waitBackground() }`; `perfColdReset = func(fx *consoleFixture) { fx.srv.resetForColdView() }`; `newPerfFixture` sets `fx.clock` and points `fx.srv.now` at it) |
| +- Modify: `internal/console/metricsview.go:361`, `internal/console/economicsview.go:288-300` (their own background sweeps run through `s.bg.Go`, Task 2's `bgWork`, as view loads do from this task on). |
| +- Create: `internal/console/viewreset_test.go`: `func (s *Server) waitBackground()` (test-only: `s.bg.Wait()`) and `func (s *Server) resetForColdView()` (test-only), which first waits for background work and then gives the server what a restart would: a fresh `newViewCache(s.now, viewCacheMax)`, an empty `manifestSeen`, an unset edge fold, and empty inner caches in `LoadMetrics` and `LoadEconomics`. `perfQuiesce` is `fx.srv.waitBackground()`, so counts and resets never run while a request-triggered worker is still reading. *(Astra round 3, finding 9.)* |
| |
| **Interfaces:** |
| - Produces: |
| - - `type viewKey struct { Acct, App, Part string }`: `Acct` is the account sqid, `""` for deployment-wide entries; `App` is `""` for account-wide entries; `Part` names the read and, for filtered reads, carries the normalized query (`logs?host=a&since=1h`). |
| + - `type viewKey struct { Acct, App, Part string }`: `Acct` is the account sqid, `""` for deployment-wide entries; `App` is `""` for account-wide entries; `Part` names the read and, for filtered reads, carries the filter key (Task 12). |
| + - part-name constants used by every later task: `partCore`, `func versionsPart(page int) string` (`versions?page=<n>`), `partTags`, `partRetention`, `partInstancesManifest`, `partAppReport`, `partTelemetry`, `partGates`, `partClaims`, `partCertWarm`, `partCatchall`, `partDeployEmpty`, `partEnvs`, `partStore`, `partMail`, `partFeatures`, `partSwap`, `partRecordHosts`, `partApps`, `func trashPart(app string) string` (one tombstone per entry, see Task 8's second rule), `partEntitlement`, `partAccountTelemetry`, `func fleetBoxesPart(fleet string) string`, `partFleetJSON`, `partBoxes`, `partEdges`, `partMetrics`, `func economicsPart(period string) string`, `partStorePending`, `partStoreUsage`, `partArchitecture`. |
| - `const (liveWindow = 30 * time.Second; writtenWindow = 5 * time.Minute; viewCacheMax = 4096)` and `var viewLoadTimeout = 15 * time.Second` (a var so a test can shorten it). |
| - `type viewCloner[T any] interface { viewClone() T }`: every cached type implements it, copying every slice and map it holds (pointer fields are shared and read-only). |
| - `type viewResult[T any] struct { Val T; At time.Time; Stale bool }` |
| - `func newViewCache(now func() time.Time, max int) *viewCache` |
| - `func viewPeek[T viewCloner[T]](c *viewCache, key viewKey, window time.Duration, load func(context.Context) (T, error)) (viewResult[T], bool)`: never blocks. A valid entry returns a clone and `true`, with `Stale` when older than `window`, in which case a refresh is started unless one is running at the entry's current generation. A missing or invalid entry returns `false` and starts a load unless one is running at the current generation. |
| - `func viewWait[T viewCloner[T]](ctx context.Context, c *viewCache, key viewKey, window time.Duration, load func(context.Context) (T, error)) (viewResult[T], error)`: a valid entry returns a clone at once; otherwise joins the load running at the current generation or starts one, and waits for it or for `ctx`. |
| - - `type viewEffect struct { Reread []viewKey; Drop func(viewKey) bool; Before []func() }` (built by Task 8's constructors). `Before` runs inside `wrote`, after the generations are bumped and before the re-reads, for a value that also sits in a cache below the view cache (Task 15's economics). |
| - - `func (c *viewCache) wrote(ctx context.Context, e viewEffect) (failed int)`: first (then `e.Before`), for every entry whose key is in `e.Reread` or matches `e.Drop` (an entry exists from the moment its first load starts), bump its generation and mark it invalid; a load that started at an older generation, first load or refresh, then discards its result. Second, for each key in `e.Reread` that has an entry, start a load at the new generation; all run concurrently under `ctx`, and `wrote` waits for them. A success publishes; a failure leaves the entry invalid and counts in `failed`. A key nobody has viewed has no entry and costs nothing. |
| - - `func (c *viewCache) quiesce()`: waits until no load is running (tests). |
| + - read sets: every entry carries `type readSet struct { keys map[string]bool; prefixes []string }`, the object keys its load read and the prefixes it listed, filled while the load runs by Task 8's tracker through the load's context (`withReadSet(ctx, *readSet) context.Context`). A new load of an entry starts with an empty set. |
| + - `func (c *viewCache) touched(key string) []viewKey`: for every entry whose read set holds `key` or a prefix of it (an entry exists, with its set, from the moment its first load starts), bump its generation and mark it invalid; a load that started at an older generation, first load or refresh, then discards its result. Returns the entries it invalidated. |
| + - `func (c *viewCache) reread(ctx context.Context, keys []viewKey) (failed int)`: for each key that has an entry, start a load at its current generation; all run concurrently under `ctx`, and `reread` waits for them. A success publishes; a failure leaves the entry invalid and counts in `failed`. |
| + - `func (c *viewCache) snapshot() []viewEntryInfo` (test-only: key, generation, valid, read set), for Task 8's coverage check. |
| - `func asOfText(now, at time.Time) string`: CPF-20 with CPF-21 to CPF-25 (under a minute, 1 minute, n minutes, 1 hour, n hours). |
| |
| The rules the implementation keeps: |
| -- A load runs in its own goroutine on `context.WithTimeout(context.Background(), viewLoadTimeout)`, never on a request's context, so a closed tab does not cancel a load other viewers share and no span lands on a finished request. (Its S3 requests are counted in `Server.PerfBackground()` by plan 1's `TimeDoer`.) `wrote`'s loads run on the mutation's own context, bounded the same way. |
| -- Each entry stores its loader (as `func(context.Context) (any, error)`) so `wrote` can re-run it, plus its value, `At`, generation and the generation of the load in flight, if any. Single flight is per key and generation. |
| +- A load runs in its own goroutine (through `s.bg.Go`) on `context.WithTimeout(context.Background(), viewLoadTimeout)`, never on a request's context, so a closed tab does not cancel a load other viewers share and no span lands on a finished request. (Its S3 requests are counted in `Server.PerfBackground()` by plan 1's `TimeDoer`.) `reread`'s loads run on the mutation's own context, bounded the same way. |
| +- Each entry stores its loader (as `func(context.Context) (any, error)`) so `reread` can re-run it, plus its value, `At`, generation and the generation of the load in flight, if any. Single flight is per key and generation. |
| - A refresh that fails leaves the previous valid value in place (the next view retries once the window has passed again) but never makes an invalid entry valid. |
| - Over `max` entries, the least recently used entries with no load in flight are dropped. |
| - Nothing runs on a timer, and no goroutine outlives its load. |
| @@ -262,18 +268,19 @@ The rules the implementation keeps: |
| - `TestViewPeekStaleServesAndRefreshesOnce`: after `window` passes, three peeks return the old value with `Stale` and the loader runs once more. |
| - `TestViewWaitJoinsTheRunningLoad`: a peek starts a blocked load; `viewWait` waits; releasing the loader returns its value to both, with one run. |
| - `TestViewWaitHonoursItsContext`: a blocked loader and a 20 ms `ctx`: `viewWait` returns `ctx.Err()`. |
| - - `TestLoadInFlightAtAWriteNeverPublishes`: two sub-tests. *First load:* a peek on a miss starts a load that blocks after reading value A; `wrote` with that key in `Reread` and a loader now answering B; release the first load; the entry holds B, never A, at any point a peek can see. *Refresh:* the same with a warm stale entry whose refresh reads A. |
| - - `TestWroteRereadsOnlyDeclaredKeys`: three keys loaded; `wrote` naming one in `Reread` and a second through `Drop`; only the first loader runs again; the second is invalid (next peek misses); the third is untouched. |
| - - `TestWroteFailureLeavesEntryInvalid`: the re-read fails; `failed == 1`; the next peek is a miss, not the pre-write value. |
| + - `TestLoadInFlightAtAWriteNeverPublishes`: two sub-tests. *First load:* a peek on a miss starts a load that records key `k` in its read set, reads value A and blocks; `touched("k")` then `reread` with a loader now answering B; release the first load; the entry holds B, never A, at any point a peek can see. *Refresh:* the same with a warm stale entry whose refresh reads A. |
| + - `TestTouchedCoversExactKeysAndListedPrefixes`: three entries, one that read `a/x`, one that listed `a/`, one that read `b/y`; `touched("a/x")` invalidates the first two and not the third; `touched("a/z")` invalidates only the lister. |
| + - `TestRereadFailureLeavesEntryInvalid`: the re-read fails; `failed == 1`; the next peek is a miss, not the pre-write value. |
| + - `TestBackgroundWaitCoversEveryWorker`: a view load, a `bg.Go` worker and a held loader; `waitBackground` returns only after all three end. |
| - `TestHungLoadIsBoundedAndRetried`: with `viewLoadTimeout` shortened to 50 ms, a loader that blocks until its context ends; while it runs, peeks start no second goroutine; after it ends, the next peek of the stale entry starts one. |
| - `TestViewKeysAreAccountScoped`: `{Acct: "a", App: "api"}` and `{Acct: "b", App: "api"}` hold different values. |
| - `TestViewCacheEvictsLeastRecentlyUsed`: `max` 3; four keys loaded; the least recently peeked is gone; an entry mid-load is not evicted. |
| - `TestViewValuesAreCopies`: changing a slice element of a peeked value does not change the next peek's value. |
| - `TestAsOfText`: 20 s → CPF-20 with CPF-21; 60 s → CPF-22; 150 s → CPF-23 with 2; 1 h → CPF-24; 3 h → CPF-25 with 3 (approved text verbatim). |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestView|TestLoadInFlight|TestWrote|TestHungLoad|TestAsOfText' -count=1 -race`. Expected: FAIL. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestView|TestLoadInFlight|TestTouched|TestRereadFailure|TestBackgroundWait|TestHungLoad|TestAsOfText' -count=1 -race`. Expected: FAIL. |
| - [ ] **Step 3: Implement**; add CPF-20 to CPF-25 to `consolePerfCopyBuilt`; set `perfQuiesce` and the fixture clock. |
| - [ ] **Step 4: Run** Step 2's command and `go test . -run TestConsolePerfCopy -count=1`. Expected: PASS. |
| -- [ ] **Step 5: Commit**, message `console: in-process view cache: view-triggered single-flight refresh, generations that cover in-flight loads, immutable values`, ending with the Co-Authored-By line. |
| +- [ ] **Step 5: Commit**, message `console: in-process view cache: view-triggered single-flight refresh, read sets, generations that cover in-flight loads, immutable values`, ending with the Co-Authored-By line. |
| |
| ### Task 7: Deferred parts |
| |
| @@ -299,7 +306,9 @@ The rules the implementation keeps: |
| - test-only: `func getAssembled(t *testing.T, c *http.Client, u string) (status int, body string)`: GET `u`; then, up to five rounds, replace each `<div class="deferred" data-part="X">…</div>` with the body of a GET of `X` on the same client, as the loader script does. `claimPageRead` uses the same splice, so claim probes assert on the assembled page. |
| - test-only: `func registerProbePart(t *testing.T, key viewKey, objectKey string)`: adds an app part `probe` (gate: `appPage`'s) whose `Fill` reads `objectKey` from `s.cfg.Releases` through `viewGet` (`writtenWindow`) into `p.Msg` and renders `part_text`; removed in `t.Cleanup`. Tests that use it are not parallel. |
| |
| -The loader script, in the Logs tab's style: for each `[data-part]` element, `fetch(el.dataset.part, {headers: {Accept: "text/html"}, signal})` with an `AbortController` aborting after 20 s; on `ok` replace the element's `outerHTML` with the response text; otherwise (or on abort) replace it with the response text when there is one, else with CPF-28. No polling and no retry: a part is fetched once per page view. With JavaScript off the `<noscript>` text stands, and a reload is a warm view because the miss started the load. |
| +The loader script, in the Logs tab's style: for each `[data-part]` element, `fetch(el.dataset.part, {headers: {Accept: "text/html"}, signal})` with an `AbortController` aborting after 20 s; on `ok` replace the element's `outerHTML` with the response text; otherwise (or on abort) replace it with the response text when there is one, else with CPF-28. After each replacement it dispatches `document.dispatchEvent(new CustomEvent("carlos:part", {detail: {part: <the part URL>, root: <the inserted element>}}))`. This plan owns that event; the operator-pages plan uses the same one. No polling and no retry: a part is fetched once per page view. |
| + |
| +**No script inside a deferred fragment.** A fragment inserted with `outerHTML` does not run its `<script>` elements, so a template rendered as a part never contains one. A page's behaviour lives in its frame as an initializer that runs once on `DOMContentLoaded` over the whole document and again on every `carlos:part` over `event.detail.root`, finds its elements by id or attribute inside the root it is given, and never uses `document.currentScript`. *(Astra round 3, finding 5.)* With JavaScript off the `<noscript>` text stands, and a reload is a warm view because the miss started the load. |
| |
| Every screen converted in Tasks 9 to 14 follows one shape: its template becomes `{{define "<name>"}}{{template "top" .}}…chrome (flash, appnav, banners, page head)…{{if .Deferred}}{{template "deferred" .}}{{else}}{{template "<name>_body" .}}{{end}}{{template "bottom" .}}{{end}}` and `{{define "<name>_body"}}{{template "asof" .}}…the existing body…{{end}}`; its handler becomes the gate, `Fill(viewCached)`, `renderView`; its part entry reuses the same `Gate`, `Fill` and `<name>_body`. *(My call: on a miss the whole body is the deferred part, except where a section can render without the missing data, which Tasks 10, 11 and 13 make parts of their own: Releases' Versions, Running's app self-report and Domains' box readings. The change to each template stays at its first and last lines.)* |
| |
| @@ -310,91 +319,66 @@ Every screen converted in Tasks 9 to 14 follows one shape: its template becomes |
| - `TestDeferredPartialsCarryTheirCopy`: executing `deferred` with `page{Deferred: "/x"}` gives `data-part="/x"`, CPF-26, and CPF-27 inside `<noscript>`; `asof` with a zero `AsOf` gives nothing and with one three minutes old gives CPF-20 with CPF-23. |
| - `TestAsOfShowsOnStaleData`: with `fx.clock` moved past `writtenWindow`, the part still answers `one` and now carries CPF-20. |
| - `TestGetAssembledFollowsParts`: a body holding one `deferred` div for the probe assembles to `one`. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEveryPartGates|TestPartRenders|TestPartFailure|TestDeferredPartials|TestAsOfShows|TestGetAssembled' -count=1`. Expected: FAIL. |
| + - `TestNoDeferredFragmentHasAScript`: on `newPerfFixture` with every seed, for every key of `appParts` and `accountParts` (the tables, so later parts are covered without an edit) and every target `perfTargets` gives it, the fragment's body contains no `<script` (case-insensitive). Tasks 9 to 14 keep it passing. |
| + - `TestPartLoaderFiresTheEvent`: the rendered `partloader` contains `carlos:part` and dispatches it after the `outerHTML` replacement (a source assertion on the partial; no browser in CI). |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEveryPartGates|TestPartRenders|TestPartFailure|TestDeferredPartials|TestAsOfShows|TestGetAssembled|TestNoDeferredFragmentHasAScript|TestPartLoaderFiresTheEvent' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Implement**; add CPF-26 to CPF-28 to `consolePerfCopyBuilt`. Add `route GET /a/{sqid}/apps/{app}/part/{part}` and `route GET /a/{sqid}/part/{part}` to `claim-routes.txt` in its sorted place; `claimFixtures` entries `claimRead("deferred part of an app page; the page's own gate")` and `claimRead("deferred part of an account page; the page's own gate")`; `claimReadProbes` entries `claimPageRead(nil, "/a/bab/apps/titogo/part/<a part Task 9 adds>", <its marker>)` and the account equivalent (until Tasks 9 and 14 add parts, point them at an unknown part name and expect the 404, then repoint them in those tasks). Add the two routes to `perfTargets` (one target per key of each table) and record each `deferred: deferred part`. |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestClaimRouteInventory|TestClaimFixture|TestClaimRead' -count=1`, `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`, `go test . -run TestConsolePerfCopy -count=1`, and the walk with `CI=1`. Expected: PASS. |
| - [ ] **Step 5: Commit**, message `console: deferred parts behind their page's own gate; loader script; route census entries`, ending with the Co-Authored-By line. |
| |
| -### Task 8: Mutations declare their effect; the cache re-reads it inside the request |
| +### Task 8: A write invalidates exactly what it touched; the request re-reads it before answering |
| + |
| +The design, and why it replaces the declared-effect table. Three review rounds found effects missing from a hand-kept table (R1-2, R2-4, R3-3), each the same class: a write changed a key some cached read depended on, and nobody listed the pair. So the console now records the dependency instead of declaring it. Every cache entry records the keys its load read and the prefixes it listed (its read set). Every successful object-store write reports its key. A write invalidates, at once, every entry whose read set holds that key or a prefix of it. The request that wrote then re-reads those entries before it answers. Correctness then rests on two things a test can check directly, rather than on a list that has to be complete: |
| + |
| +1. **Every object-store access is reported.** The two stores the console runs on report every access through one hook. A table test covers every exported method, and fails when a method is added without coverage. |
| +2. **Two caching rules hold:** |
| + - **(a) A cached value holds only facts read from the object store.** Anything joined from local state is joined per request, from the cached facts. That covers registry routes, SQLite rows and the clock. Task 9 does this for bake state and the production nudge. Task 13 does it for the route-derived hosts in `partEnvs`. |
| + - **(b) A load whose set of keys comes from local state caches one entry per key.** Trash reads one tombstone per trashed app named in SQLite, so it caches one entry per tombstone (`trashPart(app)`). A newly trashed app is then a miss, never a stale list. |
| + |
| +What the read sets cannot see (data the cache does not hold) needs no effect, because the cache holds only object-store reads. Writes made by other processes are still covered by the windows. *(Session lead's request, round 3: "choose the simpler-to-prove design and say why". This is it. The declared table, `wroteView` and its census go.)* |
| + |
| +Admission falls out of the design. A refused request (session, CSRF, owner, confirmation page, validation error) writes nothing, so it invalidates nothing and re-reads nothing. A request that writes and then fails invalidates exactly what it wrote, which is correct. |
| |
| **Files:** |
| -- Create: `internal/console/viewwrites.go`; Test: `internal/console/viewwrites_test.go` |
| -- Modify: `internal/console/claim_invariant_test.go` (`runClaimDoor` and its caller at `:312-340`: the mark witness) |
| -- Modify: every write door's handler (browser POSTs in `server.go`, `appsettings.go`, `appdomains.go`, `errorsview.go`, `analyticsview.go`, `controlplane.go`, `appswap.go`, `apitemporary.go`, `fleets.go`, `pipelinepage.go`, `pendinghandlers.go`, `ownership.go`, `storepage.go`, `economicspass.go`, `archpage.go`; the CLI's write doors in `apicli.go` and the `api*.go` files) |
| +- Modify: `internal/release/store.go` (`S3Store`: `SetObserver`, a report from each exported method), the `DirStore` file (`DirStore`: the same), `internal/release/changeindex.go` (the index's own raw read and write report too) |
| +- Create: `internal/release/observer_test.go` |
| +- Create: `internal/console/viewtrack.go`; Test: `internal/console/viewtrack_test.go` |
| +- Modify: `internal/console/server.go` (`Config.Track`; `NewServer` binds it), `internal/console/claim_routes.go:59-69` (`registerRoute`: non-GET, non-HEAD requests get a write set and the re-read writer) |
| +- Modify: `cmd/console/main.go` (`openStore` sets the observer on the store it opens; `serve()` passes the tracker in `Config.Track`); Test: `cmd/console/perfs3_test.go` (extend) |
| +- Modify: `internal/console/claim_invariant_world_test.go` (`newClaimCaseWith`: when an option sets `Config.Track`, the claim world's `DirStore` gets its observer), `internal/console/claim_invariant_test.go` (`runClaimDoor`: the coverage check) |
| |
| **Interfaces:** |
| -- Consumes: `viewCache.wrote`, `viewEffect`, `registerProbePart`. |
| +- Consumes: `viewCache.touched`, `viewCache.reread`, `viewCache.snapshot`, `withReadSet`, plan 2 Task 2's `perfLatency.Keys`. |
| - Produces: |
| - - `type viewRule func(r *http.Request, acct *Account) viewEffect` |
| - - constructors, combinable with `writes(rules ...viewRule) viewRule`: |
| - - `writesApp(parts ...string) viewRule`: re-read `{acct.Sqid, r.PathValue("app"), part}` for each part. |
| - - `writesAppGone() viewRule`: drop every entry of `{acct.Sqid, app}`; re-read the account's `apps` and `trash` (rename, move to another account, delete). |
| - - `writesAccount(parts ...string) viewRule`: re-read `{acct.Sqid, "", part}`. |
| - - `writesAccountDrop(part string) viewRule`: drop every entry of the account whose `Part` is `part`, any app (an account-level telemetry change reaches every app's resolved telemetry). |
| - - `writesAccountOf(param string, parts ...string) viewRule`: re-read `{sqid, "", part}` for the account the path names in `param` (resolved by the same lookup the handler used), for an operator door acting on someone else's account. |
| - - `writesDeployment(parts ...string) viewRule`: re-read `{"", "", part}`. |
| - - `writesAppDropPrefix(prefix string) viewRule`: drop every entry of the app whose `Part` starts with `prefix` (every page of the version list). |
| - - `before(f func()) viewRule`: adds `f` to the effect's `Before`. |
| - - `type viewWriteDecl struct { Rule viewRule; None string }`: exactly one is set. `func effect(rules ...viewRule) viewWriteDecl` (the rules combined) and `func writesNone(reason string) viewWriteDecl` (the door changes nothing the cache holds; the reason is required) build table entries. |
| - - part-name constants used by every task: `partCore`, `func versionsPart(page int) string` (`versions?page=<n>`, one entry per Releases page; the Overview reads page 1), `partVersionsPrefix` (`versions?`), `partTags`, `partRetention`, `partInstancesManifest`, `partAppReport`, `partTelemetry`, `partGates`, `partClaims`, `partCertWarm`, `partCatchall`, `partDeployEmpty`, `partEnvs`, `partStore`, `partMail`, `partFeatures`, `partSwap`, `partApps`, `partTrash`, `partEntitlement`, `partAccountTelemetry`, `partFleetBoxes` (`fleet-boxes:<name>`, dropped by prefix), `partFleetJSON`, `partBoxes`, `partEdges`, `partMetrics`, `partEconomics` (`economics:<period>`, dropped by prefix), `partStorePending`, `partStoreUsage`, `partArchitecture`. |
| - - `var viewWrites map[string]viewWriteDecl`, keyed by the registered pattern (`claimEntry.Pattern`). |
| - - `func (s *Server) wroteView(r *http.Request, acct *Account)`: looks up `viewWrites[r.Pattern]`, calls `s.onViewMark(r, acct, e)` when that hook is set, and runs `s.views.wrote` with the effect on `context.WithTimeout(context.WithoutCancel(r.Context()), viewLoadTimeout)`. A pattern with no entry, or one declared `writesNone`, panics in tests and logs in production (the census and the witness below keep that from happening). |
| - - `Server.onViewMark func(r *http.Request, acct *Account, e viewEffect)`: an unexported test hook, nil in production. |
| - |
| -Where `wroteView` goes: in each write handler, after every gate and validation has passed and the write has returned success, before the handler writes its response (the redirect, the JSON, the claim-accepted page). Not in `account()`, not on a confirmation page (`handlePromote` renders `confirmPromote` before it writes, `server.go:4595`), not on a refusal or a validation error that redirects with a flash. A door whose success leaves the response to a helper calls it just before that helper. *(My call, per the session lead: marking where the mutation is known to have happened is the only place that can be proved; the table makes each door's effect reviewable in one place.)* |
| - |
| -The effect inventory, as a starting point the implementer completes by reading each door (the census test fails on any gap): |
| - |
| -| doors (browser and CLI) | rule | |
| -|---|---| |
| -| promote, roll back, production flag, fast-track, canary create and retire, pending confirm and reject, pipeline save | `writesApp(partCore)` | |
| -| ship | `effect(writesAppDropPrefix(partVersionsPrefix), writesApp(versionsPart(1)))` (a new version shifts every page; page 1 is re-read, the rest are misses) | |
| -| tag | `effect(writesApp(partTags))` | |
| -| retention | `effect(writesApp(partRetention), writesAppDropPrefix(partVersionsPrefix), writesApp(versionsPart(1)))` | |
| -| gate, rate limit | `writesApp(partGates)` | |
| -| domain attach and detach, catch-all | `writesApp(partClaims, partCatchall, partCertWarm)` | |
| -| swap policy | `writesApp(partSwap)` | |
| -| control plane set and clear, keep | `writesApp(partCore)` (the flags and lifetime they change are SQLite reads; `partCore` because the Overview header reads production state beside them; drop to `writesNone` if the door changes nothing remote) | |
| -| app error level, app analytics setting | `writesApp(partTelemetry)` | |
| -| account error level, account analytics setting | `writes(writesAccount(partAccountTelemetry), writesAccountDrop(partTelemetry))` | |
| -| store destroy | `writesApp(partStore, partEnvs)` | |
| -| config, secrets and environment doors | `writesApp(partEnvs)` | |
| -| mail doors | `writesApp(partMail)` | |
| -| feature doors | `writesApp(partFeatures)` | |
| -| place, instance create, delete, move | `writesApp(partInstancesManifest, partGates)` | |
| -| restart (app and instance), retry, browser updates | `writesNone("instance state is live data, refreshed within liveWindow")` unless the Running tab shows a value the door writes (check `browserrestart.go`; if so, `writesApp` of that part) | |
| -| rename, delete, move to another account | `writesAppGone()` | |
| -| new app, trash restore, trash purge | `writesAccount(partApps, partTrash)` | |
| -| store apply (member) | `writes(writesAccount(partEntitlement), writesDeployment(partStorePending))` | |
| -| store decision (operator, `POST /fleet/store/{account}/{decision}`) | `writes(writesAccountOf("account", partEntitlement), writesDeployment(partStorePending, partStoreUsage))` | |
| -| fleet rotate, detach, tags, place | `writesAccount(partFleetBoxes)` (prefix drop plus re-read of the named fleet) | |
| -| economics scenario, bill and tier saves | `effect(before(s.invalidateEconomics), writesDeployment(partEconomics))` (prefix drop of every period, re-read of the periods that were loaded; Task 15 defines `invalidateEconomics`) | |
| -| architecture refresh | `writesDeployment(partArchitecture)` | |
| -| invite, revoke invite, member remove and transfer, services, CLI tokens, sign-in and session doors, SES events | `writesNone(<what it writes: SQLite rows the console reads live>)` | |
| -| account delete | `effect(writesAccountDrop(""))` with `""` meaning every part of the account | |
| - |
| -In the table, rows built from the constructors above are wrapped in `effect(…)`; `writesNone` rows stand alone. |
| - |
| -**The witness inside `TestClaimConsoleMutationInvariant`.** That suite already drives every app-scoped write door in `claimFixtures` (each `claimDoor` on its own console, `claim_invariant_test.go:144-160`): a foreign run that must not mutate (`check(…, false)`) and an open run that must (`check(…, true)`). `runClaimDoor` gains the fixture key and, before each run, sets `cx.srv.onViewMark` to record the marks of that run (the pattern is the key without its `route ` prefix). After the runs it reports a problem when: |
| -- the open run's `check` passed (the mutation happened) and `viewWrites[pattern]` is not `writesNone`, but no mark for `pattern` was recorded: "<pattern> succeeded without declaring its view effect"; |
| -- a run recorded a mark for a pattern other than its own (`r.Pattern`), or whose `Reread` keys differ from `viewWrites[pattern].Rule(r, acct).Reread` for the same request: "<pattern> marked an effect other than its declared one"; |
| -- any foreign run recorded a mark: "<pattern> marked a write that did not happen"; |
| -- the pattern is declared `writesNone` and a mark was recorded. |
| - |
| -Non-app doors (`claimNonApp` fixtures: account, operator and session doors) are not driven there; their coverage is the census plus the door tests below. *(Session lead's request: this turns "every door calls `wroteView` on success" from a review item into a test.)* |
| - |
| -- [ ] **Step 1: Write the failing tests** on `newPerfFixture`, with the probe part (`{fx.sqid, "kass", "probe"}`, here registered with `Part: partTelemetry` so the app error-level door's rule covers it) warm at `one`, then `two` written straight into `fx.rel` (uncounted): |
| - - `TestEveryWriteRouteDeclaresItsViewEffect`: every `claimEntry` route whose pattern is not `GET …` (method-less patterns included) has a `viewWrites` entry; no `viewWrites` key names a route that does not exist; every entry has exactly one of `Rule` and `None`, and every `None` is a non-empty reason. |
| - - The witness in `TestClaimConsoleMutationInvariant`, above. Prove it bites before Step 3 is finished: with `wroteView` deliberately left out of the promote handler, the suite reports `POST /a/{sqid}/apps/{app}/promote succeeded without declaring its view effect`; restore it. |
| - - `TestAppWriteRereadsItsScope`: Paul POSTs the app error level (`POST /a/<sqid>/apps/kass/errors/level`, with CSRF and a valid level); during the POST `probe.json` is read; after the 303, `ResetKeys()`; GET the probe part: `two` with zero S3 calls. |
| - - `TestRereadFailureLeavesEntryInvalid`: `SetFail` matching `probe.json` during the POST; clear it after; the next probe GET reads `probe.json` (a miss, not the old value) and answers `two`. |
| - - `TestRefusedWritesMarkNothing`, one sub-test each, all asserting `probe.json` is not read during the request and Paul's next probe GET makes zero S3 calls and still answers `one`: a CSRF failure; a second signed-in user who is not a member (404); a plain member on the owner-only door (404); a validation error (an unknown level, whatever status the handler answers today); a promote that stops at its confirmation page (`POST …/promote` without the confirm field, with the probe registered as `partCore`). |
| - - `TestCLIWriteRereadsItsScope`: the same app-level change through its CLI door with a CLI token (an existing `apicli` test shows how to mint one). |
| - - `TestWriteEffectsReachOtherScopes`: with an account-level probe registered at `{fx.sqid, "", partEntitlement}`, the operator's store decision for `fx.sqid` (with Paul in `Config.StoreOperators`) re-reads it. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEveryWriteRouteDeclares|TestAppWriteRereads|TestRereadFailure|TestRefusedWrites|TestCLIWriteRereads|TestWriteEffectsReach' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement** the constructors, the table and the `wroteView` calls. |
| -- [ ] **Step 4: Run** Step 2's command, the gate-order tests `go test ./internal/console/ -run 'NonMember|CSRF|StepUp|FreshAuth|TestEveryCLIDoorNamesItsRoles|TestAuthCLIFamily|TestPromoteFlow|TestRollbackFlow' -count=1`, and `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1` (the witness reports no problem for any door). Expected: PASS. |
| -- [ ] **Step 5: Commit**, message `console: every mutation declares its view effect after it succeeds; the cache re-reads it inside the request`, ending with the Co-Authored-By line. |
| + - `internal/release`: `type AccessOp int` with `AccessRead`, `AccessList`, `AccessWrite`; `type AccessObserver func(ctx context.Context, op AccessOp, key string)`; `func (s *S3Store) SetObserver(f AccessObserver)` and `func (s *DirStore) SetObserver(f AccessObserver)`. Reads (`Get`, `Open`, `GetIfChanged`) report the key before the request goes out. Listings (`List`, `ListMod`, `ListPage`, `ListDirs` with its trailing `/` added, `ListETags`, `ListSizes`) report the prefix before the request goes out. Writes (`Put`, `PutFrom`, `Delete`, `DeleteIfMatch`, and the change index's own write) report the key after the store has acknowledged the write. A failed write reports nothing. Set it before the store is shared; it is not synchronised. |
| + - `internal/console`: `type StoreTracker struct{…}`; `func NewStoreTracker() *StoreTracker`; `func (t *StoreTracker) Observe(ctx context.Context, op release.AccessOp, key string)`; `Config.Track *StoreTracker`. |
| + - On a read or a listing, it adds the key or prefix to the read set in `ctx`, if any. |
| + - On a write, it calls `views.touched(key)` and adds the invalidated entries to the request's write set in `ctx`, if any. |
| + - One mutex orders it with `touched`. A load records a key before it reads, and a write is checked after it lands, so a read that saw the old value is always caught. The only read that can escape the check is one that started after the write, and that read saw the new value. |
| + - `NewServer`: with `Config.Track` set, binds it to `s.views` and the cache is on. With it nil, the cache is off: `viewGet` in either mode runs the loader inline on the request's own context, with no entry and no placeholder. *(My call: a store the console cannot observe could not be invalidated, so it is never cached.)* Production always sets it: `cmd/console`'s `openStore` sets the observer on the `S3Store` or `DirStore` it opens. |
| + - The default test fixtures build on `deletableStore` and pass no tracker. Their tests therefore run every read inline, exactly as today. That is plan 1's deliberately synchronous seam, and it keeps plan 1's instrumentation tests meaningful (Task 11). |
| + - `newPerfFixture` passes one, as does the claim world (this task), so the cached path is tested where it is turned on. |
| + - `func withWriteSet(ctx context.Context) (context.Context, *writeSet)` and `type viewRereadWriter struct { http.ResponseWriter; … }` (`WriteHeader`, `Write`, `Flush`, `Hijack`, `Unwrap`; it edits no header). `registerRoute` installs both on every request that is not GET or HEAD. |
| + - On the first `WriteHeader`, or a `Write` without one, it re-reads the write set's entries through `s.views.reread`, on `context.WithTimeout(context.WithoutCancel(r.Context()), viewLoadTimeout)`, and then passes the call down. |
| + - An empty write set does nothing. A write made after the response has started, or by a background pass, invalidates and is not re-read. |
| + - test-only: `func assertWriteCoverage(t *testing.T, before []viewEntryInfo, after []viewEntryInfo, written []string)`. Every entry in `before` that was valid and whose read set holds a written key, or a prefix of one, must have a newer generation in `after`; anything else fails, naming the entry and the key. |
| + |
| +- [ ] **Step 1: Write the failing tests:** |
| + - `TestStoreObserverCoversEveryMethod` (`internal/release`): one table row per exported method of `*S3Store` (against the S3 fake) and of `*DirStore`. Each row calls the method and asserts the op and key reported; writes are reported only after success, and a refused conditional `Put` reports nothing. The test compares the table's method names with `reflect` over both types, so a method added without a row fails. |
| + - `TestReadRecordedBeforeAWriteIsNeverLost` (`internal/console`, `-race`, 1,000 iterations): a load that records `k` and reads it, racing a write of `k` and its `touched`. The entry never ends valid holding the pre-write value. |
| + - `TestUntrackedServerReadsInline`: `newConsoleFixture` (no tracker): the first GET of the Overview has no `data-part` and shows `v1`, and `fx.srv.views.snapshot()` is empty afterwards. |
| + - `TestProductionStoreIsObserved` (`cmd/console`): `openStore(rec)` over `CARLOS_DEPLOYMENT_DIR` and over the S3 fake both return a store whose observer feeds the tracker `serve()` passes in `Config.Track` (exercise the wiring helper `serve()` uses). |
| + - Warm-before-write acceptance, on `newPerfFixture`. For each case: view the screens, `waitBackground`, `snapshot`; do the write through its real door; `waitBackground`, `snapshot`. Pass both snapshots, with the keys the S3 fake saw written (`Writes()`: the oracle, independent of the tracker), to `assertWriteCoverage`. Then check the screen shows the new state with zero S3 requests on its next view. The cases Astra named, and the earlier ones: |
| + - `TestShipRefreshesDeployEmpty`: a new app `shop` with no routes; its General section warm (deploy-empty answers empty); ship `v1` through the CLI ship door; General no longer says the app is empty. |
| + - `TestInstanceCreateRefreshesHostsAndEnvs`: Logs' host picker (`partRecordHosts`) and Environments (`partEnvs`) warm; create an instance through the CLI door; the picker lists the new host and Environments shows it (its host join is per request, rule (a)). |
| + - `TestScenarioActivationRefreshesArchitecture`: Architecture warm; activate a scenario through the economics door; Architecture's rate card is the new scenario's. |
| + - `TestRefusedWritesInvalidateNothing`: a CSRF failure, a non-member, a plain member on an owner door, a validation error, and a promote stopped at its confirmation page. For each, the fake saw no write and every entry's generation is unchanged. |
| + - `TestReadSetsCoverEveryRead`: on `newPerfFixture`, for each screen in `perfTargets`: `resetForColdView`, `ResetKeys`, `getAssembled`, `waitBackground`. Every `GetObject` key and `ListObjectsV2` prefix the fake saw is held by some entry's read set, or is on a short allowlist of reads the cache does not hold: the account-manifest check, the change index, and reads that plan 1's warm walk already allows by a `calls` record. |
| + - The coverage check inside `TestClaimConsoleMutationInvariant`. The suite builds its door consoles with `newClaimCaseWith(t, func(c *Config) { c.Track = NewStoreTracker() })`; `newClaimCaseWith`, seeing `Track` set after the options run, calls `dir.SetObserver(cfg.Track.Observe)` on the claim world's `DirStore` (`claim_invariant_world_test.go:464`). Every other `newClaimCase` user stays untracked and reads inline, unchanged. In each door's `setup`, outside every measured window, `runClaimDoor` assembles every app tab, settings section and account page of the door's account and app, then calls `waitBackground` and `snapshot`. After each run, it calls `waitBackground` and `snapshot` and runs `assertWriteCoverage` with that run's written keys from the suite's own raw-store recorder (`claimRawStore`'s events: an oracle the tracker does not feed). For a foreign run (`check(…, false)`), which writes nothing, no generation may move. |
| +- [ ] **Step 2: Run** `go test ./internal/release/ -run 'TestStoreObserver' -count=1`, `go test ./internal/console/ -run 'TestReadRecordedBefore|TestUntrackedServer|TestShipRefreshes|TestInstanceCreateRefreshes|TestScenarioActivation|TestRefusedWrites|TestReadSetsCoverEveryRead' -count=1 -race`, `go test ./cmd/console/ -run TestProductionStoreIsObserved -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Some of these tests need screens converted later (Logs in Task 12, Architecture in Task 15). Write them now with `t.Skip("cached in Task N")` and remove the skip in that task. Every other case runs here, with the probe part standing in for a cached screen. |
| +- [ ] **Step 4: Run** Step 2's commands, the gate-order tests `go test ./internal/console/ -run 'NonMember|CSRF|StepUp|FreshAuth|TestEveryCLIDoorNamesItsRoles|TestAuthCLIFamily|TestPromoteFlow|TestRollbackFlow' -count=1`, and `nice -n 19 go test ./internal/console/ -run '^TestClaimConsoleMutationInvariant$' -count=1`. The claim run's background reads happen in setup, outside measured windows. A door's own re-reads are reads inside its window. If the suite's recorder treats them as anything but the door's reads, record them as the door's reads; never silence the check. Expected: PASS. |
| +- [ ] **Step 5: Prove the check bites.** Make one loader read a key without recording it (a raw `s.cfg.Releases` call through a context with no read set). `TestReadSetsCoverEveryRead` must name that key, and the matching warm-before-write case must fail. Restore, then commit with message `console: writes invalidate what they touched, by read set; the writing request re-reads it before answering`, ending with the Co-Authored-By line. |
| |
| ### Task 9: App core through the cache: every app tab's shared reads |
| |
| @@ -409,10 +393,10 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential, |
| **Interfaces:** |
| - Produces: |
| - `type appCore struct { Channels []ChannelView; ProductionFlag *release.ProductionFlag; ProductionErr error; Pipeline *release.Pipeline; PipelineErr error }` with `viewClone` (copies `Channels`; the two pointers are read-only), and `func loadAppCore(ctx context.Context, s release.Store, pub ed25519.PublicKey, acct, app string) (appCore, error)`: `assembleChannels`, `release.GetProduction` and `release.GetPipeline`, under `ctx`. It holds only what is read remotely, and only facts that do not change with the clock: every cached `ChannelView` has a zero `BakedUntil`, and the core keeps `PromotedAt`, `FastTrack` and the channel name from which it is derived. *(Astra round 2, finding 6.)* |
| - - `assembleChannels` loses its `now` parameter and its bake computation (`view.go:749-753`); `func channelBakes(channels []ChannelView, pipe *release.Pipeline, prod ProductionView, now time.Time)` sets `BakedUntil` on the request's copy: the legacy hold (`release.HoldFor(release.DefaultHolds, name)`) when there is no pipeline, the pipeline's `holdWindow` when there is (what `applyPipelineView` does today, `server.go:3480-3490`), cleared for fast-tracked channels and when production is off (`view.go:615-626`). `Assemble` and `applyPipelineView` call it with `s.now()`; the ladder is rebuilt from its result. Production's turning-off estimate is already derived per request in `productionView`. |
| + - `assembleChannels` loses its `now` parameter and its bake computation (`view.go:749-753`); `func channelBakes(channels []ChannelView, pipe *release.Pipeline, prod ProductionView, now time.Time)` sets `BakedUntil` on the request's copy: the legacy hold (`release.HoldFor(release.DefaultHolds, name)`) when there is no pipeline, the pipeline's `holdWindow` when there is (what `applyPipelineView` does today, `server.go:3480-3490`), cleared for fast-tracked channels and when production is off (`view.go:615-626`). `Assemble` calls it with its `now` argument and `applyPipelineView` with `s.now()`; the ladder is rebuilt from its result. Production's turning-off estimate is already derived per request in `productionView`. |
| - `func productionView(flag *release.ProductionFlag, err error, channels []ChannelView, routes []RouteView, now time.Time) ProductionView` (`now` is `s.now()`): `assembleProduction` minus its read (`view.go:763`), so the route-dependent nudge (`:794-803`) is still computed from the request's routes. *(Astra finding 6: the routes are a local registry read and are never cached.)* |
| - - `Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets, core func(app string) (appCore, error)) ([]AppView, error)`: routes come from `memoRoutes`; each app's channels, production flag and pipeline from `core`; `productionView`, the channel post-processing at `:615-626` and the ladder run on the request's own copy. An error from `core` is returned (callers map `errViewPending` to the placeholder). |
| - - `func storeCore(ctx context.Context, s release.Store, pub ed25519.PublicKey, acct string) func(app string) (appCore, error)`: `loadAppCore` with no cache, for callers that are not screens and for `view_test.go`'s existing `Assemble` calls. |
| + - `Assemble(ctx context.Context, regPath string, s release.Store, pub ed25519.PublicKey, acct string, apps []string, dns DNSTargets, now time.Time, core func(app string) (appCore, error)) ([]AppView, error)`: `now` is explicit (screens pass `s.now()`, tests their clock, `storeCore` callers `time.Now()`), so the clock-dependent derivation below has a clock; routes come from `memoRoutes`; each app's channels, production flag and pipeline from `core`; `productionView`, the channel post-processing at `:615-626` and the ladder run on the request's own copy. An error from `core` is returned (callers map `errViewPending` to the placeholder). |
| + - `func storeCore(ctx context.Context, s release.Store, pub ed25519.PublicKey, acct string) func(app string) (appCore, error)`: `loadAppCore` with no cache, for callers that are not screens and for `view_test.go`'s existing `Assemble` calls (which pass `time.Now()` as `now`). |
| - `func (s *Server) appCoreView(ctx context.Context, p *page, mode viewMode, sqid, app string) (appCore, error)`: `viewGet` with key `{sqid, app, partCore}`, `writtenWindow`. |
| - `appPage` keeps the gates and chrome and no longer assembles. `func (s *Server) fillAppDetail(r *http.Request, p *page, acct *Account, mode viewMode) error` sets `p.Detail` (`Assemble` with `appCoreView`), the account review and `applyPipelineView` (from the core, no read). Every tab's `Fill` calls it first; anything that reads `p.Detail` (the nav plan's `liveNowTargets`, `assembleDeploymentTargets`, the ladder, `hasPublishedChannel`) runs after it. |
| - parts `overview`, `activity`, `account-review` in `appParts`; the Overview's extra reads through `viewGet`: page 1 of the version list (`{sqid, app, versionsPart(1)}`, `writtenWindow`, a `versionPage{Views []VersionView; More bool}` with `viewClone`, loaded by `VersionsPage(ctx, …, 1)`; the same entry as Releases' first page), `appResourceMetrics` (`{"", "", partMetrics}`, `liveWindow`, loader `LoadMetrics`, filtered per app after, on the copy), `loadBoxJoin` (`{"", "", partBoxes}`, `liveWindow`, the `boxSnapshot` from Task 5). SQLite reads (events, pending changes) stay direct. |
| @@ -421,12 +405,13 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential, |
| - `TestOverviewWarmMakesNoRemoteCalls`: `getAssembled` `/apps/kass` and quiesce; reset counts; GET: zero S3 and zero host calls, 200, shows `v1` on `stable`. |
| - `TestOverviewColdArrivesWithAPlaceholder`: fresh `newPerfFixture`, latency on: the first GET's time to first byte is under 150 ms and the body has `data-part` for `overview`; `getAssembled` shows `v1`. |
| - `TestBakeStateFollowsTheClockNotTheCache`: a legacy app (no pipeline) with production on and `stable` promoted 10 minutes ago, warm; the Releases page shows the bake delay and its skip control; move `fx.clock` past the hold's end (the cached core is now stale but still served); the next GET shows no bake delay and no skip control, before any refresh has finished (hold the refresh with `HoldNext("get", …)` on the channel pointer). The same with a pipeline's own window. |
| + - `TestDeferredReadsCountAsBackground`: on `newPerfFixture`, a cold Overview: its sample's `Calls["s3"]` is 0 and `fx.srv.PerfBackground()["s3"]` rose by the fake's request count for that load. Plan 1's `TestOverBudgetPageIsLogged` still passes on its untracked fixture, where the Overview's reads run inline on the request (the synchronous seam); if its only slow read was the account manifest, it now sleeps on every `Get`. |
| - `TestProductionNudgeStillUsesRoutes`: with production off and a stable route present, the Overview shows the production-wiring nudge exactly as before; with no such route it does not. |
| - `TestSameAppNameInTwoAccountsNeverShares`: a second account owning an app `kass` with a different channel version; each member sees only their own version, warm. |
| - `TestConcurrentViewsShareNoState` (run with `-race`): warm Overview, Activity and account review (and, as Tasks 10 to 14 land, their screens: the test walks `appParts` and `accountParts`); eight goroutines each `getAssembled` every one five times; every body for one URL is identical to the first. |
| - `TestActivityAndAccountReviewWarmMakeNoCalls`. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOverview|TestBakeStateFollowsTheClock|TestProductionNudge|TestSameAppNameInTwoAccounts|TestConcurrentViews|TestActivityAndAccountReview' -count=1 -race`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Convert this task's screens' existing tests to `getAssembled` where they assert on the body (start from `grep -n 'apps/kass")\|/activity\|account-review' internal/console/*_test.go`), including `TestOverviewIsALadderNotAnEverythingPage`, `TestRecentActivity`, `TestActivityTab`, `TestAppPageInstances`, `TestAppPageRendersDomains`. Repoint Task 7's app-part probe at `overview`. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOverview|TestBakeStateFollowsTheClock|TestDeferredReadsCountAsBackground|TestOverBudgetPageIsLogged|TestProductionNudge|TestSameAppNameInTwoAccounts|TestConcurrentViews|TestActivityAndAccountReview' -count=1 -race`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** The existing tests of these screens run on the untracked fixture and need no change. Run `TestOverviewIsALadderNotAnEverythingPage` and `TestRecentActivity` on `newPerfFixture` as well, through `getAssembled`. Repoint Task 7's app-part probe at `overview`. |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestAssemble|TestAppPage|TestOverviewIsALadder|TestRecentActivity|TestActivityTab|TestAccountReview|TestAppTabBar|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| - [ ] **Step 5: Delete** the `over:` records for `GET /a/{sqid}/apps/{app}`, `GET /a/{sqid}/apps/{app}/activity` and `GET /a/{sqid}/apps/{app}/account-review`; walk with `CI=1` (PASS); commit, message `console: app core, Overview, Activity and account review read through the view cache`, ending with the Co-Authored-By line. |
| |
| @@ -446,12 +431,13 @@ Spec §2.4 C row `assembleChannels`: List plus one Get per channel, sequential, |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestReleasesWarmMakesNoRemoteCalls` (same shape as Task 9's). |
| - `TestReleasesLiveNowRendersWhileVersionsLoad`: the core warmed through Activity (which reads no versions; the Overview would warm page 1) and the version list never viewed: the first Releases GET has `id="live-now"` with its Roll back and a `data-part` for `releases-versions`. |
| - - `TestReleasesPagesAreCachedApart`: with 23 versions (the nav test's setup), warm pages 1 and 2; each warm GET makes zero S3 requests; page 1 has 20 rows and `rel="next"`, page 2 has 3 rows and `rel="prev"`; a ship of one more version makes page 2 a miss (the drop) and page 1 a re-read inside the ship request, after which page 1 starts with the new version. |
| + - `TestReleasesPagesAreCachedApart`: with 23 versions (the nav test's setup), warm pages 1 and 2; each warm GET makes zero S3 requests; page 1 has 20 rows and `rel="next"`, page 2 has 3 rows and `rel="prev"`; a ship of one more version writes under the releases prefix both pages listed, so both are invalidated by read set and re-read inside the ship request, after which page 1 starts with the new version and page 2 starts with the version page 1 used to end on. |
| - `TestPromoteShowsTheNewVersionOnTheNextView`: warm `/apps/kass/releases`; promote `v2` to `stable` through the browser form (with its confirmation step); 303; `ResetKeys()`; `getAssembled` the redirect target: zero S3 calls and `v2` on `stable`. |
| - `TestPromoteDuringABackgroundRefreshShowsTheNewVersion`: warm; move `fx.clock` past `writtenWindow`; `HoldNext("get", …)` on the `stable` channel pointer key; a GET starts a refresh, which reads `v1` and blocks (wait for `held`); promote `v2` (the promote's own read of the pointer is not held, since `HoldNext` holds one read); `release()`; quiesce; the next GET shows `v2`, never `v1`. |
| + - `TestPromoteCoverage`: the promote case through `assertWriteCoverage` (Task 8). |
| - `TestCLIPromoteShowsInTheBrowser`: the same promote through the CLI door; the next browser GET shows `v2` with zero S3 calls. |
| - [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestReleasesWarm|TestReleasesLiveNowRenders|TestReleasesPagesAreCachedApart|TestPromoteShows|TestPromoteDuring|TestCLIPromoteShows' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Convert to `getAssembled`, keeping every assertion: `TestReleasesTab` (`server_test.go:514`), the nav plan's `TestReleasesPageOrder`, `TestReleasesPageHasOneRollBack`, `TestReleasesOlderVersionsAreReachable` (its 23-version page 1 and page 2 assertions, read assembled; it must pass unchanged in substance), `TestVersionsPageMatchesVersionsOnPageOne`, `TestDeploymentRoutesAndHistory`, `TestNoLinkPointsAtDeployments`, `TestOneChannelAppHidesChannelVocabulary`, `TestOneChannelAppKeepsCanariesAndRollback`, `TestChannelsTableAndPipelineCardAgreeOnBakeWindow`, `TestReleaseSummaryStripRenders`, `TestFirstPromoteChannelOptions`. `TestReleasesLiveNowSurvivesListingFailure` (`fx.srv.cfg.Releases = listFailStore{fx.rel}`) keeps its assertions on the assembled page: 200, "Could not list this app", `id="live-now"` and the instances link. Update the claim probe for `GET …/releases` if its marker moved into a part. |
| +- [ ] **Step 3: Implement.** These keep passing unchanged on the untracked fixture, and each also runs on `newPerfFixture` through `getAssembled` with every assertion kept (a helper `onBothFixtures(t, func(t *testing.T, fx *consoleFixture, get func(path string) string))`): `TestReleasesTab` (`server_test.go:514`), the nav plan's `TestReleasesPageOrder`, `TestReleasesPageHasOneRollBack`, `TestReleasesOlderVersionsAreReachable` (its 23-version page 1 and page 2 assertions, read assembled; it must pass unchanged in substance), `TestVersionsPageMatchesVersionsOnPageOne`, `TestDeploymentRoutesAndHistory`, `TestNoLinkPointsAtDeployments`, `TestOneChannelAppHidesChannelVocabulary`, `TestOneChannelAppKeepsCanariesAndRollback`, `TestChannelsTableAndPipelineCardAgreeOnBakeWindow`, `TestReleaseSummaryStripRenders`, `TestFirstPromoteChannelOptions`. `TestReleasesLiveNowSurvivesListingFailure` keeps its assertions on both: on the untracked fixture as written (`fx.srv.cfg.Releases = listFailStore{fx.rel}`); on `newPerfFixture` with `SetFail` matching listings of the releases prefix. Both must show 200, "Could not list this app", `id="live-now"` and the instances link. Update the claim probe for `GET …/releases` if its marker moved into a part. |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestReleases|TestDeployment|TestNoLinkPointsAtDeployments|TestOneChannelApp|TestChannelsTableAndPipelineCard|TestReleaseSummary|TestFirstPromote|TestPromoteFlow|TestRollbackFlow|TestCanaryFlow|TestRetireCanary|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| - [ ] **Step 5: Delete** the `over:` record for `/releases`; walk (PASS); commit, message `console: Releases reads through the view cache; Versions loads as its own part`, ending with the Co-Authored-By line. |
| |
| @@ -476,8 +462,8 @@ Spec §2.4 C row `instances.Report`: HTTP to the app host, 30 s cache, blocks up |
| - `TestRunningTabNeverWaitsOnTheAppHost`: `HostDelay` 1 s; a cold Running tab answers within 150 ms with the instances table and a `data-part` for `instances-report`; after quiesce the report shows; exactly one host call was made. |
| - `TestAppReportNeverWakesAHibernatingHost`: with every route `Hibernate`, no host call is ever made (the rule at `instances.go:83-92`). |
| - `TestInstancePartRefusesAForeignHost`: `/apps/kass/part/instance?host=otherapp.carlosapp.dev` (the fixture's other app's route) is the same 404 the page gives for that host, with no S3 call. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestRunningWarm|TestInstancePageWarm|TestRunningTabNeverWaits|TestAppReportNeverWakes|TestInstancePartRefuses' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Convert this task's screens' tests to `getAssembled` (the nav plan's `TestRunningTabHeadingAndToolbar`, `TestRunningLeftoversNameTheTab`, `TestInstancesTab`, `TestInstancesEmptyStateHintsStable`, `TestInstancesTabRegionLine`, `TestBrowserRestart*`, the instance page tests) and their claim probes. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestRunningWarm|TestInstancePageWarm|TestRunningTabNeverWaits|TestAppReportNeverWakes|TestInstancePartRefuses|TestRunningTabTimesTheAppHost|TestDeferredAppReportCountsAsBackground' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** This task's existing tests run unchanged on the untracked fixture. Plan 1's `TestRunningTabTimesTheAppHost` stays meaningful there: the report is fetched inline on the request, so the `box` span is in its `Server-Timing`. Add `TestDeferredAppReportCountsAsBackground`: on `newPerfFixture`, a cold Running tab's sample has no `box` call, `PerfBackground()["box"]` rose by one, and the `instances-report` part's assembled body has the report. Update the claim probes whose markers moved into a part. |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestInstancesTab|TestRunningTab|TestRunningLeftovers|TestInstancePage|TestBrowserRestart|TestBrowserUpdates|TestInstanceReport|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| - [ ] **Step 5: Delete** the `over:` records for `/instances` and `/instances/{host}`; walk (PASS); commit, message `console: Running and the instance page read through the view cache; the app's self-report is a deferred part`, ending with the Co-Authored-By line. |
| |
| @@ -492,17 +478,18 @@ Spec §2.4 C row `instances.Report`: HTTP to the app host, 30 s cache, blocks up |
| - Produces: |
| - `func viewFilterKey(prefix string, filter any) string`: `prefix + "?" +` the hex SHA-256 of the canonical JSON encoding of the effective filter the loader runs with (`applog.Filter` after `browserLogsFilterFromQuery` and the page's default window; the errors, availability and analytics option structs after their own parsing). It keys on what the read will actually do, losslessly: no trimming, no truncation, no parameter the loader ignores. Two requests share an entry exactly when their loads would read the same thing. *(Astra round 2, finding 5.)* Time-relative filters ("the last hour") are made absolute by the parser; the key then carries the window's start rounded down to `liveWindow`, so a view within the same 30 s shares the entry and a later one does not. |
| - `func (s *Server) logWindowView(ctx context.Context, p *page, mode viewMode, sqid, app string, f applog.Filter, key string) (logWindow, error)`: the first window of rows for a filter (`applog.ReadWindow`, `{sqid, app, viewFilterKey("logs", f)}`, `liveWindow`, a `logWindow` with `viewClone`), shared by the page and by `/logs/data`. `handleAppLogs` reads it in `viewCached` mode: a miss renders the table empty with `data-load-now` on the form, and the existing script (`app_logs.html:66-196`) calls its fetch of `/logs/data` once at load without starting to follow. `handleAppLogsData` without a `cursor` reads the same entry in `viewBlocking` mode, so it joins the load the page started instead of reading the window again; with a `cursor` (following) it reads as today, uncached. *(Astra finding 10.)* |
| - - the host picker (`ListRecordHosts`, `{sqid, app, "record-hosts"}`, `liveWindow`). |
| + - the host picker (`ListRecordHosts`, `{sqid, app, partRecordHosts}`, `liveWindow`) as its own part `logs-hosts`: the `<select name="host">` element alone, from the template's existing markup with the current `?host=` selected. On a miss, the page renders the picker from the routes it already has (local) and a placeholder for the select. The loader replaces it with the full list; with JavaScript off, a reload shows it. The select keeps its `name`, so the filter form submits it as before, and it holds no script. *(Astra round 3, finding 4.)* |
| - parts `errors`, `availability`, `analytics`; reads through `viewGet`: `telemetry.Resolve` (`{sqid, app, partTelemetry}`, `writtenWindow`; the error-level and analytics-setting doors re-read it, Task 8), `apperr.ReadWindow` and the platform-stream `applog.ReadWindow` (`viewFilterKey("errors", …)`, `viewFilterKey("availability", …)`, `liveWindow`), `analytics.ReadRange` (`viewFilterKey("analytics", …)`, `liveWindow`). |
| |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestLogsWarmMakesNoRemoteCalls`. |
| + - `TestColdLogsFillsTheHostPicker`: with a record-only host (an instance record with no route), the cold page's picker lacks it; `getAssembled` of the page has it in the `select`, still `name="host"`; selecting it (`?host=<it>`) is preserved in the assembled select. |
| - `TestColdLogsReadTheWindowOnce`: fresh fixture; GET `/apps/kass/logs` (cold: `data-load-now`, no rows); GET `/logs/data` with the page's own query and no cursor; across both, the log prefix's listings appear in `Keys()` exactly as many times as one `ReadWindow` makes them; `/logs/data` answers the rows. |
| - `TestLogsFollowStillReadsLive`: a `/logs/data` with a cursor reads the store each time. |
| - `TestErrorsAvailabilityAnalyticsWarmMakeNoCalls`. |
| - `TestFilterKeysAreLossless`: `?since=1h&host=a` and `?host=a&since=1h&junk=x` share one entry (same effective filter); `text=failed` and `text=%20failed` do not; two 300-byte searches that differ only in their last byte do not. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLogsWarm|TestColdLogsRead|TestLogsFollow|TestErrorsAvailabilityAnalytics|TestFilterKeysAreLossless' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Convert this task's screens' tests (the nav plan's `TestLogsToolbar`, `TestTelemetryHintsLinkTheSection`, `TestAppLogs*`, `TestAppErrors*`, `TestAppAvailability*`, `TestAppAnalytics*`) to `getAssembled` and their claim probes. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestLogsWarm|TestColdLogsFillsTheHostPicker|TestColdLogsRead|TestLogsFollow|TestErrorsAvailabilityAnalytics|TestFilterKeysAreLossless|TestInstanceCreateRefreshes' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Existing tests run unchanged on the untracked fixture; run the nav plan's `TestLogsToolbar` on `newPerfFixture` too, through `getAssembled`. Remove `TestInstanceCreateRefreshesHostsAndEnvs`' skip (Task 8) once Environments is cached in Task 13, if it is not yet. Update claim probes whose markers moved. |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestAppLogs|TestLogsToolbar|TestAppErrors|TestAppAvailability|TestAppAnalytics|TestErrorLevel|TestAnalyticsSetting|TestTelemetryHints|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| - [ ] **Step 5: Delete** the `over:` records for `/logs`, `/errors`, `/availability`, `/analytics`; walk (PASS); commit, message `console: Logs, Errors, Availability and Analytics read through the view cache; the first log window is read once`, ending with the Co-Authored-By line. |
| |
| @@ -516,7 +503,7 @@ Spec §2.4 C rows `settingsGates` (cache), `aliasReadings`/`LoadBoxes` (cache, o |
| - Test: `internal/console/viewscreens_test.go` (extend) |
| |
| **Interfaces:** |
| -- Produces: parts `settings` (its `Gate` reads `?section=` and refuses one not in `appSettingsSections`, as the page refuses the path) and `domain-readings` (the box readings on Domains alone, deferred on a miss of `partBoxes` while the rest of Domains renders). Reads through `viewGet`, keyed `{sqid, app, …}` with `writtenWindow` unless marked live: `settingsGates`' records (`partGates`), the claims listing (`partClaims`; `ClaimCache` stays underneath), `warmRecords` (`partCertWarm`, live), catch-all views including their DNS TXT lookup (`partCatchall`), `appDeployEmpty` (`partDeployEmpty`), `envCards` (`partEnvs`), `storeCard` and `storeEnvCards` (`partStore`), `mailCard` (`partMail`), `featuresCard` (`partFeatures`), `telemetry.Resolve` on `errors-analytics` (Task 12's key), `loadSwapPolicy` (`partSwap`); `aliasReadings` reads the shared `partBoxes` entry. Placement is local and stays direct. The pipeline section reads the core's pipeline (Task 9). |
| +- Produces: parts `settings` (its `Gate` reads `?section=` and refuses one not in `appSettingsSections`, as the page refuses the path) and `domain-readings` (the box readings on Domains alone, deferred on a miss of `partBoxes` while the rest of Domains renders). Reads through `viewGet`, keyed `{sqid, app, …}` with `writtenWindow` unless marked live: `settingsGates`' records (`partGates`), the claims listing (`partClaims`; `ClaimCache` stays underneath), `warmRecords` (`partCertWarm`, live), catch-all views including their DNS TXT lookup (`partCatchall`), `appDeployEmpty` (`partDeployEmpty`), `envCards` (`partEnvs`: the config bundles and store records only; the route-derived host list each card shows is joined per request from `p.Detail.Routes`, rule (a)), `storeCard` and `storeEnvCards` (`partStore`), `mailCard` (`partMail`), `featuresCard` (`partFeatures`), `telemetry.Resolve` on `errors-analytics` (Task 12's key), `loadSwapPolicy` (`partSwap`); `aliasReadings` reads the shared `partBoxes` entry. Placement is local and stays direct. The pipeline section reads the core's pipeline (Task 9). |
| |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestEverySettingsSectionWarmMakesNoCalls` (one sub-test per key of `appSettingsSections`, with the populated seeds). |
| @@ -525,7 +512,7 @@ Spec §2.4 C rows `settingsGates` (cache), `aliasReadings`/`LoadBoxes` (cache, o |
| - `TestPipelineSaveShowsTheNewPipeline`: warm the pipeline section; save a changed pipeline; the redirect target shows it with zero S3 calls. |
| - `TestRenameFailureRerendersWithoutStaleData`: the existing rename-failure re-render (`renderAppSettingsForm`) still shows its message and the current values. |
| - [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestEverySettingsSection|TestDomainsArrives|TestDomainAttachShows|TestPipelineSaveShows|TestRenameFailureRerenders' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Convert the settings tests to `getAssembled` (the nav plan's `TestAppSettingsSectionRoutes`, `TestErrorsAndAnalyticsSection`, `TestAppSettingsPlacementSection`, `TestAppSettingsPlacementShowsFleet`, `TestPipelineSettingsCanonicalSectionURL`, and the existing settings, domain, gate, store and control-plane tests that read a section body) and the `settings/{section}` claim probe. |
| +- [ ] **Step 3: Implement.** Existing settings tests run unchanged on the untracked fixture; run the nav plan's `TestAppSettingsSectionRoutes` and `TestErrorsAndAnalyticsSection` on `newPerfFixture` too. Remove the skips of `TestShipRefreshesDeployEmpty` and `TestInstanceCreateRefreshesHostsAndEnvs` (Task 8). Update the `settings/{section}` claim probe if its marker moved. |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestAppSettings|TestBucketless|TestDomain|TestAppGate|TestAppRateLimit|TestStoreDestroy|TestPipeline|TestAppSwap|TestControlPlane|TestErrorsAndAnalyticsSection|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| - [ ] **Step 5: Delete** the `over:` records for the settings sections and `/settings`; walk (PASS); commit, message `console: settings sections read through the view cache; box readings deferred on Domains`, ending with the Co-Authored-By line. |
| |
| @@ -537,20 +524,23 @@ Spec §2.4 C rows `settingsGates` (cache), `aliasReadings`/`LoadBoxes` (cache, o |
| - Test: `internal/console/viewscreens_test.go` (extend) |
| |
| **Interfaces:** |
| -- Produces: parts in `accountParts`: `apps` (the account home's app list; each app's channels through Task 9's per-app `partCore` entries, so the home page and the app tabs share them), `settings` (its `Fill` keeps the owner-only panes behind the role check the page uses), `fleet`, `fleets` (its `Gate` reads `?fleet=` and runs `resolveOwnedFleet` as the page does), `trash` (the delete form for owners only, as the page), `new-app`. Reads through `viewGet`: `fleet.json` (`{"", "", partFleetJSON}`, `liveWindow`), each owned fleet's boxes (Task 11's key), the store entitlement (`{sqid, "", partEntitlement}`, `writtenWindow`), the account telemetry (`{sqid, "", partAccountTelemetry}`, `writtenWindow`), tombstones (`{sqid, "", partTrash}`, `writtenWindow`), the region picker's edges snapshot and boxes (the shared `partEdges` and `partBoxes`). Minting a first account (`server.go:2382`) is a write, unchanged. |
| +- Produces: parts in `accountParts`: `apps` (the account home's app list; each app's channels through Task 9's per-app `partCore` entries, so the home page and the app tabs share them), `settings` (its `Fill` keeps the owner-only panes behind the role check the page uses), `fleet`, `fleets` (its `Gate` reads `?fleet=` and runs `resolveOwnedFleet` as the page does), `trash` (the delete form for owners only, as the page), `new-app`. Reads through `viewGet`: `fleet.json` (`{"", "", partFleetJSON}`, `liveWindow`), each owned fleet's boxes (Task 11's key), the store entitlement (`{sqid, "", partEntitlement}`, `writtenWindow`), the account telemetry (`{sqid, "", partAccountTelemetry}`, `writtenWindow`), tombstones, one entry per trashed app (`{sqid, "", trashPart(app)}`, `writtenWindow`; the list of trashed apps is SQLite, read per request, rule (b)), the region picker's edges snapshot and boxes (the shared `partEdges` and `partBoxes`). Minting a first account (`server.go:2382`) is a write, unchanged. |
| +- `app_new.html`'s region and timezone initializer (today an inline script in the body using `document.currentScript`, `templates/app_new.html:22`) moves into the frame. It runs once on `DOMContentLoaded` and again on `carlos:part` for the `new-app` part, and finds the hidden timezone input and the automatic-region label by id inside the root it is given. The fragment carries no script. *(Astra round 3, finding 5.)* |
| |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestAccountPagesWarmMakeNoRemoteCalls` (one sub-test each for `/a/{sqid}/`, `/settings`, `/fleet`, `/fleets/fleet-a`, `/trash`, `/apps/new`). |
| - `TestAccountHomeSharesAppCoreWithAppTabs`: `getAssembled` `/apps/kass` and quiesce; the account home then makes zero channel reads for `kass`. |
| - `TestNewAppAppearsOnHomeAfterCreate`: create `shop`; the redirect target lists it. |
| - `TestDeletedAppShowsInTrash`: warm `/trash`; delete `kass` through its settings door (with its confirmation); `getAssembled` `/trash` lists `kass` with zero S3 calls. |
| + - `TestNewAppInitializerSurvivesAColdLoad`: on `newPerfFixture` with `CONSOLE_APP_REGIONS` on, a cold `/apps/new`: the frame holds the initializer (it listens for `carlos:part` and `DOMContentLoaded`, and does not use `document.currentScript`). The part's fragment has no `<script`. The assembled page holds every id the initializer looks up. When `chromium` is on `PATH` (skipped otherwise, as the nav plan's snapshots are), a headless load of the cold page served by the test server ends with the hidden timezone input non-empty. |
| + - `TestStoreDecisionShowsOnTheAccount`: the account's settings warm (its entitlement entry); the operator approves its storage application; the warm-before-write check (Task 8) passes and the account's next settings view shows the approval with zero S3 calls. |
| - `TestAccountPartsKeepOwnerOnlyContent`: a plain member's assembled `/settings` and `/trash` have no owner-only form, exactly as the pages today. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAccountPagesWarm|TestAccountHomeShares|TestNewAppAppears|TestDeletedAppShowsInTrash|TestAccountPartsKeepOwnerOnly' -count=1`. Expected: FAIL. |
| -- [ ] **Step 3: Implement.** Convert the account pages' tests to `getAssembled` (the nav plan's `TestPageHeadsOnAccountPages`, `TestTrashDeleteSitsInItsRow`, `TestAccountSettingsFormsUseSettingsRow`, and `TestEmptyStateWelcomesNewUser`, `TestCreateApp`, `TestAccountSettingsPage`, the fleet page and trash tests) and their claim probes; repoint Task 7's account-part probe at `apps`. |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestAccountPagesWarm|TestAccountHomeShares|TestNewAppAppears|TestDeletedAppShowsInTrash|TestNewAppInitializerSurvives|TestStoreDecisionShowsOnTheAccount|TestAccountPartsKeepOwnerOnly' -count=1`. Expected: FAIL. |
| +- [ ] **Step 3: Implement.** Existing tests run unchanged on the untracked fixture; run the nav plan's `TestPageHeadsOnAccountPages` and `TestTrashDeleteSitsInItsRow` on `newPerfFixture` too. Update claim probes whose markers moved; repoint Task 7's account-part probe at `apps`. |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestEmptyStateWelcomesNewUser|TestCreateApp|TestAccountSettings|TestAccountFleet|TestFleetPage|TestTrash|TestRegionPicker|TestPageHeads|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| - [ ] **Step 5: Delete** the account pages' `over:` records; walk (PASS); commit, message `console: account pages read through the view cache`, ending with the Co-Authored-By line. |
| |
| -### Task 15: Operator pages: shared loaders and write effects for Part 3 |
| +### Task 15: Operator pages: shared loaders for Part 3 |
| |
| Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the shape of their handlers. This task changes neither; it provides the loaders Part 3's Task 13 consumes. Order: this task lands (with the rest of plan 2) before Part 3's Task 13, which repoints Part 3's seam functions `opFleetJSON`, `opHostRows` and `opStorePending` (Part 3 Task 8) at `fleetJSONView`, `hostRowsView` and `storePendingView`, adds a `mode viewMode` parameter to each, adds `/fleet/part/{part}` and deletes the operator `over:` records. |
| |
| @@ -565,24 +555,25 @@ Part 3 (`2026-10-25-operator-pages.md`) owns the `/fleet*` templates and the sha |
| - `func (s *Server) fleetJSONView(ctx context.Context, p *page, mode viewMode) (*status.Fleet, error)` (`{"", "", partFleetJSON}`, `liveWindow`; the read `opFleetJSON` makes, `FleetView`) |
| - `func (s *Server) hostRowsView(ctx context.Context, p *page, mode viewMode) ([]HostRow, error)` (rows built per request from the shared `partBoxes` `boxSnapshot`, as `HostRows` builds them; what `opHostRows` returns) |
| - `func (s *Server) storePendingView(ctx context.Context, p *page, mode viewMode) (storePendingList, error)` (`partStorePending`; `storePendingList` is the slice `pendingStoreApplications` returns, with `viewClone`; `opStorePending` takes its length and keeps its own store-operator and no-bucket checks) |
| - - `func (s *Server) metricsView(ctx context.Context, p *page, mode viewMode) (metricsResult, error)` (`partMetrics`; `metricsResult` holds what `LoadMetrics` returns, whose own 60 s cache stays underneath) |
| - - `func (s *Server) economicsView(ctx context.Context, p *page, mode viewMode, period string) (*EconomicsView, error)` (`economics:<period>`; `LoadEconomics`' own cache, `economicsview.go:283-300`, stays underneath for views) |
| - - `func (s *Server) invalidateEconomics()`: the `Before` hook of every economics save (Task 8). It empties `LoadEconomics`' inner cache and bumps a generation the inner cache gains, so an inner sweep that started before the save cannot store its result, and the outer re-read that follows sweeps fresh instead of being handed the pre-save value from the inner cache. *(Astra round 2, finding 4.)* |
| + - `func (s *Server) metricsView(ctx context.Context, p *page, mode viewMode) (metricsResult, error)` (`partMetrics`; `metricsResult` holds what `LoadMetrics` returns) |
| + - `func (s *Server) economicsView(ctx context.Context, p *page, mode viewMode, period string) (*EconomicsView, error)` (`economicsPart(period)`) |
| + - Both loaders call the sweep their inner cache runs on a miss (`LoadMetrics`' and `LoadEconomics`' uncached sweep, `metricsview.go:257-410`, `economicsview.go:283-300`), never the inner caches. Their read sets are then complete, and Task 8's invalidation reaches them directly: a scenario save invalidates every entry that read the scenario keys, Architecture's rate card included. This also makes round 2's `invalidateEconomics` unnecessary. Their window is `operatorWindow = 60 * time.Second`, the inner caches' own freshness, so S3 use does not rise. The inner caches stay for the callers that use them today (the CLI's economics door, `OwnerAppMetrics` outside views). |
| - `func (s *Server) storeUsageView(ctx context.Context, p *page, mode viewMode) (storeUsage, error)` (`partStoreUsage`; what `storeBucketCount` returns) |
| - `func (s *Server) architectureView(ctx context.Context, p *page, mode viewMode) (architectureData, error)` (`partArchitecture`, `writtenWindow`; the inventory, `fleet.json` and scenario `handleArchitecture` reads, boxes from `partBoxes`) |
| - A loader assumes its caller already ran the page's full gate: `operatorOnly` for all of them, and `storePageOperator` (`storepage.go:119`, `operatorOnly` plus `storeOperator`'s check of `Config.StoreOperators`, `apistore.go:645`) for the two store loaders. Each loader's doc comment names the gate. Part 3, if it adds deferred parts for these pages, gives each part its page's gate (Task 7's `viewPart.Gate` rule); this task adds no operator part route. |
| -- The write effects for operator doors are Task 8's table rows (store decision, economics saves, architecture refresh); this task adds tests for them. |
| +- Writes from operator doors (store decision, economics saves, architecture refresh) invalidate these entries by read set (Task 8); this task's tests check the redirect targets. |
| - In `viewBlocking` mode a stale entry is served at once with a background refresh, and only a miss waits, so an operator page is warm-fast now and pays one read on its first view per window, as today. The placeholder for that first view is Part 3's, with its templates. |
| |
| - [ ] **Step 1: Write the failing tests:** |
| - `TestOperatorPagesWarmMakeNoRemoteCalls` (one sub-test per page, Paul as operator and store operator). |
| - `TestStoreQueueRefusedOperatorStartsNoLoad`: an operator not in `Config.StoreOperators` GETs `/fleet/store`: the same 404 as today, and `perfLatency.Calls()` is unchanged, no `store-pending` load started. |
| - `TestStoreDecisionShowsOnRedirect`: warm `/fleet/store` and the applicant account's settings; approve; both redirect targets show the decision with zero S3 calls. |
| - - `TestEconomicsSaveShowsOnRedirect`: warm `/fleet/economics` so both the outer entry and `LoadEconomics`' inner entry are fresh; save a changed active scenario; follow the redirect: the page shows the new scenario. Again with an inner sweep held in flight (`HoldNext("list", …)` on one of its listings) when the save lands: after release, the page still shows the new scenario. |
| -- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestStoreQueueRefused|TestStoreDecisionShows|TestEconomicsSaveShows' -count=1`. Expected: FAIL. |
| + - `TestEconomicsSaveShowsOnRedirect`: warm `/fleet/economics` (and, with it, `LoadEconomics`' inner cache through the CLI economics door); save a changed active scenario; follow the redirect: the page shows the new scenario. Again with the view's sweep held in flight (`HoldNext("list", …)` on one of its listings) when the save lands: after release, the page still shows the new scenario. |
| + - Remove `TestScenarioActivationRefreshesArchitecture`'s skip (Task 8). |
| +- [ ] **Step 2: Run** `go test ./internal/console/ -run 'TestOperatorPagesWarm|TestStoreQueueRefused|TestStoreDecisionShows|TestEconomicsSaveShows|TestScenarioActivationRefreshesArchitecture' -count=1`. Expected: FAIL. |
| - [ ] **Step 3: Implement.** |
| - [ ] **Step 4: Run** Step 2's command, `go test ./internal/console/ -run 'TestFleet|TestStoreApprovals|TestEconomics|TestArchitecture|TestArchPage|TestClaimRead' -count=1`, and the walk with `CI=1`. |
| -- [ ] **Step 5: Delete** the `over:` records of every operator screen whose reads now go through the loaders (the walk measures warm views). In the second case, the records Part 3 wrote for screens behind its seams (`GET /fleet`, `GET /fleet/boxes`) stay, with Part 3's reason ("until operator-pages Task 13"), and Part 3's Task 13 deletes them. Walk (PASS); commit, message `console: cache-backed loaders and write effects for the operator pages, for Part 3`, ending with the Co-Authored-By line. |
| +- [ ] **Step 5: Keep every operator screen's `over:` record**, in both cases. In `viewBlocking` mode each of them still waits for its remote reads on the walk's cold request (plan 1 Task 10), and only Part 3's Task 13, which adds their placeholders, makes the cold request fast. Each record's reason becomes "blocks on a cold view until operator-pages Task 13"; that task deletes them. Walk (PASS: warm views have zero remote calls and are fast; the recorded screens are exempt from the cold check). Commit, message `console: cache-backed loaders for the operator pages, for Part 3`, ending with the Co-Authored-By line. *(Astra round 3, finding 2.)* |
| |
| ### Task 16: The console DB: measure, then decide on a read pool |
| |
| @@ -608,7 +599,7 @@ Spec §2.4 C last row: `SetMaxOpenConns(1)` (`store.go:99`, `store_gate.go:1828` |
| - Modify: `internal/console/testdata/perf-budgets.txt`, `internal/console/testdata/perf-session-s3.txt` |
| - Create (by the tool): the census overlay and `docs/superpowers/notes/census-proposal-console-perf-2.md` |
| |
| -- [ ] **Step 1: The file holds no `over:` records** apart from operator screens Part 3 recorded "until operator-pages Task 13" (Task 15's second case), which that task deletes, so the file is empty of `over:` lines by the end of the round. `grep ' over:' internal/console/testdata/perf-budgets.txt` prints nothing else. Any record left is a `skip:`, `deferred:` or `calls <n>:` line with a reason; a `calls` record names the call and why no cache can hold it. |
| +- [ ] **Step 1: The file holds no `over:` records** apart from the operator screens recorded "blocks on a cold view until operator-pages Task 13" (Task 15), which that task deletes, so the file is empty of `over:` lines by the end of the round. `grep ' over:' internal/console/testdata/perf-budgets.txt` prints nothing else. Any record left is a `skip:`, `deferred:` or `calls <n>:` line with a reason; a `calls` record names the call and why no cache can hold it. |
| - [ ] **Step 2: The walk passes with `CI=1`** in under 10 s, its cold pass included (every screen's first response, from a console reset by `resetForColdView`, within 150 ms), and the nav plan's `TestReleasesOlderVersionsAreReachable` passes: `CI=1 go test ./internal/console/ -run TestConsoleScreensMeetTheBudget -count=1 -v`. Update the row in `.amadan/test-weights.tsv`. |
| - [ ] **Step 3: Total S3 use went down.** Run `TestPerfSessionS3Requests`; it prints the session's total, which counts cold views, deferred loads, the promote's own re-read and repeat views. It must be below plan 1's recorded ceiling; write the new total into `perf-session-s3.txt` with the reason `after plan 2, <date>` so a later change cannot raise it unnoticed. If it is not below, the cache is costing more than it saves: stop and find the read before going on. |
| - [ ] **Step 4: Census card**, as plan 1 Task 11 Step 1 (`NAME=console-perf-2`), CLAIMS naming each changed unit: cached reads of the same keys, no read added; `internal/provision` gains `ListRecordHosts`, a listing the unit already made. Approval by a reviewer of the other model family, recorded on #280. |
| @@ -621,6 +612,7 @@ Spec §2.4 C last row: `SetMaxOpenConns(1)` (`store.go:99`, `store_gate.go:1828` |
| |
| - **Spec coverage.** §2.4 C, row by row: account manifest (Task 2, now off the response path), `SetLastAccount` (Task 2), `AccountsFor` and `registry.List` once (Task 2), `assembleChannels` (Task 9), `dnsTargets` fold (Task 3), Overview `Versions` bounded and cached (Tasks 3, 9), pipeline once (Task 3), `instances.Report` (Task 11), `populateAppSettings` (Task 4), `appDeployEmpty` (Task 4), `settingsGates` (Task 13), `aliasReadings` (Task 13), `envCards` + `storeEnvCards` (Task 4), console DB (Task 16). Concurrency as a fallback: part endpoints start every missing load before waiting (Task 7). §2.4 A: serve cached, background refresh single flight (Task 6), miss renders a placeholder (Tasks 7, 9 to 14), read your own writes declared at the mutation, generations covering in-flight loads, re-read in the request, invalidated on failure (Tasks 6, 8; end to end in Tasks 10, 13, 14, 15), refresh only on view (Global Constraints, Task 6), windows (Task 6), "as of" (Tasks 6, 7). §2.4 B: fetch parts following the Logs pattern, HTML fragments from the same templates, no framework, usable without JavaScript, gated like their page (Task 7; Logs through its own data endpoint in Task 12). §2.5 step 3 order: C (Tasks 2 to 5), then A and B (Tasks 6 to 15). §2.6: Task 17. Every task that makes a screen fast deletes its `over:` records; Task 17 ends with none and with a lower whole-session S3 total. |
| - **Review round 1 (Astra, at `e9f42e19`), findings that applied here:** 1 parts run their page's own gate, no operator part routes, refused store operator tested (Tasks 7, 15); 2 effects declared per door with cross-scope rules (Task 8; Tasks 14, 15 tests); 3 generations cover first loads and refreshes in flight (Task 6); 4 marking at the mutation after admission and success, refusals tested (Task 8); 5 immutable values with `viewClone` and a concurrent `-race` render test (Tasks 6, 9); 6 the production flag cached, the route-dependent view derived per request (Task 9); 7 claim route, fixture and probe entries (Task 7); 8 `HoldNext` keeps the read's result and holds one read only (Tasks 2, 10); 10 page and `/logs/data` share the first window (Task 12); 11 the manifest check off the response path, tested with a held read (Task 2); 12 written against the nav plan's code, test conversion owned here, Live now survives a failed listing (Branch notes, Tasks 9, 10); 13 `boxSnapshot` keeps completeness (Task 5); 14 whole-session S3 ceiling (Task 17, with plan 1 Task 10). |
| +- **Astra round 3 (`CODEX-FINDINGS-CONSOLE-PLANS-R3.md`):** the class behind R1-2, R2-4 and R3-3 is fixed by invalidating by read set (Task 8), checked by the coverage oracle in `TestClaimConsoleMutationInvariant` and the warm-before-write cases (deploy-empty on ship, record hosts and environments on instance create, Architecture on scenario activation); the scripts class (R2-3, R3-5) by the no-script-in-fragments rule, the `carlos:part` event and `app_new.html`'s initializer (Tasks 7, 14); 2 operator records kept until operator-pages Task 13 in both orders (Task 15); 4 the host picker is its own part (Task 12); 6 untracked fixtures read inline, so plan 1's instrumentation tests keep their meaning, and background attribution is asserted (Tasks 8, 9, 11); 9 `bgWork` and `waitBackground` cover every request-triggered worker (Task 6); R2-6 `Assemble` takes `now` (Task 9). |
| - **Astra round 2 (`CODEX-FINDINGS-CONSOLE-PLANS-R2.md`):** 1 the pager kept, one cache entry and fragment per page (Tasks 8, 10); 4 economics saves empty and generation-guard `LoadEconomics`' inner cache before re-reading (Tasks 8, 15); 5 filter keys are a hash of the whole effective filter (Task 12); 6 only clock-independent facts are cached and bake state is derived per request from `s.now()` (Tasks 6, 9); 7 the cold pass reset is `resetForColdView` (Task 6; plan 1 Task 10 runs it); 8 is plan 1's; 12a the cold Versions test warms the core through Activity (Task 10); R1 #14 counts come from the S3 fake at the transport (plan 1 Task 9), so `Keys`, `SetFail` and `HoldNext` act on real requests and `HoldNext` can hold a listing (Task 2). |
| - **Round 2 (session lead):** the success-path gap is closed by the witness in `TestClaimConsoleMutationInvariant` (Task 8); Task 15's loaders carry the signatures and seams `2026-10-25-operator-pages.md` names (its Task 8 seams, its Task 13 after this plan). |
| - **Names used from plan 1:** listed under "Depends on". This plan adds `Keys`, `ResetKeys`, `SetFail`, `HoldNext`, `OnPut` to `perfLatency`, and `Assemble` gains the `core` parameter (Task 9). |