Repository navigation
perf(runtime): a write wakes its own host's subscriptions once, not twice - #771
Merged
Merged
Conversation
…wice Wakes.publish woke the writing host in memory and sent a NOTIFY that the same host's LISTEN connection then delivered back, so every write ran a second, empty subscription slot. Each NOTIFY now names its sending layer instance and that listener skips it. Payloads without an origin, from older hosts or the directory trigger, still wake every host. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The directory trigger's notifications carry no origin and still reach every host, the writer's included. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Oct 18, 2026
allisonmahmood
added a commit
that referenced
this pull request
Oct 18, 2026
…hree (#772) Every viewer resolve cost 3 platform round trips: - a claim-refresh `UPDATE users … RETURNING`, which usually changed nothing; - the `SELECT users` it then fell back to; - `Companies.findById`. A tier 2 call resolves the viewer at admission, on every directory `reauthorize`, in every document check, on stream open and on every subscription POST. That's 2 resolves per query, 1 per mutation and 3 per re-run. Now a resolve whose claims haven't changed (almost every resolve) is one statement. Every resolve stays where it was and still reads current state; nothing is cached. ## The fix `Users.refreshClaims` returns the user and their company, and reads before it writes: 1. **One lock-free read:** ```sql SELECT u.*, c.handle AS "companyHandle", c.name AS "companyName" FROM (SELECT <user columns> FROM users WHERE clerk_user_id = $1) u LEFT JOIN companies c ON c.id = u."companyId" ``` No row means no user, as before. If the stored email and name already equal the normalized claims, this row is the answer. The normalization and the `displayName` fallback are unchanged. 2. **Claims differ:** main's `UPDATE users … WHERE … IS DISTINCT FROM … RETURNING`, verbatim. It waits on any lock holder and returns the row as that holder left it. The company is then read after it, as main did, even when its id didn't change: a company renamed during the wait comes back renamed. - If the update changes nothing because a concurrent refresh already wrote these claims, the read from step 1 runs again with a fresh snapshot and answers instead. - A missing company row still comes back as `null`, and `resolveViewer` dies with `User company is missing`. `resolveViewer` no longer needs `Companies`. The `/join` redirect, the deactivation 403 page and the `Viewer` it returns are unchanged. `Door` stops capturing `Companies`, and the runtime's `Effect.Services<typeof resolveViewer>` follows on its own. ## Why it's equivalent - **Every path that waits on a lock** still goes through the same statements as before and returns the authority as it stood after the wait. That covers a deactivation, demotion, company move or company rename that an admin commits while this resolve's write waits. - **The unchanged path didn't wait before either.** The old no-op `UPDATE`'s condition was false on its snapshot, so Postgres skipped the row without locking it. Its fallback `SELECT` ran one round trip later than the new read does. That difference is a request arriving a moment earlier, not a lost guarantee. - **What round 1 got wrong** (thanks, Sol). It answered from one data-modifying CTE whose `SELECT` read the snapshot from before its own `UPDATE`'s lock wait. A resolve with changed claims that waited on an admin's deactivation, demotion or move then returned the authority from before that change. Doored POST handlers act on that viewer without resolving again. The fresh fallback has no single-statement equivalent either: when queued behind an identical refresh, a `UNION ALL` fallback still reads the old snapshot and misses a company created by the lock holder. - **Isolation.** The platform pool sets none, and no caller wraps a resolve in a transaction. Each statement runs on its own under READ COMMITTED, as before. - **Locks.** No new row locks. Only the old `UPDATE` takes one, and only when the claims changed. The first read takes none, so unchanged claims never wait behind an admin's transaction; a test pins that. ## Tests On a real Postgres, against the migrated test template: - **`RequireSession.test.ts`** (new). It counts statements with `Statement.CurrentTransformer`. - Unchanged claims and an unknown user resolve in 1 statement, and changed claims in 3: the read, the write and the company after it. - A deactivated user gets the same 403 page in 1 statement. - A missing company dies with the same defect. The test bypasses the foreign key with `session_replication_role = replica`, inside a rolled-back transaction. - **`Users.test.ts`:** - **Admin change during the wait.** Three admin changes are each held uncommitted while a refresh with new claims waits on the row. The refresh answers the role, deactivation and company as committed, and equals the stored row. The changes: - a demotion together with a rename of the user's company; - a deactivation; - a move to a company created by the same transaction. - **Unchanged claims never wait.** While a deactivation still holds the row, a refresh with matching claims returns the active row it can see within a 5 s bound and writes nothing. A locking first read times out here. - **Sol's three-session queue.** A deactivation is held while two identical refreshes queue on it. When it commits, either refresh may take the row first, so the test doesn't depend on which. One writes the claims; the other writes nothing, and its fresh read returns the deactivation. Every wait in these cases is bounded at 3 s and fails naming the step. - **The existing same-claims race** now checks the whole answer (stored row and company) and a single write. - **The existing claim-refresh tests** check the company too. Their audit-trigger "no write for unchanged claims" checks still hold. The two lock-wait tests fail on round 1's CTE, and on the `RETURNING`/`UNION ALL` variant: there the queued refresh misses the deactivation, and the moved-to company comes back null. The rename case fails on round 2, which reused the first read's company. ## Numbers Platform statements per call on `pnpm dev up brightline`, as the admin on the New Business board. The baseline is main at #771, after its echo fix. Counts come from Postgres's statement log (`log_min_duration_statement = 0`), sliced between marker statements. Queries and mutations ran 5 times; streams ran 3 opens × 3 writes. Every repeat matched. | Per call | main | this PR | resolves | | --- | --: | --: | --: | | Query `deals.board` (one-shot) | 14 | 10 | 2 | | Mutation `deals.addNote` | 18 | 16 | 1 | | Stream open | 7 | 5 | 1 | | Subscription POST and its first run | 24 | 16 | 4 | | Write + re-run | 41 | 33 | 4 (1 mutation, 3 re-run) | That's −2 per resolve: query −4, mutation −2, re-run −6. When the claims changed (the stored name edited, so the next resolve writes), that resolve costs 3 statements here and 2 on main, and a query in that state costs 12 here and 13 on main. The extra statement buys a fresh company after the write, and the path only runs when someone's name or email changes in Clerk. If a concurrent refresh already wrote the claims, the changed path costs 3 on both: the read, the empty write and the fresh read here; the write, the fallback read and the company on main. Company statements are unchanged. These totals come from `pnpm dev`'s default executor, which runs tier 2 without the fleet, so they leave out the fleet's admission and release statements that #748's counts include. The resolve statements are the same on both executors. On the same instance: - sign-in works; - after an account switch, a call still pinned to the old principal gets `principal_changed`, and the new one's `me` answers; - a person without a company is sent to `/join`; - a deactivated member gets the 403 page on the portal and on a patch address, and `access_denied` on a runtime call; reactivating restores access. Part of #748. 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.
Every write woke the writing host's subscriptions twice.
Wakes.publishwakes this host's subscribers in memory and also sends aNOTIFY, and then the host's ownLISTENconnection delivers thatNOTIFYback. When the echo lands after a re-run has started, it marks the subscription dirty again. A second slot then runs, finds nothing changed and answers up-to-date. #748 measured that slot at 11 platform + 1 company statements per woken subscription per write. It also holds one of the patch's two run slots (#743).The fix
Each
NOTIFYthatWakes.publishsends now carries anorigin: a random id that a host'sWakeslayer generates when it starts. A host's listener skips anyNOTIFYwith its own origin, because the in-memory publish already woke those subscribers. Every other host still gets exactly one wake.A payload with no
originwakes every host, the writer included. Two senders produce one:NOTIFYfrom inside the write's transaction, and no host wakes itself in memory for it, so the writing host still needs thatNOTIFY. That's why the skip uses a payload field and not the sender's backend PID.Everything else stays the same:
LISTENstill publishes the[]reconciliation;causedByEventIdattribution;NOTIFYoverhead now includes the origin);[]).Considered and rejected: drop the in-memory publish and let
LISTENdeliver local wakes too. That also wakes each host once. But if aNOTIFYfailed, or theLISTENconnection was reconnecting, the writer's own documents would miss the wake until the 30-second reconciliation. Every local wake would also wait on a database round trip. Skipping its own echo keeps both delivery paths.Rollout
{ keys, causedByEventId }and dropsorigin. Old hosts wake once for a new host's write. They keep waking themselves twice until they're replaced.Tests
WakesPostgres.test.ts, over a migrated Postgres:LISTENstill publishes[].Numbers
Setup:
pnpm dev up brightline, with New Business open as Allison, the writer, and as Jordan, a second document on the same host. Each run made 20deals.addNotewrites, 2 s apart. The counts come from the wide events:re-runevents, by trigger and disposition;checksin each document'sstreamevent: slots that answered up-to-date without a read.invalidation/deliveredre-runs, per documentchecksper documentPart of #748
Made by Claude Opus 5.5 via Claude Code; reviewed with GPT-6.1-Sol.