RolebookDocs

Protected and managed updates

Local SQLite authorization, application updates and durable recovery in one owned transaction.

createSqliteProtectedWriteAdapter() binds the original SQLite sharing adapter, VersionedSharing instance, policy store and checked local SQLite executor. Its scoped API supports a raw resource/action callback and a managed field patch. Both commit the application change, durable receipt and outbox event atomically in the same local database.

This slice supports local SQLite through createBunSqliteExecutor() from @rolebook/sharing-sqlite/bun and createLibsqlExecutor() from @rolebook/sharing-sqlite/libsql with a local file-backed client. libSQL :memory: is unsupported because its transaction connection lifecycle does not preserve one database across transactions. Remote libSQL transports and caller-owned transactions are not accepted as equivalent authority. The worker-backed createBunSqliteQueryExecutor() from @rolebook/sharing-sqlite/bun-query, which named authorized queries require, is accepted too; see on the worker executor for how its lifetime, COMMIT outcome and receipts behave. Executors are recognised by the package’s own record of the executors it made, never by their shape. Python, Go and Rust Sharing HTTP requests do not extend this transaction across processes.

Bind local authority

Use one checked executor for the original resource adapter and policy store. Configure the resource adapter’s eligibility and authorization-fact fences with createSqliteLocalIdentityProjection(), and supply its identity to the protected adapter. The application-owned projection must represent the complete local identity, assignments, groups, attributes and their absence. Every writer updates the same revisioned row. This is local authoritative state, not a claim about an external identity provider’s freshness.

import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing";
import {
  createSqliteLocalIdentityProjection,
  type SqliteSharingAdapter,
  type ParameterizedSqliteExecutor,
  applyProtectedWriteMigrations,
  createSqliteProtectedWriteAdapter,
} from "@rolebook/sharing-sqlite";

declare const executor: ParameterizedSqliteExecutor;
declare const sharingAdapter: SqliteSharingAdapter;
declare const versionedSharing: VersionedResourceSharing<SharingResourceConfigurations>;
const projection = createSqliteLocalIdentityProjection({table:"authz_identity_projection"});

await applyProtectedWriteMigrations(executor, { tablePrefix: "app_authorization" });
const protectedAdapter = createSqliteProtectedWriteAdapter({
  adapter: sharingAdapter,
  sharing: versionedSharing,
  identity: projection.identity,
  environmentId: "production",
  authorityEpoch: "installation-epoch-1",
  journalPrefix: "app_authorization",
  maxLifetimeMs: 5_000,
  managed: {
    target: {
      schema: "main",
      table: "document",
      userColumns: ["tenant_id", "id", "title", "visibility", "version", "rolebook_sharing_revision"],
    },
    fields: [
      { field: "title", column: "title", codec: "text" },
      { field: "visibility", column: "visibility", codec: "text" },
    ],
  },
});

The example column list must match your table’s actual catalog order, including migration-added columns. The adapter verifies the complete schema inside the owned transaction. Supported managed codecs are text, boolean and safe integer, with explicit nullable mappings. The actual SQLite storage class and value must match; affinity coercion is not permission to change a payload’s meaning. Field names are flat and mappings cannot target identity/version/sharing columns.

Choose the update contract

scoped.withAuthorizedTransaction(intent, callback) requires a resource-wide action allow. The trusted callback uses guard.executor and advances to postVersion. Its opaque SQL is not field-mediated, even when the adapter also has a managed mapping. It must retain incarnation, owner, ancestry and sharing authority and obey participating writer contracts.

scoped.withManagedUpdate(intent) has no SQL callback. It applies a captured patch with a compare-and-set on the expected version:

const scoped = protectedAdapter.forScope({
  tenantId: "workspace_1",
  actor: { type: "user", id: "user_123" },
});
declare const incarnationId: string;
declare const currentVersion: string;
declare const nextVersion: string;
const intent = {
  resource: { type: "document", id: "document_1" },
  action: "update",
  incarnationId,
  expectedVersion: currentVersion,
  postVersion: nextVersion,
  idempotencyKey: "rename-document_1-once",
  patch: { title: "New title" },
};
const result = await scoped.withManagedUpdate(intent);

Every declared field must pass canonical policy checks against both the authoritative before row and a separate after-state SELECT. Field-only grants can allow a managed patch; a deny covering any declared field rejects the entire patch. The actual stored patch values, full target row change set and resulting version are checked. Read-only policy attributes come from the same trusted resourceFromRow projection as writable attributes. Normalize SQLite boolean 0/1 values explicitly in that projection. Unmapped integers outside JavaScript’s safe range are supplied as exact decimal text instead of rounded numbers; mapped safe-integer values outside that range are rejected.

Versions are opaque tokens, separate from the lifecycle incarnation. The expected version must match and the supplied post-version must be nonempty and different. No global ordering or protection against application version reuse is implied. Empty patches are invalid. An allowed all-no-op patch still authorizes every declared field, advances the version and records a receipt.

SQLite transaction and clock semantics

The adapter acquires BEGIN IMMEDIATE before reading authority. SQLite serializes writers at the database level; it does not provide PostgreSQL’s row-lock concurrency. Independent connections may receive SQLITE_BUSY before application work. Neither raw callbacks nor managed updates are automatically retried. Bun leases its connection across asynchronous work; local libSQL owns a separate transaction connection. Both reject callback escape through the outer executor and close the transaction handle before commit. libSQL session-local TEMP objects are not a durable configuration mechanism.

File-backed databases require WAL, foreign-key enforcement, full synchronous durability and bounded contention settings. Protected writes use the main database; attached databases and temporary targets are outside this slice. Durable journal operations explicitly address main, so temporary table names cannot divert a receipt or event.

Expiry evidence uses validated integer epoch milliseconds and database-derived load/seal times. Equal expiry denies. The seal may share a millisecond with the load, but clock regression fails closed. The SQLite clock is millisecond resolution with no PostgreSQL microsecond parity claim. Synchronous SQLite statements cannot be preempted by a JavaScript timer: lifetime sealing prevents a late authorization from committing, while callback cancellation is cooperative.

On the worker executor

The worker executor runs each connection in its own worker thread. Build the resource adapter, the policy store and the protected-write adapter on the same executor object; a copy, a wrapper or a method taken from it is refused like any unchecked executor. A protected run is one BEGIN IMMEDIATE transaction on one worker. Authorization reads its facts inside that transaction, so a revocation committed by another worker or another process before BEGIN IMMEDIATE succeeds is seen. Inside the run the outer executor refuses calls, and a callback handle kept after the run rejects every call without reaching a worker.

Lifetime. maxLifetimeMs runs from the opening of the transaction until COMMIT is sent to the worker. Because the application thread stays responsive while the worker runs SQL, the lifetime can elapse while a statement is running. When it elapses before COMMIT has been sent, guard.signal aborts, no further statement of the run is sent, and the transaction never commits. A running SQLite statement cannot be interrupted: the run waits for it to return, rolls the transaction back and only then rejects with ProtectedWriteTimeoutError, so that error can arrive later than maxLifetimeMs by the length of the running statement. The worker returns to the pool only once the rollback is confirmed; otherwise it is retired, which drops its connection and the transaction with it.

COMMIT. Once COMMIT has been sent the lifetime no longer applies:

  • COMMIT succeeded: the run returns its normal result, even if maxLifetimeMs passed meanwhile;
  • COMMIT failed and the transaction is still open: it is rolled back and the failure is reported;
  • the worker was lost or the executor closed while COMMIT was in flight, or SQLite ended the transaction while COMMIT failed: SqliteCommitOutcomeUnknownError (COMMIT_OUTCOME_UNKNOWN), never a timeout, a denial or a claim of rollback.

The expiry check and the dispatch of COMMIT are one step: either the lifetime runs out first and COMMIT is never sent, or COMMIT is sent and the lifetime can no longer settle the call. There is no commit timeout. A running SQLite statement cannot be interrupted, so a COMMIT that never returns leaves the call pending and its worker occupied until it returns, the worker is lost or the executor is closed.

Resolve an unknown outcome after the fact with the exact-intent receipt lookup; do not assume either outcome. Running the same intent again with the same idempotency key is safe: it replays a committed receipt and runs the work only if nothing committed.

Receipts. The application change, its receipt and its outbox event are written in one transaction and are all present or all absent after any failure, including the loss of the worker. A lookup that finds no receipt is not proof of a rollback while the COMMIT may still be in flight: a lookup can run on another worker when one is free, and then answer before the run that writes the receipt has finished. With maxConnections: 1 it waits for the run holding the only connection, its COMMIT included.

Other failures. A request or response over the executor’s 2 MiB message cap inside a run fails the run with QUERY_UNAVAILABLE and rolls it back. If ROLLBACK fails or the worker dies before or during it, the caller receives the original error, the worker is retired and nothing commits. executor.close() during a run fails a run whose COMMIT was not sent, which never commits, and reports SqliteCommitOutcomeUnknownError for a run whose COMMIT was in flight.

Named queries. A protected write waits for a free worker in arrival order, like any ordinary work, and holds it until its COMMIT ends. Query pages never wait: while every worker is busy, for example with long protected writes, a page answers QUERY_UNAVAILABLE. Size maxConnections for the writes and other work you expect at once plus the pages that must still be answered, and keep protected callbacks short. A page whose lease opened before a protected write committed keeps its snapshot and does not see the write.

Parity. A protected run gives the same result here as on createBunSqliteExecutor() when every request and response fits the 2 MiB message cap and the result does not depend on the order in which concurrent runs obtain SQLite’s write lock. The two differences:

  • a run with a request or response over 2 MiB fails and rolls back here, and would succeed on the synchronous executor;
  • one synchronous connection queues runs, while separate workers contend for SQLite’s single write lock. Protected writes require busy_timeout=0, so a run whose BEGIN IMMEDIATE meets the lock held by another worker or connection fails at once with that SQLITE_BUSY error (isRetryableBusyError() recognises it). It fails whole: its callback or managed operation has not started and nothing of it is written. Protected runs are not retried automatically; retry with the same intent. With maxConnections: 1 an executor’s protected writes queue for its one worker in arrival order and never contend with each other; with more connections they can.

Every worker connection is set to synchronous=FULL when its worker starts, replacements included, and the start verifies it with busy_timeout=0, foreign keys, WAL and UTF-8. Before its BEGIN IMMEDIATE every protected run reads synchronous and busy_timeout on the connection that will run it and fails with CONSISTENCY_UNAVAILABLE, without opening a transaction, unless they are FULL and 0. A setting changed through the executor’s query() reaches one pooled connection only. With synchronous=FULL every commit through the worker executor waits for its WAL write to reach the disk.

Recovery and schema boundaries

Use lookupReceipt(rawIntent) or lookupManagedReceipt(managedIntent) after an uncertain commit. A matching durable receipt proves the recorded outcome. Absence alone is not permission to blindly replay an uncertain operation. An exact committed replay returns its stored receipt; a changed mapping or intent under the same key conflicts.

createSqliteProtectedWriteOutbox() provides environment-bound claims and lease acknowledgements. Delivery is at least once; consumers deduplicate stable event IDs. Leases use database time. Environment identity is stored data and is copied when the database file is copied.

Managed targets are ordinary permanent tables. The exact first-party key guard installed by Sharing migrations is supported; a same-name altered guard or another application/temporary trigger is rejected. Generated and automatically maintained columns are unsupported. Only version is exempt from the unchanged-column rule, and it must equal the declared post-version. The physical-row check proves nothing about other rows, tables or deferred triggers. Trusted schema and source-writer contracts remain required; this API is not an arbitrary SQL sandbox.

Atomic managed batches

withManagedUpdates() applies 1–32 updates to distinct existing resources through the same configured adapter and tenant scope. Each item uses the same field, incarnation and version checks as a single managed update. The batch shares one transaction and lifetime; final persisted-state and authority checks run after the last update. Any failure rolls back every update, the single receipt and its single outbox event. There is no per-item partial success.

import type { ManagedUpdateBatchIntent } from "@rolebook/sharing-sqlite";
declare const secondIncarnationId: string;
declare const secondCurrentVersion: string;
declare const secondNextVersion: string;
const batchIntent: ManagedUpdateBatchIntent = {
  idempotencyKey: "rename-two-documents-once",
  updates: [
    {
      resource: { type: "document", id: "document_1" },
      action: "update", incarnationId,
      expectedVersion: currentVersion, postVersion: nextVersion,
      patch: { title: "First title" },
    },
    {
      resource: { type: "document", id: "document_2" },
      action: "update", incarnationId: secondIncarnationId,
      expectedVersion: secondCurrentVersion, postVersion: secondNextVersion,
      patch: { title: "Second title" },
    },
  ],
};
const batchOutcome = await scoped.withManagedUpdates(batchIntent);
// After an uncertain commit, reconcile using the original complete batch intent:
const recoveredBatch = await scoped.lookupManagedUpdatesReceipt(batchIntent);

Choose either the single-update or batch example for a given set of expected versions; do not apply the preceding single update first and then reuse its stale expected version in this batch. The receipt result contains updates entries with resource and resulting version, ordered by resource ID using ordinary UTF-16 comparison. One environment/tenant/actor-bound key covers the entire batch. Input order is canonicalized; reordered identical items replay the original receipt. A changed item, mapping or complete intent under that key conflicts. Missing receipt evidence does not prove rollback.

schemaVersion is the stored metadata version, not a journal-table schema. A flat batch stays version 1. An enrolled batch of one update stays version 2. With admission protected_batch_receipt_floor 2, the default for every tenant and for an upgraded row, a multi-target enrolled batch stores version 2 from the UTF-16-first target. That one hierarchy block is evidence for its links[0] target only, not for the other result updates. Floor 3, set on the admission row after decoders and old writers are drained, records version 3: one targets entry per result update, each hierarchy block evidence for that target and not a capability. There is no top-level hierarchy and no separate control command. Select the entry whose resource matches the result update. Apply the admission migration first: a missing column is profile_mismatch. Running it again leaves existing rows at floor 2. An old binary cannot enforce a column it does not know. SQLITE_BUSY while opening an enrolled batch is HIERARCHY_UNAVAILABLE / serialization_conflict. A floor outside 2 or 3, or a floor that changes at the final fence, is HIERARCHY_UNAVAILABLE / protocol_floor.

PostgreSQL acquires resource locks in deterministic resource-ID order; SQLite retains its single-writer transaction behavior. No automatic retry, cross-adapter transaction, create, delete or move operation is added. The existing local-authority and supported-driver limits still apply.

Scoped outcome lookup and worker recovery

For a server route that already knows the authenticated actor, tenant and original idempotency key, use the receipt factory with the opaque route from the protected-write adapter:

import {
  createSqliteProtectedWriteAdapter,
  createSqliteProtectedWriteReceipts,
  createSqliteProtectedWriteOutbox,
  type ParameterizedSqliteExecutor,
} from "@rolebook/sharing-sqlite";
declare const journalExecutor: ParameterizedSqliteExecutor;
declare const protectedWrites: ReturnType<typeof createSqliteProtectedWriteAdapter>;
// These values must come from authenticated server context, after application access checks.
declare const authenticatedScope: {
  tenantId: string;
  actor: { type: string; id: string };
};
const receipts = createSqliteProtectedWriteReceipts({
  receiptRoute: protectedWrites.receiptRoute(),
});
const committedOutcome = await receipts.forScope(authenticatedScope).lookup({
  idempotencyKey: "rename-document_1-once",
});
const worker = createSqliteProtectedWriteOutbox({
  executor: journalExecutor, tablePrefix: "app_authorization", environmentId: "production",
});
const pending = await worker.inspectPending({ limit: 100 });
declare const deliver: (event: { eventId: string; kind: string; payload: unknown }) => Promise<void>;
for (const event of await worker.claim({ limit: 1, leaseMs: 30_000 })) {
  try {
    await deliver(event); // Destination durably accepts and deduplicates by environment/event ID.
  } catch {
    await worker.retry(event.deliveryToken, { delayMs: 5_000 });
    continue;
  }
  const acknowledged = await worker.acknowledge(event.deliveryToken);
  // false means the lease was lost; delivery may be repeated.
}

Key-only lookup reports the original committed result; it does not compare a new proposed payload. An empty, oversized, or NUL-bearing idempotency key is rejected before a read opens. An enrolled tenant passes the current gate in that checked read before any journal access: the adapter port, captured authority epoch, current admission and bootstrap, and whether this resource type is enrolled. A successful gate returns the stored outcome verbatim, or undefined when no row matches. A refused gate — missing port, epoch mismatch, quarantine, corrupt admission, or a type that is not enrolled — throws and does not read the journal, so the refusal discloses neither a receipt nor a miss. Use lookupReceipt, lookupManagedReceipt or lookupManagedUpdatesReceipt with the exact original intent for retry validation. undefined after a successful gate means not observed, not proof that an uncertain transaction cannot still commit, in particular while its COMMIT may still be in flight. Never mint a new key solely because lookup is empty.

Inspection is an oldest-pending snapshot (limit 1–1000), including leased rows and excluding delivered rows. It does not decode payloads, so a poison payload remains visible. Retry requires the current unexpired claim and a delay of 0–300000ms; it immediately invalidates the old token. Stale, expired, delivered and foreign-environment tokens return false. Generation counters also advance on retry, so they are not exact attempt counts. Restrict these operations to trusted workers/operators; they do not authenticate callers. A deferred retry appears as leased until its database deadline, even though the previous worker has released ownership.

Delivery is at least once. ACK only after durable acceptance; destination effects must be idempotent by (environmentId, eventId). Executor errors propagate. If a worker crashes or cannot release its lease, normal claim recovers after expiry. Size batches and leases to finish delivery before expiry; lease renewal is not provided. Do not hold business transactions during delivery.

Receipts and all outbox rows are retained indefinitely, including delivered rows. Explicit quarantine/requeue is described below; deletion, scheduler and HTTP/console routes remain outside this API. Permanent failures remain pending unless explicitly quarantined. Exhausted generation counters remain visible but cannot be reclaimed; operators must investigate rather than reset fencing history.

Quarantine and explicit operator recovery

Stop and drain all old outbox workers before running the explicit protected-write migrations, then start only upgraded workers. The additive <prefix>_dead_v1 table leaves the original event and receipt schemas intact. Old workers do not consult quarantine state, so mixed-version delivery or rollback to old workers with active quarantines is unsupported. New worker operations fail closed when the side table is missing. Apply the existing migration API through the application’s migration owner; construction does not migrate. PostgreSQL’s generated migration step now ends in :v1:quarantine-v1:relation-admission-v1:operator-history-v1; SQLite validates and adds the new side-table definition.

The environment-wide operator below must be authenticated and authorized by your application. This uses an exact-event inspection lease so even a payload that normal claim cannot decode can be quarantined. It never steals an existing lease; allow that lease to expire first.

import { createSqliteProtectedWriteOutbox, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite";
declare const executor: ParameterizedSqliteExecutor;
const operator = createSqliteProtectedWriteOutbox({
  executor, tablePrefix: "app_authorization", environmentId: "production",
});
declare const eventId: string;
const lease = await operator.claimForInspection({ eventId, leaseMs: 30_000 });
if (lease) {
  const quarantine = await operator.quarantine(lease, { reason: "destination-rejected-event" });
  // undefined means the lease is no longer eligible; inspect current state before proceeding.
}
const deadLetters = await operator.inspectDeadLetters({ limit: 100 });
// In a separate authorized recovery action, after resolving the cause:
declare const approvedForRequeue: boolean;
const selected = deadLetters.find((event) => event.eventId === eventId);
if (approvedForRequeue && selected) {
  const requeued = await operator.requeue(selected.quarantineToken);
  // true makes the original event available for ordinary claim; it does not deliver it.
}

Quarantine requires a current unexpired token and a nonblank 1–1024-character reason with no NUL; it advances the generation, clears the lease and persists the quarantine atomically. Never put credentials or whole payloads in the reason. Requeue requires the exact active quarantine token and advances the generation again. Old ACK, retry and operator tokens cannot act on later state. Foreign-environment tokens are rejected. Worker limits remain 1–1000 records and 1–300000ms leases. Quarantine reserves headroom for requeue and a subsequent claim; generations at or above 9223372036854775805 cannot be quarantined. Counters are never reset or wrapped.

Dead-letter inspection omits payload decoding and returns immutable identity, kind, reason, time and token. It is a bounded oldest-active snapshot, not pagination or an authentication boundary. The side row retains the latest quarantine/requeue state per event; it is not a full history of operator actions; the separate history log records successful post-upgrade transitions. Pending inspection excludes quarantined events; use dead-letter inspection for them. Neither operation changes or deletes the original payload or receipt.

A crash before quarantine leaves ordinary lease expiry/reclaim in effect. A committed quarantine persists until explicit requeue; inspection recovers its token after a lost acknowledgment. An absent active quarantine is not proof of delivery. Serialization/busy/connection failures propagate without automatic replay. PostgreSQL can commit a normal claim’s lease before payload decoding fails; SQLite rolls its claim transaction back. Inspection leasing must respect any remaining live lease in either case.

Quarantine cannot recall an external delivery already in flight. Destinations must continue to deduplicate by (environmentId, eventId) across requeue cycles. Requeue does not repair malformed payloads: resolve the producer/schema/decoder or destination cause first. No payload-edit, scheduler, automatic retry policy, route/console integration, retention expiry or deletion is added.

For callback-free single-resource deletion, use managed deletion. The raw update callback still cannot delete resources.

Retained operator-action history

After the explicit operator-history migration, every successful quarantine/requeue atomically appends a record to <prefix>_actions_v1. An append failure rolls back the transition. Stale, foreign, expired and exhausted tokens do not create successful records. Original events and receipts remain unchanged. The log is append-only through the library API, not tamper-evident against database administrators; there is no pruning, failed-attempt log or administrative UI.

Bind an optional operator: { type, id } when constructing the outbox worker. The factory copies this application-attested identity; authenticate and authorize it in the application first. Existing factories without an operator record null, never an inferred or authenticated actor. Both identity fields must be nonblank strings of at most 1024 characters with no NUL.

inspectOperatorActions({ eventId, limit, afterGeneration? }) returns immutable records for that event in the factory’s environment. Limit is 1–1000. Records include stable actionId, environmentId, eventId, resulting decimal generation, action, nullable operator, nullable reason and ISO recordedAt. Requeue reasons are null. Times describe the transition inside the transaction, not exact COMMIT time. The exclusive cursor defaults to "0"; use the last returned generation for the next page. Pagination follows numeric generation, so clock changes cannot skip records. Gaps are normal. This is a live per-event traversal, not a frozen or cross-event feed. Malformed records fail closed; inspection does not decode the event payload.

Stop/drain old operator binaries, run the explicit migration, then start upgraded workers only. The additive table retains previous schemas and data. History starts at this rollout: existing quarantines have no fabricated historical action. Their later requeue is recorded. An empty history cannot prove there were no pre-upgrade actions. Mixed-version operators can leave gaps and are unsupported. Record the rollout boundary in application operations records.

import { createSqliteProtectedWriteOutbox, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite";
declare const executor: ParameterizedSqliteExecutor;
// Obtain this identity only after application authentication and operator authorization.
declare const trustedOperator: { type: string; id: string };
declare const eventId: string;
const worker = createSqliteProtectedWriteOutbox({
  executor, tablePrefix: "app_authorization", environmentId: "production",
  operator: trustedOperator,
});
const firstPage = await worker.inspectOperatorActions({ eventId, limit: 100 });
const last = firstPage.at(-1);
if (last) {
  const nextPage = await worker.inspectOperatorActions({
    eventId, limit: 100, afterGeneration: last.generation,
  });
}

Stored-text fidelity in managed operations

Managed updates, batch entries, deletion pre-state and moves validate stored text before calling the application resource projection or evaluating policy. The check covers the complete configured projection, including keys, versions and policy attributes that are not writable patch fields. A value that the driver has shortened or otherwise changed fails closed; it is never silently normalized into a different policy value. Generated-write post-state and batch final reloads use the same loader. Rejection rolls back the business write and its receipt/event together. Exact retained receipt replay still occurs before current schema or authorization checks.

SQLite first reads ASCII-safe SQL hex/storage-class evidence and the main database encoding. It strictly validates UTF-8, UTF-16LE or UTF-16BE before fetching raw text, then compares the decoded value to the physical bytes. This prevents malformed encoded text from reaching native libSQL decoding. Valid Unicode and null/empty values remain supported. Embedded NUL is accepted when faithfully represented by the driver (Bun SQLite); local libSQL truncation is rejected. Literal BOM characters are not stripped by the fidelity validator. Database/driver transformations during a generated write still must satisfy the existing exact postcondition; they are not repaired.