Repository navigation
perf(patches): tier 2 calls reuse their server bundle instead of re-reading it - #764
Merged
Merged
Conversation
Every tier 2 call read its version's server bundle from object storage and hashed it before bind. Stored artifacts never change, so after the live retained-version, company and wire checks the bundle now comes from an in-memory LRU keyed by object key and digest, bounded by tier2.bundleCache.bytes and tier2.bundleCache.entries. Simultaneous misses share one read; failures and hash mismatches are never kept. Wide events record bundleLoad: cached, read or joined. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A load could miss the kept bundles, then reach the shared read only after another call's read had settled and left it. It read again and kept the same identity a second time, charging its bytes twice for good. The coalesced lookup now rechecks the kept bundles first, and keeping an identity that is already kept releases the old entry's bytes. bundleLoad is documented as the last load's source: a retried mutation loads on each attempt, and fields are last-write-wins. Tests drive the interleaving deterministically, and cover the entry bound, a stopped leader with a waiting joiner, and two loads in one event. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A focused test replaces one kept identity through two real lookups and checks the exact byte capacity and the replacement's recency. The bundleLoad docs now say it describes the last load to reach the cache, that joined waits on another lookup rather than promising a read, and that a refusal before the cache leaves an earlier value in place. Co-Authored-By: Claude Opus 5.5 <[email protected]>
allisonmahmood
force-pushed
the
perf/747-bundle-cache
branch
from
October 18, 2026 12:01
91e6fb2 to
5361bda
Compare
allisonmahmood
added a commit
that referenced
this pull request
Oct 18, 2026
…g ECS twice (#768) Each tier 2 call asked ECS where its task was twice: one `DescribeTasks` before bind and another before invoke. For a resource-backed query, the second lookup runs after the company snapshot opens, so it also lengthens how long the company connection is held. Caching the address alone wasn't safe. A stopped task's private IP can be reassigned to a fresh spare that holds the same management secret, and nothing in a management request said which task it was meant for. ## The fix 1. **The supervisor checks who it is.** Every management request (`bind`, `invoke`, `stop`, `stats`) can carry `taskId`, the task the host resolved. Before anything else, the supervisor compares it with its `EXECUTION_TASK_ID`. If they differ, or the supervisor has no task id, it refuses with 421 `wrong_task` and does nothing else. 2. **The host reuses the endpoint.** `EcsTaskProvider` keeps each task's resolved endpoint (address, ARN, revision) once a request through it succeeds and its reply decodes, and reuses it for `execution.endpoint.lifetime`, a new host-scoped operating limit, one minute by default. - The cache holds at most `execution.fleet.budget` entries; expired entries are swept on insert. - Any failed, interrupted or undecodable request forgets the entry, without re-sending, and so does any ECS response that shows the task stopped. - A request refused before it took effect (`unauthorized`, `invalid_request` or `wrong_task`) is sent once more, after resolving the task again. - `Fleet.route`'s live binding checks are unchanged. 3. **No replay.** A transport failure through a cached endpoint is never re-sent, because an invoke may already have run. It fails exactly as before, and the next call resolves again. The local fleet provider now names the task on every request too. Its child supervisors always run the same checkout as the host, and this is the path where the identity check runs end to end against real supervisor processes. ## Rollout During a deploy, old and new hosts run side by side, and tasks of both releases keep serving. - **Old hosts** never send `taskId` and never cache. The field is optional, so new supervisors still accept their requests. - **Old supervisors** decode request bodies strictly (`onExcessProperty: "error"`). They have done so since the listener first landed in #428, before the first production deploy. A request that carries `taskId` therefore gets 400 `invalid_request` before the supervisor runs. So a new host must not send the field to them. - **The signal is the task's exact task-definition ARN.** A new host sends the field, and caches the endpoint, only for tasks running its own exec task definition (`ECS_EXEC_TASK_DEFINITION`). ECS reports that ARN for every task. Task definitions never change once registered, and `apps/infra` pins the release image by digest in each one. A task on the host's own definition therefore runs the same image as the host, and its supervisor checks identity. Every other task is resolved on every call, as today. - **Considered and rejected:** a protocol version echoed in bind or stats replies. The host would have to send a request without the field first to learn it, while the definition ARN is known before the first request. - **One PR is enough.** A release ships the host and the exec supervisor as one image, and the host caches only for supervisors from that same image. No deploy has to land first. **The reused-address hazard is closed at every stage of a rollout.** The management secret stays the same across releases, so a cached address that now reaches another task fails in one of these ways, each before any effect: | Who answers at the cached address | Result | | --- | --- | | A spare from this release | 421 `wrong_task` | | An older release's spare | 400 `invalid_request`: it doesn't know the key | | Nothing | Transport failure, not re-sent | In the first two cases the host resolves again and gets `stopped`, the same answer a fresh lookup gives today. ## Lifetime and bounds `execution.endpoint.lifetime` goes in the limits registry as a host-scoped operating limit, the precedent from #764's bundle-cache bounds. That makes it tunable through `PATCHY_LIMITS_JSON` without a release. The entry bound reuses `execution.fleet.budget`: live tasks can't exceed it, so the cache doesn't need a number of its own. The identity check makes a stale entry safe, so the lifetime only sets how often a host re-checks ECS on its own. At one minute, the burst of queries when a screen opens costs one lookup, and an open page costs at most one lookup per task per host per minute. ## What invalidates an entry | Event | How the cache learns, or why a stale entry is still safe | | --- | --- | | This host stops a task (release, drain, deploy retirement) | `stop` polls `DescribeTasks` until `STOPPED`, and any described stopped task is dropped | | Another host stops it, or it crashes | The lease holder's housekeeping `list` drops it, or any later lookup does. Until then, a request either gets an identity refusal or a transport failure (forgotten, not re-sent), or the entry expires | | Address reused by a fresh spare | `wrong_task` or `invalid_request` before any effect, then a fresh lookup returns `stopped` | | Rebind, adoption, epoch change | Same task, same address. The supervisor still checks the epoch on every request | | Spare recycling | A released task is stopped, never handed to another company. Its address reuse is the row above | | Deploy or host replacement | The cache is in memory and starts empty. Tasks of other definitions are never cached | | Any failed or interrupted request through the entry | Forgotten | Housekeeping reads final stats right after listing a task as stopped, and accepts only `stopped`. Because the listing itself drops the entry, those stats calls still get `stopped`, not `transport`. ## Tests - `Management.test.ts`, with a real listener, supervisor and workerd: a misdirected `bind` reserves nothing and loads nothing. A misdirected `invoke`, `stop` or `stats` leaves `callsServed: 0` and the task running. Requests without `taskId`, as an older host sends them, still work. A supervisor without a task id refuses any request that names one. - `EcsTaskProvider.test.ts`. The ECS fake now models each supervisor with the secrets its host injected, models the previous release as refusing `taskId`, and returns fresh task copies, as the SDK does: - a cached endpoint serves seven management requests with one `DescribeTasks`, and is looked up again after its lifetime; - a previous-release supervisor is resolved on every call and never sent the field; - a stopped task's address, reused by a spare from either release, is refused before any effect and re-resolved to `stopped`; - ECS reporting the task stopped drops the entry; - an invoke whose reply was lost is sent once, not re-resolved, and the next call looks up again. - Mutation checks: removing each of the four mechanisms (the field, stop invalidation, caching other definitions, re-sending after a transport failure) fails exactly its test. Sending a wrong task id from the local provider fails the local fleet journey in `DevelopmentExecution.test.ts`. ## Numbers ECS can't be faked outside the unit fake, so these counts come from that test. The sequence is one bind, then three calls of bind and invoke: | | `DescribeTasks` | | --- | ---: | | `main` | 7, one per management request | | This branch | 1 | Expected production effect: - **Lookups.** One or two `DescribeTasks` round trips removed per call: two for a top-level call (bind and invoke), one for a nested call that reuses its parent's bind. - **Connection hold.** For resource-backed queries, the company connection is held for less time, because the lookup before invoke used to run after the snapshot opened. - **ECS load.** Lookups fall to about one per task per host per minute. The lookup's own latency was never measured, so re-measure `dbMs` and `durationMs` after the deploy, as #754 plans. ## Known gaps - A task that dies without any host observing it can leave its address cached until the first failure or ECS observation. If nothing answers at that address, the first request may wait for its connect timeout or call bound instead of failing at once with `stopped`. - A narrow race: a call can cache a running task just as housekeeping lists it stopped. That housekeeping pass then fails its final stats with `transport`. The next pass resolves again and finishes. Closes #752 Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol. --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood
added a commit
that referenced
this pull request
Oct 18, 2026
…e task (#773) Every top-level tier 2 call sent the version's whole server bundle (about 216 KB in production) in `POST /bind`. When the version was already loaded with the same hash, the supervisor returned the existing process and never used the bytes, so on a warm call the upload, its JSON encoding and the supervisor's two strict decodes were pure waste. ## The fix **A bind by hash.** `BindRequest` gains an optional `binding` (company, patch, version and SHA-256) that names the version without its bytes. A request carries `bundle` or `binding`, never both; the schema refuses both as `invalid_request`. The supervisor makes the same checks as for a bundle bind: company, epoch, limits and callback URLs. - **Held** (a live process for that version, loading or ready): it adopts the epoch, limits and callback URLs, waits for a loading process, checks the epoch again after the wait, and returns the current generation, exactly as an idempotent bundle bind does. A different hash for a held version is `binding_conflict`. - **Not held** (never loaded, reaped, evicted or dying): it refuses `bundle_required` (409). It looks the version up before changing anything, so this refusal comes **before any effect**: no company is reserved, no epoch adopted, no limits or callback URLs applied. That is why the host can safely send the same bind again with its bundle. **The host binds by hash first.** `TaskProvider.bindByHash` sends the bind by hash. Only after a decoded refusal that proves it had no effect does it send the same bind with its bundle: `bundle_required`, or `invalid_request`, which a supervisor from before this change gives the unknown `binding` key. It never sends a second bind after a transport or protocol failure. - `EcsTaskProvider` does this only for same-release supervisors (see Rollout), inside its per-task `answer`, so both requests reach the same resolved task. A `bundle_required` is answered after the supervisor's identity check and recovered there. It neither forgets a cached endpoint nor triggers another `DescribeTasks`. Every other #768 rule is unchanged: identity first, re-sends only after `unauthorized`, `invalid_request` or `wrong_task`, never after a transport failure, and reply decoding inside the endpoint-cache boundary. - `LocalTaskProvider` and the in-process `local.ts` executor always bind by hash first. A local task owner can outlive its host's checkout, so a host restarted after an update may reach an older supervisor; it answers `invalid_request` and gets the bundle. In process no bytes move, but `pnpm dev`, `patchy dev` and the runtime suites now run the fleet's path. **The host's own bundle read is unchanged.** Runtime still loads the bundle before binding. Since #764 that is a retention check plus a memory hit (`bundleLoad: cached`). Loading only after `bundle_required` would need a hash-only lookup on `ServerBundles`, which is `Content.ts` (#746's lane), and would save a read only when the host's cache missed but the supervisor was warm. I left it out. **Eviction between bind and invoke recovers.** Before, an invoke refused `bundle_required` or `stale_generation` surfaced as `handler_failed`. Now Runtime's attempt loop binds again **once**, under a fresh attempt and capability, and invokes the current generation. It does this only when all of these hold: - the call is top-level; - the failure is an `invoke` refusal with one of those two codes; - the attempt settled (nothing uncertain). Every pass checks the call's deadline before it binds, so a call refused at its deadline times out instead of binding again. What proves nothing ran: - The supervisor's `select` refuses both codes before it registers the attempt or calls the engine. - The loader's own `bundle_required` refuses before any handler runs. - Both providers produce these reasons only from a decoded refusal reply. A lost reply is `transport`, which is never retried, so an invocation is never replayed after uncertain transport loss. Each pass takes its generation from its own bind reply, so a stale generation is never reused. A second refusal fails the call as before. The refused invoke ran no handler, so it doesn't count toward `tier2.mutation.attempts`: a recovered mutation still gets its three conflict attempts. The call's request or re-run event records `rebound: true`, whatever came of the rebind, so a rebind that then fails `busy` still shows the refusal behind it. **Nested calls are unaffected.** They reuse their parent's bundle and bound version, never bind, and never take the recovery path: their parent is running in that process, so if it's gone, the parent fails too. ## Wire shape I chose an optional `binding` on `bind` over a new route. The reply, the checks and the epoch semantics are bind's own, so a second route would duplicate them. An older supervisor would also answer an unknown route with a router 404 rather than a typed refusal. A `bind` without `bundle` already means a company bind (claim, adoption, limit updates), so the version has to be named. Strict decoding stays meaningful: unknown keys are still refused, and `bundle` with `binding` is refused by the schema. ## Rollout Management schemas are strict, so an older supervisor refuses `binding` as an unknown key, just as it refuses #768's `taskId`. I reused #768's gate and renamed it from `checksIdentity` to `sameRelease`: a task on the host's own exec task definition runs the host's own image, pinned by digest, so its supervisor speaks the host's management wire. | Host | Supervisor | What happens | | --- | --- | --- | | New | Same release | Bind by hash, full bind on `bundle_required` | | New | Older release | Full binds only, as today; never sent `binding` | | Older | New | Full binds, accepted unchanged | | New, local fleet | A retained owner from an older checkout | Bind by hash refused `invalid_request` before any effect, then the full bind | The recovery needs nothing from the supervisor: both refusals predate this change and come before dispatch in every release. One PR is enough, because host and supervisor ship in one image. One behaviour change for every host: a bundle bind whose hash conflicts with a live process of the same version is now refused before it adopts its epoch and limits, where before it was refused after. Versions are immutable, so this doesn't happen outside tests. ## Tests - `Management.test.ts` (real listener, supervisor and workerd): a bind by hash to a version not held gets 409 `bundle_required` and leaves the task an unreserved spare. After a bundle bind, a bind by hash returns the same reply. A different hash is `binding_conflict`, and `bundle` with `binding` is 400 `invalid_request`. - `Supervisor.test.ts`: a bind by hash waits for a loading version and returns its generation. When adoption raises the epoch during the wait, both waiting binds fail `stale_epoch`. - `EcsTaskProvider.test.ts`. The fake supervisors now hold versions, and the previous release refuses `binding`: - a current-release task gets the bundle once across four binds, and again only after it drops the version, all on one cached endpoint with no extra `DescribeTasks`; - a previous-release task gets only full binds. - `LocalTaskProvider.test.ts`, with a real task and a transport layer that answers like an older supervisor: each version bind is refused by hash and then sent with its bundle, and a bind by hash whose reply was lost is never followed by the bundle. - `Invocation.test.ts`: - an invoke refused `bundle_required` or `stale_generation` rebinds and succeeds on the new generation, with a new attempt id; its event reports one attempt and `rebound: true`; - a second refusal fails after exactly two binds and two invokes, still marked `rebound`; a lost invoke reply (`transport`) is never re-sent and isn't; - a refusal at the deadline binds no more, and a rebind that outlasts the deadline invokes no more; - a nested call keeps its parent's generation and never binds. - `MutationTransaction.postgres.test.ts`, real `SERIALIZABLE` Postgres: after a rebind, a contended mutation still gets three handler attempts before `write_conflict` (event `attempts: 3`, `rebound: true`), and a committed mutation's key replays its stored reply without running the handler again. - Mutation checks: each of these breaks exactly its test. - the post-wait epoch check - the `parent` and once-only guards, and leaving the refused attempt counted (in both the unit and the Postgres test) - binding by hash without the release gate (the older supervisor's hash-bind count), or never - recovering `bundle_required` outside the endpoint-cache boundary (that one breaks both provider tests) - dropping `invalid_request` from the fallback (the previous-wire local test) ## Validation On this worktree's `pnpm dev up brightline`, I ran a second host on the same database with tier 2 on the local task provider (`EXECUTION_PROVIDER=local-fleet`). Calls went through real supervisor and workerd processes. New Business's server bundle is 196 KB; production's is about 216 KB. **Bytes sent to `/bind` per warm call** (temporary request logging, not committed; 40 warm `deals.board` calls each): | | Bind body | Bind round trip, p50 | | --- | ---: | ---: | | `main` | 221,293 bytes | 6.5 ms | | This branch | 608 bytes | 2.4 ms | **Warm call latency**, without the logging: 100 sequential calls per run after 10 warm-ups, at load ≈3, alternating main and branch: | | p50 | p90 | | --- | ---: | ---: | | `main`, two runs | 26.1 / 26.8 ms | 28.9 / 30.9 ms | | This branch, two runs | 23.5 / 23.9 ms | 26.5 / 26.5 ms | That's about 2.8 ms (11%) off each warm call on loopback. **Cold, reaped and evicted versions still load:** - **Cold** (a fresh task): the 608-byte bind by hash is refused `bundle_required` in 4.4 ms, then the full bind loads the version and the call succeeds. - **Reaped** after 60 s idle: the same, and the next call binds by hash again. - **Evicted** (residency capped at one process, alternating the two tier 2 patches): each bind evicts the other version, and each call reloads by full bind and succeeds, 6 of 6. - **Evicted between bind and invoke** (three versions capped at two processes, three concurrent loops of 60 calls): 28 invokes were refused `bundle_required` before dispatch. - 5 calls rebound and succeeded on the new generation. - 21 were refused `busy` on the rebind (429 with `retryAfter`), because the tiny cap had no idle process to evict. - 1 was evicted again and failed `handler_failed`, which is the bound. - On `main`, all 28 would have failed `handler_failed`. - I counted rebinds by `attempts: 2` on those queries. That run came before I stopped counting the refused attempt, which changes only the count. **Expected production effect:** - A warm top-level call no longer sends about 216 KB to its task. That saves the host's JSON encoding, the transfer across the VPC, and two strict decodes on the supervisor's Fargate CPU, which is smaller than this machine. Expect at least the local saving; re-measure `durationMs` after the deploy, as #754 plans. - A cold or reaped version pays one small extra round trip, the refused bind by hash, before its full bind. - Nested calls never bound, so they're unchanged. - A call whose process is reaped between bind and invoke now succeeds, or gets `busy`, instead of failing `handler_failed`. ## Known gaps - The host still reads its bundle (a memory hit since #764) before every top-level bind; see above. Closes #751 Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol. --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood
added a commit
that referenced
this pull request
Oct 18, 2026
#770) Every load of a scripted patch fetches its document from `/~content/:patchId/:versionId`. The server let the viewer in, then read the version's HTML from object storage: p50 122 ms in production, a large part of the content's 228–375 ms time to first byte. The body then went out uncompressed: 296 KB for a typical tier 2 patch. Now, once the door has let the viewer in, the document comes from the host's memory, and it goes out compressed with brotli or gzip by `Accept-Encoding`, with `Vary: Accept-Encoding`. The door, retention, company, lifecycle and wire checks still run on every request, cache hits included. Only the storage read moves to memory. Browser caching is unchanged: `private, no-store` behind the door, and a public patch's current version keeps `public, max-age=60`. ## Measured On the local instance (`pnpm dev up brightline`), each patch was opened in Chromium through Playwright as Allison, 11 loads per run after a server restart. The throttled runs used CDP's 100 ms latency and 20 Mbps down, as in #761. The figures are medians of loads 2–11, plus 5 separate cold loads, each the first load after a restart. Wire bytes include response headers. | New Business (tier 2) | main | this branch | | --- | ---: | ---: | | Content on the wire | 235,112 B | 96,195 B (br) | | Storage reads in 22 loads | 22 | 1 | | Warm time to first byte | 6.0 ms | 4.3 ms | | Cold time to first byte, 5 restarts | 19–26 ms | 32–34 ms | | Throttled, request to last byte | 196 ms | 139 ms | | Kudos (tier 1) | main | this branch | | --- | ---: | ---: | | Content on the wire | 173,060 B | 84,442 B (br) | | Storage reads in 22 loads | 22 | 1 | | Throttled, request to last byte | 170 ms | 135 ms | I counted storage reads with `inotifywait` on the stored document files, and they match the new `contentLoad` field: one `read`, then `cached`. The local store is a filesystem, about a millisecond away, so the warm gain here is small. **Expected in production:** every load after a host's first read of a version skips the 122 ms p50 storage read, and a typical 296 KB document is about 120 KB with brotli. These documents compress 2.4–2.5× (234,517 → 95,556, 213,495 → 89,847, 172,465 → 83,803 bytes), less than the broker's 3.3×. With TLS and TCP slow start, cutting 175 KB saves more than the 57 ms it saved locally. Each host keeps its own copies, so after a deploy every host reads each version once. That first load pays the read plus compression, about 11 ms here and likely two to three times that on a 0.5 vCPU host; see below. New Business and Kudos both rendered fully as their personas, with compression on and no browser errors. With `curl`, `br`, `gzip` and identity each decode to main's exact bytes. `HEAD` carries `Content-Encoding: br`, `Vary` and the br `Content-Length`. A signed-out request gets its 401 door with no `Content-Encoding` and no `Vary`. ## Design **One cache helper for bundles and documents.** I generalized #764's bundle cache into `Content.makeArtifactCache`. It holds the least-recently-used map with its byte and entry bounds, one job per miss, and the `cached` / `read` / `joined` labels. - **Jobs.** A miss starts a job that reads the artifact and keeps it. Simultaneous misses join that job. The job runs in the host's scope until it settles, even when every load waiting on it stops. A retry therefore joins it or finds what it kept, and never starts the read or compression again. - Each load decides cached, joined or started in one synchronous step, so there's no gap between a miss and its join. - A job's read is stopped after 30 seconds. Without that, a hung read would hold its identity forever: S3 reads have no request timeout of their own. Native compression can't be interrupted, so it finishes first, and a job past its deadline keeps nothing. - A job settles from its fiber's exit observer, which sees every exit. That covers a host scope closing before the job's fiber has run, which round 1's `onExit` missed (round 2). - **Why not Effect `Cache` (round 1).** This replaces the zero-lifetime Effect `Cache` from #764. That `Cache` removes a lookup and interrupts it as soon as its last waiter leaves. A retry then started a second read, while the first one's native zlib work kept running. - **Bundles.** They share the change. An abandoned bundle read now finishes and is kept, and a hung one fails at 30 s. #764's test for "a read with no one left waiting stops" is rewritten for that. - **Dead code removed.** #764's "replaced bundle" test covered two lookups of one identity both keeping it, which can no longer happen. It now checks that the second load joins the first. - **Where it's built.** The document cache is built in Serving's route layer, not inside `Content`, because its compressed bodies come from `compression.ts` in Serving. `Content.read` still does the read. - **Size check up front.** The helper decides whether an artifact will be kept from its recorded size before reading it, and tells the read. A document too large to keep is then sent as stored instead of being compressed on every load. **Compression is bounded and never on the event loop.** Synchronous brotli 9 plus gzip on these documents blocks for 25–31 ms (234 KB: 22 + 9 ms). `compress` now runs on libuv's threadpool; the event loop's longest gap during it was 2–4 ms in the same measurement. - **One at a time (round 1).** The host compresses one document at a time, with brotli then gzip on a single pool thread. That leaves the other three pool threads for file, crypto and DNS work. On a half-vCPU task, running the codings in parallel would finish no sooner. - **The permit counts native work.** Compression runs uninterruptibly inside the permit, so the permit is only released when zlib has finished, not when a waiting fiber stops. - **Four documents at a time (round 2).** A host reads and prepares at most four documents at a time, from the read through keeping them. Documents waiting their turn haven't been read, so they hold no bytes, and their wait counts against the job's deadline. Within those four, storage reads overlap and compression queues. - **Measured:** three different cold documents requested at once after a restart get their first byte at about 22, 35 and 46 ms (three runs). - A **miss** costs the storage read, a digest check, and both codings in turn. - A **hit** costs a map lookup, `negotiate` and the response headers. - The broker now uses the same async `compress` once at startup, and the synchronous `precompress` is gone, so `compression.ts` has one compressor and its header comment names both users. - I kept brotli 9. Quality 5 makes these documents 0.1–0.3% larger for about 55% of the CPU (New Business: 13 ms against 22 ms). It's the next lever if misses on the 0.5 vCPU hosts show up in traces. **Memory.** I added two host-scoped operating limits, following #764's precedent: - `serving.contentCache.bytes`: 64 MiB, counting the raw, brotli and gzip bytes together. - `serving.contentCache.entries`: 256. A typical 296 KB document holds about 550 KB with both codings, so a host keeps about 120 documents. A document whose stored size is over a quarter of the byte bound (16 MiB) is never kept or compressed. The largest scripted document a publish accepts is 10 MiB, so that only happens if the bound is tuned down. Peak memory per host is 64 MiB of kept documents beside #764's 64 MiB of bundles, on a 2 GiB task. On top of that come the documents being prepared: at most four, each holding its decoded string (up to twice its size for non-Latin text), its bytes and its compressed outputs: four to five times its size. Worst case that's about 200 MiB with today's 10 MiB publish cap; with typical 300 KB documents it's about 6 MB. Every other cold load waits without bytes. A document too large to keep goes through the same four places, then its body is held by the requests sending it, as on main. A compressed body under 16 KiB can keep zlib's 16 KiB output chunk alive, which is bounded by the entry count. **What's cached is the same for every viewer.** The body is the stored bytes verbatim. The document nonce stays in the URL, and the server never reads it. Everything else is computed per request from the version row and the request, as before: the CSP from the tier only, `Permissions-Policy`, `Cache-Control`, cookies and the new `Vary` and `Content-Encoding`. No header depends on the body. The key comes from the version row the door admitted, `objectKey#contentHash`, never from the URL. The object key contains the version id, so a viewer can only ever get bytes of a version they were just admitted to. There's no ETag or 304 path. Refusals return before the cache is touched, so they are never cached, compressed or varied. **Integrity.** A miss checks the bytes against the version's recorded `contentHash`, as #764 does for bundles. A mismatch fails as `StoredDocumentMismatch`, a fault answered with a 500 like a missing object, and is never kept. **Scope.** Only `/~content`. A tier 0 page embeds its HTML in the shell's `srcdoc` through `Content.read` and never fetches its content URL. Moving that page onto the cache would need extra code, so it isn't here. A tier 0 version's own content URL goes through the same route, so it is cached too. **Observability.** A content request's wide event adds `contentLoad` (`cached` / `read` / `joined`) and `contentEncoding` (`br` / `gzip` / `identity`). `responseBytes` is now the compressed size. Both fields are in the analytics glossary and OPERATIONS' wide events section. ## Tests `Pages.test.ts` builds one host's routes over a store that counts document reads, with each request inside a request event: - Three loads read storage once: `read` then `cached`, in `br`, `gzip` and identity. - Two simultaneous loads share one read, labelled `read` and `joined`. A failed read and a digest mismatch are faults, and the next request reads again. - With the document kept, a signed-out reader gets 401, another company 404, a deactivated member 403, and an operator-disabled patch 404. None of these is compressed or varied, and the read count stays at 1. - `Accept-Encoding` picks br, gzip or identity, including weights, with `Vary`, and each body decodes to the stored bytes. - A document over a quarter of the byte bound is sent as stored and read on every load. The entry bound evicts the least recently used document. - Round 1: - Three different cold documents become ready to compress at the same moment, and only one compresses at a time. A watched compressor counts calls and the most running at once. - A load abandoned mid-compression, then retried at once, takes one read and one compression. The retry is `joined` and the next load `cached`. - Two documents that fit the byte bound by raw bytes, but not by everything they hold, evict the least recently used. Charging raw bytes alone fails this test. - Over a real socket, `HEAD` carries `Content-Encoding: br`, `Vary` and the brotli body's `Content-Length`, with no body. - I checked the tests by breaking the code on purpose: without the permit, with the job tied to its first waiter, or with raw bytes charged alone, the matching new test fails. - Round 2: - Six cold documents whose loads are all abandoned are read four at a time, and all six are still kept. That's six reads and six compressions in total, never two at once. - With the bound removed, the test fails (6 reads instead of 4). `Content.test.ts`: - An abandoned bundle read finishes, and a retry joins it. - A read that never settles fails at 30 s and is read again. - Round 2: closing the host's scope before a job's fiber runs leaves no load waiting, and a later load starts afresh. Round 1's helper hangs on this test. The existing UTF-8 and BOM test now records each rewritten document's digest, because stored bytes never change once published. Round 2: `pnpm check` (5/5, 1,923 tests) and `pnpm verify` (9/9, including tier2-smoke, cli-smoke and browser) both passed in full. Round 1: `pnpm check` passed format, lint, synth and all 1,890 tests. Typecheck failed on one type annotation in the new test helper; I fixed it, and `pnpm typecheck` then passed on its own. Outside `Pages.ts`, `compression.ts`, `Content.ts` and their tests, round 1 only changes the analytics glossary and comments, so I didn't run `pnpm verify` again. `pnpm verify` (before round 1): 8 of 9 steps passed, including tier2-smoke, cli-smoke and browser. The `test` step had one failure, a 5 s timeout in `packages/sdk/src/SdkApi.test.ts` ("retains advertised archives after a same-version repack prunes local copies"), while the machine's load average was about 13. That file passed 3 of 3 runs alone, and the full suite passed in `pnpm check` an hour earlier. It packs and prunes SDK archives and touches nothing here. Closes #746 Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol. --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
allisonmahmood
added a commit
that referenced
this pull request
Oct 19, 2026
…ng Reconnecting (#783) Release 14's What's new entry, written from \`7694bab\`. It covers everything merged since release 13's \`through\` (\`c9b8fc4\`), and sets the \`patchy\` release to \`0.14.0\` (\`packages/patchy/package.json\` and \`CURRENT_RELEASE\`). | Change | PRs | | --- | --- | | Improved: Tools with server code answer faster | #756, #764, #768, #769, #771, #772, #773, #775, #778 | | Improved: Your company's tools and pages open sooner | #759, #761, #766, #770 | | Fixed: Tools stop flashing Reconnecting while they load | #755, #776, #780 | | Improved: Publishing is quicker | #729 | | Improved: New tools start with a tidy layout | #763 | | Improved: Your usual is easier to scan | #721 | | Fixed: A page that isn't there says what to do | #762 | | Fixed: A logo Patchy can't read is refused, not a crash | #728 | | Behind the scenes: richer logs for live data | #758 | #720 is release 13's own entry, so it's left out. Made by Claude Opus 5.5 via Claude Code. Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Every tier 2 call and re-run read its version's server bundle from object storage and hashed it before bind. In production that read is p50 45 ms, p90 129 ms and p99 338 ms, on the critical path of every query, for bytes that never change once stored.
Now, once the retained-version, company and wire checks pass, the bundle comes from memory, keyed by artifact identity: object key plus sha256. Those checks still run on every call; only the storage read and the hash are skipped.
tier2.bundleCache.bytes(64 MiB) andtier2.bundleCache.entries(256). They are starting values and can be tuned throughPATCHY_LIMITS_JSON. A bundle over a quarter of the byte bound is never kept.Cachewith a zero lifetime does the coalescing only, so it holds nothing once the read settles. The shared read rechecks the kept bundles first, for a load that missed just as another read settled.bundleLoadfor the last load to reach the cache:cached,read, orjoined(waited on another call's lookup). A retried mutation loads again on each attempt that passes the retained-version checks and reports the last.Numbers
Local instance, brightline environment, with a six-query tier 2 screen modelled on the one in #754 (176 KB server bundle). The local store had 45 ms of latency added to bundle reads, matching production's p50; that instrumentation is not committed. Five warm screen loads and five add-note waves per run, at low machine load:
durationMsp50 / p90After a server restart, the first load's two simultaneous first queries did one read between them: one recorded
read, the otherjoined. The other four werecached.Dev paths
patchy dev(packages/patchy/src/devExecution.ts) supplies its ownServerBundlesfrom memory, with execution version ids derived from each bundle's sha256. It never reads storage, so it does not need the cache.DevelopmentInvocation(local and test hosts) usesContent.serverBundlesLayerand gets the cache. Keys include the recorded sha256, so an artifact that changes under the same version id misses.Server.tsprovidesContent.serverBundlesLayertoFleetInvocationand toDevelopmentInvocationin mutually exclusive branches, so each server process builds one cache. Effect would memoize the same layer within one build anyway.Tests
Over a migrated database, with a counting
ContentStorelayer:readandjoined; a later load iscached;Closes #747
Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.