Skip to content

perf(runtime): a re-run reuses its fence instead of re-reading the directory revision - #774

Closed
allisonmahmood wants to merge 1 commit into
mainfrom
perf/748-rerun-reuses-fence
Closed

allisonmahmood wants to merge 1 commit into
mainfrom
perf/748-rerun-reuses-fence

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

A subscription re-run read the members-directory revision twice, about 2 ms apart, and got the same value both times. The first read is in its slot's fence, the second is the before revisions of the hosted query's read. That's one platform round trip per re-run that buys nothing.

Fix

QuerySubscriptions.read now takes the slot's fence. Each platform source (members: or patch:) the fence already read starts its before there. Only the declared sources the fence didn't cover are read. after, the document check after the run and reachesFence stay as they are.

Why it's sound

before brackets the read. A run accepts a platform source only when before equals after, and its vector carries the before value.

  • A platform revision never goes back to a value it left. The directory revision is a counter that a trigger on users bumps on every directory change. A patch's lifecycle_revision only increments, and it reads -1 once the row is gone; patch ids aren't reused. The existing bracket already relies on this.
  • The fence comes first. The fence's directory read happens before the old before read. So when the fence equals after, nothing changed from the fence through the read, and that interval contains the old one. Any run this accepts, main would have accepted too, with the same vector value: fence = old before = after.
  • The gap holds nothing that writes the directory. The check, the binding refresh and admission all run before the fence reads revisions, not between the fence and the read. The gap holds the rest of the fence: any patch lifecycle read, the company lease and the company resource revisions. The rest is in-memory work.
  • A concurrent write in the gap is still caught. A directory write that commits in the gap makes after differ from the fence. The run is then refused as source_unavailable and runs again after its backoff, which is how a change during the read is handled today. On main that run would have been accepted with the newer before. This is the one change in behaviour. It widens the refusal window by about 2 ms, against a read of about 30 ms.
  • Only the server's own reads are reused. The reused values come from reads for the same binding and company. admit filters the client's resume keys down to declared sources, and the fence reads those from storage. A client's vector values are never reused.
  • perf(runtime): a replace during a run keeps its work #769's guarantees hold. Its post-replace freshness fence compares the read's vector with a fence taken after the replace. Reused values equal after, so that check sees the same vector it saw before.

Not done:

  • Reusing the fence's company lease (placement and company.connections*) for the snapshot. The snapshot opens inside Invocation.call → QuerySnapshot.open, so this would need a lease context threaded through Invocation and a reuse API in CompanyDatabases. That isn't cheap, and Invocation is another lane's file right now (perf(execution): warm calls stop re-sending their server bundle to the task #773).
  • Tier 1 reads. Their own before/after lives in Primitives' reader, behind the SubscriptionReads port. They read the fenced revision twice in the same way.

Tests

Two focused cases in QuerySubscriptions.test.ts:

  • Statement count. A re-run's revision reads are, in order:

    • the fence, [members];
    • the declared sources the fence didn't cover, [patch:source, patch:filesource];
    • after, [members].

    On main the middle read also held members. Each members: key in a revision read is one directory statement in production's reader.

  • A change between the fence and the read. The fence reads 8, then a directory write lands at 9 before the read starts. The run sends a non-permanent source_unavailable error and never an answer that carries 8. After the 250 ms backoff it runs again and answers with 9.

Both fail on main. I counted at the SubscriptionReads port rather than with Statement.CurrentTransformer. Runtime's suites replace that port with a fake, and no suite wires the real directory into the subscription path. The local instance below gives the real statement count.

Numbers

These come from the local brightline instance with the local workerd executor, while Allison has the New Business board open:

  • Each round renames a deal owner with one psql UPDATE users. Its trigger bumps the directory revision and sends a NOTIFY, so each window holds exactly one deals.board re-run.
  • Statements are counted from Postgres's own log, with log_min_duration_statement = 0 (reset afterwards).
  • There were six rounds on each side.
Per re-run Platform Company Directory revision reads
main 23 6 3 (fence, before, after)
this branch 22 6 2 (fence, after)

Every round gave the same counts. On both, the board showed the new name about 88 ms after the rename.

pnpm verify passes: format, lint, typecheck, synth, test, postgres-concurrency, cli-smoke, tier2-smoke and browser.

Part of #748

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

…rectory revision

A subscription re-run read the members-directory revision twice, about
2 ms apart: once in its slot's fence and again as the before revisions
of the hosted query's read. The read now starts each platform source's
bracket at the fence's value. Revisions never return to a value they
left, so an equal after revision still proves no change from the fence
through the read; a change in between refuses the run as
source_unavailable and it runs again.

Part of #748

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added area:server Touches the server area size:s Under 100 changed lines labels Oct 18, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Closing this one as not worth it.

The reuse is sound: no stale value gets accepted. But it widens the window in which a members-directory write refuses an otherwise fresh re-run as source_unavailable. That window isn't just the ~2 ms between the fence and the read. A mixed table and directory subscription samples members before it waits for a company connection, which can take up to company.connections.queue (1 s by default).

A refused run throws away a completed invocation, and the viewer sees a transient error. The starter template shows that as a "reconnecting" banner. The gain is one platform statement per re-run, and locally the time to a visible update was the same, about 88 ms, on both branches.

So before stays a fresh read. Recorded on #748 as item 5, tried and dropped.

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

allisonmahmood added a commit that referenced this pull request Oct 18, 2026
…, not 16 (#778)

A warm tier 2 call spent 16 platform statements, in two explicit
transactions, getting admitted to its company's binding and releasing it
(#748's counts):

- a breaker upsert and a read of the same row;
- a pool-wait limit read;
- a claim transaction and an admissibility check for a binding that was
already active;
- a six-statement release.

Now it's 7 statements and no transactions.

## What's in, and why authority holds

**Warm read: 6 statements become 1.** That's the claim transaction,
`isAdmissibleTask` and the `execution.pool.wait` read. `ensure` first
reads the company's `active` binding whose task is bound to a deployment
that isn't retired. Only on a miss does it read the pool wait and run
today's claim loop.
- `protect` is unchanged and still decides admission: the epoch,
`active`, a bound task and a deployment that isn't retired. The warm
read, `protect` and `adopt` now share one SQL fragment for the task
check.
- The claim lock serializes creating a binding, and it was released
before `protect`. It gave an existing active binding nothing that
`protect` relied on.
- Every case the claim loop handled differently still goes there:
  - no binding;
- a `claiming` binding, after adoption, replacement or a lost bind
acknowledgement;
- a task that can't take admissions. The claim loop fences it with cause
`deployment`, as before.
- If something changes between the read and `protect`, `protect` refuses
and `acquire`'s existing loop reads again:
  - adoption advances the epoch;
  - a fence, drain or replacement moves the binding to `stopping`;
  - a retirement fails the task check.

The next read misses unless the binding is active and admissible, so it
falls through to the claim loop.
- `binding_epoch` is unique and a binding's company never changes, so
`protect`'s epoch check also pins the company.
- `connect`, `ensureBinding` and the limit-override rebind get the
answer they got before: an active binding whose task could take
admissions when it was read.

**Release: 6 statements become 2.** The touch and the four-statement
transaction become one statement: `UPDATE … WHERE (the company's
admission binding) OR binding_id = <the call's binding>`. A `CASE`
clears that binding's protection only when `pg_try_advisory_xact_lock`
succeeds.
- The statement's implicit transaction holds the exclusive try-lock
until commit, as the old transaction did:
- a new holder's shared lock waits, then `protect` sets protection
again;
  - a holder already in place makes the try fail, and protection stays.
- A draining binding's protection is still cleared, so its drain
finishes. The company's current binding is still touched.
- The plan is a `BitmapOr` over the admission partial index and the
primary key, checked with 50k rows of binding history.
- The unlock stays on the activity session, because a try-lock there
would succeed against that session's own shared locks.

## Dropped after review

**The one-statement breaker.** I had used `WITH synced AS (upsert …
RETURNING) SELECT COALESCE(synced, the row)`. When the upsert waits on a
row lock and then writes nothing, the fallback read sees the row as it
stood when the statement started, not after that wait. Two races follow:
- an admission that waited on a breaker trip was admitted;
- an admission that waited on a publish clearing the pause was refused.

The read is its own statement again, with a comment saying why. Two new
lock-wait tests cover both races, and both fail against the
one-statement version.

**Releasing after the reply.** Forking the release from the owner's
finalizer let it escape a closing host scope. The activity session and
pool could then be disposed under it, which leaves protection in place
through the crash window. Release timing is exactly as on main: quiet
queries release after the reply, everything else before.

Main's existing quiet-query fork has a narrow version of the same gap,
which I didn't touch here. If a quiet query's owner finishes its run
exactly while the host scope is closing, the settlement fiber is forked
into the closing scope and never starts. Its release is then skipped,
with the same conservative result. An Effect probe confirms the
ordering. It's a separate issue.

**Not done:** 3b, `Fleet.route` reusing the binding `protect` returned,
is a follow-up. `route` still reads `execution_bindings` before both
bind and invoke, so it would save 2 more statements per call.

## Numbers

Local `brightline` with tier 2 on the local task provider, which runs
the same fleet controller as ECS. Each call is Allison on New Business.
- Statements come from Postgres's own log, with
`log_min_duration_statement = 0` on the instance's own cluster, reset
afterwards.
- Each call is counted in a window between housekeeping passes, with the
activity probe excluded.
- Re-runs are triggered by renaming a deal owner with the board open in
headless Chromium, as in #774.

| Per warm call | main | this branch |
| --- | --: | --: |
| Query `deals.board` | 29 platform + 5 company | 20 + 5 |
| Mutation `deals.addNote` | 35 + 20 | 26 + 20 |
| Re-run of `deals.board` | 36 + 6 | 27 + 6 |
| A write with the board open (mutation + its re-run) | 71 + 26 | 53 +
26 |
| Admission and release | 16, in 2 transactions | 7, in none |

Platform statements before the reply, by statement order: the query went
from 21 to 16 and the mutation from 35 to 26.

Every main window was identical: 5/5 query, 5/5 mutation, 6/6 re-run. On
this branch:
- query 5/5, mutation 5/5 and write with the board open 3/3;
- re-run 7 of 8, with the eighth also holding a keepalive touch (+2).

The keepalive touch itself is unchanged.

The board renders and notes save. The board re-runs after every write
and rename, and `pnpm dev shot` reports no errors.

## Tests

`Fleet.test.ts`, over real Postgres:
- **Statement count.** A warm acquire and release sends exactly the
pause upsert and read, the warm read, `protect` and the release, none of
them in a transaction. On main it's 10 statements in 2 transactions.
- **Two holders and a drain.** The first release keeps protection. After
a drain while the call is held, the last release clears protection on
the `stopping` binding and touches the company's fresh one, and
housekeeping then stops the old task.
- **Adoption between the warm read and the hold.** The call is admitted
on the new epoch, never the old.
- **A retired deployment.** The warm read skips the binding, the claim
loop fences it with cause `deployment`, and the call lands on a fresh
task.
- **A breaker trip during an admission's wait.** The admission is
refused `patch_paused`, and the call already admitted keeps running.
- **A publish clearing the pause during an admission's wait.** The
admission is admitted.

The adoption and both breaker cases hold a real transaction open and
wait until the call is blocked on its lock (`pg_stat_activity`) before
committing. Every case except the statement count also passes on main.
The breaker test now uses a shared helper to publish versions.

`pnpm verify` passes: format, lint, typecheck, synth, test,
postgres-concurrency, cli-smoke, tier2-smoke and browser.

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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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