Skip to content

perf(serving): the shell script is cached and compressed - #761

Merged
allisonmahmood merged 2 commits into
mainfrom
perf/745-broker-cache-compress
Oct 18, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
perf/745-broker-cache-compress

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

Every scripted patch load downloaded /~shell/broker.js in full: 294 KB, no-store, uncompressed. In production traces that took 0.3–0.9 s, and the patch frame waits for it.

Now the shell loads /~shell/broker.js?v=<SHA-256 of the script>:

  • A host whose broker hashes to v serves it public, max-age=31536000, immutable. A foreign or missing v, from a shell another release rendered, gets the host's current bytes no-cache, never immutable.
  • The script is compressed once at startup with brotli and gzip, chosen by Accept-Encoding (honouring identity and q=0), with Vary: Accept-Encoding. Shell HTML, patch content, API JSON, refusals and event streams stay uncompressed.

The URL uses a query string rather than a hashed path because of rolling deploys. A host still on the previous release only knows /~shell/broker.js, ignores the query, and answers no-store as it does today, so a new shell routed to it still loads a broker. I checked this live: main's server answers this branch's ?v= URL with 200, no-store and its own bytes. A shell and broker from different wire versions still take the existing one-refresh shell_outdated path: broker.ts compares the shell's data-wire with its own WIRE_VERSION, and the runtime refuses a stale X-Patchy-Wire.

scripts/build-serving-broker.mjs writes the digest next to the script it hashes, so the two can't drift.

Measured

On a local instance (pnpm dev up brightline), the tier 2 New Business board was opened in Chromium through Playwright, throttled with CDP Network.emulateNetworkConditions to 100 ms latency and 20 Mbps down. Each figure is the median of 10 runs.

main this branch
Broker bytes on the wire, first load 294,918 (identity) 89,932 (br)
Broker on reload and on a new visit re-downloaded, 222 ms from cache, 0 bytes
Navigation → patch frame request, first load 384 ms 289 ms
Navigation → patch frame request, reload 348 ms 124 ms
Navigation → patch frame request, new visit 348 ms 123 ms

Byte counts include response headers; gzip is 94,442 bytes. Locally there's no TLS or TCP slow start, so production's saving on a first load should be larger: 90 KB needs fewer round trips than 294 KB.

Other surfaces

  • patchy dev renders the same shell. Its broker route ignores the query and stays uncached and uncompressed; devServer.test.ts now loads the shell's versioned URL.
  • Shell CSP: script-src 'self' matches on origin, never on the query, so the versioned URL is allowed. The measured runs execute the broker under this policy.
  • apps/infra: clients reach hosts through the ALB alone (HTTP/2, no CloudFront, no WAF). An ALB doesn't compress and passes Content-Encoding, Vary and Cache-Control through unchanged, so nothing double-compresses or strips headers.
  • Docs: no doc described broker caching, and ADR-0010's one-refresh rule is unchanged.

Tests

  • Pages.test.ts:
    • A scripted shell's v is the SHA-256 of the served script.
    • A matching v gets br, gzip or identity by Accept-Encoding, including weights and q=0, immutable and with Vary. Each body decompresses to exactly the script.
    • A missing or foreign v gets the current bytes no-cache.
    • The previous release's route answers the new shell's URL. This test rebuilds main's route on the same router, because what old hosts rely on is that the router matches the path and their handler never reads the query; the live check above covers the rest.
  • compression.test.ts:
    • A header that refuses everything, identity included (*;q=0, identity;q=0), still gets identity rather than a 406, and so does *;q=0, identity. RFC 9110 §12.4.1 allows this, and a 406 on the shell's own script would break the page.
    • An entry whose weight breaks §12.4.2's grammar (q=2, q=0.0001, q=1e0) is ignored, as if it weren't listed.
  • render.test.ts checks the versioned URL's shape, and devServer.test.ts loads it from patchy dev.

Closes #745

Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.

The shell loads /~shell/broker.js?v=<sha256>. A host whose broker matches v
serves it immutable; any other v, or none, revalidates. Bodies are brotli or
gzip, precompressed once at startup and chosen by Accept-Encoding.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:ui Portal and first-party browser pages, shared rendering and styles size:m 100-500 changed lines labels Oct 17, 2026
…ignores malformed weights

A header refusing every coding still gets identity, per RFC 9110 §12.4.1,
rather than a 406 on the shell's own script. A weight outside §12.4.2's
grammar drops its entry instead of ranking it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit fe4b612 into main Oct 18, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the perf/745-broker-cache-compress branch October 18, 2026 11:57
allisonmahmood added a commit that referenced this pull request Oct 18, 2026
Since #759, company and local documents send subscriptions without
waiting for the broker's `me` round trip. Everything else still waited
for it: calls, mutations, actions, tier 1 direct reads and downloads. So
a page that never asks for `me` still paid that round trip, about 125 ms
in production, on its first save or read.

The wait added nothing. Runtime's dispatch admission checks every one of
those operations against the pinned viewer before running it. Company
and local shells now forward them straight away. `me` stays lazy, and
`route.set` still checks the account through `me` first, because it
changes history without calling Runtime.

Unchanged:

- the `failure()` handling for `session_expired`, `principal_changed`
and `shell_outdated`;
- the fresh `me` probe after `access_denied`. A refused shared source
leaves the document usable; losing access to the document ends it;
- public directory binding;
- tier 2's execution-ready and closed gates.

There are no new retries. A stale first mutation racing a session
refresh is still refused, as before.

## What Runtime checks, per forwarded operation

Every forwarded operation reaches `dispatch` in
`packages/runtime/src/Runtime.ts`. That includes `/api/runtime/call` and
the file `GET`/`PUT` routes for `files.get`, `files.put`,
`shared.files.get`, `files.stage` and `files.redeem`. Before anything
runs, dispatch:

- authenticates the session, or refuses `session_expired`;
- refuses `access_denied` when the version isn't served or the viewer
can't open it, such as a deactivated viewer or another company's;
- compares `X-Patchy-Principal` with the session's user, or refuses
`principal_changed`. On POST, it also requires the envelope principal to
match the header.

When those checks run:

- **Reads and mutations**, including `tables.*`, `files.*`, `shared.*`
and `members.*`: before the handler runs.
- **`server.call`**: before `Invocation.call`. A new unit test pins
this.
- **Integrations** (`postgres.*`, `posthog.*`): before the query runs,
inside the recorded attempt. A refused first integration call therefore
leaves a refused row in the integration log, attributed to the session's
actual viewer. That already happens today for any integration call after
the first one.

## Measured

On this worktree's dev instance, a `team` environment signed in as its
admin, with two starter patches that never call `me`:

- a tier 2 page whose first operation is a `server.call` query, or a
mutation at `/write`;
- a tier 1 page whose first operation is `tables.list`.

A Playwright `route` delay added 120 ms to every `/api/runtime/call`, as
in #759. Each figure is the median of 8 warm loads, measured from the
document request to the first operation's response. For the main column,
I restarted the same instance with main's broker.

| First operation | main | this branch |
| --- | --- | --- |
| tier 2 `server.call` (query) | 316 ms | 198 ms |
| tier 2 `server.call` (mutation) | 318 ms | 209 ms |
| tier 1 `tables.list` | 301 ms | 193 ms |

A second branch run, after restarting the instance, gave 199, 189 and
175 ms. On main, every load sent one `me`. On this branch, none did.

The waterfall for one tier 2 load, in ms from the document request:

```
main                         this branch
  0–13   document              0–12   document
 10–22   /~shell/broker.js     9–21   /~shell/broker.js
 30–41   /~content/…          29–41   /~content/…
 53–179  me                   48–188  server.call
180–317  server.call
```

The tier 1 load has the same shape: main sends `me` from 45 to 171 ms
and `tables.list` from 171 to 298 ms; this branch sends `tables.list`
from 50 to 177 ms.

The shell's broker URL changed from `?v=39732119…` to `?v=a2596dfd…`.
The digest is a hash of the built script, so the immutable cache from
#761 busts by itself.

## Tests

`test/browser-tier1/pinned-subscriptions.spec.ts` is renamed to
`pinned-viewer.spec.ts`, since it now covers more than subscriptions.
Each new case runs in company and local scope, on a page whose patch
never asks for `me`:

- The first write and, on a reload, the first read and a subscription
all complete with no `me`. When the patch then asks, exactly one `me`
goes out. This replaces #759's lazy-`me` case.
- After an account switch, the first write gets a `409` and ends the
page as `principal_changed`. No `me` is sent, and the table stays empty.
- After the session expires, the first read gets a `401` and ends the
page as `session_expired`.
- With its shared source retired, a first shared read is refused with
`access_denied`. The probe `me` answers `200`, and an owned write then
succeeds on the same page. After a reload, with the viewer deactivated,
the first read gets a `403`, the probe is refused, and the page ends as
`access_denied`.

Against main's broker, all four new cases fail in both scopes. #759's
three held-`me` cases still pass.

`packages/runtime/src/InvocationAdmission.test.ts` adds one unit test. A
`server.call` whose principal isn't the session's viewer is refused with
`principal_changed`, and `Invocation` never runs. It fails if
`server.call` skips admission. The browser cases cover tier 1 operations
only.

`pnpm verify` passes on this head, rebased on main: format, lint,
typecheck, synth, test, postgres-concurrency, cli-smoke, tier2-smoke and
browser (75 tests).

## Surfaces

- **Wire contract and runtime schemas:** unchanged. No request, response
or schema moved.
- **CLI:** none. `patchy dev` serves this same broker in local scope,
which the local cases cover.
- **Vocabulary and product shape:** ADR-0010's pinned-viewer sentence is
updated.
- **Served pages:** the broker script and its digest.

Closes #760

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:server Touches the server area area:ui Portal and first-party browser pages, shared rendering and styles size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The shell script is re-downloaded uncompressed on every load

1 participant