Sync / foldkit-durable

External effects and the crash gap

When a committed operation triggers work outside SQLite—such as sending an email or charging a card—no local database commits atomically with an external provider. If the process crashes after the provider succeeds but before recording that success, a restarted server cannot tell whether the provider acted.

The journal's effect ledger records a stable intent identity and its outcome (pending, succeeded, or failed) so recovery can reuse known successes and apply an explicit policy for uncertain work.

runEffect(key, run) reuses a recorded succeeded result without calling run again, deduplicates concurrent calls on the same key within one Journal instance, and retries pending or failed records by default (pass { retryFailed: false } to fail with EffectFailedError, or pass a custom predicate):

RecordRecovery can concludePolicy
noneNo run was recorded; a committed operation may still need workDerive the intent from the operation and start it
pending or failedThe provider's outcome is unknownRetry only with provider idempotency; else resolve manually
succeededThe result is knownrunEffect reuses it without contacting the provider

Derive each effect key from the document, operation id, and semantic action before calling the provider, and pass that same key as the provider's idempotency key:

ts
const confirmationKey = (order: Order) =>
  JSON.stringify(['orders', order.opId, 'send-confirmation:v1'])

const sendConfirmation = (journal: Orders, order: Order) => {
  const key = confirmationKey(order)
  return journal.runEffect(
    key,
    Effect.tryPromise(() => provider.sendConfirmation({ orderId: order.id, idempotencyKey: key })),
  )
}

Effect keys are database-global. Avoid array-index keys (reordering shifts keys across actions), and choose a new semantic name for distinct new work. Without provider idempotency, a crash right after an external call can cause a duplicate on retry.

Recovery. Because pending is written when runEffect starts rather than at commit time, journal.recover scans committed operations after an application-owned cursor, executes or reuses each intent, and stops before the first failed or skipped operation, returning the settled cursor:

ts
const settle = (journal: Orders, from: Cursor) =>
  journal.recover({
    key: DocumentId.make('orders'),
    from,
    intents: order => [
      {
        key: confirmationKey(order),
        run: Effect.tryPromise(() =>
          provider.sendConfirmation({ orderId: order.id, idempotencyKey: confirmationKey(order) }),
        ),
      },
    ],
    // Default: retry. `skip` stops before this operation for manual resolution.
    onUnresolved: (_intent, record) =>
      Option.isSome(record) && record.value.status === 'failed' ? 'skip' : 'retry',
  })

Your application controls when recover runs, which documents it covers (keys()), and where the settled cursor is stored (avoid compacting past it). Inspect unresolved items with unfinished(), effect(key), and clearEffect(key).

One executor per database. The in-flight map lives in one Journal.make handle; a pending row is a crash marker rather than a distributed lock, so route execution through one handle. See test/effectRecovery.test.ts for idempotent recovery and crash-window tests.

Named cursors and parked runs. Store recovery cursors and set-aside runs beside the ledger via journal.cursors (used by foldkit-sync reactions):

ts
const mailer = Effect.gen(function* () {
  const key = DocumentId.make('orders')
  // Once, before serving: starts at the document's cursor (or `from: 'floor'`).
  yield* orders.cursors.track(key, 'mailer')
  const tracked = yield* orders.cursors.settled(key, 'mailer')
  return Option.map(tracked, ({ epoch, cursor, attempts }) => ({ epoch, cursor, attempts }))
})

// After a run of `order` finished, or was set aside:
const advanced = (epoch: string) =>
  orders.cursors.advance(DocumentId.make('orders'), 'mailer', epoch, Cursor.make(order.sequence))
  • Lower bound: advance only moves forward and clears failure counts when it advances; moving a cursor back only causes ledger reads without re-running succeeded effects.
  • Failure tracking: stalled(key, name, epoch, at) tracks attempt counts and timestamps persistently across restarts.
  • Parked runs: park, parked, and unpark store failed runs with retry input (surviving compaction) and error text.
  • Epochs: Every cursor and parked row is scoped to its epoch; writes against an old epoch become no-ops, and single-statement writes keep these guarantees on D1.
  • Schema 7 tables: Cursors and parked runs live in foldkit_durable_cursors and foldkit_durable_parked (older builds refuse migrated databases with UnsupportedJournalVersionError).