Skip to content

feat(execution): stop runaway patch processes - #428

Merged
allisonmahmood merged 3 commits into
mainfrom
tier2/396-supervisor
Oct 1, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
tier2/396-supervisor

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

A spinning or leaking tier 2 handler must not take down other loaded versions. The host also needs process measurements and interrupted attempt identities when a process dies.

Run one workerd process per loaded version with bounded residency, watchdog termination and fenced callbacks. Add private management endpoints and a supervised local Executor. Process reports carry CPU, peak RSS and interrupted attempts without claiming a transaction rollback. Public tier 2 admission remains closed.

Stacked on tier2/395-execution-engine. This PR contains only the supervisor work for #396.

Closes #396.

Verification

  • Typecheck and lint passed.
  • All 19 supervisor, management and local Executor tests passed.
  • The full offline run passed 110 files. Concurrent test setup rebuilt CLI artifacts during that run; the serialized CLI rerun passed all 231 tests.
  • Packaged production-mode exec smoke killed a spinner in 1.639 seconds while its sibling kept serving, reported metrics, rejected unauthorized and stale requests, and reaped all processes.
  • Docker build was not run because daemon access was denied. The packaged entrypoint was verified outside Docker.
  • Standards and Spec reviews have no remaining findings.

Implemented with OpenAI GPT-6 Astra in the omp harness.

@github-actions github-actions Bot added area:server Touches the server area area:docs Touches the docs area size:xl Over 1,000 changed lines; review in multiple passes labels Sep 28, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Reviewed origin/tier2/395-execution-engine...ba9a01e against #396 and spec #384 §5/§14. Ran the three new suites, then the memory-pressure case on its own three more times, and typechecked execution, runtime and server.

Blocking

1. A sampling race in the watchdog tick can stop the whole supervisor. packages/execution/src/supervisor.ts:461, :485-495, packages/execution/src/process.ts (sampleProcess)

tick samples each resident without catching errors. sampleProcess only turns ENOENT into undefined. Any other read error becomes WorkerdError, and the tick's catchTags handles that by setting stopped = true and terminating every resident. Another fiber can reap the child between the open and the read of /proc/<pid>/status: bind's evict(1) (:539 → :310), /stop (:727, :737), or an external crash. The read then fails with ESRCH. I checked this on Linux by opening /proc/<pid>/status, SIGKILLing and reaping the child, then reading, and got ESRCH. After that, every bind returns stopped. execution/local maps stopped to transport, so the local executor stays dead until restart. That breaks the "health-probe recovery" the issue asks for. terminate already tolerates a failed final sample (:220-228). Either treat ESRCH like ENOENT, or catch per-resident sample errors inside tick, so one vanished child cannot stop the others.

2. The aggregate-memory-pressure test is flaky. packages/execution/src/Supervisor.test.ts:371

It failed in 3 of 4 runs here: once in the full-file run and twice in three isolated runs (-t "aggregate memory pressure"). Each time, bind(supervisor, "ver_memory_overflow") succeeded where the test expected busy. The ceiling is process.memoryUsage.rss() + 512 MiB, measured when the test starts. After both idle processes are evicted, the test needs the busy process's 480 MiB fill plus workerd's baseline to stay above 512 MiB plus however much the vitest worker's RSS has moved since. That margin is a few MiB, so the test will flake in CI. Finding 3 is the root cause.

3. In local mode the host process's RSS counts against the 1.5 GiB residency ceiling. packages/execution/src/supervisor.ts:178, packages/execution/src/local.ts:31

aggregateRss adds process.memoryUsage.rss() as "the supervisor". Under execution/local the supervisor runs inside the host process, so that figure is the whole dev host: the vitest worker today, and patchy dev with Vite and the runtime later. Dev would return busy and evict because of the dev tool's own memory, which is not how production behaves, and residency tests depend on the runner's heap (finding 2). One fix is to count the process's own RSS only where it is the dedicated supervisor, the exec entrypoint. Local mode would count the children plus a fixed allowance for retained bundles and reports. With that, the test can compute its ceiling from the children alone.

4. YAGNI: Executor.implementation and requireProduction have no caller. packages/runtime/src/Executor.ts:37, :46

Only Local.test.ts uses them. Local.make already refuses construction when NODE_ENV or its option is production, which covers "a production server refuses tier 2 admission on it" for this ticket. The port now names "engine" | "local" | "fleet", implementations from a package Runtime must never import (§3). A second, unwired refusal path adds nothing until host admission exists. Drop both and let the ticket that installs the host's executor (#401/#405) choose its guard. A smaller instance of the same thing: WorkerdProcess.closed (packages/execution/src/process.ts:172, :385) is exported but never read.

Judgment on the Dockerfile and exec entrypoint (not blocking)

The Dockerfile line is correct wherever apps/server/src/exec.ts lands. Once apps/server depends on @patchy/execution, pnpm install --frozen-lockfile needs that manifest. exec.ts itself is #406's second image entrypoint. It is small and harmless. It does fix the exec env contract early (a static EXECUTION_CALLBACK_URLS list, EXECUTION_TASK_ID), and it ships workerd in today's host image. The image also runs as USER node, so the per-version uid separation this PR adds never applies there. #406 should inherit that knowingly; a note on #406 is enough.

Checked and fine

  • Epoch fencing on all four verbs, with adoption raising the epoch.
  • Callback routes deleted before reap, with generation, epoch, attempt and capability checked before forwarding and again before delivering the reply.
  • Authentication before the body is read, current and previous secrets compared in constant time, capabilities refused, and wildcard or public binds refused.
  • Kills at deadline + 1 s, at 6 s of stall and at 512 MiB, with in-flight attempts carried in the report.
  • Oldest-idle and largest-idle eviction, and the 60 s idle reap.
  • A scope closed mid-spawn still kills the child, because Effect runs finalizers added to a closed scope immediately.
  • Glossary, ADR-0012, docs/limits.md and docs/API.md are updated.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed ba9a01e against origin/tier2/395-execution-engine at b10524a, using #396 and #384. One pass, no subagents; merge blockers only.

Standards

No merge-blocking method or YAGNI findings.

Spec

  1. [P1, intent] Bound asynchronous bundle loading so it cannot permanently exhaust residency.

    In supervisor.ts:594–599, engine.bind() has no load deadline. A guest's describe handler can wait forever while yielding to a timer, so /healthz continues answering. The resident stays loading, has no invocation deadline, and is excluded from both eviction and idle reaping.

    feat(execution): the supervisor and the local executor: a process per loaded version, residency, the watchdog, the fence, the management listener #396 requires bounded residency and says, "Processes are reaped after 60 s idle." These unfinished loads instead reserve slots indefinitely and can prevent healthy versions from loading.

    Reproduced against the real exec entrypoint with default limits: bind 12 versions whose describe handler loops over await new Promise(resolve => setTimeout(resolve, 100)). After 65 seconds, all 12 processes remained, each with zero active invocations. Binding a healthy version returned 503 busy, limitId: execution.residency.processes, value: 12. Only an explicit stop reaped them.

    Give bundle initialization a bounded lifetime and terminate/reap the loading resident on expiry. Cover an asynchronous unfinished load that keeps health probes responsive, not only the existing synchronous-spinner case.

Verification also exercised a deadline kill in 1.276 seconds, a surviving sibling invocation, capability rejection with 401, and stale-epoch rejection with 409. The isolated supervisor and its children were stopped. No repository files changed.

Standards: 0 blockers. Spec: 1 P1 blocker, unfinished loads permanently exhaust residency.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Reviewed ba9a01e against tier2/395-execution-engine at b10524a, issue #396, and the supervisor slice of spec #384, sections 3, 5, 14, 15, and 19. Separate passes covered Effect conventions, docs and the wire, code smells, the spec, the ticket, the implementation method, and YAGNI.

One workerd per loaded version, a private four-route listener, and a local executor that only binds and invokes is the right size. The five done-when checks in #396 are implemented and covered by live tests. Two behaviors are wrong.

Standards

Effect services

Hard. The load fiber in packages/execution/src/supervisor.ts handles failure with Effect.catch and Schema.is(SupervisorError).

effect-service-conventions, Errors and predicates: catch a known tag with Effect.catchTags, including when there is only one tag. Map a failure where the stage and reason are already known, instead of wrapping a multi-step pipeline in one generic error.

startWorkerd and sample fail with WorkerdError. That tag is dropped. The caller waiting on bind sees transport. The process report records load_failed. Pass SupervisorError through with catchTags, map WorkerdError onto a supervisor reason, and keep cause.

Judgement. CallbackBodyTooLarge carries no fields. The byte length and GuestProtocol.callbackFileLimit are both in scope inside readCallbackBody. The error stays inside the supervisor and becomes a fixed 413, so this is small.

Left alone after checking: Supervisor and Executor are one file each, in the usual order. Management.serve stays a function and takes Supervisor from the environment. NodeRuntime.runMain appears only in apps/server/src/exec.ts. SupervisorError.reason is the wire refusal union, which the conventions allow for an adapter.

Docs and the wire

Hard. docs/limits.md, under Runaway code and residency, and ADR-0012 say memory pressure evicts the largest idle process, and new work receives busy only when no process is idle. Supervisor.bind and the watchdog call evict. Supervisor.invoke does not. At the byte ceiling it returns busy immediately, while an idle resident can still be reaped. CLAUDE.md says an ADR the change contradicts gets updated, and docs stay aligned with the code. The docs already state the rule. The invoke path should follow it.

Judgement.

  • docs/API.md, generated from packages/api/src/markdown.ts, says a same-epoch bind is idempotent. A dead resident is reaped and the next bind mints a new generation. Local recovery depends on that. ADR-0012 also says the host binds again after a health kill to receive a new generation. The idempotent sentence needs that qualifier.
  • ADR-0012 decision 2 still says 1.5 GB and 512 MB. The enforcer uses 1610612736 and 536870912 bytes, which are 1.5 GiB and 512 MiB. docs/limits.md already treats those units as binary.
  • The management refusal paragraph never mentions 413 too_large. management.ts returns 413 when the body exceeds execution.management.bodyBytes.
  • CONTEXT-MAP.md still describes execution as the loader and inspection only, and says hosted admission waits on the supervisor ticket. This PR lands the supervisor and the local executor. Hosted admission still waits on the fleet ticket. docs/product.md already says that. The hit-every-surface rule requires a map edit when a package is added or removed, so this is a stale wayfinding sentence.

Left alone after checking: management schemas live in packages/api and are not mounted on the public HttpApi. The glossary entries for Supervisor, Process generation, and Binding epoch match the code. The new limit rows match the registry, the generated limits doc, and the server skill. docs/product.md keeps tier 2 publish and hosted admission closed. docs/DEVELOPMENT.md and the dev-loop skill match exec.ts. Bind has stop, and stats keeps each report until the host acknowledges it.

Smells

Judgement only.

callbacks names two different maps. The module map is a proxy path to a resident. Resident.callbacks is a caller URL to a proxy URL. terminate deletes an entry in the first map by reading values from the second. callbackRoutes and proxyUrls say which is which.

aggregateRss reads like a total. Every call also writes peakProcesses and peakAggregateRssBytes onto every resident. invoke and evict call it as a predicate, so a read rewrites peaks. Split the sum from the stamp, and stamp from the watchdog and from reap.

identity is a map key of patch id and version id. It drops sha256. A second sha for the same version correctly returns binding_conflict. The name is doing too much work.

Looked for a split of the one-file Effect service, a second RPC layer, a middle man in local.ts, and a speculative fleet controller behind the "fleet" guard. The production refusal needs that name. Those did not show up.

Spec

Issue #384, sections 3, 5, 14, 15, and 19, judged only for the supervisor ticket. Fleet, mutations, subscriptions, and public admission belong to later tickets.

What matches: one workerd process per loaded version. Private bind, invoke, stop, and stats, accepting the current or previous deployment secret. Generation fence on callbacks. Kill at the caller deadline plus 1 second, after 6 seconds without a healthy probe, and at 512 MiB. Idle reap and the 12-process cap. Bundles pushed by the host. Process reports carry CPU seconds, peak RSS, interrupted attempt identities, and the process event. No analytics sink and no Postgres process rows. The local executor has no pool, and production construction is refused. ADR-0012, the Runtime glossary, docs/limits.md, and docs/product.md stay inside what this ticket admits.

Partial. Section 5 says at most 12 processes and 1.5 GB aggregate, enforced continuously, and past that the idle process goes first, with busy if none is idle.

Bind and the watchdog do that. invoke returns busy as soon as aggregate RSS is at the ceiling:

if (aggregateRss() >= limit("execution.residency.bytes"))
  return yield* new SupervisorError({
    operation: "invoke",
    reason: "busy",
    limit: limitRefusal("execution.residency.bytes", limit("execution.residency.bytes"))
  });

An idle sibling stays loaded. evict uses the same >= comparison, so the ceiling already counts as past the limit.

Scope. The process event on /stats is the supervisor report section 14 asks for. acknowledgeReports is how that report reaches the host. The housekeeping lease and the deployment revision stay names, not a fleet controller.

Wrong. Section 5 kills at the caller deadline plus 1 second when the invocation is still running, and reaps a process after 60 seconds idle.

Any failed engine.invoke, while the process is still alive, leaves the attempt in invocations until reap:

if (resident.alive && Exit.isFailure(exit)) {
  // Transport loss cannot prove execution ended. Keep its deadline and identity until reap.
  yield* Deferred.done(result, exit);
  return;
}

The comment describes transport loss. The condition keeps every failure. engine.invoke also fails with protocol when the loader answered and the body did not decode, and with the loader's own refusal codes. Those calls have finished. The version cannot go idle, and the watchdog later kills the whole process for deadline, including other attempts on that version. Keep the attempt when the reason is transport. Remove it when the loader returned a refusal.

Issue 396

The done-when list is met in code and in live tests.

  • A spinning handler is killed at its deadline plus 1 second, and the sibling version still serves. The grace is tier2.query.kill minus tier2.query.deadline, which is 1000 ms. The test accepts a kill from deadline + 1s up to deadline + 3s.
  • A real resident leak is killed at the registry's 512 MiB RSS.
  • The 13th process evicts the oldest idle version and fences that generation.
  • A late callback from a killed generation is refused.
  • A stale epoch is refused. A capability presented as the management secret is refused before the body is read.

A few ticket lines are implemented narrowly, and the code says so. Distinct uids are applied only when getuid() is 0. ADR-0012 and docs/DEVELOPMENT.md say an unprivileged runner cannot grant that separation. Aggregate RSS is process.memoryUsage.rss() plus each child's sample, so the supervisor sits inside the 1.5 GiB ceiling. Samples run at the start of every watchdog tick, and a missing /proc entry keeps the previous sample. Reports list attempt identities and return process_killed. They do not record a commit outcome. The host classifies. Local recovery is a new generation on the next bind, with no replay. In the local test the spin's deadline is 30 seconds out, and the stall kill lands inside 15 seconds.

The residency sentence is only partly met. "Past it the idle process goes first, busy if none is idle" is the invoke gap above. The largest-first comparator is in evict. The memory-pressure test records that the large idle process was evicted and the busy one survived. It never asserts that the smaller idle process is still resident at that moment. An oldest-first comparator can still pass the test.

requireProduction is called from Local.test.ts only. apps/server has no tier 2 admission in this PR, and Local.make already refuses NODE_ENV=production. The helper is the host hook for the fleet ticket. "Admitted at merge: nothing" still holds.

This earns Closes #396 after invoke evicts an idle process before it returns busy. That sentence in the ticket is unambiguous.

Method

One workerd per loaded version is the smallest model that keeps a spinning or leaking handler off its siblings. Isolates inside one process do not survive a synchronous spin. The stall test loads a wedged module and still invokes a sibling. A process per invocation would blow the 12-process cap.

The watchdog and the callback proxy belong in this design. A wedged workerd cannot police itself. An epoch or generation check inside the loader can be skipped by anything that can open the callback socket. The proxy checks the attempt, the capability, the deadline, the epoch, and the generation. terminate drops the callback routes before it reaps the child.

Epoch and generation stay distinct. Bind adopts the host epoch when the request is greater than or equal to the current epoch, and every management call checks it. Generation is a counter inside the supervisor, and invoke requires it. Management is four POST routes, schemas in packages/api, and a sha256 digest compared with timingSafeEqual before the body is read. local.ts builds that supervisor, freezes epoch 1, and maps bind and invoke. There is no second pool and no replay.

Two changes to the method:

  1. The watchdog loop should survive a failure that belongs to one child. The tick catches WorkerdError by setting stopped and terminating every resident. Any other failure, including rm rejecting during reap, ends the fiber. The remaining processes then have no deadline kill, no stall kill, and no RSS kill. A missing /proc entry already returns undefined and keeps the last sample. A thrown sample should do that for the one pid, log it, and let the tick continue.

  2. Refuse a probe interval greater than or equal to the 6 second stall. The interval is an overridable operating limit, and exec.ts passes the deployment value through. The stall check runs at the start of the tick, before that tick's probe. At an interval of 6 seconds or more, the next tick kills a process whose last good probe is still the previous tick. The 250 ms default is sound. The override is not checked.

Sampled RSS is the right kill signal. The same loop has to report CPU seconds and peak RSS, so a cgroup limit would be a second mechanism. Linux uses VmRSS for the kill and VmHWM for the peak. macOS ps has no high-water mark, and ADR-0012 says so.

The watchdog reads the query kill and deadline to get its 1 second grace. Mutation and action have their own kill limits, both also 1 second today. A later change to one kind's grace will leave the watchdog on the query pair. A named 1000 ms next to the tick, or the grace for the attempt's own kind, would keep the rule visible.

YAGNI

Keep one Resident map, one tick, and terminate fencing callbacks before reap. local.ts is the whole local executor: refuse production, epoch 1, bind, invoke.

The process-event fields are the section 14 process event, carried on the management report because this ticket has no analytics sink and no database. Keep the cause, CPU seconds, peak RSS, calls served, interrupted attempts, and event.limits. The next ticket would otherwise rebuild the same object.

What does not earn its place:

  • operatingLimits is typed as every OperatingLimitId. Breaker, pool, and Fargate keys type-check. When configRevision is omitted, startup hashes every operating limit, including limits this process does not enforce. Accept the five keys the watchdog reads: probe interval, RSS, process count, aggregate bytes, and idle.
  • replicaId has no caller. exec.ts sets the deployment revision and the task id. The default, supervisor- plus the pid, is enough until a replica id exists.
  • Lifetime residency peaks exist to fill event.limits. Stamp them from the tick. invoke should be able to read the total without writing those peaks.

"fleet" on Executor.implementation is the production refusal. requireProduction accepts only that value. It is not a fleet controller.

Tests that earn their cost: the spinning sibling and its exact report, the 512 MiB leak, the 13th process, the epoch and generation fence, management auth before the body is read, and local rebind without replay. The occupied-port test only checks that listen failure becomes ListenerUnavailable. The memory-pressure test should assert that the smaller idle process is still resident when the larger one is evicted.

Summary

Standards: 2 hard findings, plus judgement calls. Worst: the load fiber turns WorkerdError into transport while the report says load_failed.

Spec: 2 findings. Worst: invoke returns busy at the byte ceiling without evicting an idle process.

@github-actions github-actions Bot added area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area labels Sep 28, 2026
@allisonmahmood

allisonmahmood commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner Author

Fixed in 8238840 and b1e39ba.

Reviewed the conversation comments from Opus, Astra and Grok, plus the Reviews tab APIs. There were no submitted review bodies or inline review comments.

Fixed

  • Sampling and teardown isolation. Linux ESRCH, like ENOENT, means the child vanished. Other sampling failures now reap only the affected resident with metering_failed; they do not permanently stop the supervisor or its siblings. A failed temporary-directory removal is logged after the child is killed and reaped, so it cannot disable the watchdog. Regression coverage exercises a real filesystem permission failure and sibling recovery after an external process exit.
  • Unfinished asynchronous loads. Initialization now expires at the idle limit, 60 seconds by default, even while health probes answer. It releases residency and reports load_failed. The readiness failure is published before the process-death signal to avoid a race that returned the wrong refusal.
  • Invocation admission and attempt lifetime. Invoke evicts idle siblings before returning busy, protects its target from that eviction, and rechecks authorization and generation after asynchronous cleanup. Completed loader refusals clear their attempts and deadlines; uncertain transport failures stay tracked. Scope-shutdown coverage verifies that in-flight attempts reach the process report.
  • Memory-pressure regression. The busy child's measured RSS must exceed the whole configured aggregate ceiling by 256 MiB, so a fall in the test runner's RSS cannot reverse the expected refusal. The first-eviction assertion still distinguishes largest-first from oldest-first. Invoke-time eviction has separate coverage.
  • Contracts and dead code. Load failures use tagged catches and preserve their causes. Callback size errors carry actual/max bytes. Probe intervals at or above six seconds are refused. Options and their configuration hash cover only the five enforced supervisor limits; the unused replica override, public closed promise, Executor implementation marker and unwired production guard are gone. Local construction still refuses production.
  • Clarity and docs. RSS reads no longer mutate lifetime peaks; explicit load/tick/reap points record them. Proxy URL and version-key names are clearer. The deadline grace is a named 1,000 ms constant, independent of query-only limits. Updated binary units, live-resident bind idempotence, rebind generations, HTTP 413, the context map and the local RSS caveat.
  • CI timing. The failing description test launches six real CLI processes; it now uses the existing 30-second multi-process budget. cli-smoke was canceled at its ten-minute job ceiling while still progressing, before its final Preact smoke. Its job budget is now twenty minutes. The full offline run also exposed a Postgres reconnect test's one-off test-clock advance racing the real socket-disconnect event; that real-Postgres scenario now uses the live clock, without changing runtime behavior or increasing its timeout.

Kept as is

  • Actual RSS in local mode. The in-process supervisor shares the local host's memory, including retained bundles and reports. A fixed allowance would undercount real memory and weaken the aggregate bound. Local accounting remains conservative and is documented; production has a dedicated exec process.
  • Private exec entrypoint and Docker dependency. These make the supervisor runnable without host services. The image needs the execution manifest before dependency installation. Added the requested handoff on feat(execution): the fleet on ECS: the image with two entrypoints, the spike deploy and the Fargate acceptance #406 identifying apps/server/src/exec.ts, its compiled command and the current unprivileged-uid limitation.
  • Largest-first assertion. Sustained pressure may legitimately evict both idle processes, so requiring the smaller one to remain would be incorrect in that scenario. Checking the first reported eviction proves ordering; the separate invoke test proves target protection.
  • Occupied-port coverage. This checks a real listener acquisition failure and its host/port diagnostic context, not a mocked forwarding path.
  • Two short test pollers. One returns a stats snapshot, the other a generation-specific report. Kept their direct loops instead of adding a generic polling abstraction or an extra report search solely for deduplication.

Verification

  • Workspace typecheck and lint passed; all 49 execution tests passed.
  • The real production-mode exec entrypoint held 12 responsive unfinished loads, expired them after 60.281 seconds with load_failed, accepted a fresh invocation without restart, and finished with zero child processes.
  • The full offline run passed 111 files and exposed that reconnect fixture race. After the fix, both Postgres wake tests and the cleanup regression passed; Runtime and Execution typechecks and lint passed again.
  • Focused Standards and Spec re-reviews found no remaining issues.
  • CI on 8238840 passed every job except Node 22, where two real CSS publishing scenarios exceeded their default five-second test budget. b1e39ba applies the neighboring build tests’ 30-second budget to that table without changing assertions; all four scenarios, CLI typecheck and lint passed locally.
  • The Postgres reconnect test now uses a live clock because its real socket-disconnect event could arrive after the former single test-clock advance; runtime behavior and the test timeout are unchanged.
  • Latest head b1e39ba: all eight checks passed. CI run: Node 22 and 24 full suites, lint, CLI smoke, Clerk live, Postgres concurrency and dependency review; PR labels also passed. GitHub reports no configured required checks for this stacked branch; every reported check is green.
  • Rechecked conversation comments, review bodies and inline comments after the final push: no new findings. GitHub reports MERGEABLE and CLEAN against tier2/395-execution-engine. PR left open, not merged.

Surface audit for the review fixes: wire/API contract, executor consumers, limits and generated skill mirrors, product/domain/development docs, and tests applied. CLI flags/JSON, dev-runner/seed, migrations, company resources, served UI and package layout are unchanged. Load expiry/rebind and scope-shutdown scenarios cover the reverse lifecycle.

Add residency eviction, runaway termination, generation fencing and process reports. Expose private management and a supervised local Executor while keeping production admission closed.

Closes #396
Bound responsive unfinished loads, isolate sampling and cleanup failures, and evict idle siblings before invocation refusal. Release completed refused attempts, preserve shutdown reports, and remove unwired executor guards.

Stabilize real memory-pressure and reconnect scenarios and give multi-process CLI checks their existing integration-test budget.
@allisonmahmood
allisonmahmood merged commit 5ce0399 into main Oct 1, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/396-supervisor branch October 1, 2026 02:25
allisonmahmood added a commit that referenced this pull request Oct 18, 2026
…g ECS twice (#768)

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 #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.

---------

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:ci CI, shared testing infrastructure, development scripts and tooling 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.

feat(execution): the supervisor and the local executor: a process per loaded version, residency, the watchdog, the fence, the management listener

1 participant