Skip to content

feat(patchy): run dev on the production handler engine - #437

Merged
allisonmahmood merged 7 commits into
mainfrom
tier2/404-dev-engine
Oct 1, 2026
Merged

allisonmahmood merged 7 commits into
mainfrom
tier2/404-dev-engine

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

patchy dev could not exercise the full tier 2 handler loop through the production engine. It now uses the supervised local executor and callback gateway over PGlite and fixtures, with live server rebinding that preserves browser state and in-flight calls.

Subscriptions rerun on the new binding, failed builds keep the last good version, and new server modules become callable without restarting. Both tiers expose a non-admin colleague mount, and local logs attribute calls to their viewer. The docs and skills explain the limits of local execution compared with production.

This PR is stacked on tier2/403-query-subscriptions and targets that branch, not main.

Closes #404. Part of #384.

Verification

  • pnpm typecheck, pnpm lint, and pnpm test passed: 1,422 tests across 130 files.
  • Browser smoke covered both viewers, live subscriptions, retained nested-call bindings, module discovery, failed-build recovery, and source-triggered reload.
  • Real verify-full TLS acceptance passed with a non-superuser role; handlers also read shared-table and connection fixtures.
  • Warm rebinding measured 125–144 ms; the browser displayed the updated subscription at 159 ms.
  • Standards and spec re-reviews found no remaining issues.

Implemented with openai-codex/gpt-6-astra in the omp harness.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:cli Touches the cli area area:docs Touches the docs area area:integrations Company connections and integration implementations size:xl Over 1,000 changed lines; review in multiple passes labels Sep 29, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed fa9110a against origin/tier2/403-query-subscriptions at 6a6649b, using #404 and parent spec #384. One pass, no subagents; merge-blocking findings only.

Standards

No separate merge-blocking method or YAGNI findings.

Spec

[P1] Intent: keep local fixtures out of the production execution-task residency budget

packages/patchy/src/devExecution.ts:68–72 constructs Local.make without a local capacity policy. environment: "development" does not change the supervisor's operating limits. Its aggregate RSS calculation counts the entire Node host, including PGlite workers, plus workerd against the production 1.5 GiB execution-task cap.

This breaks #404's acceptance requirement that “handlers read shared-table and connection fixtures in dev.” The new fixture acceptance test failed during initial binding with busy, limitId: execution.residency.bytes, peak 1647030272, limit 1610612736.

I reproduced the same failure outside Vitest through DevResources.prepare, with an owned table, a shared-table fixture and one connection fixture. The host alone reached 1550843904 bytes; the first resource-free query then returned busy at aggregate 1626898432 bytes. This is not handler load or database contention. Ordinary fixture initialization consumes the executor's budget.

Give the dev composition appropriate residency accounting/policy rather than treating its PGlite/Vite host as a production Fargate execution task. Preserve the fixed handler contract limits and watchdog. Verify a fixture-bearing dev session can start, call handlers and rebind; changing only the test's limit would leave the user path broken.

Verification

  • Focused offline run: 102 passed, 1 failed across 9 files. The failure was devExecution.test.ts's fixture/transaction/viewer acceptance case. TLS, watcher, lifecycle, stream, inspection and client-transport suites passed.
  • Separate real-engine smoke without connection fixtures passed: calls stayed on the old binding while the replacement was staged, switched after installation, and printed viewer-attributed compact logs.
  • The fixture-bearing smoke reproduced the residency refusal outside the test runner. No source changes made.

Summary: Standards 0; Spec 1, worst issue P1: valid fixture-bearing dev execution returns busy under the production residency cap.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Reviewed origin/tier2/403-query-subscriptions...HEAD (3 commits) against #404, spec #384 §13 and decision r301, the "Hit every surface" list and effect-service-conventions. Three blocking findings, most severe first.

1. correctness/security: the loader's closed-module check can now be bypassed (packages/execution/src/loader.ts:97)

This PR replaces the acorn walk with es-module-lexer. A lexer has to guess whether / starts a regex or is division, and it guesses wrong after an unparenthesised function expression. With function(){} / import("cloudflare:sockets") / 1, parse(bundle)[0] returns no imports, so the bundle loads. This is valid JS that runs the import.

I reproduced it against the built loader in real workerd. Inspection.inspect on this bundle succeeds:

let loaded = "none";
const p = function(){} / import("cloudflare:sockets").then((m) => { loaded = typeof m.connect; }) / 1;
export default { async fetch() { /* after 50ms */ return Response.json({ ok: true, handlers: { ["probe." + loaded]: ... } }); } };

It returned {"probe.function": ...}, which means the guest imported cloudflare:sockets and got connect. The old acorn check refuses this bundle. The test at Inspection.test.ts:150 only covers the parenthesised (function() {}) / import(name), and the lexer happens to handle that one.

Why it blocks: this check is the server-side enforcement of the wire 1 closed module. Publish inspection and production bind both go through load(). The CLI's new oxc check in toolchain.ts only protects bundles built by the CLI, not bytes posted to the API. loader.ts:366 also states the invariant this breaks: "closed bundles cannot import socket APIs." #404 did not ask for a loader change either. The change was a speed-up for per-save inspection.

Fix: go back to a real parser in the loader (acorn full walk, as on the base branch). Add the unparenthesised function(){} / import(...) case to the refusal test.

2. method/YAGNI: a new handlers frame in the wire contract for a dev-only race (packages/api/src/runtime.ts:190)

Neither #404 nor §13/§15 asked for a new RuntimeStreamFrame. To support it, the PR also adds:

  • a per-host kinds registry and rebind fan-out in Subscriptions.ts:113-117,646-660
  • lastHandlerKinds bookkeeping on every refresh pass of the hosted RuntimeStream.ts:223-230
  • replay in the shell's serving/src/stream.ts:66,248,396
  • a mutable kinds table in clientTransport.ts:154
  • new text in docs/API.md

Production never sends the frame: executionVersionId is dev-only and nothing in prod calls rebind. So the wire 1 contract and the hosted stream path now carry dead weight for dev.

The frame only matters when a rebind changes handler kinds (a new or renamed handler, or a changed kind) and the page has not already reloaded. The page cannot call a new handler without a src/ edit, and that edit already reloads the shell with fresh handlerKinds (devServer.ts:191). The remaining race has a smaller fix inside dev: in DevExecution.install, bump revision when handlerKinds(descriptors) differs from the previous kinds, so the existing /~dev/build poll reloads the shell. Body-only edits, the case #404's "about 120 ms without dropping an in-flight call" is about, still rebind without a reload. Nothing in @patchy/api or the hosted stream would need to change.

3. method: Invocation takes platform dependencies as constructor arguments (packages/runtime/src/Invocation.ts:209-226,421,754,915-938)

makeWithOptions(options, platform?) takes PlatformBehavior, a plain object whose methods return Effects (actionLimits wrapping OperatingLimits, and settleQuietQuery wrapping QueryRollups). The dev variant leaves it out. It also adds a dev.observe hook, an observed latch and an options.dev !== undefined || branch in settlement.

effect-service-conventions line 36 flags exactly this: implementation dependencies must come from the environment, not factory arguments. It also puts dev branching inside the production invocation path. The idiomatic shape:

  • Dev provides a local OperatingLimits (registry defaults, like StreamLimits.layerLocal) and a no-op quiet-query rollup.
  • The dev.log line comes from the dev InvocationLog layer. devExecution.ts:33 already replaces it with journals. Its begin + finish together are exactly DevSettlement ({ ...begin, ...settled }).

Quiet queries would then need to reach that layer in dev. Making QueryRollups a service with a dev implementation that writes the line does that without an options.dev flag in Invocation.


What checked out, with no blocking issue found:

  • Admitted calls and nested ctx.run keep their binding: the WeakMap bundle lookup is keyed by the admitted manifest, and the parent's bundle/bound are reused.
  • Subscriptions re-read the binding after check, and epoch++ discards runs that cross a swap. Removed handlers and breaking args become permanent invalid_request.
  • Failed builds and inspection refusals keep the last good binding. New-module discovery logs the refresh reminder.
  • The colleague mount runs on tiers 1 and 2 with a distinct origin, is non-admin, is health-checked with the primary, and colleagueUrl appears in --json.
  • dev.log attributes viewer, handler, outcome and ms, plus ctx.log and the guest's message/stack. No runtime-log rows are written.
  • Handlers read shared-table and connection fixtures, and the HandlerTls.test.ts verify-full acceptance uses a non-superuser role.
  • Idle and timed-out processes are reaped by the supervisor and inspection scope.
  • The mirrored surfaces are updated: ADR-0004, README, DEVELOPMENT, the patchy-dev-loop, patchy-server and patchy-loop skills, the global skill with a correct skills-lock.json hash, and the Colleague mount glossary entry.

@allisonmahmood

allisonmahmood commented Sep 29, 2026 •

Copy link
Copy Markdown
Owner Author

Addressed in aa88c7b, dbaaa48, 8ca5a33 and cc98e88.

Fixed

  • Opus 1, guest network capability: every inspected, bound and invoked Worker now gets globalOutbound: null. The fetch-only Outbound entrypoint is gone. The static check remains an early error, not containment. Regressions execute Opus's exact unparenthesized function(){} / import("cloudflare:sockets") / 1 form, observe that the import exposes connect, then prove TCP, fetch and WebSocket attempts cannot reach a real listener. The host control connects and authenticated callback RPC still succeeds.
  • Astra, local residency: Local.make counts only supervised workerd RSS. PGlite, fixtures, Vite and other host allocations no longer consume the executor ceiling. Fleet accounting still includes the host; actual workerd aggregate/per-process limits, process count and watchdog remain enforced. Boundary regressions cover both accounting modes and genuine active-child pressure.
  • CI failures: watcher fixtures now publish complete saves by rename instead of exposing a truncated file between writes. They still assert every distinct build/refusal. The packed CLI contract now includes colleagueUrl and checks that it uses a separate loopback origin.
  • Generated documentation: moved the local-residency note into the limits renderer and regenerated its output. The first follow-up CI run caught this missed source update; both generated-doc checks now pass locally.
  • Node 22 integration deadline: the deletion/cache scenario launches five real CLI processes and exceeded Vitest's five-second default on CI. It now uses the existing 30-second integration budget; all assertions remain intact, and its focused run passed. Node 24 and every other check passed before this test-only adjustment.

The production loader introduced in #395 had the same fetch-only outbound configuration, but its Acorn check rejected this exact import. Opus demonstrated access to connect, not a successful pre-fix TCP connection. There is no evidence here of a successful production network escape. The runtime capability fix applies to production as well as dev, independently of either parser.

Kept, with reasons

  • Opus 2, live handlers frame: cached/dynamic clients can call new handlers or change an existing handler from query to mutation without editing src/. They need updated mutation-key metadata. Reloading for kind changes would discard unsaved browser state; the frame preserves the live-rebind behavior. Existing client and real-browser checks cover this case.
  • Opus 3, private Invocation strategy helper: exported make/layer acquire the platform dependencies from Effect and expose their requirements. The private shared implementation takes deliberate callback strategies, covered by the service conventions' explicit exception. Keeping this split lets dev use the same invocation lifecycle without platform SQL or runtime-log rows; it does not hide an external service dependency. The remediation standards/spec reviews found no remaining blocker.

Verification

  • pnpm typecheck: 38 tasks passed; pnpm lint passed.
  • Focused execution/dev/watcher/client suite: 110 tests across 10 files passed.
  • pnpm test:packed-cli-e2e passed the complete packed CLI, real-server and browser contract.
  • Standalone default-limit dev smoke passed with host RSS 1,579,597,824 bytes: both viewers read shared/connection fixtures, the colleague mutation committed, staged calls kept the old binding, installation switched to the new binding, and fixture reads still worked afterward. Seven calls were attributed to their viewers.
  • All eight checks passed on cc98e88: Node 22, Node 24, packed CLI smoke, live Clerk, Postgres concurrency, lint, dependency review and labeling. CI run.
  • Final feedback sweep found no new conversation findings, submitted review bodies or inline comments. GitHub reports the non-draft PR clean and mergeable against tier2/403-query-subscriptions. Not merged.

@allisonmahmood
allisonmahmood force-pushed the tier2/403-query-subscriptions branch from 6a6649b to 39a7c23 Compare October 1, 2026 03:56
Base automatically changed from tier2/403-query-subscriptions to main October 1, 2026 04:10
Implement issue #404's local engine, atomic server rebinding, colleague mounts, fixture callbacks and viewer-attributed logs. Preserve in-flight bindings and refresh trusted client handler metadata without reloading. Add TLS verify-full acceptance and update the development contracts.
Dispose each inspection Worker with its request, retain actionable build diagnostics, and make the shared subscription registry an explicit dependency. Use an import scanner instead of allocating a full AST during worker loading, and observe distinct watcher transitions in the regression tests.
Use pnpm 11 configuration variables and real archive integrity metadata. Cancel timed-out CLI children before removing their fixtures, and use the existing integration deadline for the cold-install refresh scenario.
Give every inspected and bound Worker null outbound authority, independent of static import detection. Keep trusted callback RPC intact and cover the exact socket-import bypass against real listeners.

Count only supervised workerd RSS in local mode while preserving fleet host-inclusive accounting and genuine child residency enforcement.
Publish complete watcher fixture saves by rename rather than exposing truncated files between writes. Keep checking every distinct build or refusal.

Accept colleagueUrl in the tier 1 dev JSON contract and verify its distinct loopback origin in the packed CLI smoke.
@allisonmahmood
allisonmahmood merged commit 0ae8078 into main Oct 1, 2026
14 of 15 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/404-dev-engine branch October 1, 2026 04:35
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:integrations Company connections and integration implementations 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(patchy): patchy dev on the production engine: live server rebinding, the colleague mount on both tiers, dev.log

1 participant