Mutations
`*.mutation.ts` + `*.mutation.server.ts` pairs — atomic writes with typed schemas and auto-optimistic metadata.
A mutation is the write primitive. Every ctx.store.insert, update, and delete inside one mutation runs in a single transaction. If the executor throws, the transaction rolls back and subscribers never observe a partial write.
Declare target metadata in the descriptor so the client can derive optimistic patches for queries whose source points at the same table.
Live — submitting adds the row optimistically (it shows instantly, then the server's post-acknowledgement snapshot reconciles it):
<AutoForm api="app" mutation="todos.create" submitLabel="Add todo" />
<DataTable api="app" query="todos.list" />
Mutation Pair
Descriptor:
// apps/api/mutations/notes.create.mutation.ts
import { defineMutation } from '@voltro/protocol'
import { Schema } from 'effect'
export const createNote = defineMutation({
name: 'notes.create',
target: { table: 'notes', op: 'insert' },
guards: [{ scope: 'notes:write' }],
input: Schema.Struct({
title: Schema.NonEmptyString,
body: Schema.String,
}),
output: Schema.Struct({
id: Schema.String,
}),
})
guards:is what makes this file boot. A wire-exposed mutation must declare exactly one ofguards:,openAccess: '<reason>'orinternal: true— a descriptor with none of them is refused at boot, naming the file. A write is also where a rubber-stamp guard costs the most, so name the scope the write actually needs rather than one every caller already holds. Full rules: Authorization.
Server executor:
// apps/api/mutations/notes.create.mutation.server.ts
import type { AppContext } from '@voltro/runtime'
export default async (
input: { title: string; body: string },
ctx: AppContext,
) => {
const inserted = await ctx.store.insert('notes', {
title: input.title,
body: input.body,
authorId: ctx.request.subject.id,
tenantId: ctx.request.subject.tenantId,
})
return { id: String(inserted['id']) }
}The descriptor is the wire contract. The .mutation.server.ts file is the server-only implementation.
insert returns the post-image as an untyped Row (Readonly<Record<string, unknown>>), so narrow the field you need (String(...)) instead of asserting it with as string — an assertion silences the compiler without checking anything. To read a row back, use the fluent terminals: ctx.store.select('notes').where('id', id).one() fails with the typed NoRowFound when the row is missing (or when more than one matches), so you never need a hand-written not-found branch; .first() / .maybeOne() return null instead. That fluent builder is string-keyed and yields an untyped Row; for a TYPED single row, pass the database.<table> builder to the store's own terminals — await ctx.store.one(database.notes.where(eq('id', id))) returns the row type with no cast. See single-row terminals.
What The Runtime Does
- Decode
inputwith the descriptor schema. - Run mutation plugin interceptors.
- Execute the server file inside
store.transactional(...). - Encode
outputwith the descriptor schema. - Commit the transaction.
- Drain the batched change events so matching query subscriptions receive new snapshots or deltas.
Missing required columns fail LOUD, at the call
ctx.store.insert / upsert / insertIgnore check the payload against the
table before the statement runs. A column that is NOT NULL, has no default, and
isn't auto-stamped — a business FK like teamId, a plain timestamp() like
lastRefreshedAt — must be present, or the write raises a typed
TableValidationFailed naming it:
TableValidationFailed: missing required column 'lastRefreshedAt'
— NOT NULL with no default and not auto-stampedWithout this the omission slips past tsc and boot and surfaces only as a raw
dialect SqlError: Failed to execute statement — and only on the INSERT path, so
it stays dormant until the first row with no existing cache entry. An
upsert / insertIgnore whose payload omits one of its own conflictColumns is
named the same way (an absent conflict key can't match its target). The check
runs after stamping, so auto-id, tenantId, and audit columns never trip it, and
it skips nullable and defaulted columns — the ones you may legitimately omit.
Catch it at COMPILE time — insertRow / upsertRow
The runtime guard above is the backstop. To catch a missing column at compile
time, use insertRow / upsertRow — they take the table object (not a
string name), so the payload is typed against the table's required columns:
import { insertRow } from '@voltro/database'
// ✗ compile error — lastRefreshedAt is NOT NULL with no default
await insertRow(ctx.store, roadmapEpicStats, { teamId })
// ✓
await insertRow(ctx.store, roadmapEpicStats, { teamId, lastRefreshedAt: new Date() })InferInsertRow<T> makes a column optional exactly when you may omit it — it's
nullable, has a .default(), or is a framework-filled id / tenantId / audit
column — and required otherwise. upsertRow's conflictColumns are constrained
to the table's own columns, so a typo is a compile error too. The string-keyed
ctx.store.insert / upsert still work unchanged; the typed seam is opt-in.
If you adopt it, check your tooling for the old spelling.
insertRowreplacesstore.insert('<tableName>', …), so anything that matches on that string stops matching — a lint rule, a codemod, an architecture test. One team had a test asserting every mutation writes an audit log; it matchedstore.insert('auditLogs', and migrating toinsertRowsilently blinded it. Green suite, gap reintroduced. Grep for the old spelling before you migrate, not after.
The same, as an Effect — and they live in a different package
insertRow / upsertRow are the Promise forms and come from
@voltro/database. Inside Effect code there are five typed counterparts, and
they come from @voltro/runtime:
import { insertRowEffect, insertIgnoreRowOutcomeEffect } from '@voltro/runtime'
await ctx.store.transactional((tx) => Effect.gen(function* () {
yield* insertRowEffect(tx, roadmapEpicStats, { teamId, lastRefreshedAt: new Date() })
const { row, outcome } = yield* insertIgnoreRowOutcomeEffect(tx, memberships, { userId, teamId }, {
conflictColumns: ['userId', 'teamId'],
})
// `outcome` is 'inserted' | 'ignored' — a conflict is not a write
if (outcome === 'inserted') yield* recordAudit(tx, 'membership.created', row.id)
}))The set is insertRowEffect, insertManyRowsEffect, upsertRowEffect,
upsertRowOutcomeEffect and insertIgnoreRowOutcomeEffect. The transaction
handle tx is accepted directly — it hands out an EffectStoreOps.
The package split is the thing to remember, because knowing one family sends
you looking for the other in the wrong place: the Promise helpers sit beside the
store in @voltro/database, the Effect helpers sit with the Effect surface in
@voltro/runtime.
Two reasons to prefer them inside Effect code over Effect.promise(() => ctx.store.insert(...)). A constraint violation reaches the typed error
channel instead of becoming a defect — a thunk throws the failure away, and the
client sees an opaque Failed to execute statement. And the *Outcome* variants
return what actually happened: reading only the row and then recording a
created event writes an audit entry for a write that a conflict skipped.
The tooling warning above applies here too, and doubly: a rule matching
store.insert(sees neitherinsertRownorinsertRowEffect.voltro doctormatches all three.
Partial updates: ctx.store.applyDefined
A partial-update mutation should set only the fields the caller actually sent — not overwrite an omitted field with undefined. Instead of hand-writing if (input.x !== undefined) patch.x = input.x per field, use ctx.store.applyDefined(input, keys):
const execute = async (input: UpdateNote, ctx: AppContext) =>
ctx.store.update('notes', input.id, ctx.store.applyDefined(input, ['title', 'body', 'dueAt']))It returns a patch containing only the listed keys whose value is not undefined (a defined falsy value like 0 / '' / false IS kept). Also importable standalone (import { applyDefined } from '@voltro/runtime') for seeds/tests.
Calling From React
import { useMutation } from '@voltro/client'
export default function NewNote() {
const create = useMutation<{ title: string; body: string }, { id: string }>(
'app',
'notes.create',
)
return (
<form onSubmit={async (event) => {
event.preventDefault()
const form = new FormData(event.currentTarget)
await create.mutate({
title: String(form.get('title')),
body: String(form.get('body')),
})
}}>
<input name="title" />
<textarea name="body" />
<button disabled={create.pending}>
{create.pending ? 'Saving...' : 'Save'}
</button>
</form>
)
}useMutation returns mutate, pending, error, data, plus the chainable optimistic helpers.
Handling the result — onSuccess / onError / notify
Pass a result handler to mutate instead of wrapping every call in
try/catch/finally + toasts. pending already replaces the finally:
const create = useMutation('app', 'teams.create')
await create.mutate(input, {
onSuccess: (team) => setOpen(false),
notify: { success: t('teams.created'), error: (e) => messageFor(e) },
})The load-bearing rule: supplying an error handler (onError or
notify.error) marks the failure handled — mutate then resolves with
undefined instead of rejecting, which is what removes the try/catch. With no
error handler it rejects exactly as before, so an unhandled failure stays loud.
You opt in per call.
notify routes to an app-wide sink you register once — the framework is not
bound to any toast library:
import { setMutationNotifier } from '@voltro/client'
setMutationNotifier({ success: (m) => toast.success(m), error: (m) => toast.error(m) })The callback form is for SINGLE-SHOT writes. A loop or a multi-step sequence relies on the promise throwing to stop. Once the failure is handled the promise resolves, so the loop cheerfully continues past the row that failed:
// WRONG — onError handles the failure, so the loop never stops
for (const row of rows) {
await create.mutate(row, { onError: (e) => toast.error(messageFor(e)) })
}
// RIGHT — bare mutate rejects, so the sequence aborts where it broke
try {
for (const row of rows) await create.mutate(row)
} catch (e) {
toast.error(messageFor(e))
}The same applies to run on actions.
Idempotency — a retried mutation runs exactly once
An interrupted unary call has an unknown outcome: the connection may have
died before the server saw it, or after the transaction committed but before
the response arrived. useMutation reports that honestly as
{ kind: 'transport', outcome: 'unknown' }.
The client automatically retries a mutation once only after the deployed
server proves that idempotency is active. It reuses the exact same
idempotency key, so the handler runs once and the original mutate() promise
receives the first result. Unknown capability, a disabled server, an expired
replay window, or a full pending queue means no replay — the original unknown
outcome rejects instead. Actions are never replayed automatically.
Enable it once (this also covers the REST Idempotency-Key header — one switch, both surfaces):
// app.config.ts
export default {
idempotency: true, // or { ttlMs: 600_000 } — the dedup window (default 24h)
}For a HIGHER-level guarantee — dedupe a double-click or an offline resend of the same logical action — pass a STABLE key derived from the action's identity, instead of the per-call one:
await placeOrder.mutate(cart, { idempotencyKey: `order:${cart.id}` })The key is scoped to (tenant, subject, mutation), so one user's key can never
replay another's. The replayed result is byte-for-byte the first one — a Date
in the output comes back a Date, not a string — because it round-trips through
the mutation's output schema. Off by default: with no idempotency config,
every call runs and the browser refuses automatic replay.
A key is in flight while its first call runs: a second send of it answers
MutationInFlight (REST: 409) with retryAfterMs. The running call holds its
key on a 30-second lease, renewed while the handler works. If the process dies
mid-handler, the lease lapses and the next send with that key runs the mutation —
once, because the dead call's transaction never committed. A crashed process
blocks its key for at most 30 seconds, not for the replay window.
Capability discovery is fail-closed. The api exposes
/_voltro/runtime-capabilities and, for a socket at /api/sync, also
/api/_voltro/runtime-capabilities; the client probes the sibling path. If your
edge routes WebSocket and ordinary HTTP through unrelated paths, set
web.api.recovery.capabilitiesUrl in the web app. A missing, slow, or malformed
response never counts as permission to replay.
For a workspace API, both web listeners (voltro dev and voltro start)
forward the public GET automatically: /ws/app uses
/_voltro/api/app/_voltro/runtime-capabilities; a custom socket uses its
sibling capability path. This is a narrow proxy to the configured API's real
answer, not production access to dev's inspect proxy. External APIs are probed
directly. Give custom sockets distinct parent paths when several APIs share
one web listener; an ambiguous discovery path refuses boot.
During the bounded wait, the optimistic patch, subscription base and revision
stay visible. The default limits are 32 waiting mutations and a 10-second replay
window; configure them under web.api.recovery. A subject or tenant change is
the security boundary: it carries none of those rows or patches into the new
identity. The client rechecks that boundary, the capability proof, the live
transport and the age limit immediately before it sends the replay; permission
reserved under an earlier identity cannot cross the switch.
Connection-bound side effects
A room join changes the current connection's state. Replaying its old result
on a replacement WebSocket does not restore that state. For this class of
mutation, declare idempotencyScope: 'connection':
import { defineMutation } from '@voltro/protocol'
import { Schema } from 'effect'
export const joinRoom = defineMutation({
name: 'rooms.join',
input: Schema.Struct({ roomId: Schema.NonEmptyString }),
output: Schema.Void,
guards: [{ authenticated: true }],
idempotencyScope: 'connection',
})With idempotency enabled, the scope is (tenant, subject, mutation, native connection id). Repeating a key on the same connection replays its result or
returns MutationInFlight; on another connection it executes again. The ID
is assigned by the server, never taken from a browser's client ID or payload.
Ordinary mutations retain the default 'subject' scope and deduplicate across
reconnects. Never use connection scope for payments or other writes that must
not repeat when the transport changes.
Connection-scoped RPCs require a live WebSocket even without a key or with
idempotency disabled. HTTP or a closed/missing native connection fails with
typed MutationConnectionRequired { traceId }, automatically included in the
mutation's wire error union. internal, publicApi and exposeAsTool
projections are refused at declaration. Dev and serve use the same runtime
binding. With dedup disabled or no key, each admitted call still executes.
This option does not join a room, grant authorization, schedule a rejoin, or
persist pending writes. The executor must validate room access and change
ctx.connectionState within its transaction; the client must await a confirmed
join on the current connection before sending scoped writes. A completed join
is not automatically repeated merely because a later connection opens.
Disconnect/crash cleanup of persisted participant rows remains application
work. Native HTTP/WebSocket regression coverage is in the runtime's
connectionIdempotency.test.ts.
Restore setup before dependent writes
Use the typed useConnectionSetup binding for a connection-scoped mutation,
then attach its handle to each dependent mutation. The declaration above is
required: ordinary subject-scoped mutations are refused as setup before sending.
// src/lib/api.ts
import { createHooks } from '@voltro/client'
import type { AppProcedures } from '@app/api/rpcGroup'
export const { useSubscription, useMutation, useAction, useConnectionSetup } =
createHooks<AppProcedures>('app')import { useConnectionSetup, useMutation } from '../lib/api'
// Inside the component that owns the selected room:
const setup = useConnectionSetup('rooms.join')
const write = useMutation('rooms.write').withConnectionSetup(setup.handle)
const leave = useMutation('rooms.leave')
async function openRoom(roomId: string) {
await setup.activate({ roomId })
}
async function sendMessage(roomId: string, text: string) {
await write.mutate({ roomId, text })
}
async function leaveRoom(roomId: string) {
setup.clear()
await leave.mutate({ roomId })
}activate(input) replaces the previous desired setup and resolves only after
its server acknowledgement. Only acknowledged intent is restored automatically
on a replacement socket, including reconnect within the same client runtime.
An initially refused or interrupted activation rejects and is not restored
later. Treat its input as immutable; call activate again to change it.
Concurrent dependent writes share one setup attempt on that physical socket. The setup uses a stable key per activation; its explicit connection scope makes the same key execute again on a replacement connection. Each business write keeps its own subject-scoped key. The native first-send and replay paths both wait for setup, then recheck the connection, activation and replay permit. A late acknowledgement cannot extend an expired replay window.
A late transport failure from an ended mutation attempt stays a failed call,
including its possibly unknown commit outcome. When the native client can
prove that its physical attempt ended, the raw RPC error carries
affectsTransport: false: diagnostics still receive it, but it cannot mark the
replacement socket disconnected. Emitters without this lifetime evidence keep
the conservative default. Handle the write failure; healthy transport is not
proof that the write was saved.
status is idle, pending, ready or error; ready means the current
setup was acknowledged, not that every business write was saved. data holds
the setup output when ready; error records setup failure. clear() forgets
intent and interrupts dependent work but does not send a domain leave RPC.
Unmount and the native subject/tenant reset clear intent too. A cleared or
replaced activation cannot be borrowed by an older pending write. Handles from
another API, or fabricated handles, are rejected.
When an activation ends, its promise rejects with a reason that says WHICH of
those happened. superseded means a later activate() on the same setup
replaced it — the caller's own successor is running, and in React StrictMode
that is the ordinary development path, since every mount effect runs twice.
inactive means the setup itself is gone (cleared, unmounted, subject changed).
connection-unavailable and connection-changed are the socket; timeout is
the bounded wait. Only inactive should read to a user as "this no longer
exists"; treating superseded the same way reports a failure while the
replacement succeeds.
Readiness and setup waits are bounded. This is not a durable offline queue and does not implement persisted participant cleanup, application authorization, or browser-restart recovery. Continue to validate access in the executor; use the native outbox when business writes must survive process/browser loss.
What the server stores, and how a replay meets the first call
- The key travels as the
idempotency-keyheader — on REST as an HTTP header, on the rpc socket as the same-named header of the rpc request;useMutationsets it per call, or you pass{ idempotencyKey }. - What
_voltro_idempotencyholds: the scope(tenant, subject, mutation)(plus the native connection ID when explicitly connection-scoped), the key, the status, the mutation's encoded wire output andcreatedAt. Not the input, and not the raw handler value — the output as it crossed the wire, so a replay decodes to exactly what the first caller received. Stored in plaintext, not redacted: what you return to the client is what is kept. The retention sweep deletes a row aftermax(VOLTRO_IDEMPOTENCY_TTL_HOURS, window + 24h)— 48 h by default, and never inside its own window, because a record dropped while a replay is still possible lets the request run twice. - Claim, transaction, completion. The claim is atomic (one row per key —
a second caller sees it); the handler's transaction and the recording of the
result are not one unit with it. A crash between commit and
completedleaves a claimed row without a result; the next replay of that key runs the handler again — the one window this scheme does not close, and why a handler is still asked to be idempotent for its own writes where it can. - Request interruption is not a process crash. On the WebSocket path,
acquiring the claim and registering its cleanup form one protected boundary.
A caller that disconnects during acquisition gets its fresh claim released
without the executor starting. A plain-Promise executor that has started
cannot be cancelled, so the runtime waits for its actual result and records
the completion even after the socket closed — a replay meets the receipt, not
a second run. Effect executors stay interruptible and finish their rollback
before the claim is released; a synchronous throw releases a fresh claim too;
an interrupt delivered after a successful write never deletes its receipt.
Before this a claim taken by a still-pending store promise stayed
in_flightafter the socket cut, and the optimistic patch stayed visible over two later saved mutations. - In flight. A replay whose key the first call is still executing is the
typed
MutationInFlight { retryAfterMs }— on every mutation's wire union — and REST answers 409.useMutationwaitsretryAfterMsinside the original replay window and retries the same key while time remains, even through several in-flight replies. One pending slot and optimistic patch stay attached to the call; neither the deadline nor the key is renewed. Subject, capability, transport and setup are rechecked before each send. Non-positive or non-finite delays use the 1-second fallback, not a busy loop. A handler still running at the socket cut is the normal case for a long mutation; other handler errors do not acquire automatic retry permission. - A stale read. A keyed update of a
.version()row the handler read is measured against the version it read; a row that moved is a conflict the runtime replays (mutations.replayAttempts, default 3), and past the bound the typedVersionConflict { expected, actual }— on every mutation's wire union — reaches the client. See read-modify-write, per engine. - A mixed rollout. The capability probe answers for whichever replica
served it; the socket may land on another.
idempotencyis app config, so every replica of one deployment carries the same answer — a replica without the binding re-executes a replay. Roll the config out with the code, not ahead of it, and do not run replicas of two configurations behind one socket path. - The proof is public.
@voltro/runtime'sidempotencyReplay.test.tsdrivesbindMutation— the socket path — through "same key twice → one run, same result", "replay while running →MutationInFlight, no second run" and "no key → every call runs".
Preserve the order of edits to one resource — serialize
A row lock serialises transactions, not the order a browser invoked them in.
Two quick clicks that save the same session can take the lock in reverse order,
and the older snapshot then overwrites the newer one. Server-side idempotency
does not see it (two different keys), and .version() detects the conflict and
replays the OLDER write — the older intent still wins. What is needed is an
order per resource, on the client, and the mutation declares it:
// sessions.apply.mutation.ts
export default defineMutation({
name: 'sessions.apply',
input: Schema.Struct({ sessionId: Schema.String, playerLimit: Schema.Number }),
output: Schema.Struct({ ok: Schema.Boolean }),
target: { table: 'sessions', op: 'update' },
serialize: { key: (input) => input.sessionId, maxPending: 32 }, // maxPending optional
})key names the resource from the input. Calls sharing a key run one at a time,
in invocation order, per subject — for every useMutation('sessions.apply') in
the app, not one hook: a second component writing the same session queues
behind the first. The turn is reserved at invocation, before the API boot or
connection waits, so those cannot reorder calls; optimistic patches are staged
at once, only the rpc waits; the permit spans connection setup, the request,
replay and its acknowledgement. Different keys run independently, and pending
stays true until every admitted call settles.
An unknown outcome — a transport failure after the request started — blocks
that key for that subject and rejects its successors with
MutationSerialExecutionError { reason: 'unknown-predecessor' }: the first
write may still commit, so sending a later snapshot would break the promise.
Reconcile it before editing again; remounting is not proof of success. A known
failure releases its permit. A subject change cancels the waits, and the new
subject owns its own lanes. maxPending (default 32) bounds active plus
waiting calls per subject; beyond it a call rejects with reason: 'capacity';
an empty key rejects with 'invalid-key'.
This is not a durable outbox, a distributed lock, a cross-tab merge, an automatic retry permission, or a transaction spanning several mutations.
Auto-Optimistic
The default path is declarative:
defineQuery({
name: 'notes.list',
source: 'notes',
guards: [{ scope: 'notes:read' }],
input: Schema.Struct({}),
output: Schema.Array(Note),
})
defineMutation({
name: 'notes.create',
target: { table: 'notes', op: 'insert' },
guards: [{ scope: 'notes:write' }],
input,
output,
})Then the client can stay plain:
const notes = useSubscription('app', 'notes.list', {})
const create = useMutation('app', 'notes.create')
await create.mutate({ title, body })The client stages an optimistic patch, calls the server, then retires the patch. Server-pushed deltas are still the source of truth.
Retiring the patch has exactly two shapes, and they are not interchangeable:
- Rollback — only when the write FAILED. The server did not write, so the preview must go, immediately. Nothing else ever rolls a patch back: not a timer, not an elapsed window, not a heuristic.
- Hand-off — a primary snapshot read after the mutation acknowledgement. The cache opens a new subscription with a per-attempt reconciliation token. The server bypasses snapshot caching and delta-resume, reads the primary and returns that token. Base and the previews covered by that read change in one notification. A normal delta, an unrelated changed row or a higher revision is not proof that this mutation is present. An identical causal snapshot still counts: a no-op, server normalisation or a later writer may legitimately differ from the preview. Newer unconfirmed previews remain applied.
Acknowledgements in the same tick share one read per affected cache entry.
This costs an additional subscription read after a successful optimistic write;
apps do not add refetch calls. That entry keeps primary-read consistency for
its lifetime, including same-subject transport replacements, so a lagging
replica cannot undo the hand-off. A different subject receives a new, unseeded
cache. This is not a durable offline outbox or a conflict-resolution policy.
If no matching causal answer arrives within five seconds, the client keeps the preview, reports the missing reconciliation on the error bus and retries once. Errors, mismatched tokens and expired deadlines never roll back a successful write. A still-failing read can leave a diagnosed preview outstanding.
For special shapes, override the patch:
const create = useMutation('app', 'notes.create').withOptimistic((cache, input) => {
cache.forTag<ReadonlyArray<{ id: string; title: string }>>('notes.list', (rows) => [
{ id: `temp:${Date.now()}`, title: input.title },
...rows,
])
})Use .withoutOptimistic() for effects that should not preview locally.
Nested / path-targeted optimistic
By default a target patches the flat top-level row array a query returns, keyed by id. When a query returns a nested array — a JSON array column (snapshot.projects) or a computed/shaped value — add path (and, if the item key isn't id, by) to patch at item granularity, with no hand-written .withOptimistic reducer:
target: {
table: 'projectRoadmaps', op: 'update',
path: 'snapshot.projects', // dot-path to the nested array in the value
identify: (input) => input.projectId, // which item to patch (default input.id)
}op: 'insert'appends (ororder: 'prepend') a new item into the nested array — safe even on a computed query (a path insert targets a KNOWN document, not a blind top-level add).op: 'delete'filters the item out by its key.byoverrides the item-key field (default'id').
Shape the item with shapeItem (not shape). For a nested target, build/patch the item with shapeItem — it is typed to the item of the nested array, not the mutation's output, so current needs no cast:
target: {
table: 'projectRoadmaps', op: 'update', path: 'snapshot.projects',
identify: (input) => input.projectId,
shapeItem: (input, current) => ({ ...current, startDate: input.startDate }), // `current` IS the item
}(The flat shape stays bound to the output row — a single field can't be both, so the nested shaper is its own.)
Bulk (multi-item) patches. identify may return an array of ids to patch or delete many items in one mutation — exactly the group-drag / batch-edit where per-item parallel writes used to race:
target: {
table: 'projectRoadmaps', op: 'update', path: 'snapshot.projects',
identify: (input) => input.projectIds, // ← ARRAY: patch them all
shapeItem: (input, current) => ({ ...current, shiftedBy: input.delta }), // each keeps its own key
}(This works for flat top-level targets too — identify returning an array patches/deletes every matching row.)
Add match to patch only the entries whose current value satisfies a predicate — the guard that stops a patch bleeding across sibling subscriptions sharing a source table:
target: {
table: 'projectRoadmaps', op: 'update', path: 'snapshot.projects',
identify: (i) => i.projectId,
match: (value, input) => value.id === input.roadmapId, // only THIS roadmap's subscription
}path, by, match, and shapeItem are browser-safe descriptor data (a dot-path string + pure functions) — the same discipline as identify/shape.
Declared relations — a junction saved in the same mutation
A form with a multi-reference field (assigned stores, tags, members) writes a JUNCTION table beside the row. Declare that on the write target and the framework reconciles the links INSIDE the mutation's transaction — no hand-written junction code in the executor, and a failure rolls the whole write back:
export const employeesUpdate = defineMutation({
name: 'employees.update',
input: EmployeesUpdateInput, // carries assignedStores: string[]
output: Employee,
target: {
table: 'employees',
op: 'update',
relations: {
assignedStores: {
junction: 'employee_assigned_stores',
anchorColumn: 'employeeId', // the junction reference() pointing at `employees`
targetColumn: 'storeId', // the junction's other reference()
},
},
},
})After the executor succeeds, input.assignedStores is reconciled against the
junction via the diff-based link writer (store.relationLinks): missing rows
inserted, surplus rows deleted, unchanged rows untouched — so reactive
subscriptions on the junction see one change per changed row.
The semantics worth knowing: an ABSENT input field leaves the links
untouched — absent is not empty; an empty array is the explicit "clear them
all". The row id comes from the executor's output.id, falling back to
input.id. The link writes go through ctx.store, so undo capture and
cross-table rules see them like any other write.
The same declaration drives the optimistic update
A junction change used to reach the browser only with the server delta — so on
one submit the renamed title flipped immediately and the assigned stores sat on
their old value until the roundtrip landed. It does not any more: useMutation
reconciles the junction rows of every subscription sourced on junction the
moment the mutation is sent, against the same input[field] the server will
write.
It is a diff, not a redraw: a surviving link keeps its own row (and its real id), a surplus link disappears, and only a genuinely new link is a staged optimistic row. The patches ride the ordinary optimistic lane — reverted if the mutation fails, kept after it succeeds until the server data actually moves. Nothing is on a timer.
Client-side the anchor id is input.id; for an insert it is the same
optimistic id the new row was stamped with, since the server's output.id is
not knowable before the response arrives.
Why you state the two columns. The optimistic patch runs in the BROWSER, and
the browser cannot import your db/ schema — @voltro/database is server-only
by construction — so the junction's two reference() columns cannot be derived
there. anchorColumn is the one pointing at the target's own table;
targetColumn is the other. They are not taken on trust: before it writes, the
server compares your declaration against the junction's real reference columns
and refuses, naming the correct pair, if they disagree. A self-junction (both
columns referencing one table) is still refused by name, never guessed.
Typed Errors
import { Schema } from 'effect'
class NoteQuotaExceeded extends Schema.TaggedError<NoteQuotaExceeded>()('NoteQuotaExceeded', {
limit: Schema.Number,
}) {}
export const createNote = defineMutation({
name: 'notes.create',
target: { table: 'notes', op: 'insert' },
guards: [{ scope: 'notes:write' }],
input,
output,
error: NoteQuotaExceeded,
})Throw a matching error from the server file; the client can narrow on _tag.
Matching typed errors on the client
Tagged errors round-trip structurally over the wire — the caught value carries _tag plus every declared field as real properties (and instanceof works, same Schema class both ends). You do not need to parse the error message string.
Inside Effect, use Effect.catchTag('NoteQuotaExceeded', …). In a React try/catch (outside Effect, where catchTag isn't available and the decoded value may be a plain object, not a class instance), match with errorTag(err) — the dependency-free tag reader @voltro/protocol ships (it reads what toRpc writes):
import { errorTag } from '@voltro/protocol'
try {
await createNote(input)
} catch (err) {
if (errorTag(err) === 'NoteQuotaExceeded') {
// err.limit is the declared field — read it directly, no regex
}
}Trace id for debugging. An error caught from useMutation / useAction
carries the non-enumerable client-span id __voltroTraceId:
const traceId = (err as { __voltroTraceId?: string }).__voltroTraceId
// If the server accepted the call: `voltro logs --trace <traceId>`For a declared handler error, the server necessarily accepted the call and the
id joins to its span. For a transport error it may not: the connection can fail
before the request arrived or after the handler ran but before its response
returned. Use kind from
useOnRpcError for that distinction;
the presence of the id alone proves only that the client span existed.
errorTag lives in @voltro/protocol rather than in the client for a reason
worth knowing before you decide where your own error handling goes: _tag is a
wire concept, and protocol owns the wire. So a shared error handler in a package
that has no business depending on @voltro/client — a UI kit, an i18n layer —
can read a tag without taking that dependency. instanceof is the thing that
does NOT survive the wire: what arrives in the browser was decoded from JSON and
never constructed, so match on the tag, not on the class.
Exhaustive matching with the generated matchError. Codegen emits a per-app matchError (plus AppError / AppErrorTag) into rpcGroup.generated.ts, derived by reference from every descriptor's error: schema + your plugins' cross-cutting errors — so there's no hand-maintained tag list to drift out of date (a dead/renamed tag is a compile error):
import { matchError } from './rpcGroup.generated'
const message = matchError(err, {
NoteQuotaExceeded: (e) => `Limit ${e.limit} reached`, // e is typed
ScopeError: (e) => `Missing ${e.required}`,
}, () => 'Something went wrong')Cross-table business rules — .rule()
A typed error is declared on ONE mutation. A rule is declared on a TABLE: an invariant the runtime enforces on EVERY mutation that writes that table, no matter which one did the write. Declare it in the schema with .rule(name, predicate):
import { table, id, integer, eq } from '@voltro/database'
import { database } from '../database/schema'
export const invoices = table('invoices', {
id: id(),
total: integer(),
}).rule(
'totalMatchesLineItems',
async (row, { store }) => {
const items = await store.query(
database.lineItems.where(eq('invoiceId', row.id)).descriptor,
)
const sum = items.reduce((acc, l) => acc + Number(l.amount), 0)
return sum === row.total || { params: { computed: sum, declared: row.total } }
},
)The predicate receives the post-write row and a context whose store is the SAME transactional store the mutation wrote through — so a cross-table read shares the write's MVCC snapshot and cannot race it. It runs INSIDE the mutation transaction, after the write and before commit, and it is dialect-neutral (the same predicate is correct on all four dialects — no per-dialect code). Return true (or nothing) when the invariant holds; return false or a RuleViolationDetail ({ params?, field?, message? }) to signal a violation for THIS row.
Unlike .check() — a single-row SQL CHECK the DATABASE enforces as DDL — a rule is a PREDICATE the runtime evaluates, so it can read OTHER tables. Use .check() when the database itself must guarantee a single-row constraint; reach for .rule() for a cross-table invariant (an invoice total matching its line items, a booking not exceeding a resource's capacity).
The violation is a typed error — automatically
A violated error-severity rule rolls the whole mutation back and fails with the typed, wire-preserved BusinessRuleViolation. You do not declare it on the mutation's error: — the runtime auto-merges it into every mutation's error union at the wire boundary, exactly like ScopeError. A rule declared on a SCHEMA table can fail ANY mutation that writes that table, so no single descriptor could know to declare it; the auto-merge is what keeps the violation a typed error the client decodes by _tag rather than an untyped defect.
Match it on the client the same way as any typed error:
import { errorTag } from '@voltro/protocol'
try {
await createInvoice(input)
} catch (err) {
if (errorTag(err) === 'BusinessRuleViolation') {
// err.rule — the rule name; err.params — the offending values; err.field — the pointer
}
}BusinessRuleViolation carries rule (the declared name), optional params (i18n params for the offending values), an optional field pointer, and severity (always 'error' on the wire — a warning-severity rule never reaches the client as an error).
severity: 'warning' — log without blocking
export const invoices = table('invoices', { id: id(), total: integer() }).rule(
'totalMatchesLineItems',
async (row, { store }) => true,
{ severity: 'warning' },
)A warning-severity rule LOGS and audits the violation but lets the write commit — useful while backfilling data that does not yet satisfy a newly-added invariant. The default is 'error' (roll back).
Rules run on voltro dev and voltro serve through the same mutation runner, so the two boot paths cannot disagree about whether a rule fires. Inserts and updates on your own tables are re-validated; a delete is not (there is no post-write row to check).
internal: true — off the wire entirely
Every discovered *.mutation.ts / *.query.ts / *.action.ts / *.stream.ts
gets a route on the WebSocket — which is why each one has to declare who may
call it, and why an app carrying an undecided procedure does not boot at all.
internal: true is the third answer to that question, beside guards: and
openAccess:: there is no wire surface to make a decision about, because the
procedure never gets a route. (publicApi and exposeAsTool go the other way
and opt IN to wider surfaces — which is why neither combines with internal.)
Reach for it when the caller is other server code — a workflow step, a schedule, another executor — and never a browser:
export const createFromAction = defineMutation({
name: 'auditLog.createFromAction',
input: Schema.Struct({ actorId: Schema.String, eventType: Schema.String }),
output: Schema.Void,
internal: true,
})It is not emitted into rpcGroup.generated.ts, and neither voltro dev nor
voltro serve registers a route — the tag is unroutable over /rpc and the
WebSocket. Server code calls it by importing its executor directly.
A naming convention is not a boundary. One app had grown 18 procedures named
*Internal, meaning "only other server code calls this"; all 18 were in the
client group, and one of them accepted actorId / actorEmail / actorType
from the caller and wrote an audit row. No guard, zero callers, reachable by
anyone logged in. If the only thing keeping a procedure off the wire is that
nobody wrote a client call for it, it is on the wire — the same reasoning as
.serverOnly() on a column, one level up.
That app is why the boot gate exists: all 18 declared no access decision, so
today it does not start until each of them says guards:, openAccess: or
internal: true. The gate turns "reachable and nobody looked" into a refusal
naming every file — but it only forces the question, it cannot answer it, and
internal: true is the right answer only when no browser is meant to call the
procedure at all.
It is not a substitute for a guard. An internal procedure still runs with
whatever authority its caller has. This removes the wire surface, not the need to
check who is asking; voltro doctor's authz scan still covers it.
It cannot be combined with publicApi or exposeAsTool. Those add a REST
route and an agent tool respectively — opt-ins to a different surface — so a
procedure carrying both would be unreachable from your own client and reachable
from the internet. That combination throws where it is declared:
auditLog.createFromAction: `internal: true` cannot be combined with `publicApi`.Neither silent resolution would be right: dropping the REST route breaks a live
endpoint invisibly, and keeping it defeats the flag. Drop internal: true if the
wider surface is intended, or remove the annotation if it is not.
The flag also removes the procedure from voltro dev's inspect invoker, so the
devtools "invoke" panel will not list it. That is deliberate — an internal
procedure is the one most likely to carry no guard, since "only server code calls
this" is the reason people write them.
When Not To Use A Mutation
- External I/O. Use an action or workflow.
- Progress output. Use a stream.
- Reads. Use a query.
- Long-running durable work. Use a workflow.