Skip to content

perf(execution): calls reuse a verified task address instead of asking ECS twice - #768

Merged
allisonmahmood merged 4 commits into
mainfrom
perf/752-ecs-endpoint-cache
Oct 18, 2026
Merged

allisonmahmood merged 4 commits into
mainfrom
perf/752-ecs-endpoint-cache

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Oct 18, 2026 •

Copy link
Copy Markdown
Owner

Each tier 2 call asked ECS where its task was twice: one DescribeTasks before bind and another before invoke. For a resource-backed query, the second lookup runs after the company snapshot opens, so it also lengthens how long the company connection is held. Caching the address alone wasn't safe. A stopped task's private IP can be reassigned to a fresh spare that holds the same management secret, and nothing in a management request said which task it was meant for.

The fix

  1. The supervisor checks who it is. Every management request (bind, invoke, stop, stats) can carry taskId, the task the host resolved. Before anything else, the supervisor compares it with its EXECUTION_TASK_ID. If they differ, or the supervisor has no task id, it refuses with 421 wrong_task and does nothing else.
  2. The host reuses the endpoint. EcsTaskProvider keeps each task's resolved endpoint (address, ARN, revision) once a request through it succeeds and its reply decodes, and reuses it for execution.endpoint.lifetime, a new host-scoped operating limit, one minute by default.
    • The cache holds at most execution.fleet.budget entries; expired entries are swept on insert.
    • Any failed, interrupted or undecodable request forgets the entry, without re-sending, and so does any ECS response that shows the task stopped.
    • A request refused before it took effect (unauthorized, invalid_request or wrong_task) is sent once more, after resolving the task again.
    • Fleet.route's live binding checks are unchanged.
  3. No replay. A transport failure through a cached endpoint is never re-sent, because an invoke may already have run. It fails exactly as before, and the next call resolves again.

The local fleet provider now names the task on every request too. Its child supervisors always run the same checkout as the host, and this is the path where the identity check runs end to end against real supervisor processes.

Rollout

During a deploy, old and new hosts run side by side, and tasks of both releases keep serving.

  • Old hosts never send taskId and never cache. The field is optional, so new supervisors still accept their requests.
  • Old supervisors decode request bodies strictly (onExcessProperty: "error"). They have done so since the listener first landed in feat(execution): stop runaway patch processes #428, before the first production deploy. A request that carries taskId therefore gets 400 invalid_request before the supervisor runs. So a new host must not send the field to them.
  • The signal is the task's exact task-definition ARN. A new host sends the field, and caches the endpoint, only for tasks running its own exec task definition (ECS_EXEC_TASK_DEFINITION). ECS reports that ARN for every task. Task definitions never change once registered, and apps/infra pins the release image by digest in each one. A task on the host's own definition therefore runs the same image as the host, and its supervisor checks identity. Every other task is resolved on every call, as today.
  • Considered and rejected: a protocol version echoed in bind or stats replies. The host would have to send a request without the field first to learn it, while the definition ARN is known before the first request.
  • One PR is enough. A release ships the host and the exec supervisor as one image, and the host caches only for supervisors from that same image. No deploy has to land first.

The reused-address hazard is closed at every stage of a rollout. The management secret stays the same across releases, so a cached address that now reaches another task fails in one of these ways, each before any effect:

Who answers at the cached address Result
A spare from this release 421 wrong_task
An older release's spare 400 invalid_request: it doesn't know the key
Nothing Transport failure, not re-sent

In the first two cases the host resolves again and gets stopped, the same answer a fresh lookup gives today.

Lifetime and bounds

execution.endpoint.lifetime goes in the limits registry as a host-scoped operating limit, the precedent from #764's bundle-cache bounds. That makes it tunable through PATCHY_LIMITS_JSON without a release. The entry bound reuses execution.fleet.budget: live tasks can't exceed it, so the cache doesn't need a number of its own.

The identity check makes a stale entry safe, so the lifetime only sets how often a host re-checks ECS on its own. At one minute, the burst of queries when a screen opens costs one lookup, and an open page costs at most one lookup per task per host per minute.

What invalidates an entry

Event How the cache learns, or why a stale entry is still safe
This host stops a task (release, drain, deploy retirement) stop polls DescribeTasks until STOPPED, and any described stopped task is dropped
Another host stops it, or it crashes The lease holder's housekeeping list drops it, or any later lookup does. Until then, a request either gets an identity refusal or a transport failure (forgotten, not re-sent), or the entry expires
Address reused by a fresh spare wrong_task or invalid_request before any effect, then a fresh lookup returns stopped
Rebind, adoption, epoch change Same task, same address. The supervisor still checks the epoch on every request
Spare recycling A released task is stopped, never handed to another company. Its address reuse is the row above
Deploy or host replacement The cache is in memory and starts empty. Tasks of other definitions are never cached
Any failed or interrupted request through the entry Forgotten

Housekeeping reads final stats right after listing a task as stopped, and accepts only stopped. Because the listing itself drops the entry, those stats calls still get stopped, not transport.

Tests

  • Management.test.ts, with a real listener, supervisor and workerd: a misdirected bind reserves nothing and loads nothing. A misdirected invoke, stop or stats leaves callsServed: 0 and the task running. Requests without taskId, as an older host sends them, still work. A supervisor without a task id refuses any request that names one.
  • EcsTaskProvider.test.ts. The ECS fake now models each supervisor with the secrets its host injected, models the previous release as refusing taskId, and returns fresh task copies, as the SDK does:
    • a cached endpoint serves seven management requests with one DescribeTasks, and is looked up again after its lifetime;
    • a previous-release supervisor is resolved on every call and never sent the field;
    • a stopped task's address, reused by a spare from either release, is refused before any effect and re-resolved to stopped;
    • ECS reporting the task stopped drops the entry;
    • an invoke whose reply was lost is sent once, not re-resolved, and the next call looks up again.
  • Mutation checks: removing each of the four mechanisms (the field, stop invalidation, caching other definitions, re-sending after a transport failure) fails exactly its test. Sending a wrong task id from the local provider fails the local fleet journey in DevelopmentExecution.test.ts.

Numbers

ECS can't be faked outside the unit fake, so these counts come from that test. The sequence is one bind, then three calls of bind and invoke:

DescribeTasks
main 7, one per management request
This branch 1

Expected production effect:

  • Lookups. One or two DescribeTasks round trips removed per call: two for a top-level call (bind and invoke), one for a nested call that reuses its parent's bind.
  • Connection hold. For resource-backed queries, the company connection is held for less time, because the lookup before invoke used to run after the snapshot opened.
  • ECS load. Lookups fall to about one per task per host per minute.

The lookup's own latency was never measured, so re-measure dbMs and durationMs after the deploy, as #754 plans.

Known gaps

  • A task that dies without any host observing it can leave its address cached until the first failure or ECS observation. If nothing answers at that address, the first request may wait for its connect timeout or call bound instead of failing at once with stopped.
  • A narrow race: a call can cache a running task just as housekeeping lists it stopped. That housekeeping pass then fails its final stats with transport. The next pass resolves again and finishes.

Closes #752

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

…g ECS twice

Every management request now names the task the host resolved, and the
supervisor refuses `wrong_task` before any effect when it is another task.
The ECS provider then reuses a resolved endpoint for
`execution.endpoint.lifetime`, only for tasks running its own exec task
definition, forgets it on any failure or observed stop, and never re-sends
after a transport failure. Older supervisors refuse the field as an unknown
key, so other tasks are resolved per call as before.

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:m 100-500 changed lines labels Oct 18, 2026
allisonmahmood and others added 3 commits October 18, 2026 16:29
Reply decoding now runs inside the endpoint cache's boundary. An address is
kept only once its reply decodes, and a reply that fails to decode forgets it
without re-sending, as any other failed request does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@allisonmahmood
allisonmahmood merged commit 04a13a7 into main Oct 18, 2026
13 checks passed
@allisonmahmood
allisonmahmood deleted the perf/752-ecs-endpoint-cache branch October 18, 2026 14:49
allisonmahmood added a commit that referenced this pull request Oct 18, 2026
When a shell's `replace` named a subscription that was already running
with the same signature, the server bumped the subscription's epoch. The
running read's result was thrown away, and the query ran again from the
back of the queue. A tier 2 query that overlapped a slow-path `replace`
cost a full extra run, and its panel waited twice as long.

The work can't simply be kept, though. The run took its fence before it
read. A `replace` may be recovering a committed write whose wake was
lost. If the old read answered the new fence, reconciliation would
finish on stale data and nothing would run the query again.

## Fix

A same-signature `replace` during a run no longer bumps `epoch`. The run
keeps its work, but it answers the replace only once it proves that work
fresh:

- When the read finishes, the run takes a new fence over the keys the
read saw, after the `replace` was admitted. If it equals the read's
vector, the result is the answer: a snapshot, or `up-to-date` if
unchanged.
- If not, the result is discarded and the subscription runs again, dated
from the replace. The client's vector from the replace stays, so the
next run compares against what the client actually has.
- A run takes at most one such fence. A replace that lands during it,
during the final authority check, or before a read in the revision phase
ends the run. The run then runs again from the replace, and its document
rotates behind any queued ones, so repeated replaces can't hold a slot.
- A failure, or an `up-to-date` from the revision phase, answers only if
no replace arrived after the run started. Otherwise it is dropped and
the subscription runs again, as before.

**Design choice: a server-side check, not frames that name their
sequence.** The shell already counts the first answer after `admitted`
as answering the fence. So the server never sends an answer-bearing
frame it can't prove fresh, and the wire contract, the shell and
`docs/API.md` stay as they are. A tab running an older shell gets the
same guarantee. Frames that name their sequence could also send a stale
read as data-only, but an older shell would ignore the new field and
count stale data as the answer. That would also need a wire bump. The
only thing given up is early stale data in the rare case where a write
lands during an overlapped run; that case costs the same rerun it does
on `main`.

**What stays:**

- **Full-snapshot recovery.** A replace whose revision differs still
clears the stored result, so the kept run sends a full snapshot, never
`up-to-date`.
- **Epoch invalidation.** A rebind still bumps `epoch`. A changed
signature, an unsubscribe/re-add, or a document close or replacement
still fails the presence check.
- **The `duringRun` wake intersection** is unchanged.

The runtime and analytics glossaries and ADR-0010 now say how a resync
treats a read it overlaps.

## Tests

New deterministic cases in `Subscriptions.test.ts`, using gates on the
read and on the revision fence:

- **Cheap path.** A replace during a read with no write gets that read's
snapshot as its answer, with one read in total.
- **Lost wake + replace.** A write commits during the read, its wake is
lost, and a replace follows. The stale read is discarded, and the first
answer after the replace carries the write.
- **Missed full snapshot + unchanged rerun.** The kept read sends a full
snapshot (revision 3), not `up-to-date`, in three reads rather than
four.
- **Overlapping replaces.** Two replaces land during the read, then a
write and a third replace land during the freshness check. The read
can't answer the third, and the rerun delivers the write.
- **Rebind, unsubscribe/re-add and document close during a run** each
discard the read and send nothing from it.
- **Fairness.** Both company slots are held by one document's checks
while another replace lands. The runs end, and a queued document gets a
slot.
- **A replace during the final authority check**, after a successful
freshness check, and **during a revision-only `up-to-date`'s check.**
Neither old answer is sent; a second run answers.
- **An overlapped read failure and a failing freshness check.** Neither
error is sent, and the next run starts at once, without any time
passing.
- **A key-aware reader.** The freshness fence covers the read's own
dependencies: a write to a dependency only the read revealed, or an
absent (`-1`) resource appearing, forces a rerun; nothing changed
answers with one read.
- The existing coalesced-wait test now expects the overlapped runs to
deliver.

Against `main`'s `Subscriptions.ts`, the cheap-path, missed-snapshot and
coalesced-wait tests fail; the guarantee tests pass on both. With the
freshness check removed, the lost-wake and overlapping-replace tests
fail. Each later guard has its own test, which fails alone when the
guard is removed: a looping freshness check, the final, `up-to-date` and
failure replace checks, and a fence over only the keys known before the
read.

## Validation

I ran a local instance with a tier 2 patch whose `notes.slow` query
reads a table and then waits 1.5 s. A script opened a document stream,
subscribed with `replace` seq 0, and sent the same set as `replace` seq
1 500 ms later, while the query ran. Runs come from the `re-run` wide
events.

| | `main` (3 runs) | this branch (3 runs) |
| --- | --- | --- |
| Query runs | 2: `initial` → `discarded`, then `replace` → `delivered`
| 1: `initial` → `delivered` |
| Slot wait of the second run | 1.02–1.11 s | — |
| Subscribe to the replace's answer | 3.03–3.14 s | 1.53–1.68 s |

**A committed write during the run.** A `notes.create` mutation ran 300
ms into the read, before the replace. On both, the first run was
`discarded`, a second run (`invalidation` → `delivered`) followed, and
the answer at about 3.0 s contained the new note.

`pnpm verify` passes locally: format, lint, typecheck, synth, test,
postgres-concurrency, cli-smoke, tier2-smoke and browser. It ran before
rebasing onto #766 and #768, which don't touch this code; the
subscription suites passed again after the rebase.

Closes #750

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 18, 2026
…e task (#773)

Every top-level tier 2 call sent the version's whole server bundle
(about 216 KB in production) in `POST /bind`. When the version was
already loaded with the same hash, the supervisor returned the existing
process and never used the bytes, so on a warm call the upload, its JSON
encoding and the supervisor's two strict decodes were pure waste.

## The fix

**A bind by hash.** `BindRequest` gains an optional `binding` (company,
patch, version and SHA-256) that names the version without its bytes. A
request carries `bundle` or `binding`, never both; the schema refuses
both as `invalid_request`.

The supervisor makes the same checks as for a bundle bind: company,
epoch, limits and callback URLs.
- **Held** (a live process for that version, loading or ready): it
adopts the epoch, limits and callback URLs, waits for a loading process,
checks the epoch again after the wait, and returns the current
generation, exactly as an idempotent bundle bind does. A different hash
for a held version is `binding_conflict`.
- **Not held** (never loaded, reaped, evicted or dying): it refuses
`bundle_required` (409). It looks the version up before changing
anything, so this refusal comes **before any effect**: no company is
reserved, no epoch adopted, no limits or callback URLs applied. That is
why the host can safely send the same bind again with its bundle.

**The host binds by hash first.** `TaskProvider.bindByHash` sends the
bind by hash. Only after a decoded refusal that proves it had no effect
does it send the same bind with its bundle: `bundle_required`, or
`invalid_request`, which a supervisor from before this change gives the
unknown `binding` key. It never sends a second bind after a transport or
protocol failure.
- `EcsTaskProvider` does this only for same-release supervisors (see
Rollout), inside its per-task `answer`, so both requests reach the same
resolved task. A `bundle_required` is answered after the supervisor's
identity check and recovered there. It neither forgets a cached endpoint
nor triggers another `DescribeTasks`. Every other #768 rule is
unchanged: identity first, re-sends only after `unauthorized`,
`invalid_request` or `wrong_task`, never after a transport failure, and
reply decoding inside the endpoint-cache boundary.
- `LocalTaskProvider` and the in-process `local.ts` executor always bind
by hash first. A local task owner can outlive its host's checkout, so a
host restarted after an update may reach an older supervisor; it answers
`invalid_request` and gets the bundle. In process no bytes move, but
`pnpm dev`, `patchy dev` and the runtime suites now run the fleet's
path.

**The host's own bundle read is unchanged.** Runtime still loads the
bundle before binding. Since #764 that is a retention check plus a
memory hit (`bundleLoad: cached`). Loading only after `bundle_required`
would need a hash-only lookup on `ServerBundles`, which is `Content.ts`
(#746's lane), and would save a read only when the host's cache missed
but the supervisor was warm. I left it out.

**Eviction between bind and invoke recovers.** Before, an invoke refused
`bundle_required` or `stale_generation` surfaced as `handler_failed`.
Now Runtime's attempt loop binds again **once**, under a fresh attempt
and capability, and invokes the current generation. It does this only
when all of these hold:
- the call is top-level;
- the failure is an `invoke` refusal with one of those two codes;
- the attempt settled (nothing uncertain).

Every pass checks the call's deadline before it binds, so a call refused
at its deadline times out instead of binding again.

What proves nothing ran:
- The supervisor's `select` refuses both codes before it registers the
attempt or calls the engine.
- The loader's own `bundle_required` refuses before any handler runs.
- Both providers produce these reasons only from a decoded refusal
reply. A lost reply is `transport`, which is never retried, so an
invocation is never replayed after uncertain transport loss.

Each pass takes its generation from its own bind reply, so a stale
generation is never reused. A second refusal fails the call as before.
The refused invoke ran no handler, so it doesn't count toward
`tier2.mutation.attempts`: a recovered mutation still gets its three
conflict attempts. The call's request or re-run event records `rebound:
true`, whatever came of the rebind, so a rebind that then fails `busy`
still shows the refusal behind it.

**Nested calls are unaffected.** They reuse their parent's bundle and
bound version, never bind, and never take the recovery path: their
parent is running in that process, so if it's gone, the parent fails
too.

## Wire shape

I chose an optional `binding` on `bind` over a new route. The reply, the
checks and the epoch semantics are bind's own, so a second route would
duplicate them. An older supervisor would also answer an unknown route
with a router 404 rather than a typed refusal. A `bind` without `bundle`
already means a company bind (claim, adoption, limit updates), so the
version has to be named. Strict decoding stays meaningful: unknown keys
are still refused, and `bundle` with `binding` is refused by the schema.

## Rollout

Management schemas are strict, so an older supervisor refuses `binding`
as an unknown key, just as it refuses #768's `taskId`. I reused #768's
gate and renamed it from `checksIdentity` to `sameRelease`: a task on
the host's own exec task definition runs the host's own image, pinned by
digest, so its supervisor speaks the host's management wire.

| Host | Supervisor | What happens |
| --- | --- | --- |
| New | Same release | Bind by hash, full bind on `bundle_required` |
| New | Older release | Full binds only, as today; never sent `binding`
|
| Older | New | Full binds, accepted unchanged |
| New, local fleet | A retained owner from an older checkout | Bind by
hash refused `invalid_request` before any effect, then the full bind |

The recovery needs nothing from the supervisor: both refusals predate
this change and come before dispatch in every release. One PR is enough,
because host and supervisor ship in one image.

One behaviour change for every host: a bundle bind whose hash conflicts
with a live process of the same version is now refused before it adopts
its epoch and limits, where before it was refused after. Versions are
immutable, so this doesn't happen outside tests.

## Tests

- `Management.test.ts` (real listener, supervisor and workerd): a bind
by hash to a version not held gets 409 `bundle_required` and leaves the
task an unreserved spare. After a bundle bind, a bind by hash returns
the same reply. A different hash is `binding_conflict`, and `bundle`
with `binding` is 400 `invalid_request`.
- `Supervisor.test.ts`: a bind by hash waits for a loading version and
returns its generation. When adoption raises the epoch during the wait,
both waiting binds fail `stale_epoch`.
- `EcsTaskProvider.test.ts`. The fake supervisors now hold versions, and
the previous release refuses `binding`:
- a current-release task gets the bundle once across four binds, and
again only after it drops the version, all on one cached endpoint with
no extra `DescribeTasks`;
  - a previous-release task gets only full binds.
- `LocalTaskProvider.test.ts`, with a real task and a transport layer
that answers like an older supervisor: each version bind is refused by
hash and then sent with its bundle, and a bind by hash whose reply was
lost is never followed by the bundle.
- `Invocation.test.ts`:
- an invoke refused `bundle_required` or `stale_generation` rebinds and
succeeds on the new generation, with a new attempt id; its event reports
one attempt and `rebound: true`;
- a second refusal fails after exactly two binds and two invokes, still
marked `rebound`; a lost invoke reply (`transport`) is never re-sent and
isn't;
- a refusal at the deadline binds no more, and a rebind that outlasts
the deadline invokes no more;
  - a nested call keeps its parent's generation and never binds.
- `MutationTransaction.postgres.test.ts`, real `SERIALIZABLE` Postgres:
after a rebind, a contended mutation still gets three handler attempts
before `write_conflict` (event `attempts: 3`, `rebound: true`), and a
committed mutation's key replays its stored reply without running the
handler again.
- Mutation checks: each of these breaks exactly its test.
  - the post-wait epoch check
- the `parent` and once-only guards, and leaving the refused attempt
counted (in both the unit and the Postgres test)
- binding by hash without the release gate (the older supervisor's
hash-bind count), or never
- recovering `bundle_required` outside the endpoint-cache boundary (that
one breaks both provider tests)
- dropping `invalid_request` from the fallback (the previous-wire local
test)

## Validation

On this worktree's `pnpm dev up brightline`, I ran a second host on the
same database with tier 2 on the local task provider
(`EXECUTION_PROVIDER=local-fleet`). Calls went through real supervisor
and workerd processes. New Business's server bundle is 196 KB;
production's is about 216 KB.

**Bytes sent to `/bind` per warm call** (temporary request logging, not
committed; 40 warm `deals.board` calls each):

| | Bind body | Bind round trip, p50 |
| --- | ---: | ---: |
| `main` | 221,293 bytes | 6.5 ms |
| This branch | 608 bytes | 2.4 ms |

**Warm call latency**, without the logging: 100 sequential calls per run
after 10 warm-ups, at load ≈3, alternating main and branch:

| | p50 | p90 |
| --- | ---: | ---: |
| `main`, two runs | 26.1 / 26.8 ms | 28.9 / 30.9 ms |
| This branch, two runs | 23.5 / 23.9 ms | 26.5 / 26.5 ms |

That's about 2.8 ms (11%) off each warm call on loopback.

**Cold, reaped and evicted versions still load:**
- **Cold** (a fresh task): the 608-byte bind by hash is refused
`bundle_required` in 4.4 ms, then the full bind loads the version and
the call succeeds.
- **Reaped** after 60 s idle: the same, and the next call binds by hash
again.
- **Evicted** (residency capped at one process, alternating the two tier
2 patches): each bind evicts the other version, and each call reloads by
full bind and succeeds, 6 of 6.
- **Evicted between bind and invoke** (three versions capped at two
processes, three concurrent loops of 60 calls): 28 invokes were refused
`bundle_required` before dispatch.
  - 5 calls rebound and succeeded on the new generation.
- 21 were refused `busy` on the rebind (429 with `retryAfter`), because
the tiny cap had no idle process to evict.
  - 1 was evicted again and failed `handler_failed`, which is the bound.
  - On `main`, all 28 would have failed `handler_failed`.
- I counted rebinds by `attempts: 2` on those queries. That run came
before I stopped counting the refused attempt, which changes only the
count.

**Expected production effect:**
- A warm top-level call no longer sends about 216 KB to its task. That
saves the host's JSON encoding, the transfer across the VPC, and two
strict decodes on the supervisor's Fargate CPU, which is smaller than
this machine. Expect at least the local saving; re-measure `durationMs`
after the deploy, as #754 plans.
- A cold or reaped version pays one small extra round trip, the refused
bind by hash, before its full bind.
- Nested calls never bound, so they're unchanged.
- A call whose process is reaped between bind and invoke now succeeds,
or gets `busy`, instead of failing `handler_failed`.

## Known gaps

- The host still reads its bundle (a memory hit since #764) before every
top-level bind; see above.

Closes #751

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 18, 2026
…ading it (#775)

The supervisor reaped a version's process 60 s
(`execution.process.idle`) after its last call, whether or not anyone
had the patch open. In production, 25 of 44 reaps in a week happened
while a document for that version was open, so reading a page for a
minute and then switching screens reloaded the process: first runs took
p50 1.12 s against 0.50 s warm, and 3 of 44 hit the 3 s query deadline.
The load also only started when the first query arrived, while the
client was still booting.

Now a host keeps the version of each connected, ready tier 2 document
warm by **touching** it before each idle window ends, and a document's
first stream **warms** its version as it becomes ready.

## How it works

**Touch** is a new private management operation, `POST /touch {
bindingEpoch, binding }`. For a ready process of exactly that version
and hash at the current epoch, it restarts the idle clock and answers
`touched`. A loading process answers `loading` and keeps its
initialization deadline from spawn; no live process answers `absent`. It
never loads, reserves, evicts or changes the epoch. Every reply also
carries `idleMs`, the idle window the supervisor reaps by: its last
bind's setting. A different hash is `binding_conflict`; it checks
`wrong_task` and the epoch like every other operation.

**Where the bookkeeping lives:** a new runtime module,
`ConnectedVersions`, one per host, built beside the fleet in
`FleetInvocation` and used by `RuntimeStream` (absent in no-pool dev,
like `ExecutionLifecycle`). It keeps one keepalive per company + patch +
version, not per document:

- **Open:** when a tier 2 stream sends `ready`, it calls
`connect(version, { warm })` for the stream's lifetime. The first holder
starts the keepalive, whose first touch is immediate.
- **Reconnect, reauthentication, resume:** the shell sends
`X-Patchy-Generation` on every stream after a document's first hello, so
`warm` is true only when it is absent. A document warms once; its
renewals only touch, so a version evicted under pressure reloads on
demand, never on renewal. No state is needed for this, and it holds
across hosts.
- **Last disconnect or hidden suspension:** both close the stream, which
releases its hold. The last release ends the keepalive, and the process
idles out as before.
- **Binding changes (adoption, epoch, deployment replacement):** each
touch goes through `ExecutionLifecycle.touch`, which reads the company's
current *active* binding and sends to that task at that epoch. It never
admits, claims a task or binds; a company without an active binding gets
no touch (`unbound`).
- **Pause:** each touch reads the patch's breaker first (as admission
does, off in dev). A paused patch gets no touch, and its warmup doesn't
bind.
- **Retire and delete:** the stream's existing authority checks close
those documents, which ends their keepalive.
- **A new publish while open:** the document keeps its loaded version,
so its keepalive keeps that version. A reload opens a new document on
the new version, which warms it; the old one idles out.

**Cadence:** the first touch is immediate. Each later touch starts at a
random 30–40 % of the idle window after the previous one *started*,
whatever that one cost, and gives up after 10 %. The window is the
smaller of the company's configured `execution.process.idle` (read
through `StreamLimits`) and the `idleMs` the supervisor last answered. A
changed limit reaches the supervisor only with its next bind, so a raise
spreads touches out only once the supervisor has it, and a cut applies
from the next turn. A cut can still reap a process already idle longer
than the new window, as it would without touches; demand reloads it. So
a lost touch, even one that fails only at the provider's timeout, still
leaves the next to land within 90 % of the window after the last that
landed, and versions spread out. This is derived from the idle window,
so there is no new registry tunable.

**Warmups:** on a first stream, the keepalive's touch decides. `touched`
or `loading` is enough (`resident`, `loading`). On `absent`, it binds
the version under a normal call admission (`acquire`, then the server
bundle, then `executor.bind`, which binds by hash first), concurrent
with client boot, without delaying `ready`. A `paused` or `unbound`
touch tries nothing. Warmups are bounded:
- one per logical document;
- coalesced per company, version and host: a holder joins or creates its
version's keepalive in one synchronous step, and warm requests set a
flag that keepalive serves, so concurrent documents share one touch and
at most one bind at a time. The bind runs beside the touches, so it
never delays them;
- only for documents whose company task is already bound, so they never
claim a task or count against the fleet budget beyond what the first
call would;
- the supervisor's residency and memory caps and the provider's
management timeout bound the bind like a call's, and its admission stays
interruptible as a call's does, so a keepalive whose last document
leaves mid-admission claims and binds nothing;
- a failed warmup is silent apart from the wide event. It doesn't take a
subscription run slot, so it never delays the first queries.

**More open versions than the process cap (13 under 12):** touches never
reserve or load, so they can't cause evict/reload churn. Touched
residents count as recently used in the eviction order, so versions
without open documents go first. Under pressure, demand (a call or a
first-stream warmup) still evicts the least recently used, and touches
of the evicted version then answer `absent` until demand reloads it.
Memory-pressure eviction is unchanged.

**Observability:** one new wide event, `type: "keepalive"`, per company
version per host when its last document leaves: `peakDocuments`,
`touches` by outcome (`touched`, `loading`, `absent`, `unsupported`,
`paused`, `unbound`, `failed`) and `warmups` by outcome (`resident`,
`loading`, `loaded`, `bound`, `paused`, `unbound`, `failed`). This
measures what the issue asks for:
- `touches.absent` counts versions evicted or reaped while open;
- process events with `callsServed = 0` after a `loaded` warmup are
unused warmups;
- `cause = "evicted"` is residency churn;
- the first call per process generation against warmup timing gives the
cold calls avoided.

A touch per open version every ~25 s per host would be too noisy as its
own event, so they are counted. OPERATIONS has a query.

## Rollout

Touch is a new route, and supervisors' schemas are strict, so it follows
#768/#773:
- The ECS provider sends it only to tasks of its own release's task
definition (`sameRelease`), and through the same verified endpoint
cache.
- A task of another release gets `unsupported` without a request. Its
release is remembered, so later touches don't ask ECS again; a task's
definition never changes, and the memory is forgotten on stop.
- Older hosts never send it.
- A local task owner that outlived its host's checkout answers 404,
which counts as a `failed` touch: no retry before the next turn, and
nothing reaches viewers.
- A warmup for an older supervisor (`unsupported`) is a normal bind
(`bound`).

No migrations.

## Tests

- `Supervisor.test.ts` (real workerd):
- a touched process outlives its idle window, and a touch for a version
it doesn't hold loads nothing;
  - hash and epoch mismatches are refused;
  - once untouched, the process idles out and a touch finds `absent`;
- an unfinished load still expires at its deadline from spawn while
touches arrive;
- one more touched version than the process cap: no evictions and no
reloads across two idle windows; a demand bind then evicts once, and
that version's touches find `absent` without reloading it. This runs at
a cap of 2 rather than 12: touches never reserve, so the property
doesn't depend on the cap, and twelve workerd processes would dominate
the suite.
- `Management.test.ts`: `/touch` authenticates before reading the body
and refuses `wrong_task` before any effect.
- `EcsTaskProvider.test.ts`: an older-release supervisor is never sent a
touch, and ECS is asked once about it; a same-release touch reuses the
cached endpoint.
- `Fleet.test.ts`: a touch claims nothing for an unbound company,
follows adoption's new epoch, and sends nothing for a paused patch.
- `ConnectedVersions.test.ts` (TestClock, injected ports):
  - warms once per document and coalesces documents;
  - a renewal of an evicted version only touches;
  - a paused version is neither loaded nor woken;
- each version gets one touch per turn within 40 % of the idle window,
however many documents hold it;
- with the widest jitter and every other touch lost, failing only at the
provider's 10 s timeout, each landing still follows the last within the
idle window;
- four concurrent first holders, interleaved by a small scheduler
budget, share one keepalive;
- touches keep to the supervisor's acknowledged window while a raised
limit hasn't reached it, spread out once it has, and tighten from the
next turn after a cut;
- a warmup waiting for admission is cancelled when its last document
leaves: nothing is admitted afterwards, and the keepalive reports once;
  - the last document leaving stops touches.
- `RuntimeStream.test.ts`: a ready document holds its version until
disconnect, with `warm` only on its first stream.

## Numbers

I measured on the local fleet (`pnpm dev up brightline`,
`EXECUTION_PROVIDER=local-fleet` via a temporary, uncommitted runner
edit) with `PATCHY_LIMITS_JSON={"execution.process.idle":20000}`. Each
pass, as a member:
1. open the New Business board cold;
2. keep it open 30 s;
3. open a deal (a new `deals.timeline` query on the same version);
4. close the page.

There were three passes each, on `origin/main` and this branch.

| | main | this branch |
| --- | --- | --- |
| Open → board shows deals (browser) | 311, 313, 323 ms | 215, 216, 221
ms |
| Stream open → first board answer (server) | 160–168 ms | 130–137 ms |
| Process reaped while the board was open | yes, 20.1 s after the first
call | no |
| Deal opened after 30 s: its run | 115–124 ms, **new process
generation** | 28–30 ms, same generation |
| Deal opened: click → timeline shows (browser) | 217–231 ms | 120–128
ms |
| After closing | reaped 20 s after the last call | reaped 20 s after
close (lifetime 50.4 s = 30.3 s open + 20 s) |
| `keepalive` event per pass | none | `touches {touched: 3, absent: 1}`,
`warmups {loaded: 1}` |

A local load costs ~90 ms; in production the first run was p50 1.12 s,
so the gap there should be correspondingly larger. The open-time gain is
small locally because the client boots in ~100 ms here, against ~1 s in
production.

`pnpm verify` passes.

Closes #753

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:m 100-500 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Each call asks ECS where the task is, twice

1 participant