Repository navigation
fix(serving): the shell stops re-sending subscriptions while the server is still answering them - #755
Merged
Merged
Conversation
…er is still answering them The document stream's reconciliation timer re-sent the whole desired set whenever any subscription was unanswered, so a load of several slow tier 2 queries got timer replaces after 1 s and 3 s and the server ran queries again. Reconcile fast only while the server has not admitted the latest sequence, as a lost POST or a lost admitted frame leaves it. Once admitted, missing answers wait for the reconcile interval. The timer policy moves to its own module so it can be unit-tested. Closes #742 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 17, 2026
This was referenced Oct 17, 2026
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]>
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.
The shell re-sent its whole subscription set whenever any subscription was still unanswered: 1 s after the last change, then 2 s later, and so on. A tier 2 screen with several slow queries always tripped it, so the server ran queries again, and the page showed "Reconnecting" while it loaded.
Fix
admittedframe leaves exactly that state.admittedthat catches up cancels an armed fast timer, and a new unadmitted delta shortens a pending slow timer.hello.packages/serving/src/reconciliation.tsso it can be unit-tested.stream.tsreports where its desired set stands.The server side, where a
replacethat overlaps a run discards its result, is #750.Tests
reconciliation.test.tscovers the interval wait for an admitted set, the fast backoff and its reset, admission cancelling a fast timer, a delta shortening a slow one, and reconciling andstop()each cancelling the timer.stream.spec.ts:mainthis fails: the pill shows.admittedframe each still get a replace within 1 s.holdStreamFrames("answers")holds only snapshot, up-to-date and error frames.admittedcase still takes the fast path and passes unchanged.Validation
On a local instance I published a tier 2 patch with six live queries, each burning about 0.54 s of CPU, and opened it as a persona with Playwright. I counted
/api/runtime/subscriptionsPOSTs, the time to the last panel, andre-runwide events indev.log, through 10 s after the last panel.main(2 runs)replacePOSTshello, then +1.1 s and +3.1 shellopnpm verifypasses locally: check, postgres-concurrency, cli-smoke, tier2-smoke and browser.Closes #742
Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.