Repository navigation
feat(runtime): wide events show re-run queue waits, dispositions and subscription POSTs - #758
Merged
Merged
Conversation
…subscription POSTs Re-run events now start when a run takes its slot and carry slotWaitMs, readyWaitMs, backoffMs, trigger, disposition, documentId and the admitted taskId. Revision checks that answer without a read add their slot time to the stream event's checks and checkMs. Subscription POSTs record a request event with the desired-set change, the document this host holds, the refusal subtype and cookie booleans. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nd check Sol's first review found four gaps: - durationMs keeps its old boundary; slotOccupancyMs now reports the whole slot, checks included. - A wake for a dependency the run only discovers counts from its arrival, not from the run's end. - A recoverable failure is a dirty transition with its backoff as an interval, so backoffMs is reported even when earlier dirt won, and the slot wait loses only the real overlap. - Checks are accounted at slot release. The stream summary closes its document before reading its totals, so a check that settles later reports itself as a discarded re-run event. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…them Co-Authored-By: Claude Opus 5.5 <[email protected]>
…bscription-events
…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 18, 2026
…t once (#776) When a subscription POST is refused as `409 invalid_request` but still names the current stream generation and latest sequence, the stream has been lost: a **current-generation loss**. The shell tears it down, then waited its jittered backoff (250–500 ms right after a `hello`) before reconnecting. In the traced production load on #754, that wait sat in front of the first query. Two refusals produce this loss: - `StreamReplaced`, from a host that doesn't hold the stream, such as a misrouted POST; - `StaleSequence`, from a document that just closed. ## Fix - **One immediate reconnect.** On a 409 the shell reads the body. If it is `invalid_request` and the POST still names the current generation and latest sequence, the stream reconnects at once instead of waiting for the backoff. - **The allowance comes back only when the document reconciles.** A new `hello` doesn't restore it. A second loss before then waits for the backoff, as on main, so a persistent misroute can't loop faster than it does today. - **Everything else keeps its handling:** - a stale-generation or stale-sequence refusal is ignored; - `401`, a `409 principal_changed` and `429` tear the stream down and wait for the backoff; - a pending tier 2 bind deadline still wins; - the reconnect still sends `X-Patchy-Generation`, so #775 only touches the version and doesn't warm it again. - **ADR-0010 is updated.** The stickiness cookie lasts one day (`duration_seconds=86400`), which is what `AppStack.ts` sets. The new reconnect rule is recorded next to the backoff. ## What "reconciled" means This uses the shell's existing `reconciled` state: the server has admitted this stream's latest sequence, and every desired subscription has been answered past its fence, by a snapshot, an up-to-date or a refusal. It is the state that already clears the Reconnecting pill. It's the first point where the shell has proof that its POSTs reach the stream's host. A `hello` only proves the GET landed somewhere, and an empty set still needs its replace admitted. So between any two immediate reconnects there is at least one full, successful round trip through the stream's host. ## Tests `stream.spec.ts`, with the page clock paused so that no backoff timer can fire unless the test runs the clock: - **Allowance.** - A current-generation loss reconnects at once. - The new stream admits its replace while its answers are held, so it hasn't reconciled; a loss there waits for the backoff. - Once the answers arrive, the next loss reconnects at once again. - Every reconnect carries the generation it replaces. - **Fails on main**: no second `hello` arrives without the clock. - **Other refusals.** - A stale-sequence `409` leaves the stream alone. - `401 session_refresh_required`, `409 principal_changed` and `429 rate_limited` each tear the stream down and wait for the backoff. - The unreconciled replacement's own current-generation loss then still reconnects at once, so these refusals didn't spend the allowance. - Passes on main and here. I checked that each test catches the bug it pins: - restoring the allowance on `admitted` fails the first test; - spending it on any refusal fails the second. `pnpm verify` passes locally: check, postgres-concurrency, cli-smoke, tier2-smoke and browser. ## Numbers Setup: - a local brightline instance, opening New Business (tier 2) as a persona; - a temporary, uncommitted server hook that refused every subscription POST of a document's first generation as `StreamReplaced`; - 10 loads each, timed in the shell from the `409` response. | From the refusal to… | main (backoff) | this branch | | --- | --- | --- | | the new stream's request | median 358 ms (274–473) | 15 ms (14–18) | | its `hello` | 368 ms (282–480) | 24 ms (21–30) | | the first query answer | 410 ms (317–781) | 51 ms (49–59) | With every POST refused, a persistent misroute, over 10 s: - main reconnected 23 times, 300–570 ms apart; - this branch reconnected 27 times: the first after 23 ms, then 294–498 ms apart. The allowance adds one immediate reconnect per unreconciled streak. Jitter alone moves the count over a 10 s window, so the totals don't measure that exactly. **Unchanged here.** On main, `hello` resets the backoff's failure count, so a persistent misroute already reconnects every 0.25–0.5 s indefinitely instead of backing off further. Part of #749. Steps 1 and 2, diagnosing the cause from #758's wide events and fixing it, need production data. 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.
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/subscriptionsemitted 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:slotWaitMsreadyWaitMsandbackoffMs. 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.readyWaitMsbackoffMsslotOccupancyMstriggerinitial(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,rebindorready.dispositiondelivered(snapshot),unchanged(up-to-date) ordiscarded(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 recordsoutcome: failure.taskIdprocessGeneration, so runs join to processes. Also lands on runtime call request events.documentIdstreamIdwas already there but changes on every reconnect;documentIdjoins 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
streamevent gainschecksandcheckMs: 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 (aserver.callkeeps its slot until it settles) reports itself as adiscardedre-run event with itsslotOccupancyMs. 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, andRuntimeApi's handlers open their own events, but the stream group'ssubscriptionshandler never did. It now opens one likeRuntimeApiand records refusals throughrecordFailure. This is the volume the change adds: one unsampled event per subscription POST, refusals included. Fields:subscriptionRequest,sequencesubscribe,unsubscribeorreplace, and its desired-set sequence.refusalstream_replacedorstale_sequence. Both are 409invalid_request.documentConnectedstreamId,currentStreamIdstream_…form this host mints), and this host's generation for the document.currentSequencestale_sequencewas stale.affinityCookie,affinityMatched,balancerCookiepatchy_stream_affinitywas sent and names this host, and whether anAWSALBAPP*cookie was present. Booleans only, never values.replicais 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.
WideEventsdrops 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, anddocs/OPERATIONS.mdhas 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:
slotOccupancyMsfor each slot;backoffMsand keeps the wait before it (wake at 50, fail at 100, backoff 250:slotWaitMs50,backoffMs250).replacediscards a run in flight;retrywith no backoff;trigger: readyemitted by holding the ready reconcile's limit lookup while a pump runs the subscription first.checks: 0, then the check reports itself asdiscardedwithslotOccupancyMs: 200.StaleSequence,StreamReplaced(stale generation and unknown document), and a 401 refused before admission;taskIdlands besideprocessGeneration.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, anddurationMsstays the read whileslotOccupancyMsadds 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 samereplacewhile the first run was in flight. That run isdiscardedand re-runs asreplace:{"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:
{"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, sotaskIdandreadyWaitMsdon't appear locally; tests cover both.pnpm verify(first commit): format, lint, typecheck, synth, postgres-concurrency, cli-smoke, tier2-smoke and browser pass. Intest, 1831 of 1832 passed; the failure was the knowncliRepoBuild.test.ts30 s timeout under load (#757), and that file passes alone (12/12). After the review fixes and the merge withmain, format, lint, typecheck (code and tests) and the runtime, analytics and dev-execution suites (220 tests) pass locally, and CI reran everything.Notes
trigger: readyis real but rare. Nothing runs before ready, so subscriptions installed while starting are already dirty when the ready reconcile marks them; they keepinitialand reportreadyWaitMs.readyappears only when a run takes its slot during the ready reconcile's limit lookup, which a test holds open.mainafter fix(serving): the shell stops re-sending subscriptions while the server is still answering them #755 and perf(runtime): a patch runs two queries at a time #756 landed, by mergingmainin. That includes perf(runtime): a patch runs two queries at a time #756's new subscription tests, updated for this PR's changed signatures:attachnow takes adocumentId, andreconciletakes its trigger first. The subscription suites pass alongside perf(runtime): a patch runs two queries at a time #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.