Skip to content

perf(runtime): a patch runs two queries at a time - #756

Merged
allisonmahmood merged 3 commits into
mainfrom
perf/743-two-reruns-per-patch
Oct 17, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
perf/743-two-reruns-per-patch

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

A tier 2 screen ran its queries one at a time. subscriptions.reruns.patch defaulted to 1, so a page waited for the sum of its queries rather than the slowest one, even though its company was allowed two re-runs at once.

The patch default is now 2. subscriptions.reruns.company stays at 2, so a company's re-run concurrency and connection use don't change; one patch can now use the whole allowance. The two limits are set separately, and overriding one doesn't move the other. The company limit counts runs, not connections: a re-run reading shared tables or stores briefly takes a second company connection for its access check, and none are reserved for writes. The registry, docs/limits.md, ADR-0010, the API description and the patchy-server skill now say so. Setting {"subscriptions.reruns.patch":1} in PATCHY_LIMITS_JSON restores the old behaviour without a release.

Measured locally

A tier 2 patch with six queries on one screen. Each query waits 400 ms in the guest while holding its company snapshot, so it is I/O-bound like production's. Playwright loaded it five times after a warm load. Concurrency comes from the re-run wide events.

main this branch
One page: last panel (median of 5) 2.98 s (2.98–3.00) 1.75 s (1.75–1.78)
One page: peak re-runs per patch 1 2
Two patches opened together: last panel (median of 10) 3.02 s (2.97–3.03) 3.01 s (2.59–3.04)
Two patches opened together: peak re-runs per company 2 2

Panels now arrive in pairs, at about 0.49, 0.91 and 1.75 s, instead of a 415 ms staircase. Two pages of one company still share its two slots. Their documents take turns, and each turn runs two of that document's queries, so neither page is slower than on main. A run discarded by the shell's reconcile replace (#742, #750) adds the rest of the gap above the ideal of about 1.3 s.

Tests

  • Subscriptions.test.ts: a document with several dirty subscriptions starts two runs at once. A second test runs three documents of two patches under sustained invalidation on the TestClock. Peaks are 2 per company and 2 per patch, and every subscription runs at least once every two rounds.
  • QuerySubscriptionsLocal.test.ts runs on real workerd and Postgres. Two tier 2 patches query a shared table: each run leases a snapshot connection, then takes a second one for each shared read's access check.
    • Three documents subscribe. Each round writes the shared table and commits one patch's mutation, until every document has six fresh snapshots. Every write and mutation commits, and every document converges on the last write.
    • One patch's two runs are held inside their access checks, so all four company connections are taken. A mutation started then stays queued, neither committed nor refused. It commits once the checks release. I checked by hand that it really queues: holding past the one-second connection wait turns it into busy.
  • All four tests fail on the old default.

pnpm verify on the first commit passed apart from one 30 s timeout in cliRepoBuild.test.ts (Vite repo builds), on a loaded shared machine. This change doesn't touch that file; it passes when run alone and passed in pnpm check. The follow-up commit changes docs and tests only; its suites, lint and typecheck pass locally.

Closes #743

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

subscriptions.reruns.patch defaulted to 1, so a screen's first load ran its
queries one after another and waited for their sum. It now defaults to 2,
matching subscriptions.reruns.company, which stays at 2. The two limits are
set independently; the docs now say so.

Closes #743

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:m 100-500 changed lines labels Oct 17, 2026
subscriptions.reruns.company said it bounded company connections, but the
scheduler counts runs, and a re-run reading shared tables or stores briefly
takes a second connection for its access check. Two such runs can occupy all
four company connections, and none are reserved for writes. The registry
row, its generated docs, the patchy-server skill, the subscriptions API
description and ADR-0010 now say so.

The real-workerd tests share one setup. A new one holds one patch's two
shared-table runs inside their access checks, so all four connections are
taken, and checks that a mutation queues, is neither committed nor refused,
and commits once they release. The sustained test's name and comment now
claim only what it shows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit f544372 into main Oct 17, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the perf/743-two-reruns-per-patch branch October 17, 2026 19:53
allisonmahmood added a commit that referenced this pull request Oct 17, 2026
…trigger

They call attach and reconcile, whose signatures this branch changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
allisonmahmood added a commit that referenced this pull request Oct 17, 2026
…subscription POSTs (#758)

Diagnosing slow tier 2 loads (#754) took browser traces, because the
server's wide events left out what mattered. They didn't show how long a
dirty subscription waited for a re-run slot, or whether a run's result
was delivered, unchanged or thrown away. They didn't show the slot time
of cheap up-to-date checks. And `POST /api/runtime/subscriptions`
emitted no event at all, so its 409s (#749) were invisible.

This adds those to the events that already go to stdout (CloudWatch) and
PostHog, so the other #754 fixes can be measured before and after, and
#749 can be diagnosed.

## What changed

**Re-run events** keep their `durationMs` (the read after the admission
and revision checks), so production numbers stay comparable across this
deploy. New fields:

| Field | Meaning |
| --- | --- |
| `slotWaitMs` | From the oldest pending dirty transition to taking a
slot, less `readyWaitMs` and `backoffMs`. A recoverable failure is a
dirty transition. A wake for a dependency the run only discovers counts
from when the wake arrived. Includes time behind capped runs and behind
its own previous run. |
| `readyWaitMs` | Time spent dirty before the document's execution was
ready (tier 2 with the fleet). |
| `backoffMs` | Time a retry backoff held the run back, until it ended
or a wake, replace or rebind ended it early. Reported whichever trigger
won. |
| `slotOccupancyMs` | From taking the slot to releasing it, checks
included. |
| `trigger` | What first made it dirty: `initial` (install), `replace`
(same subscription re-sent), `invalidation` (wake, incl. one during its
previous run), `retry` (a recoverable failure, or a read behind its
fence), `periodic`, `rebind` or `ready`. |
| `disposition` | `delivered` (snapshot), `unchanged` (up-to-date) or
`discarded` (epoch changed, subscription or document gone, or read
behind its fence). Absent when the run sent an error or a refusal. A
discarded failure also records `outcome: failure`. |
| `taskId` | The admitted execution task, beside `processGeneration`, so
runs join to processes. Also lands on runtime call request events. |
| `documentId` | The shell's document nonce. `streamId` was already
there but changes on every reconnect; `documentId` joins a document's
runs, POSTs and streams across them. |

**Cheap up-to-date checks** still emit no event while their document is
open. The document's `stream` event gains `checks` and `checkMs`: how
many slots ended at the revision check without a read, and the slot time
they took. Checks are counted when their slot is released. The summary
closes its document before reading those totals, so a check still
holding its slot at close (a `server.call` keeps its slot until it
settles) reports itself as a `discarded` re-run event with its
`slotOccupancyMs`. That's the cheapest queryable option. Periodic
reconciliation re-checks every subscription of every open document every
30 s; an event per check would have added about 12 PostHog events a
minute for each open six-query page, and this avoids them. The aggregate
answers the real question: how much slot time did checks take?

**Subscription POSTs** emit a request event. They had none because the
server's request middleware leaves `/api/runtime/*` to its handlers, and
`RuntimeApi`'s handlers open their own events, but the stream group's
`subscriptions` handler never did. It now opens one like `RuntimeApi`
and records refusals through `recordFailure`. This is the volume the
change adds: one unsampled event per subscription POST, refusals
included. Fields:

| Field | Meaning |
| --- | --- |
| `subscriptionRequest`, `sequence` | `subscribe`, `unsubscribe` or
`replace`, and its desired-set sequence. |
| `refusal` | `stream_replaced` or `stale_sequence`. Both are 409
`invalid_request`. |
| `documentConnected` | Whether this host holds an open stream for the
document. |
| `streamId`, `currentStreamId` | The generation the request named (kept
only in the `stream_…` form this host mints), and this host's generation
for the document. |
| `currentSequence` | This host's desired-set sequence for the document
when the request got the gate. It says why a `stale_sequence` was stale.
|
| `affinityCookie`, `affinityMatched`, `balancerCookie` | Whether
`patchy_stream_affinity` was sent and names this host, and whether an
`AWSALBAPP*` cookie was present. Booleans only, never values. |

`replica` is already on every event. Patch and version attribution come
from the stream this host admitted, never from the request body. A POST
refused before admission (say, a 401) records only its outcome, code and
cookie booleans. Generation ids are fence tokens, not credentials: a
POST still needs the viewer's session.

**Schemas.** `WideEvents` drops fields its per-type schema doesn't know,
and the PostHog sink sends that filtered record, so the per-type schemas
are the allowlist. Each type got only its own fields; a test checks
every type keeps its own and drops the rest. The fields are named in the
Analytics glossary, and `docs/OPERATIONS.md` has CloudWatch queries for
a screen's runs and for refused POSTs. Telemetry stays best-effort:
enrichment is in memory, and delivery stays detached.

**One scheduling change.** A recoverable failure now marks its
subscription dirty immediately, and the pump holds it through the
backoff it already honoured. Before, the retry timer marked it dirty
when the backoff ended. If a wake had re-run the subscription during the
backoff, it then ran once more when the timer fired; now it doesn't.

## Validation

Tests:
- **Slot waits:**
  - rise behind a capped queue, with `slotOccupancyMs` for each slot;
  - a coalesced wait keeps its first trigger;
- a wake for a dependency the run discovers counts from its arrival (0
before the fix, 400 ms now);
- a retry backoff behind an earlier wake reports `backoffMs` and keeps
the wait before it (wake at 50, fail at 100, backoff 250: `slotWaitMs`
50, `backoffMs` 250).
- **Triggers and dispositions**, each on its real path:
  - `replace` discards a run in flight;
  - fence miss gives `retry` with no backoff;
- a discarded result and a discarded failure when the document closes
mid-read;
- `trigger: ready` emitted by holding the ready reconcile's limit lookup
while a pump runs the subscription first.
- **Cheap checks:**
  - counted with their slot time;
- with the real RuntimeStream, a check blocked through a drain: the
summary emits `checks: 0`, then the check reports itself as `discarded`
with `slotOccupancyMs: 200`.
- **POST events:**
- success, `StaleSequence`, `StreamReplaced` (stale generation and
unknown document), and a 401 refused before admission;
  - no cookie value appears in any event.
- **Schema:** each event type keeps its own new fields and round-trips
them.
- **`taskId`** lands beside `processGeneration`.

Removing the keep-oldest rule, the ready exclusion, the wake arrival
time, the backoff overlap or the late-check event each fails a test.

End to end, on this worktree's `pnpm dev up`, with a tier 2 page whose
six panels share one query handler, at one re-run per patch (the default
before #756 raised it to two). Ids are redacted and lines trimmed to the
relevant fields.

A normal page load through `pnpm dev shot`. The waits rise as the queue
drains, and `durationMs` stays the read while `slotOccupancyMs` adds the
checks. As `[slotWaitMs, slotOccupancyMs, durationMs]`: `[2, 179, 173]`,
`[179, 30, 28]`, `[201, 29, 27]`, `[231, 28, 27]`, `[259, 29, 26]`,
`[288, 29, 27]`.

One stream driven by hand: a six-subscription `replace`, then the same
`replace` while the first run was in flight. That run is `discarded` and
re-runs as `replace`:

```json
{"type":"re-run","handler":"panels.panel","trigger":"initial","disposition":"discarded","slotWaitMs":1,"slotOccupancyMs":26,"durationMs":25,"outcome":"success","processGeneration":1,"guestMs":17,"dbMs":21.43016,"streamId":"…","documentId":"…"}
{"type":"re-run","handler":"panels.panel","trigger":"initial","disposition":"delivered","slotWaitMs":27,"slotOccupancyMs":28,"durationMs":26}
{"type":"re-run","handler":"panels.panel","trigger":"initial","disposition":"delivered","slotWaitMs":56,"slotOccupancyMs":32,"durationMs":31}
{"type":"re-run","handler":"panels.panel","trigger":"initial","disposition":"delivered","slotWaitMs":88,"slotOccupancyMs":28,"durationMs":27}
{"type":"re-run","handler":"panels.panel","trigger":"initial","disposition":"delivered","slotWaitMs":117,"slotOccupancyMs":26,"durationMs":25}
{"type":"re-run","handler":"panels.panel","trigger":"initial","disposition":"delivered","slotWaitMs":144,"slotOccupancyMs":25,"durationMs":24}
{"type":"re-run","handler":"panels.panel","trigger":"replace","disposition":"delivered","slotWaitMs":155,"slotOccupancyMs":26,"durationMs":24}
```

After a periodic reconcile, three 409s were forced, and then the stream
closed with six up-to-date checks counted:

```json
{"type":"request","outcome":"refused","code":"invalid_request","refusal":"stale_sequence","subscriptionRequest":"replace","sequence":1,"currentSequence":2,"documentConnected":true,"streamId":"…","currentStreamId":"…","affinityCookie":true,"affinityMatched":true,"balancerCookie":false,"documentId":"…"}
{"type":"request","outcome":"refused","code":"invalid_request","refusal":"stream_replaced","subscriptionRequest":"replace","sequence":3,"documentConnected":true,"streamId":"…","currentStreamId":"…","affinityCookie":true,"affinityMatched":false,"balancerCookie":true,"documentId":"…"}
{"type":"request","outcome":"refused","code":"invalid_request","refusal":"stream_replaced","subscriptionRequest":"replace","sequence":1,"documentConnected":false,"streamId":"…","affinityCookie":false,"affinityMatched":false,"balancerCookie":false,"documentId":"…"}
{"type":"stream","peakSubscriptions":6,"reruns":8,"checks":6,"checkMs":19,"closeReason":"disconnected","documentId":"…"}
```

Neither the affinity value nor the fake balancer value appeared anywhere
in `dev.log`. Dev runs without the fleet, so `taskId` and `readyWaitMs`
don't appear locally; tests cover both.

`pnpm verify` (first commit): format, lint, typecheck, synth,
postgres-concurrency, cli-smoke, tier2-smoke and browser pass. In
`test`, 1831 of 1832 passed; the failure was the known
`cliRepoBuild.test.ts` 30 s timeout under load (#757), and that file
passes alone (12/12). After the review fixes and the merge with `main`,
format, lint, typecheck (code and tests) and the runtime, analytics and
dev-execution suites (220 tests) pass locally, and CI reran everything.

## Notes

- `trigger: ready` is real but rare. Nothing runs before ready, so
subscriptions installed while starting are already dirty when the ready
reconcile marks them; they keep `initial` and report `readyWaitMs`.
`ready` appears only when a run takes its slot during the ready
reconcile's limit lookup, which a test holds open.
- Brought up to date with `main` after #755 and #756 landed, by merging
`main` in. That includes #756's new subscription tests, updated for this
PR's changed signatures: `attach` now takes a `documentId`, and
`reconcile` takes its trigger first. The subscription suites pass
alongside #756's two-runs-per-patch cap, including its connection
contention test.

Closes #741

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 17, 2026
…759)

On company and local pages, the shell held every subscription until the
viewer's `me` round trip came back, about 125 ms in production. That
wait bought nothing. These shells already pin the viewer when they
render, and the document stream checks that viewer on every open and
subscription update. The production traces in #754 show all of a page's
subscription POSTs leaving the instant `me` returned.

Now the broker forwards subscribe and unsubscribe on company and local
pages without waiting for `me`. `me` stays lazy: it runs when the patch
asks for it or a direct operation needs it, and the shell adds no
background request. A stale cookie still refreshes and an account change
still ends the page as `principal_changed`, now through the stream.
Public pages are unchanged, because they bind the directory principal
first.

The local shell also stops asking `me` eagerly when the frame is ready,
so it behaves like company. ADR-0010 said the local shell got its viewer
through `me`; it pins the viewer like company, and the ADR now says so.

Not changed: other direct operations still wait for `me`. A page that
never calls `me` itself now pays that round trip on its first direct
operation, such as a mutation, instead of during load.

## Measured

A five-query tier 2 page that also calls `me()`, on this worktree's dev
instance, with 120 ms added to every `/api/runtime/call` through a
Playwright `route` delay. The figures are medians of 8 warm loads. The
main column is the same instance restarted with main's broker.

| | main | this branch |
| --- | --- | --- |
| Navigation → first subscription POST | 216 ms | 87 ms |
| `me` finished → first subscription POST | −1 ms (they leave together)
| −128 ms (before `me` returns) |
| Navigation → all five panels ready | 297 ms | 180 ms |

A second branch run gave 89 ms, −130 ms and 165 ms.

## Tests

`test/browser-tier1/pinned-subscriptions.spec.ts` runs each case in
company and local scope:

- with `me` held in the browser, the first subscription is posted and
answered while `me` is pending, and `me` then answers `usr_dev`;
- on a page whose patch does not ask `me`, a subscription completes with
no `me` request attempted; when the patch then asks, exactly one goes
out and answers `usr_dev`;
- with `me` held, a stale cookie on a subscription refreshes through the
stream, with no notice;
- with `me` held, switching accounts ends the page as
`principal_changed`.

The held-`me` cases fail against main's broker. The lazy case fails when
the eager local bootstrap call is restored. The local cases serve the
company shell with `data-scope="local"`, since `patchy dev` runs the
same broker; this drives its local branch against the real runtime,
whose sessions can expire and change account. The full browser suite
passes (69 tests). There are no broker unit tests: its logic lives in
the browser mount closure.

`pnpm verify` passed on every suite before #755 and #756 merged. On the
current head, merged with main, the full browser suite and the test
typecheck pass.

Closes #744

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:docs Touches the docs area area:server Touches the server area size:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A patch runs one query at a time per host

1 participant