Skip to content

Tier 2: hosted server code, live sync and the execution service #384

Closed
32 of 32 issues completed
Closed

Description

@allisonmahmood

Charted on the Tier 2 map (2026-09-19 to 2026-09-28). This issue is the tier 2 spec. It carries every shape decision the build implements, assembled from the map's closed tickets, which hold the reasoning. The resolutions add up to about three times what an issue body holds, so each section below states the effective contract: the decision as it stands after every later ticket amended it, with the resolution linked for the detail and the evidence. Where a section and its linked resolution disagree, this issue wins and §2 says why. The build runs from the sub-issues at the end, one PR and one agent session each, and main stays green throughout. Mid-build decisions go back to the map as grilling tickets, not into PR threads.

Problem Statement

A tier 1 patch acts as the viewer in a sandboxed frame. Any viewer who can open it can write any row the page can write, straight from devtools. So "only managers approve deals" is advisory, a change that touches three rows can stop halfway, and anything that combines a company's data before a person sees it runs in that person's browser. Two people with a patch open don't see each other's saves until they reload. There is no server code a company can trust, no transaction, no live view, and nowhere to put work that should never reach the browser. A CRM-class tool cannot be built honestly on tier 1.

Solution

A tier 2 patch has a server/ directory of handlers: queries that read, mutations that write inside one transaction, and actions that reach outside the transactional domain. Its page talks only to those handlers, through a generated client. Patchy runs the handler code on its own machines while someone has the patch open. Each company gets its own Fargate task, taken from a pool of spares, and each loaded patch version runs in its own workerd process with no credential and no network. Every call reaches Patchy through a callback gateway: as the patch for its own tables and stores, and as the viewer for company data. Every write is logged for admins. Queries can be subscribed, and every open document holds one stream that keeps it in sync, tells it when a new version is served, and says when its access is gone. Tier 1 gets the same subscriptions and stream, moves to Preact with compat semantics, and gains shared file stores and the member directory. patchy init --tier 2 lays down the repo, patchy dev runs the production engine locally over PGlite with two viewers, and patchy publish uploads two artifacts that the server re-derives before it serves either. Limits come from one registry, wide events go to CloudWatch and PostHog, and metering is recorded from the first call. The build ends with the platform's first deploy to AWS.

User Stories

  1. As an agent building a tool, I want:

    • init --tier 2, handlers named by file and export, and a server/ rename that breaks the page at compile time;
    • atomic mutations with a safe retry(), and write_conflict told apart from busy;
    • useQuery in sync without polling;
    • the SDK's limits and refusals stated in the skills;
    • CSV, downloads, members and shared stores provided, never hand-rolled.

    Then the tool works hosted the first time.

  2. As an agent proving a tool, I want patchy dev on the production engine with a colleague on a second URL, so that two-viewer flows fail locally.

  3. As a viewer, I want colleagues' saves live in my tab, a plain notice while data may be stale or tools are starting, and publishes that never interrupt my typing.

  4. As a company, I want:

    • no other company's code in our tools' kernel;
    • no credential, and no path out except through Patchy as the viewer;
    • every write attributed;
    • a runaway patch killed without taking our other tools' calls with it.
  5. As an owner or admin, I want to read a patch's invocations and ctx.log lines.

  6. As Patchy, I want:

    • bound seconds, database time and calls metered from the first call;
    • one limits registry with overrides;
    • the fleet's claims measured on real Fargate before it merges.

Implementation Decisions

Settled on the map's tickets; each build ticket names the sections and resolutions it implements. Where no ticket decided a name, value or boundary, it is decided here and listed under Further Notes.

1. The shape in one paragraph

Tier 2 is execution while a viewer has the patch open. Handlers are request-scoped. There is no instance per patch, no supported durable state or background execution in patch code (guest memory may survive between calls and is never authoritative), and Patchy owns presence and sync (destination). Execution with no viewer, including inbound routes, webhooks and schedules, is tier 3. The client of a tier 2 version is server-only: it has me, the route bridge, authorised file handles, staged uploads and generated-file download, and nothing else (contract, composition, SDK). Handler code runs in a credential-free execution service (workerd with the Worker Loader, one Fargate task per company from a global pool, one process per loaded version) and reaches Patchy through callbacks under a per-invocation capability (execution service). A mutation is one SERIALIZABLE company transaction owned by the host (transactions, init prototype). A subscription is a query re-run as its subscriber when a resource it read changes, delivered over one stream per document (reactive queries). The patch identity adds no entitlements in v1: own primitives are reached as the patch, company data as the viewer (identity). A patch imports only the Patchy SDK; everything else is company code (SDK). Dev runs the production engine (repo and dev loop). Every number is a starting value from one registry (limits).

2. What superseded what

Build from the right-hand column. Resolutions are linked for reasoning; where they conflict, the later one wins.

Earlier wording Effective now Decided on
A per-release allowlist of audited packages; direct preact/@preact/signals pins; jsxImportSource: "preact" patchy is the only import root and bundles exact Preact 10.29.8, @preact/signals 2.11.2 and their signals-core; managed pins are patchy, plus workerd on tier 2; jsxImportSource: "patchy/preact"; Zag.js and TanStack are not listed SDK, reference CRM
ctx.run runs any handler of the patch sibling queries and mutations only, enforced host-side, with parent/child admission accounting init prototype
Two shell exceptions (me, handles) me, the route bridge, handles, staged uploads and generated-file download composition, SDK
The superseded lifecycle frame the served frame carries the served version's id and tier; superseded stays the glossary state identity
Unsharing a source permanently ends the subscription a refusal inside a handler keeps the subscription and its dependencies for a reshare; loss of document-level authority ends it reference CRM
busy at once when the company pool is full (ADR-0009) a bounded wait: at most 32 waiters, at most 1 s inside the call's deadline, then busy with retryAfter; both tiers limits
An empty-pool wait of "one cold start" 40 s behind the shell's starting state, then busy limits
Query deadline "shorter than the mutation's"; action deadline "longer" 3 s, 5 s, 60 s, killed one second later limits
Two wake points one wake rule: the transaction owner announces the resources it touched after commit init prototype
In-process wakes until there is more than one host replica NOTIFY on the platform database from day one, because every rollout runs two replicas (§8) this spec
A new server/ file needs refresh and a dev restart dev re-reads server/ live; refresh alone regenerates the module list and types repo and dev loop
Dev stores two-viewer attribution rows dev writes dev.log lines and no runtime-log rows repo and dev loop
Every invocation metered on its row; queries logged only on ctx.log or failure both hold: quiet query runs meter into exact per-minute rollups (§14) this spec
"Billing reads bound seconds" metering records bound seconds, database-held time and calls; billing decides what is priced limits, this spec
"Readers stay unwatched" retired as a PatchPage leftover; PostHog gets viewer ids limits
A shipped example CRM none ships; the four runs on PR #381 are internal reference reference CRM

3. Packages and services

One package is born and nine gain code. Each owns its migrations and its HttpApi group; apps/server is wiring plus its two entrypoints.

package gains
execution (born) The credential-free side, as separate entrypoints: engine (the loader Worker, the guest entry and the guest protocol's implementation), supervisor (§5's process, residency, watchdog and fence rules, the management listener, process reports), inspection (a bundle loaded in a throwaway process to derive descriptors, with no company binding and no Runtime), local (the supervised executor for dev and tests, no pool) and fleet (§5's controller over the platform database, binding history, process metering, the breaker, the ECS client). The exec task never imports platform persistence, and patchy/dev never bundles fleet or the AWS SDK. The package implements Runtime's ports and shares Runtime's glossary; it is not a context of its own.
runtime The whole host-side path on both tiers, reused by patchy dev: admission, the capability, the callback gateway, the host-owned transaction and settlement, mutation keys, invocation rows, rollups and metering, wakes and their cross-host delivery, subscriptions, the stream and lifecycle frames. It declares an Executor tag that only executes admitted work (bind a bundle and invoke; no pool, release or stop) beside LoadedVersions, and never imports execution.
api Every new wire shape, as dependency-safe schemas (Execution owns the guest protocol's implementation and compatibility tests): server.call, the stream and its frames, handler descriptors and the server artifact in the manifest, the guest protocol, members.*, shared-store, handle, stage and download operations, and every new refusal code (§15).
primitives Per-resource revisions advanced inside each write's own transaction; shared file stores; handle minting and redemption; staged uploads and adoption; the files/<patchId>/<objectId> key layout and its sweep; the member directory's members.* handlers and the t.member() write check through a MemberDirectory port it declares.
companies Domain only: directory reads, the candidate check, the directory revision committed with every membership and profile change, and its after-commit change fact. It imports no Runtime and no Primitives; the host adapts it to Primitives' MemberDirectory port.
company-database The bounded connection wait, per-company pool overrides, the Neon provisioning amendments, and idempotent inventory upgrades (§16). The company admission rate is Runtime's, since it counts operations that never take a connection.
limits The registry: every limit's id, kind, default, unit, scope, measure, refusal and overridability. It also owns overrides with history, the generated docs/limits.md, and the generated skill table.
analytics Wide events: the Effect-scoped accumulator emitted in a finalizer, stdout and PostHog sinks, the five emitters' schemas.
serving The shell's stream client over the document-bound port, the reconnecting, new-version, reload-to-keep-saving and starting-your-tools elements, the download action, handle redemption and staging through the broker.
patchy patchy/server (the builders, HandlerError, bound per-kind Context types), patchy/preact (compat loaded once, useQuery, useFileUrl, the JSX runtime entries), patchy/csv, the bundled Preact, the server build and import checks, init --tier 2, tier changes in refresh, add shared-store, add members, and dev on the production engine.
sdk Generation of the tier 2 client and patchy/_generated/server.ts, the "What the SDK gives you" section, the content-digest release URL, the patchy-server, patchy-preact, patchy-members and shared-store skills.
content-store An S3 layer for Neon Object Storage (path-style, branch-scoped), the production store.
portal The per-patch log view.

Direction: execution → runtime, api (implements Executor; fleet also → sql, limits, analytics); runtime → auth, limits, analytics, sql, api; primitives → company-database, runtime, content-store; patchy/dev → runtime, execution/local, execution/inspection, primitives, integrations, company-database; patches → execution/inspection (re-derivation at publish). Auth → Companies stays as today; Companies gains no new dependency. The host wires Executor from execution/fleet in production and execution/local in dev and tests, and adapts Companies to MemberDirectory (dev supplies the two mount identities). A production server refuses to start tier 2 admission on the local executor.

4. The contract

The contract decision is the text; the effective points:

  • Handlers are exports of server/*.ts built with query, mutation and action, named <file>.<export>, one level deep. A non-handler export fails the build. Descriptors { kind, args, result, errors? } go in the manifest under handlers; the server re-derives them (§13).
  • t grows object, array, enum, nullable, row("<table>") and fileHandle() (results only), plus upload() (action arguments only) and member() (columns only, §11). On an argument field optional means the key may be omitted and t.nullable means null; on a column optional means nullable. Results are readonly. Args are validated before the handler (a refusal) and results after it (handler_failed).
  • The context object, narrowed per kind by bound per-kind Context types and refused per kind at the gateway: ctx.viewer (never null); ctx.tables (read-only in a query); ctx.shared (queries and actions); ctx.files (list and stat in a query, put/get/delete in an action, a mutation may write a row that names a file); ctx.connections (actions only); ctx.members when declared (all kinds); ctx.log (32 KiB per invocation); ctx.run.<module>.<handler> (actions only, sibling queries and mutations, typed, each nested mutation its own transaction under the parent's remaining deadline).
  • Errors. HandlerError(code, details?) with an optional declared errors list, enforced host-side (an undeclared code is handler_failed). A handler error rides a successful wire reply as { ok: false, source: "handler", code, details } and gets its own handler_error outcome. Patchy's refusals are { ok: false, source: "patchy", code, ... }. Refusals cross the loopback as data, never as throws.
  • Mutation keys. The shell's core client mints each key as <ms>-<128 random bits, base64url>, with the time on the server's clock as learned from the stream's hello. The key is stored with patch, handler, version, initiating viewer and an argument fingerprint. A key older than 24 h is refused as expired whether or not a row survives; a key more than 5 min in the future is refused; inside the window, a key with no committed outcome visible is run (an overlapping attempt resolves by §5's race rule). A nested mutation an action runs gets a key the host mints, used to resolve an uncertain commit, never to replay the parent action. A mutation with no callbacks still opens a transaction to write its key and result.
  • The client. patchy.server.<module>.<handler>(args) for every kind, .subscribe(args, onSnapshot) on queries, and useQuery(handler, args) returning { status, data, error, loading }, keeping data through a stream error. Handler types come by type-only import of the server modules. A lost query reply is retried once. Every mutation call carries a fresh mutation key. Its unknown_outcome carries retry(), which re-sends the same key and arguments (lifecycle point 4). Actions are never replayed. A mutation may execute up to three times inside one call, and aborted attempts leave no writes.
  • What a tier 2 page never gets: name-based direct primitive operations (tables.*, files.* by name, shared.*, connections, members.*), whatever tier the patch serves. The shell capabilities stay: me, the route bridge, files.url/download by handle, files.stage/discard and generated-file download. A tier 2 page calling one is refused at the runtime, not only absent from its types (reference CRM).

5. The execution service and hosting

The execution service decision is the ADR in decision form, with its addenda from the init prototype and the reference CRM. The effective points:

  • workerd 1.x (pinned by the release) with the Worker Loader; one dynamically loaded Worker per company/patch@version; globalOutbound bound to a refusing loopback; the guest holds an RPC stub naming its invocation, never a token.
  • One Fargate task per company, us-east-1, 0.5 vCPU / 2 GB, taken from a global pool of spares (max(2, wake rate over 15 min × measured cold start) under a fleet budget). It is bound on first open and stopped on release, never reused. The empty-pool wait is 40 s behind the shell's "starting your tools" state, then busy. Release happens after 30 minutes with zero connected tier 2 documents and nothing in flight (retry attempts, nested calls after departure and transaction cleanup all count), with admissions fenced first.
  • One workerd process per loaded version inside the task. At most 12 processes and 1.5 GB aggregate (supervisor, bundles and overlapping versions included), enforced continuously; past it the idle process goes first, busy if none is idle. Processes are reaped after 60 s idle and killed at 512 MB RSS. The kill comes at the caller deadline plus 1 s or after a 6 s event-loop stall (probe every 250 ms). The company task is the security boundary; the process is availability isolation and is never described as security.
  • The controller is host code over the platform database, not a service: atomic bind claims with company-level uniqueness enforced by the database, an idempotent retry by task identity and binding epoch, the stopping state entered under the owner check in one statement before any stop, and one replica's housekeeping lease for replenishment, idle release, orphan reconciliation and superseded-deployment replacement. The binding epoch, the process generation, the housekeeping lease and the deployment revision stay four distinct things. One image with two entrypoints (host, exec); adjacent releases interoperate during a rollout, nothing further apart.
  • Authority separation. The exec management listener (bind, invoke, stop, stats) is private to the host security group and takes the deployment secret, current or previous during a rollout. The host callback listener is private to the exec security group and takes only invocation capabilities. Nothing administrative is public. Fleet operations are controller operations run as code, never row edits.
  • The eight ADR contracts hold as written: deadline versus termination (three guarantees), cross-host mutation-key races (23505 at insert or commit, the loser resolves the winner's outcome, unrelated uniqueness violations never deduplicate), the atomic stopping state, administrative authority separate from the capability, the Neon connection lifecycle (retained connections are disposable; a resolved COMMIT on an aborted transaction is a rollback), attempt identity at the stub, callback completion (serialised on the transaction, pending jobs refused before finalisation), and rollouts fence then drain.
  • Settlement never depends on the caller. At the deadline the host fences effects and begins cancellation whether or not the client is still connected, then settles within the cleanup bound (tier2.settlement.cleanup, 5 s after the deadline). A connection whose cancellation or commit outcome is unresolved at that bound is destroyed, never returned to the pool, and the invocation stays unknown_outcome until reconciliation by its mutation key establishes the outcome; it is never reported as handler_timeout. The reference CRM's dropped-client leak (idle in transaction past both deadlines, filling the four slots) is an acceptance blocker for the mutations ticket.
  • The capability is an opaque per-attempt reference minted by the host and resolvable only by the issuing replica. It names invocation, attempt, company, patch, version, initiating viewer, kind, deadline and process generation. It ends on return, deadline, 40001 supersession or process kill, and a replay is refused from a 5 min tombstone. Callbacks go to the private address of the host that opened the transaction. File bytes ride the callback body under 20 MiB. The host pushes bundles on bundle_required or a generation change; the task never pulls from storage.
  • The promise, appended to ADR-0010 and docs/product.md: A tier 2 patch's server code runs on Patchy's machines, never on yours. It holds no login and no credential and has no path to the internet: everything it does goes through Patchy, as you, while you have the patch open. It reaches outside systems only through your company's integrations, and every write is logged for your company's admins.
  • Neon (ADR-0009 amendments from the spike): GRANT company_x TO patchy_admin WITH SET TRUE, INHERIT FALSE after each CREATE ROLE, DROP DATABASE under SET ROLE company_x, protocol-level cancellation instead of pg_cancel_backend, and suspend disabled on the production compute.
  • Measured numbers are on the spike and the init prototype; §14's bounds are the ones enforced.

6. Transactions and settlement

From one transaction per mutation and the init prototype as built on PR #380 (Transaction.ts):

  • One company transaction per mutation, owned by the host in Runtime: one fiber per invocation, callbacks as jobs on it, savepoints under the table handlers, the invocation's connection reused by its callbacks so four slots carry four invocations. It opens on the first callback (or at result commit for a mutation with none), runs at SERIALIZABLE, and commits only after the validated result.
  • On 40001 the whole handler is re-invoked, up to three attempts, abort-only after any 40001. Exhaustion is write_conflict (never committed, safe to retry). An absolute deadline covers acquisition and settlement (statement_timeout is per statement). Each attempt's transaction timeout is the remaining budget, never a fresh 5 s.
  • A driver-acknowledged commit phase: a known non-40001 commit rejection is a rollback. handler_timeout is reported only on confirmed non-commit; unknown_outcome only while the commit outcome is unresolved.
  • Mutation keys (format and expiry in §4): the key, its binding and the result (≤ 64 KiB) are written inside the transaction, into a company-database table swept after 24 h. A repeat returns the stored result; a mismatched binding or fingerprint, another principal or an expired key is refused, never run fresh.
  • A query run is one read-only REPEATABLE READ transaction holding one connection, its commit watermark captured before the read, cancelled at 3 s.
  • Actions have no transaction; each nested mutation owns its own.

7. Identity, admission and attribution

The identity decision is the text; the effective points:

  • Invocation admission, once per call: session live, viewer may open the patch, the patch live, the document's version eligible (retained, not revoked), scope not public, not paused, and the per-kind and company admission limits. Callback authorisation, per callback in the gateway: own primitives inherit admission, while shared tables, shared stores, connections and members re-check live on every callback. Nested handlers inherit the parent's admission and never widen it.
  • The served-version gate: while the patch is tier 2, a document whose loaded version is below tier 2 gets me and nothing else; every other direct operation is server_required. Server functions are admitted by the loaded version's eligibility, direct operations by the patch tier, the tier of the served version. Rollback to a tier 1 version reopens direct operations for tier 1 documents, never for tier 2 pages (§4).
  • Public tier 2 is refused: tier2_not_public on sharing a patch publicly while it serves tier 2, and on publishing tier 2 to a public patch without --share company. The runtime also refuses any server.call from a public-scope document.
  • Attribution. Operation rows stay, one per own-primitive mutation and connection call, each with its own correlation id and pre-execution write, plus invocation_id. Each invocation is a row: handler, kind, initiating viewer, patch, version, parent link, outcome, timing, metering, ctx.log lines. Every row carries its effective principal (patch or the viewer's id), so user_id becomes nullable. Mutations and actions always get an invocation row; queries (subscription re-runs included) only when they ctx.log or fail. The log is an attribution record, not an access audit. The per-connection recent-calls list reads unchanged.
  • The patch identity is the patch id. Owner deactivation changes nothing for it. Reassignment moves who publishes and who opens the log view. Retire and delete stop new invocations; dispatched work completes under its deadline.

8. Sync: revisions, wakes, subscriptions, the stream

The reactive queries decision is the text, with the prototype's fences (reactive prototype); the effective points:

  • Revisions are durable, per resource (table, store, the member directory), advanced inside the transaction of every write to it by the resource's owner. That covers row writes, store put and delete, and unshare and delete of a source. The member directory's revision advances in the platform transaction. A shared resource's vector entry also carries its source patch's lifecycle revision, a counter on the patch row advanced by every publish, sharing change and lifecycle act (retire, delete, restore, the portal's included). So every change a consumer depends on leaves durable evidence that reconciliation compares.
  • One wake rule. The transaction owner announces the resource keys it touched after commit; wakes are keys only. Cross-host delivery is NOTIFY on the platform database, one listener connection per host replica, and in-process on the same host. Notifications are hints: a host can commit and die before notifying. So every host also reconciles periodically (an operating limit, 30 s to start) and whenever its listener reconnects. It re-checks the revision vectors of every subscription it holds, and for every connected document its served version, patch state and authority, from durable state. Reconciliation is attempted every interval. Freshness is established only when a subscription reaches its fence, so a missed wake or frame delays a document and never leaves it wrong.
  • Dependencies are traced from the callbacks the host observes, canonicalised to the owner's resource, and replaced after every successful run. A wake arriving mid-run is retained and applied to the new set. Until a successful run replaces it, the set is the previous set plus every resource a failed run attempted, so a source first reached by a failing run still wakes it. A callback refused for access still records its resource as a dependency before returning the refusal, so an initially failing subscription wakes on a reshare.
  • Resync by revision vector. Frames carry { [resourceKey]: revision }. On resume the server re-admits, then answers up-to-date without a re-run when the vector is equal, a fence against the commit watermark. Desired and admitted sets reconcile by ordered deltas: each subscribe/unsubscribe carries the stream generation and a per-generation sequence number, and the server applies them strictly in order. The out-of-order buffer holds at most 64 deltas. A gap still open after 5 s, or an overflow, makes the server send resync_required, and the client answers with its full desired set, which carries its generation and the sequence it covers. Installing it supersedes buffered deltas through that sequence, and an older replacement is refused. A mutation resolves on commit with the revisions it wrote; patches render from the subscription.
  • Failures. Transient failures (busy, rate_limited, source_unavailable, handler_timeout) back off and keep the last value. A permanent failure (handler_failed, a result schema violation, a removed handler) ends the subscription with an error frame and the last value kept. A refusal inside a handler is recoverable (§2). Loss of document authority is a stopping notice.
  • Scheduling. At most 2 of a company's connections run re-runs, and at most 1 re-run per patch at a time (an operating limit, per host replica, overridable); coalesced.
  • The stream is one fetch-streamed SSE per company document, opened at bootstrap on both tiers and carried over the document-bound port. HTTP/2 at ingress is proven by the seven-document check. Hidden documents suspend after 30 s and resync on return; remount grace is ~1 s. The shell shows its reconnecting element after a short delay and clears it only on reconciliation to the fences.
  • Tier 1 subscriptions: list.subscribe and get.subscribe on the tier 1 client, on the same machinery; a get wakes at table grain.
  • Not dependencies: company Postgres reads (subscriptions over them are refused), time and randomness. Member directory reads come from the platform database and are not inside a query's company-database snapshot; the skill says so.

9. Lifecycle

The lifecycle decision is the text; the effective points:

  • Presence is derived: a document is connected while its stream is open; there is no lease, heartbeat or presence row. Departure gates starting, not finishing: a running mutation or action runs to commit or deadline, its reply is dropped, and the log records the true outcome. Nested calls after departure inherit the parent's admission.
  • A document keeps its loaded version until it closes. The served frame (id and tier) drives the shell's non-stopping "a new version is available, reload" element, or "reload to keep saving" when the served tier closes direct operations; it clears when a rollback serves the loaded version again. Revocation is a stopping notice, and every re-admission re-checks eligibility. The timed session-expiry check rides the stream.
  • Starting. A tier 2 document's bootstrap asks the controller to ensure its company is bound. While it binds, the stream sends starting and the shell shows its starting element and holds the frame's server.calls in the broker. On ready they are released. Invocation admission, and every deadline, begins only then. Held calls count against the frame's outstanding and byte bounds. After 40 s without a binding the stream sends start_failed (busy with retryAfter) and held calls are refused busy, never replayed. The shell keeps its starting element with a retry and retries the bind with backoff while the document is open, and a later ready admits new calls. A stream drop while starting keeps held calls held until the reconnected stream reports ready or start_failed. A resumed hidden document may start again.
  • The execution service loads any eligible version on demand; zero connected documents is never evidence a version's artifacts may go.
  • A deployment drain is the normal reconnect (drain addendum): EOF, reconnect, resync, keyed retry(). The deregistration delay is 90 s, above the action deadline, and the host stops admitting once signalled.
  • Named escalation: explicit cancellation between irreversible action steps. Until then the skill says bulk actions take bounded batches.

10. Composition

The composition decision is the text, with the reference CRM's findings; the effective points:

  • Shared file stores are shared whole (files(description, { shared: true })), declared as uses: { kind: "sharedStore", patchId, store, id, revision } by patchy add shared-store <patchId>/<store> --as <alias>. Tier 1 reads them through the broker with patchy.shared.<alias>.list/get/url/download; tier 2 reads them with ctx.shared.<alias>, list and metadata in a query and bytes in an action. Reads and redemptions re-check live. The reverse states match shared tables: omission and rollback never change sharing; unshare, retire and delete refuse without force and list dependants, restore brings consumers back unchanged, a new patch under the old name never rebinds. Store dependants are reported as stores, not in a table field.
  • Authorised file handles ride on every list and stat entry. A handle is bound to viewer, company, consuming patch, loaded version, source store and exact object, is deterministic for that tuple, and is 57 characters with no filename and no clock. Redemption checks the MAC, then the pointer (not_found), then access (access_denied). When a replace and an access loss coincide the answer is not_found. Every redemption is re-authorised live, broker byte-cache hits included. On the page: patchy.files.url(handle) (a frame-local blob URL), patchy.files.download(handle, filename?), and useFileUrl(handle), which drops a stale image on failure. Handle redemptions are not logged.
  • Staged uploads: patchy.files.stage(bytes, { contentType }) returns a single-use Upload bound to viewer, patch and loaded version. t.upload() in action arguments; ctx.files.<store>.put(name, bytes | Upload) adopts it with a pointer write. Object keys become files/<patchId>/<objectId>. An object is swept only when no store references it, adoption cannot race the sweep, and unadopted stages are swept after 1 h. patchy.files.discard(upload) removes a stage early under the same binding. Adoption and discard both take the stage row under lock, so whichever commits first wins, and a consumed or discarded stage answers not_found. Put then mutation is not atomic.
  • Dev: refresh lays down fixtures/shared-<alias>/ (named after the source's store) and dev loads it at start without overwriting. Authority changes are not simulated. To change a shared source locally, the builder edits that fixture directory or its .sql and restarts dev.

11. The member directory

The member directory decision is the text. It is a declared company Primitive (patchy add members, the patchy-members skill, ctx.members, patchy.members on tier 1). Candidates (list, prefix search, pages of 50) are the active users of the company. Resolution (get, getMany ≤ 1,000) covers any user of the company, deactivated users flagged. The directory is live through the directory revision, refused outside the company, and a lower-tier document of a tier 2 patch still gets only me. A t.member() column requires the declaration, remove members is refused while one exists, and on insert or change the write path refuses a non-candidate with invalid_row; unchanged values pass. Eligibility is checked when the write arrives, not at commit, and the skill states that edge. Dev lists the two mount identities.

12. Dependencies and the SDK

The SDK decision is the text. It supersedes every allowlist mention on the map. The SDK has four parts: Core (the client, the contract, Preact with compat semantics and useQuery, me, the route bridge, file downloads, generated-file download), Primitives, Integrations and Helpers (patchy/csv). Anything else is company code. The import check is a build contract, not a security boundary. Allowed imports are graph-specific entry points (page: patchy/preact with its JSX runtimes, patchy/csv, the generated client; server: patchy/server, patchy/csv). import_refused names the package, the importer, the entry points and the rule once. package.json is not checked. The runtime promise has three statuses with a tested server list. The toolchain belongs to the builder as caret ranges, with a range check. refresh announces new capabilities. v1 supports Chromium desktop only. What the SDK doesn't offer yet (PDF, spreadsheets beyond CSV, time-zone arithmetic, phone parsing, component libraries, rich text, charts, HTML sanitisation) is stated as a fact, not a prohibition.

13. The repo, CLI and dev loop

The repo and dev loop decision is the text, and PR #380 is the recipe as built; the effective points:

  • The tree: server/, src/main.tsx and src/App.tsx, patchy/_generated/server.ts, exact managed pins (patchy, and workerd on tier 2 with scripts off), tsconfig jsx: react-jsx, jsxImportSource: "patchy/preact", isolatedModules, verbatimModuleSyntax, oxc.jsx.importSource matching, modulePreload off; debugging support is initialised by the SDK in DEV against its bundled instance, never imported by patch code. Tier 1 gets the same page scaffold; tier 0 is unchanged. AGENTS.md describes the src//server/ split in words that hold on either tier.
  • Tier choice: the global skill picks tier 1 by default and tier 2 for enforced rules, atomic multi-row writes, or server-side work; live sync and sequential steps are not reasons. Changing tier is a config edit plus refresh, both ways; refresh adds or removes the workerd pin, the generated server file and the patchy-server skill.
  • refresh alone writes the managed pins and the generated server module list, and removes stale generated context files. Publish refuses a stale list with stale_generated and a mismatched pin with release_mismatch.
  • Publish builds both artifacts. The server bundle is one closed module with no dynamic imports. The import check runs on both graphs. Page code may import server/ only as types. The server re-derives handlers from the stored bytes by inspection in a throwaway process; a disagreement, a throw at load or a load that doesn't finish is invalid_manifest. A tier 2 version with zero handlers publishes with a warning, and server/ below tier 2 stays tier_mismatch. The manifest records the SDK entry points the import check found. --json gains artifacts.html on every tier, and artifacts.server plus handlers: [{ name, kind }] on tier 2. Stored versions keep the wire they were built for, and for tier 2 wire 1 also fixes the guest protocol and the compatibility date.
  • The release tarball URL carries its content digest.
  • patchy dev runs the loader Worker and pinned workerd with the local runtime as host, over PGlite, as the machine's user and on a second listener (the colleague mount, a fixture non-admin member, both tiers; --json gains colleagueUrl). A server rebuild binds bundle and descriptors as one new binding. Admitted calls (nested ctx.run included) finish on their binding. Open subscriptions re-run on the new one and a run finishing after the swap is discarded. A failed build keeps the last good binding. Contract limits are enforced; production scheduling, contention (PGlite has one connection), serialization conflicts and containment are not, and a spinning handler recovers by health probe. Each call writes one dev.log line (viewer, handler, outcome, ms, then its ctx.log lines, and in dev only a handler_failed message and stack), with the full wide event behind --json.

14. Limits, metering and observability

The limits decision is the text, and its bounds table is authoritative for every number not restated here. The effective points:

  • One registry in packages/limits: contract limits fixed per release and enforced in dev; operating limits as deployment config with per-company overrides set by controller operation and kept with history. Enforcement reads it, docs/limits.md and the patchy-server limits table are generated from it, and a test fails when either is stale. Refusals carry code, scope, limit id, value and retryAfter where safe. Admission is counted per host replica in v1.

  • New refusals: write_conflict, patch_paused (three kills in 10 minutes across a patch's versions pause it for 10 minutes; a new publish clears it; off in dev), limit_exceeded with its limit id.

  • Metering is Postgres, never sampled and never on the logging path:

    • invocation rows carry kind, host elapsed ms, guest ms, db ms (time holding a company connection), callbacks, args and result bytes, attempts and outcome;
    • query rollups: every completed query run without an invocation row, a client's retry counted as its own run, adds one increment to its row (company, patch, version, handler, the UTC minute the run started). The row counts runs, re-runs, failures, guest ms, db ms, callbacks, and args and result bytes. The increment and the run's id commit together in one platform-database transaction (the id deduplicated, ids pruned after an hour), issued by the run's settlement and never by the wide-event finalizer, and retried with the same id after an ambiguous failure, so a run is counted exactly once. A run counts when it settles; a host that dies after replying but before settling loses those runs, and its binding event records the crash;
    • process rows record CPU seconds and peak RSS on reap or kill, sampled every watchdog tick;
    • binding history yields bound seconds per company, reconciled from ECS stop times by the housekeeping lease.

    Elapsed time is inclusive and never summed over a tree; additive metrics are. CPU is attributed to a patch, never to an invocation.

  • Wide events, one per hop from five emitters: request (host; runtime routes in this build), re-run, stream, process (supervisor, including kills) and binding (controller). Each carries identity, trace, parent, replica and deployment revision, plus company, patch, version, viewer, handler, kind, tier, task and generation where attributable, and peak usage against each applicable limit with its registry id and config revision. Events are built on an Effect-scoped accumulator, emitted in a finalizer, delivered best-effort to stdout (CloudWatch) and PostHog, and unsampled. patchy dev prints them compactly. The rest of the server moves on #383, outside this spec.

  • The publish event carries the tier, SDK entry points, declared primitives and integrations, handler counts by kind and bundle sizes.

15. The wire

Everything below lives in packages/api, the server, the CLI's --json, and docs/API.md, and the shell validates runtime operations with the same schemas.

  • Runtime operations: server.call { handler, args, mutationKey? } (one operation for all kinds, queries included); members.list, .search, .get, .getMany; tier 1 shared.<alias> store reads; list.subscribe and get.subscribe and query subscriptions as stream requests; handle redemption; files.stage and files.discard. Generated-file download is shell-local and never reaches the server.
  • The stream: GET fetch-streamed SSE per document. Frames: snapshot (subscription id, per-query revision, result, revision vector), up-to-date (id, vector), admitted (last applied sequence), resync_required, error (id, permanent, and the structured error union: source, code, details, limit fields), hello at open (generation, serverTime), and the lifecycle frames served (version id, tier), revoked, session_expired, starting, ready and start_failed. Requests subscribe/unsubscribe carry the generation and sequence; a full desired set answers resync_required.
  • Publish: the server artifact beside the HTML (sha256, bytes), handlers and sdkImports in the manifest, force as today; response artifacts and handlers.
  • Codes added: handler_failed, handler_timeout, write_conflict, patch_paused, server_required, tier2_not_public, limit_exceeded, invalid_row (member check), busy (now with retryAfter, scope and limit id); unknown_outcome gains the retry contract; import_refused (local, exit 1) and invalid_manifest (exit 1 local, 2 rejected) under ADR-0004.
  • Private, not public API: the guest protocol (wire 1) and the management protocol live in packages/api as schemas the exec and host share, never mounted on the public HttpApi.

16. Persistence and migrations

Platform migrations are named symbolically here and take the next id when they merge, spread into all three migrator call sites (apps/server, scripts/dev, the vitest template), with ADR-0003's ledger and the migration list in CLAUDE.md updated.

  • runtime_invocations (Runtime): runtime_calls.user_id nullable, plus effective_principal, invocation_id and the handler_error outcome; a runtime_invocations table (handler, kind, initiating viewer, patch, version, parent, outcome, timing, metering with db_ms, log lines); a runtime_query_rollups table keyed by company, patch, version, handler and minute, with its applied-run ids.
  • execution_fleet (Execution): tasks (identity, deployment revision, state), bindings (company, task, binding epoch, state including stopping, one admission-serving binding per company as a unique partial index), binding history, the housekeeping lease, process metering rows, breaker kills.
  • limits_overrides (Limits): overrides with history (company, limit id, old and new value, who, from when) and the config revision.
  • companies_directory (Companies): the directory revision per company.
  • patches_lifecycle_revision (Patches): the lifecycle revision counter on the patch row.
  • Company databases: the inventory schema gains resource revisions, mutation keys, staged objects and adoption state, and the new object key layout. Changes to existing structures are idempotent upgrades (ADD COLUMN IF NOT EXISTS and the like) run at database init. Each is tested against an already-initialised database, not only a fresh one. Nothing is deployed, so no data migrates, but retained dev and acceptance databases must upgrade. A versioned per-company migration mechanism is a named deferral until after first deploy.

17. First-party UI

Six Patchy-drawn surfaces, designed together by one HITL ticket at the front of the build: static mocks published through PatchPage and Allison's pick, composed from the shared component set under the ui-consistency spec. The six are the delayed reconnecting element, "a new version is available, reload", "reload to keep saving", the "starting your tools" wait, the shell's download action (filename and size), and the per-patch log view (owners for their own patches, admins for every patch: the invocation tree, effective principals, outcomes, ctx.log lines). The tickets that render them wait on that pick; nothing else does. No continuously repainting animation.

18. Deploy

Tier 2's fleet ticket proves itself on the spike account before it merges, with the image, its two entrypoints and a scripted, repeatable deploy there (§ Testing). The last tickets take the whole platform live after everything else has merged:

  • the Neon Object Storage content store (buildable any time);
  • production infrastructure as code in AWS CDK (TypeScript), with the VPC, ALB with HTTP/2 and a real certificate, a host ECS service and an exec task definition (never a desired-count service; the controller owns every exec task), ECR, the security-group pair, secrets and a CI deploy on Allison's trigger, all written and not applied;
  • the first deploy, HITL: a guided checklist for the production Clerk instance, the domain and DNS, the production Neon project with suspend off, secrets, the deploy itself and the live check.

19. ADRs, docs, skills and glossaries

Each ADR is written or amended by the ticket whose behaviour it records; the docs pass reconciles, it writes nothing for the first time.

  • Writes ADR-0012, Handler code runs in a credential-free execution service, with the engine ticket: engine and unit, the seven decisions and eight contracts, the callback path and what the task holds, the closed managed path, and the promise. The supervisor, mutation, fleet and deploy tickets amend it as they land.
  • Amends ADR-0009 (Neon grants, bounded wait, per-company overrides, per-replica counting) with the company-database ticket; ADR-0010 (the stream over the port, the shell's elements, the tier 2 promise and server-only client) with the stream and tier 2 publish tickets; ADR-0011 (Preact bundled in patchy, the content-digest URL, stored versions keep the guest protocol) with the packaging and engine tickets; ADR-0004 (every new code, command and --json field) with each CLI ticket; ADR-0003 (each migration).
  • docs/product.md: § Tier 2 rewritten from proposed to built, with the promise; § What a patch is made of (the SDK paragraph); § Building a patch (tier choice, init, dev, publish); § Declaring and changing a tier; § Primitives (shared stores, handles, uploads, the member directory); the Chromium line; the public tier 2 and admin integration grant proposals marked deferred; § Tier 3 stated plainly as the next line. Each ticket turns its paragraph from decided to built.
  • Glossaries: the terms drafted on each resolution land in their owning CONTEXT.md: contract, reactive queries, lifecycle, identity (Patch identity moves from Serving, Effective principal replaces Acting identity, Initiating viewer replaces Principal) and execution service into Runtime, whose glossary packages/execution shares, with Inspection added; composition and member directory into Primitives; repo and dev loop, SDK and the contract's Compat semantics into Publishing; limits into Limits, Paused into Runtime and Wide event into Analytics, with "readers stay unwatched" removed. CONTEXT-MAP.md adds packages/execution to Runtime and its relationships.
  • Skills. The global patchy skill gets init --tier 2 and the tier choice, and skills-lock.json is refreshed by hand. Project skills: patchy-server (the contract, the kinds, the generated limits table, write_conflict versus busy, the stall rule, the retry contract, the three-attempt rule, the readonly results and optional facts, bulk actions in batches, the log is not an audit), patchy-preact (compat semantics and what compat doesn't emulate), patchy-members, a shared-stores sibling of patchy-shared-tables, and patchy-loop (moving tiers, "What the SDK gives you", talk through edge cases with the person first, presence is Patchy's, render from the subscription). The reference CRM's fixes: which tier the transactions line in patchy-tables applies to; "stores are not shareable" removed; a bigint-safe finance aggregate; the import.meta.env.DEV comment for patchy dev; a ref's index named; helpers get a directory, with the warning that server imports leak into the page bundle; --name marked file-only; both concurrency limits stated; the file cut-off line ("to cut off a file when a record narrows, re-put or delete it; handles already selected keep redeeming until then"). The repo-internal patchy-dev-loop skill gets containment and the colleague mount on both tiers. No skill says "like Convex" or ships an example CRM.
  • docs/DEVELOPMENT.md (workerd, the local executor, the spike deploy), docs/API.md, packages/patchy/README.md, docs/limits.md (generated), README.md's layout.

Testing Decisions

A good test asserts what a caller sees: the reply, the rows a transaction left, the frames a document received, the document and exit code a command produced. It never asserts the SQL or mocks Postgres.

  • Seams. it.layer over the migrated template for transactions, keys, revisions, the controller and rollups; HttpApiTest.groups for routes; NodeHttpServer.layerTest for the stream, the callback gateway and handle redemption; the local executor with the real workerd for handler behaviour; Playwright for the shell's elements, two-browser sync, handles and staging; the packed e2e for the agent contract. Faults come through alternate layers: an executor that loses a reply after commit, kills a process mid-transaction, or answers bundle_required; a listener that drops NOTIFY; a content store that fails after the bytes; a client that disconnects mid-call.
  • Invariants on real Postgres (postgres-concurrency): eight concurrent increments total eight; write-then-throw leaves zero rows; 40001 exhaustion is write_conflict; one key commits once across two hosts, with 23505 at insert and at commit both resolved to the winner; a dropped client's invocation is fenced at its deadline and settles within the bounded cleanup, freeing its connection; two binds for one company leave one admission-serving binding; a stop racing an adoption never crosses the stopping state; a wake published on one host reaches a subscriber on another, and a dropped listener recovers by revision check.

Acceptance ownership. Each item has one owning ticket, never the e2e:

Acceptance Owner
One preact, @preact/signals and signals-core in a clean install; JSX types through patchy/preact packaging
Signals, hooks, compat components and useQuery update together in one installed runtime, in dev with Vite optimisation on and in the published artifact tier 2 query subscriptions
Seven documents over HTTP/2 at ingress stream
Source publish, retire, delete, restore and unshare wake consumers; portal acts included revisions and wakes
The dropped-client leak settled in all three kinds, including when cancellation or the database connection fails mutations
Cross-host mutation-key races mutations
TLS verify-full ctx.connections with a non-superuser role; handlers read shared-table and connection fixtures in dev; the dev log attributes each call dev on the production engine
Management isolation, rollout interoperability, a 90 s drain, and two spinning processes on half a vCPU before the spec claims siblings keep their speed fleet on ECS
A fresh agent builds the reference CRM journey on main from the skills alone: discover, declare a shared table and store, owned mutations, handles, staging, members, live views across two viewers e2e and acceptance
The tier-picking check: fresh agents build several patches from the global skill and the tier each picks is recorded against the tier-choice wording, for Allison e2e and acceptance

Out of Scope

Everything in the map's Out of scope section, plus: prefix or narrower store sharing, public file URLs and clawing back delivered bytes; explicit action cancellation; row-level dependency tracking; the wire retirement policy; a versioned per-company migration mechanism; a Patchy-staff fleet view (the first thing after v1); browsers other than Chromium desktop. Tier 3 is the next map.

Further Notes

Calls the spec makes on its own (not grilled; amend here if wrong):

  • the package cut in §3, in particular one execution package with separate engine, supervisor, inspection, local and fleet entrypoints, and an Executor tag in Runtime that only executes admitted work;
  • the controller as execution/fleet rather than a package of its own;
  • NOTIFY on the platform database for cross-host wakes from day one, as hints, with periodic and on-reconnect reconciliation of subscriptions and document state;
  • the starting frames and the broker holding calls until ready;
  • the mutation key format and its clock;
  • ordered stream deltas with resync_required;
  • the Companies-to-MemberDirectory adapter in the host, and the admission rate in Runtime;
  • one re-run per patch at a time beside the company's two;
  • the local executor refused for production tier 2 admission;
  • db_ms and the per-minute query rollups (Allison confirmed the shape);
  • symbolic migration names and their tables in §16;
  • idempotent inventory upgrades tested against an initialised database;
  • the stream's frame names and the stream as a GET;
  • server.call carrying mutationKey;
  • invalid_row for the member check;
  • limit_exceeded carrying the limit id;
  • the dev source-change recipe (edit the fixture, restart);
  • store dependants reported as stores;
  • not_found winning over access_denied at redemption;
  • ADR-0012's title;
  • packages/execution sharing Runtime's glossary rather than a context of its own, with Inspection added;
  • the exec entrypoint living in apps/server;
  • the S3 layer on content-store;
  • CDK for production infrastructure (Allison agreed);
  • the design ticket at the front (Allison agreed);
  • the deploy tickets last (Allison agreed).

Facts for the build: the ALB cuts streams before SIGTERM; a fresh-agent prompt must say the design is decided, or the mocks rule derails it; fleet acceptance runs on the spike stack (aws-spike.env, neon-spike.env), never production.

Skills every build session consults: effect-service-conventions and node_modules/effect/AGENTS.md before Effect code; ui-consistency for every rendered surface; patchy-dev-loop to prove a change; Hit every surface before calling a ticket done.

Build order

One sub-issue each, filed ready-for-agent unless marked HITL (ready-for-human). Blocking is wired as native dependencies, the real ones only, so independent tickets run in parallel. The numbering is the recommended order. Filed from Write the tier 2 spec and file the build tickets on 2026-09-28 after two review passes by a second model.

Every ticket states what its merge admits and what stays refused, so main never accepts a promise it cannot enforce:

  • The server refuses tier 2 publish until 17. From then, dev and test instances admit tier 2 on the local executor. A production server admits it only on the fleet executor, which 22 proves.
  • A tier 2 page's direct primitive operations are refused from 13.
  • list.subscribe and get.subscribe are admitted at 10, query subscriptions at 19.
  • Shared stores are refused at publish until 23, and member columns until 26.

Startable on day one: 1, 2, 3, 4, 5 and 7.

  1. The six first-party surfaces (HITL)
  2. Patchy as the only import root
  3. The limits registry
  4. Wide events
  5. The tier 2 contract
  6. Admission and the bounded connection wait, after 3
  7. The Neon Object Storage layer
  8. The Preact scaffold on tier 1, after 2
  9. The stream and lifecycle frames, after 1, 3 and 4
  10. Revisions, wakes and tier 1 subscriptions, after 3 and 9
  11. The engine, inspection and ADR-0012, after 5
  12. The supervisor and the local executor, after 3, 4 and 11
  13. The invocation seam, after 6 and 12
  14. Queries and actions, after 13
  15. Metering and the request event, after 4 and 14
  16. Mutations, after 14
  17. Publish tier 2, after 8, 11 and 16
  18. init --tier 2 and changing tier, after 17
  19. Tier 2 query subscriptions, after 10 and 16
  20. Dev on the production engine, after 10, 18 and 19
  21. The fleet controller, after 1, 9, 12 and 15
  22. The fleet on ECS, after 17 and 21
  23. Shared file stores, after 10 and 14
  24. Authorised file handles, after 19 and 23
  25. Staged uploads, after 24
  26. The member directory, after 10 and 14
  27. patchy/csv and generated-file download, after 1 and 8
  28. The per-patch log view, after 1 and 15
  29. The tier 2 e2e and acceptance, after 20, 22, 25, 26, 27 and 28
  30. The map after tier 2, after 29
  31. Production infrastructure in CDK, after 7, 22 and 30
  32. The first deploy (HITL), after 31

Sub-issues

Sub-issues

32 of 32 Issues completed
Loading 32 sub-issues

Activity

  1. added
    area:server
    area:ci
    area:cli
    area:core
    area:docs
    on Sep 28, 2026
  2. 27 remaining items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:ciarea:cliarea:corearea:docsarea:server

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions