Skip to content

perf(runtime): a write wakes its own host's subscriptions once, not twice - #771

Merged
allisonmahmood merged 2 commits into
mainfrom
perf/748-no-self-wake
Oct 18, 2026
Merged

allisonmahmood merged 2 commits into
mainfrom
perf/748-no-self-wake

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Every write woke the writing host's subscriptions twice. Wakes.publish wakes this host's subscribers in memory and also sends a NOTIFY, and then the host's own LISTEN connection delivers that NOTIFY back. 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 NOTIFY that Wakes.publish sends now carries an origin: a random id that a host's Wakes layer generates when it starts. A host's listener skips any NOTIFY with its own origin, because the in-memory publish already woke those subscribers. Every other host still gets exactly one wake.

A payload with no origin wakes every host, the writer included. Two senders produce one:

  • older hosts, during a deploy;
  • the companies directory trigger (ADR-0003). It sends its NOTIFY from inside the write's transaction, and no host wakes itself in memory for it, so the writing host still needs that NOTIFY. That's why the skip uses a payload field and not the sender's backend PID.

Everything else stays the same:

  • a reconnected LISTEN still publishes the [] reconciliation;
  • causedByEventId attribution;
  • the 8,000-byte batching (the per-NOTIFY overhead now includes the origin);
  • a payload that doesn't decode is still logged, and still requests durable reconciliation ([]).

Considered and rejected: drop the in-memory publish and let LISTEN deliver local wakes too. That also wakes each host once. But if a NOTIFY failed, or the LISTEN connection 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

  • Old hosts decode with Schema's default excess-property handling, which ignores unknown keys. I checked this by running main's decoder on a new payload: it returns { keys, causedByEventId } and drops origin. Old hosts wake once for a new host's write. They keep waking themselves twice until they're replaced.
  • New hosts treat an old host's payload, which has no origin, as foreign, and wake once.
  • Hosts can roll out in any order, so one PR is enough. Nothing stores the field, so a revert rolls it back.

Tests

WakesPostgres.test.ts, over a migrated Postgres:

  • Exactly once per host. One publish wakes the writing host and a second host (a second layer instance on the same database) exactly once each. The test then sends a payload with no origin, the way an older host or the directory trigger does, and every host takes it. Postgres delivers notifications in commit order, so this payload arrives after any echo and works as a fence. With the skip removed, the writing host gets the echo where the fence should be, and the test fails.
  • Batching. Splitting a large wake below the 8,000-byte limit is now its own case.
  • Reconnect. Unchanged: a dropped LISTEN still 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 20 deals.addNote writes, 2 s apart. The counts come from the wide events:

  • re-run events, by trigger and disposition;
  • checks in each document's stream event: slots that answered up-to-date without a read.
Writes invalidation/delivered re-runs, per document checks per document
main, run 1 20 20 14
main, run 2 20 20 21
this branch, run 1 20 20 1
this branch, run 2 20 20 1
this branch, no writes, open as long (46 s) 0 0 1
  • The branch's one check is the 30-second durable reconciliation. An idle document open just as long gets the same single check. Main's runs therefore had 13 and 20 echo slots for 20 writes.
  • Whether an echo costs a slot is a race. It does when the echo lands after the run has started. Locally that window is under a millisecond. In production, with a real round trip to the database, more echoes should land late.
  • Other documents still update. Jordan's document re-ran and delivered on all 20 writes.

Part of #748

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

…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]>
@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:s Under 100 changed lines labels Oct 18, 2026
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]>
@allisonmahmood
allisonmahmood merged commit a436aae into main Oct 18, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the perf/748-no-self-wake branch October 18, 2026 15:57
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]>
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:s Under 100 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant