Skip to content

feat(runtime): wide events show re-run queue waits, dispositions and subscription POSTs - #758

Merged
allisonmahmood merged 6 commits into
mainfrom
feat/741-rerun-and-subscription-events
Oct 17, 2026
Merged

allisonmahmood merged 6 commits into
mainfrom
feat/741-rerun-and-subscription-events

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 17, 2026 •

Copy link
Copy Markdown
Owner

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:

{"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, 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

Closes #741

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

…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]>
@github-actions github-actions Bot added area:server Touches the server area area:cli Touches the cli area area:docs Touches the docs area size:l 501-1,000 changed lines labels Oct 17, 2026
…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]>
@github-actions github-actions Bot added size:xl Over 1,000 changed lines; review in multiple passes and removed size:l 501-1,000 changed lines labels Oct 17, 2026
@allisonmahmood
allisonmahmood merged commit 77b14b1 into main Oct 17, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the feat/741-rerun-and-subscription-events branch October 17, 2026 20:08
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Touches the cli area area:docs Touches the docs area area:server Touches the server area size:xl Over 1,000 changed lines; review in multiple passes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wide events don't show the subscription queue wait, discarded runs or subscription POSTs

1 participant