RolebookDocs

SQLite concurrency, fences, and lifecycle

BEGIN IMMEDIATE, busy retries, identity fences, teams, initialization, deletes, and moves on SQLite.

Concurrency model

SQLite has one writer per database file. Every sharing mutation, initialization, and lifecycle transaction runs in BEGIN IMMEDIATE. Inside it the adapter re-reads the resource row, compares the expected resource version and sharing revision, runs the identity fences against the authoritative rows, writes, increments the revision with an exact compare, records the idempotency key and fingerprint, and appends the audit event. A mutation commits completely or not at all.

Reads (readAccess, readAccessBatch) run in a deferred transaction: in WAL mode one consistent snapshot that never blocks a writer.

SQLITE_BUSY (and its extended codes, plus SQLITE_LOCKED_SHAREDCACHE) means another connection holds the lock. The adapter retries the whole unit of work: busyRetry.attempts (default 10, at most 100, including the first) with capped, fully jittered backoff of 0 to min(100, 5 x 2^(retry - 1)) ms; backoffMs(retry) (0 to 1,000 ms) and wait(ms) replace the schedule and the timer. isRetryableBusyError() recognizes bun:sqlite, better-sqlite3, libSQL, and node:sqlite error shapes, also wrapped in a cause. Retries are safe because every mutation is idempotent.

Limits of the model:

  • Throughput is one writer per file. Keep transactions short and slow work (network calls, token delivery) outside them.
  • The identity fence holds only for identity tables in the same database file, or in a schema ATTACHed on every writing connection. A remote identity API cannot be fenced; use subject-bound invitations.
  • Writers outside SQLite’s locking (another file copy, a backup restore, a sync engine rewriting rows) are not serialized.
  • Without a clock, membership expiry uses the adapter process’s clock and invitation expiry the SQLite host’s 'now'.
GuaranteePostgreSQLSQLite
Mutation isolationSERIALIZABLE plus row locksBEGIN IMMEDIATE: one database-wide writer
Retried errors40001, 40P01; 3 attempts, 50 ms capSQLITE_BUSY*, SQLITE_LOCKED_SHAREDCACHE; 10 attempts, 100 ms cap
Remote serversupportedrefused
Resource ID typestext or uuidTEXT only, BINARY collation
Key changes outside a moverefused by ON UPDATE RESTRICT (23001)refused by the key guard trigger
Foreign keysalways enforcedper connection; writes refuse to run without them
lower_trim emailUnicode-aware LOWERASCII-only lower()

Fences

The SQLite fences mirror the PostgreSQL ones and run under the write lock:

import {
  createSqliteEmailInvitationRecipientFence,
  createSqliteMembershipEligibilityFence,
  createSqliteWorkspaceRoleAuthorizationFactFence,
} from "@rolebook/sharing-sqlite";
import { BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT } from "@rolebook/sharing-better-auth";

const lockEligibleSubjects = createSqliteMembershipEligibilityFence({
  table: "member",
  tenantColumn: "organization_id",
  subjectIdColumn: "user_id",
});

const lockInvitationRecipient = createSqliteEmailInvitationRecipientFence({
  membershipTable: "member",
  membershipTenantColumn: "organization_id",
  membershipSubjectIdColumn: "user_id",
  userTable: "user",
  userIdColumn: "id",
  userEmailColumn: "email",
  userEmailVerifiedColumn: "email_verified",
});

const revalidateAuthorizationFacts = createSqliteWorkspaceRoleAuthorizationFactFence({
  table: "member",
  tenantColumn: "organization_id",
  subjectIdColumn: "user_id",
  factType: BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT,
  memberIdColumn: "id",
  roleColumn: "role",
});

Every shipped fence matches identity rows in SQL and then compares the matched columns, read back as text, exactly in JavaScript: a TEXT COLLATE NOCASE or INTEGER identity column would otherwise match another spelling. A second matching row, a NULL, or a non-string value fails closed. The email fence’s lower_trim uses SQLite’s lower(trim(...)), which folds only ASCII letters: store addresses normalized, or use exact, when they may contain other letters.

revalidateAuthorizationFacts decides the mutation after the eligibility fence: true proceeds, "conflict" rolls back and lets the sharing module re-authorize, anything else is identity_ineligible. Without it, a mutation carrying authorization facts fails closed and the adapter warns once.

Teams on SQLite

@rolebook/teams ships team fences for PostgreSQL only. With withTeams() on SQLite, configure team-aware fences that read your team tables in the adapter’s transaction:

  • lockEligibleSubjects must verify that a team grant target is a team of the tenant and refuse any team listed in ownerCandidates;
  • revalidateAuthorizationFacts must check that every rolebook.teams.team-member.v1 fact still matches a team-membership row, and that every rolebook.teams.team-set.v1 fact equals encodeTeamSet() of the subject’s teams read again, returning "conflict" when it does not. Membership facts whose subject has no team-set fact must be refused.

The Teams package’s SQLite contract suite (packages/teams/tests/sqlite-contract.integration.test.ts) shows SQLite equivalents. Run sharingTeamsContract against yours.

Nested lineage is separate from those flat fences. Configure it with @rolebook/teams/sqlite and the adapter’s groupGraph option, as in the teams guide. Flat withTeams() stays the direct-membership wrapper.

Lifecycle

Create the application row and its owner in the same BEGIN IMMEDIATE transaction:

import { withImmediateTransaction, type ParameterizedSqliteExecutor, type SqliteSharingAdapter } from "@rolebook/sharing-sqlite";

declare const executor: ParameterizedSqliteExecutor;
declare const projectAdapter: SqliteSharingAdapter;
const user = { type: "user", id: "user_123" };

const result = await withImmediateTransaction(executor, async (transaction) => {
  await transaction.query("INSERT INTO project (workspace_id, id, title, version) VALUES (?, ?, ?, 1)", [
    "ws_456",
    "project_1",
    "Q3 launch",
  ]);
  return projectAdapter.initializeResourceInTransaction(transaction, {
    tenantId: "ws_456",
    resourceId: "project_1",
    owner: user,
    actor: user,
    occurredAt: new Date(),
  });
});

initializeResource() opens its own transaction for existing resources. Results, the owner checks, and the revision-floor rule are those of the PostgreSQL adapter; the error is SqliteLifecycleConflictError. asImmediateSqliteTransaction() asserts that a transaction your driver opened is BEGIN IMMEDIATE.

Deletes and moves go through withLifecycleTransaction() and resourceDeletedInTransaction() or resourceMovedInTransaction(), with exactly the PostgreSQL semantics: the callback performs a conditional change with the pre-version, a cross-tenant move keeps only the destination-eligible owner, a non-applied result or a failed postcondition throws SqliteLifecycleConflictError and marks the transaction rollback-only, and the standalone resourceDeleted() and resourceMoved() return "unsupported". Callbacks must decide on RETURNING rows rather than change counts, because drivers disagree on whether change counts include cascades. Transactions handed to callbacks refuse transaction-control statements (BEGIN, COMMIT, ROLLBACK, SAVEPOINT, RELEASE).

Reads, cursors, and audit

Candidate cursors are ordered by the ID column with COLLATE BINARY; a cursor must be a non-empty string of at most 128 characters, or listCandidates() throws InvalidSqliteCursorError. IDs that cannot be issued as cursors (non-TEXT values, empty IDs, IDs over 128 UTF-16 units) are filtered in SQL before paging. No read uses *; without resourceColumns, an application-table read lists the table’s current columns from the catalog in the same transaction.

Audit pages, incarnations, event IDs, and row errors follow the PostgreSQL rules, with InvalidSqliteAuditCursorError for a refused audit cursor and SqliteSharingRowError for a row that does not decode. Pruning (pruneSettledRecords()) deletes each kind in its own BEGIN IMMEDIATE transaction.