Skip to content

feat(runtime): make server mutations atomic and safe to retry - #432

Merged
allisonmahmood merged 3 commits into
mainfrom
tier2/400-mutations
Oct 1, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
tier2/400-mutations

Conversation

@allisonmahmood

Copy link
Copy Markdown
Owner

Tier 2 handlers could run queries and actions, but mutations had no atomic execution path or safe way to recover a lost reply.

Run mutations in host-owned SERIALIZABLE transactions with bounded conflict retries. Writes, mutation keys, results, and revisions commit together; explicit retry() preserves the key and captured arguments. Nested mutations, disconnected-client cleanup, database-time accounting, and late-commit reconciliation are covered. Includes migration 0012_runtime_mutation_commit_proof and the API, ADR, and skill updates. Tier 2 publishing remains refused.

Stacked on tier2/399-metering; this PR targets that branch and contains only the #400 changes.

Closes #400.

Verification

  • pnpm typecheck and pnpm lint passed.
  • pnpm test: 1,375 tests passed.
  • pnpm test:postgres-concurrency: 24 tests passed, including mutation races and disconnect cleanup.
  • Real HTTP/workerd/Postgres smoke: lost-reply recovery, preserved arguments, fresh keys, and nested mutations.
  • Standards and spec reviews: no remaining findings.

Authored with GPT-6 Astra in the omp harness.

@github-actions github-actions Bot added area:server Touches the server area area:cli Touches the cli area area:docs Touches the docs area area:primitives Patch tables and files 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 769036d077651e41ad21c992e152a87efc2e4d24 against origin/tier2/399-metering at 1177d5f3283802b770d1e9537165f38836e2755b, using git diff origin/tier2/399-metering...HEAD. Spec: #400 and the relevant contracts in #384, including #400's nested-mutation database-time acceptance.

One pass, no subagents. Merge blockers only.

Standards

No merge-blocking method or YAGNI findings. The transaction owner, storage adapter, explicit retry path, and commit reconciliation address the requirements of this issue.

Spec

No merge-blocking intent findings found.

Verification run:

pnpm exec vitest run --config vitest.postgres.config.ts \
  packages/runtime/src/MutationTransaction.postgres.test.ts \
  packages/runtime/src/MutationDisconnect.postgres.test.ts

Both files passed: 17 tests. These exercise real Postgres transaction behavior, key races at insert and commit, rollback, uncertain-commit recovery, dropped callers in all three handler kinds, and nested mutation database-time accounting. I did not rerun the full suite, typecheck, or lint.

Summary: Standards 0 findings, no blocking issue; Spec 0 findings, no blocking issue.

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Opus review

Reviewed origin/tier2/399-metering...769036d against #400, spec #384 §4–§6 and §14–§16, decisions r310/r314/r304, and the effect-service conventions. Three findings, most severe first.

1. A committed mutation can be reported handler_timeout (correctness)

packages/runtime/src/MutationTransaction.ts:169-171 sets committed = true, then runs session.publish, and only then resolves completion. Wakes.publish in production is WakesPostgres.publish, which runs the in-process listeners and a platform-database NOTIFY with no bound (packages/runtime/src/WakesPostgres.ts:63-90). If the deadline fires in that window, settlement interrupts the owner after the commit. The owner exits cleanly, so settled is true, and uncertain is false because the transaction is "committed". Invocation.ts:610 then runs the key lookup through databases.withCompany. If that lookup returns busy or fails, Invocation.ts:633 reports handler_timeout. That breaks the rule "handler_timeout only on confirmed non-commit". A client that trusts it and calls again gets a fresh key and writes twice.

The same ordering holds the company lease through publish, because Effect.scoped at :183 closes only after publish. The slot is therefore held past commit, which contradicts the ADR-0009 text this PR adds. It also delays the reply, which should resolve on commit.

Fix: resolve completion right after the acknowledged COMMIT, then publish after the lease scope closes. Also expose committed on the resource, so that Invocation never reports handler_timeout for an attempt the resource itself saw commit.

2. write_conflict has no limit fields (intent, wire contract)

WriteConflict (packages/runtime/src/MutationTransaction.ts:18) has no limitId, scope or value, so Runtime.toFailure sends a bare { code: "write_conflict", error }. The registry makes write_conflict the refusal of tier2.mutation.attempts (packages/limits/src/registry.ts:310-318). Spec §14 and r304, which #400 cites for write_conflict, say refusals carry code, scope, registry limit id and value. The request wide event also has no tier2.mutation.attempts entry: the peaks list in Invocation.ts leaves it out, and nothing enriches limitId on exhaustion, although it does for deadlines. Build the error from limitRefusal("tier2.mutation.attempts", bounds.mutationAttempts) and add attempts to the peaks.

3. The patchy-server skill says mutations can read file metadata (surface)

packages/sdk/skills/patchy-server/SKILL.md:55-56: "It can inspect file metadata". The gateway refuses files.list and files.stat for mutations (packages/runtime/src/CallbackGateway.ts:82), and MutationContext has no files (packages/patchy/src/server.ts:187). Spec §4 gives list/stat to queries only. An agent following the skill writes code that fails the type check and is refused at runtime. Drop that clause.

Checked with no finding

  • SERIALIZABLE open, remaining-budget timeouts, and savepoints with RELEASE
  • 40001 detection through callback causes, save and COMMIT; abort-only close, whole-handler retry with a fresh attempt, and exhaustion
  • 23505 at INSERT and at deferred COMMIT, resolved to the winner and matched by constraint name; unrelated immediate and deferred violations not deduplicated
  • Classification of rejected, aborted (ROLLBACK tag) and ambiguous (08*, 40003, FATAL) commits
  • Key format, expiry, future skew and binding/fingerprint refusal; callback-free first call on a fresh or retained company database; hourly sweep
  • Client key minting from hello and retry() reuse of key and arguments
  • Nested mutations: host-minted key, parent deadline, parent performEffect, db_ms roll-up
  • Dropped-client tests for all three kinds
  • Migration 0012 in the ledger, ADRs, glossary, API docs and dev-loop docs

@allisonmahmood

Copy link
Copy Markdown
Owner Author

Addressed all three Opus findings in 6249fe5.

Fixed

  1. Committed mutation versus stalled wake: the transaction owner records and resolves the committed reply as soon as COMMIT is acknowledged. It releases the company lease before starting bounded, host-scoped wake delivery. Invocation settlement uses that local commit proof before timeout or key-lookup recovery, so a stalled wake and failed lookup cannot turn known success into handler_timeout.
  2. Conflict refusal and accounting: write_conflict now carries the registry's enforced tier2.mutation.attempts limit, value, and viewer scope. Mutation request events record the attempts peak; exhaustion also sets the root event's limitId.
  3. Incorrect skill guidance: the server skill no longer claims mutations can read file metadata. It directs file metadata reads to queries and file bytes to actions. API documentation and ADR-0012 describe the corrected commit/wake and conflict behavior.

Kept as is

  • Mutation runtime authorization and SDK types still refuse file metadata. They already match the spec; expanding capabilities would fix the documentation by changing the product instead.
  • The four-slot company pool, three-attempt/five-second mutation bounds, Tier-2 deployment refusal, and stacked PR base remain unchanged.
  • Astra reported no blockers, so that review required no additional changes.

Verification

  • Three new real-Postgres regressions failed before the fixes (committed reply became a timeout, fourth company lease was busy, and conflict metadata was missing) and passed afterward.
  • pnpm typecheck: 38 successful tasks.
  • pnpm lint: passed.
  • Full Postgres concurrency suite: 27 tests passed across 3 files.
  • Affected runtime/server unit suites: 29 tests passed across 4 files.
  • Standalone runtime/Postgres smoke: committed result 42 returned while wake delivery stalled; all four company slots were reusable; stored-key lookup returned the same result; wake delivery completed after release.
  • Two independent, scoped read-only reviews of the remediation found no additional issues.

CI harness corrections

The first CI run exposed two test issues, not failures in the new commit/wake regressions:

  • The dropped-action acceptance test observed the parent settlement and immediately asserted that no child invocation remained pending. Those journal writes are independent. It now waits for the whole invocation tree within the existing timeout before asserting no pending rows or held transactions.
  • The unrelated tier-0 noscript CLI test hit Vitest's default five-second timeout while running real config/compiler/Vite subprocesses. It now uses the neighboring real-build tests' 30-second allowance; its assertions and all production limits are unchanged.

Final status

The harness corrections are pushed in 027bf0d. Both affected suites passed locally afterward (all 27 Postgres tests and the focused real CLI test).

All eight configured checks pass on latest head 027bf0dda5385bc24fb3b607c710cce1229fbfc1: test (22), test (24), lint, postgres-concurrency, clerk-live, cli-smoke, dependency-review, and label. Latest CI run. GitHub reports no separately required checks; the PR is MERGEABLE / CLEAN.

Refreshed the conversation comments, Reviews-tab bodies, and inline comments after CI completed. No additional findings or Grok review are present. All reported findings are addressed; none were dismissed as false positives. Not merged.

Base automatically changed from tier2/399-metering to main October 1, 2026 03:19
@allisonmahmood
allisonmahmood merged commit 0067c62 into main Oct 1, 2026
8 checks passed
@allisonmahmood
allisonmahmood deleted the tier2/400-mutations branch October 1, 2026 03:31
allisonmahmood added a commit that referenced this pull request Oct 3, 2026
…y before launch (#503)

Before launch (#416) no database we need to keep exists, yet the
platform record carried 15 migrations, and several tests and code paths
existed only to upgrade databases built by older steps (decision O1 from
the test audit). This squashes each capability into one baseline that
builds exactly today's schema, and deletes the upgrade-only code and
tests with it.

- **One baseline per capability**, ids 1–8 in foreign-key order:
companies, auth, patches, company_database, runtime, integrations,
limits, execution. The names drop `_baseline`, so an old ledger can
never match the new history by name.
- **Faithfulness proof** (run outside the repo, `/tmp/lane-e-proof`):
databases built from main's record and from this record have identical
`pg_dump --schema-only`, identical data apart from the ledger, and an
identical catalog listing (columns, defaults, constraints, indexes,
functions, triggers, grants). That holds for the platform database, a
Postgres company inventory and a PGlite company directory.
- **The ledger guard** (`packages/sql`): `migrate` now refuses a ledger
whose history differs from the record's, up to the lower of the two
highest ids. The Migrator only applies ids above the ledger's highest,
so a pre-squash database would otherwise silently skip the baselines and
every future migration with an id up to 15. Ids above the record's
highest still pass, so an older build can start after a newer one
migrated (the rollback in OPERATIONS.md). The dev runner now writes the
refusal to `dev.log`.
- **Removed upgrade paths:** `Inventory.upgrade` and its calls in both
`ensureReady`s, the mutation-key lookup's missing-table retry (added in
#432 for databases created before mutation keys), and the upgrade-only
tests: `runtime` and `patches` `migrations.test.ts`, the directory
migration block, two inventory-upgrade tests, and an orphan-sweep case
for retained inventories. Docs: DEVELOPMENT.md, `packages/sql` README
and CONTEXT (new **Baseline** term), ADR-0003/0009/0012, product.md,
API.md.

**After this merges:**
- Every existing local dev instance, in every worktree, needs `pnpm dev
reset`, which wipes its local data. An instance that isn't reset refuses
to start and says why in `dev.log`.
- The disposable tier 2 spike database needs recreating before its next
deploy.
- `patchy dev` data in patch repos made by a CLI older than #449 needs
`patchy dev reset`.

Upgrade tests start again with the first migration that has to keep
retained state.

Made by Claude Opus 5.5 via Claude Code

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Touches the cli area area:docs Touches the docs area area:primitives Patch tables and files 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(runtime): mutations: the host-owned SERIALIZABLE transaction, mutation keys and retry(), write_conflict

1 participant