Retention and pruning
Pruning settled idempotency records and invitations with pruneSettledRecords().
Two kinds of sharing rows otherwise only grow: the idempotency record every committed mutation writes,
and invitations once they are consumed, revoked, or expired. The memory, PostgreSQL, and SQLite adapters
each offer pruneSettledRecords() (the SettledRecordPruner interface) to delete them in bounded
batches. Audit rows, lifecycle idempotency records, and revision floors are never pruned: audit rows are
the access history, and a pruned revision floor could let a re-created resource repeat old revisions.
Pruning is maintenance, not a sharing operation: it runs no authorization, writes no audit event, bumps no
sharing revision, and never changes who has access. Call it only from trusted server code, such as one
scheduled job, never from a user request. It is not part of SharingAdapter, so a third-party adapter need
not implement it.
import {
DEFAULT_IDEMPOTENCY_RETENTION_MS,
DEFAULT_INVITATION_RETENTION_MS,
type SettledRecordPruner,
} from "@rolebook/sharing";
declare const adapter: SettledRecordPruner; // a memory, PostgreSQL, or SQLite sharing adapter
declare const log: { info(message: string, fields: Record<string, unknown>): void };
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
// Drain one kind at a time, and pause between batches to spread the write load.
const retention = {
idempotency: DEFAULT_IDEMPOTENCY_RETENTION_MS, // 30 days: keep it longer than any client's retry window
invitations: DEFAULT_INVITATION_RETENTION_MS, // 30 days: the retention the app owner chose
};
for (const kind of ["invitations", "idempotency"] as const) {
let result;
do {
result = await adapter.pruneSettledRecords({
scope: { allTenants: true }, // or { tenantId }; there is no implicit "all"
...(kind === "idempotency"
? { kinds: ["idempotency"], idempotencyRetentionMs: retention.idempotency }
: { kinds: ["invitations"], invitationRetentionMs: retention.invitations }),
limit: 500,
});
log.info("rolebook prune", { kind, cutoffs: result.cutoffs, deleted: result.deleted });
if (!result.exhausted) await sleep(250);
} while (!result.exhausted);
} Run exactly one such job, for example one daily scheduled task rather than a timer in every replica: concurrent runners pick the same oldest rows, so on PostgreSQL they collide and retry, and on SQLite they wait for each other. Alert when no run has succeeded for a couple of days.
The request
- Either pass neither
kindsnor a retention, and both kinds are pruned at their 30-day defaults (DEFAULT_IDEMPOTENCY_RETENTION_MS,DEFAULT_INVITATION_RETENTION_MS), or namekinds(["idempotency"],["invitations"], or both) and give a retention for each named kind and no other. Nothing falls back to a default by accident: a retention withoutkinds, or a named kind without its retention, isINVALID_INPUT, and a retention for a kindkindsleaves out isINVALID_RETENTION. PruneSettledRecordsInputis a union of those shapes (PruneWithDefaultsInput,PruneIdempotencyInput,PruneInvitationsInput,PruneBothInput), so TypeScript refuses the same mistakes. Buildkindsper branch as above: aSettledRecordKind[]read from configuration does not match a branch.scopeis{ tenantId }or{ allTenants: true }. To leave a tenant out, for example one under legal hold, prune tenant by tenant from your own tenant list. Prune or erase an offboarded tenant’s rows before removing it from that list.limit(1 toMAX_PRUNE_BATCH, 1,000) bounds the rows deleted per kind in one call, oldest first. Loop untilexhausted.- Retentions are at least one day (
MIN_IDEMPOTENCY_RETENTION_MS,MIN_INVITATION_RETENTION_MS) and at mostMAX_RETENTION_MS(100 years). The cutoff is the adapter’s clock (the database clock on PostgreSQL unless aclockis configured) minus the retention;result.cutoffsreports it. - A pending invitation that has not expired is never deleted, whatever the retention.
- An unknown key, or an optional key present but
undefined, isINVALID_INPUTrather than ignored.
A call it will not run throws before anything is deleted. A bad request throws RetentionError (a
RangeError with code INVALID_INPUT, INVALID_SCOPE, INVALID_LIMIT, INVALID_RETENTION, or
RETENTION_TOO_SHORT): map it to a client error. A database not ready to prune throws
RetentionSchemaError (an Error with code SCHEMA_NOT_UPGRADED): the idempotency table predates its
created_at column, has a created_at of the wrong type, lacks a valid index for pruning, or on PostgreSQL
has no DEFAULT now(). Running the adapter’s migrations fixes a missing column, index or default; a wrong
column type must be repaired explicitly first (a rerun rejects that drift), and on PostgreSQL an INVALID
index left by a failed CREATE INDEX CONCURRENTLY must be dropped first. Alert an operator.
Pruning leaves no record of its own. Log every call’s scope, cutoffs, and counts from the job if you need evidence of retention. The SQL adapters delete each kind in its own transaction, so a call can throw after its idempotency batch committed; the next call simply continues.
What pruning changes
- Idempotency. A retry whose record was pruned is no longer recognized: it runs as a new command, re-authorized against current state. A grant retried after a later revocation grants again; an ownership transfer retried after a transfer back moves ownership again. Keep the retention longer than every client’s retry window, offline outboxes included. After pruning, one idempotency key can name two commits in the audit rows.
- Invitations. On
createSharing(), a retried acceptance replays asALREADY_APPLIEDonly while both its invitation and its idempotency record are kept, and answersINVITATION_UNAVAILABLEonce either is pruned. An expired invitation answersINVITATION_EXPIREDwhile its row is kept andINVITATION_UNAVAILABLEafter, so offer “ask for a new invitation” on both codes.createVersionedSharing()replays from the idempotency record alone.
Invitation rows hold recipient email addresses, so the invitation retention is also a data retention
decision. Pruning is not an erasure mechanism: a pending invitation keeps its address until it expires and
its retention passes (revoke it and prune to remove it sooner), the issueInvitation idempotency record
holds a keyed digest of the command including the email and follows the idempotency retention, and audit
rows keep actor and subject identifiers and are never pruned.
For adapter authors
capturePruneSettledRecordsInput (returns a PruneSettledRecordsRequest), pruneCutoffs, pruneResult,
and invitationSettledBefore are exported so a custom adapter implements SettledRecordPruner with exactly
the same validation and rules. See the API reference.