Learn / Errors and failures

Write failures and typed refusals

When a mutation fails, Remote removes its optimistic layer and records the failed input in Data.failedWrites until retried, dismissed, or cleared by Data.forget. Continuing the project example with a declared Rename mutation:

ts
import { Mutation, Refusal } from 'foldkit-remote'

const Rename = Mutation.make('Rename', {
  Input: { id: Schema.String, name: Schema.String },
  Output: {},
  Refusal: Schema.Union([Refusal.field('name', Schema.String), Refusal.conflict]),
})
const WriteData = Remote.make({ model: App.model.remote, entities: [Project], mutations: [Rename] })

const notices = (model: Model): ReadonlyArray<string> =>
  WriteData.failedWrites(model, Rename).map(write =>
    Option.match(write.refusal, {
      onNone: () => `"${write.input.name}" was not saved: ${write.error.message}`,
      onSome: Match.valueTags({
        Field: ({ reason }) => `"${write.input.name}": ${reason}`,
        Conflict: () => 'Someone changed this project meanwhile.',
      }),
    }),
  )

const retried = (model: Model, requestId: string): Update.Return<Model, Message, RemoteClient> =>
  Option.match(WriteData.retry(model, requestId), {
    onNone: () => ({ model }),
    onSome: started => ({ model: started.model, commands: [started.command] }),
  })
const dismissed = (model: Model, requestId: string): Model => WriteData.dismiss(model, requestId)
  • Data.failedWrites(model, Rename) returns failed writes oldest-first with typed input and refusal. Non-durable writes clear on page reload.
  • write.refusal holds Option.some for declared business refusals and Option.none for network or unexpected server errors.
  • Data.retry re-sends the write with the same request ID and operation ID (so a ledgered server returns the previous outcome instead of re-applying) and restores its optimistic overlay.

To react to a failure in update (such as restoring focus), share MutationFailed in Data.wiring(actives, { shared: ['MutationFailed'] }). Unshared failed writes emit a WriteUnheard diagnostic.

Durable writes that outlive a reload

Using Data.mutate(model, M, input, { durable: true }) with outbox(Data, ...) stores the mutation in KeyValueStore before sending:

FailureOrdinary mutationDurable mutation
Unreachable (offline or timeout)Failed; manual Data.retryStays Waiting; retries with backoff
Declared server refusalFailed in failedWritesSame; persisted until dismissed or retried
Reload before response arrivesLostRe-sent on load with same operation ID

Use outboxStatus(Data, model) ({ waiting, failed, items }) to render indicators such as "3 changes waiting" when attempt > 0. Durable mutations require a ledgered writer (RemoteServer.write or foldkit-remote-drizzle's writer with a ledger) so retries of already-applied writes return cleanly.

The outbox emits two diagnostics when local persistence has trouble:

  • OutboxUnreadable: A stored entry cannot be decoded by the current schema; outboxStatus surfaces it as Unreadable, later items proceed, and Data.dismiss clears it.
  • OutboxUnsaved: Writing to storage failed; current writes still send, but a reload loses them.

For multi-device offline editing that merges concurrent changes, use foldkit-sync; see Remote mutation vs Sync operation.

Refusals from declared writes

A Mutation.write over an Entity's Write evaluates rules in a fixed order so unauthorized callers learn nothing about row state:

RefusalCauseResponse
Forbidden (RemoteError)Guard rule fails or row is hiddenShow denial; retrying changes nothing
ConflictRow revision passed expectRe-read row and let user decide
UnmetRow fails when or from predicateShow state change message
InvalidRow after write breaks an invariantShow message at each path field
TakenInsert ID already existsPick a new ID (retries hit ledger)

An Invalid over a hidden member omits the rule ID and path. Use Refusal.isInvalidBy(refusal, invariant) to match a specific Entity invariant. When the client holds the required fields or may flag, it computes Forbidden and Invalid locally using the exact same rules before sending; see Refused where it is made.

Database CHECK constraints (checkConstraints or entityChecks) act as a final safety net: tripping one directly returns Internal error with an incident ID and logs StatementFailed and ServerDefect. See Declared writes.