@ultimat3/jobs
v31.58.0
Published
Durable background work: steps, transactional outbox, cron tasks, one driver interface
Maintainers
Readme
@ultimat3/jobs ⚙️
Durable background work. Steps that replay, a transactional outbox, and one driver interface so a job's code never names a backend.
bun add @ultimat3/jobs · guide: Jobs And Workflows
import { job, t } from '@ultimat3/jobs';
import { type AnyMailDefinition } from '@ultimat3/mail';
declare module '@ultimat3/core' {
interface CtxServices {
readonly orgs: {
provision(id: string): Promise<{ id: string; name: string }>;
byId(id: string): Promise<{ id: string; name: string }>;
};
readonly mail: { send(mail: unknown, to: unknown): Promise<void> };
}
}
declare const welcomeEmail: AnyMailDefinition;
declare const nudgeEmail: AnyMailDefinition;
export const onboardOrg = job({
input: t.object({ orgId: t.uuid }),
idempotencyKey: ({ orgId }) => `onboard:${orgId}`, // REQUIRED by the type
tenant: ({ orgId }) => orgId, // REQUIRED by the type — or tenant: 'none'
retry: { attempts: 5, backoff: 'exponential' },
async run({ input, step, ctx }) {
const org = await step.run('provision', () => ctx.orgs.provision(input.orgId));
await step.run('welcome-email', () => ctx.mail.send(welcomeEmail, org));
await step.sleep('3d');
await step.run('nudge', () => ctx.mail.send(nudgeEmail, org));
},
});welcome-email fails? Attempt 2 replays provision from storage and re-sends only the
email. The 3-day sleep does not hold a process: the run suspends and the queue redelivers it.
The handle is the surface
import { type JobHandle, type TaskHandle } from '@ultimat3/jobs';
import { type Ctx } from '@ultimat3/core';
declare const orgId: string;
declare const nightlyDigest: TaskHandle;
declare const onboardOrg: JobHandle<{ orgId: string }>;
declare const ctx: Ctx;
await onboardOrg.enqueue({ orgId }); // joins the ambient transaction
await onboardOrg.as(ctx.actor, { orgId }); // same, tenantId stamped from the actor
onboardOrg.describe(); // the manifest row for this job
await nightlyDigest.enqueue(); // fire a task's entries now
nightlyDigest.describe(); // { kind: 'task', cron, tz, jobs, … }| Member | On | Behaviour |
|---|---|---|
| enqueue(input, options?) | JobHandle | queues through jobsFacade(); joins the caller's tx when the outbox is installed. Answers { id, runId, deduped } — the job's own ids on every path, staged or direct. options.runId names the run instead of having one minted |
| enqueueMany(inputs, options?) | JobHandle | many of one job: one round trip per 1,000 inputs (a statement on Postgres, a script on Redis) on the same path enqueue takes, answered in input order. At most MAX_ENQUEUE_BATCH (10,000, else X_JOB_ENQUEUE_BATCH_TOO_LARGE); EnqueueManyOptions is EnqueueOptions without runId, onConflict or expiresAt. A loop of enqueue is X_N_PLUS_ONE_WRITE, whose fix names this call. JobDriver.enqueueMany is required of every driver (it opens with assertEnqueueMany: onConflict: 'error' or 'replace' and expiresAt are refused in a batch); OutboxStore.stageMany / markPublishedMany are optional: absent, the facade and the relay loop |
| as(actor, input, options?) | JobHandle | enqueue on behalf of an actor — fills tenantId from actor.orgId so per-tenant limits apply |
| describe() | JobHandle | the JobDescriptor the manifest, /_x and MCP read |
| entries() | TaskHandle | the declared [job, input] pairs |
| enqueue(options?) | TaskHandle | fires every declared entry now, one result per entry |
| describe() | TaskHandle | TaskDescriptor — cron, tz, catch-up, jobs in declaration order |
Debounce, expiry, back-pressure and the body's lease
Four mechanisms an app used to rebuild around the queue, each one field As of 2026-11:
| Ask | Spelling | What happens |
|---|---|---|
| debounce | enqueue(input, { onConflict: 'replace', runAt }) | a row of the job still WAITING (ready/delayed) under the same idempotency key takes the new input and runAt in one statement per driver (SQL_ENQUEUE_REPLACE); a running or suspended holder is past replacing. Answered deduped: true with the holder's ids either way. The holder takes the newer request's expiresAt too, or loses its own when the newer names none. Fenced by request order (x_jobs.debounced_id, the request's uuidV7): a replace no newer than the input a row of the key holds — live or finished — moves nothing and starts no run, so an outbox row published again after a relay crash never puts old input back |
| expiry | enqueue(input, { expiresAt }) | epoch ms past which the work is worthless: the claim that finds the row waiting after then settles it failed, lastError JOB_EXPIRED ('expired'), and reports it beside the burials (ClaimOptions.onExhausted), so its onSettled hears dropped — at least once: the claim records the debt in the same write. Only a row never claimed (attempt 0) expires: a started run — a retry waiting out its backoff included — is never expired. x jobs retry clears it. Lazy: no index, no sweep |
| back-pressure | job({ maxPending }) | an enqueue onto a queue already holding that many ready/delayed rows is X_JOB_BACKLOG_FULL, a 429 (JobBacklogFullError); a batch that would cross it is refused whole. One capped count first (JobDriver.backlog), plus the rows the caller's own transaction already staged for that queue (a key staged twice counts once). An enqueue that adds no row — a dedupe, or a replace onto the key's live holder (JobDriver.holds, asked only once full) — is never refused. Soft across producers: concurrent ones can overshoot by their number, and committed rows the relay has not published yet are not counted. A driver without backlog refuses a job declaring it at enqueue (X_INVARIANT) |
| a long body | run({ lease }) | lease.renew() renews now and answers whether the attempt still holds the row — false once the lease is lost or the attempt's settle is sent; lease.lost(); lease.signal aborts on either. Call renew() between the chunks of a section longer than the visibility timeout — the renewal timer cannot fire inside it. A lock that outlives one job is withLock() |
onConflict: 'replace' and expiresAt hold inside a transaction too: the staged row carries both
(x_outbox.on_conflict, x_outbox.expires_at) and the relay publishes it alone through
driver.enqueue, in staged order, while the plain rows around it keep batching. Neither is an
enqueueMany option (assertEnqueueMany
refuses both in a driver batch). lease is optional on JobRunArgs so a test that drives a body by
hand need not build one; the worker always supplies it.
Fan-out per row is a job, not a task
A task's enqueue is synchronous by design — (occurrenceMs) => [[job, input], …] — and it
stays that way, As of 2026-09-05, for two reasons that are the same reason. describe() reads
entries() to project the task's job names into x.manifest.json, /_x and x tasks show, so an
enqueue that awaited a database would make the manifest an I/O operation; and a task that reads
the hosts table inside its tick is a task doing work, which the primitive's own header rules out.
So "one job per row" cannot be written in the task. It is written as one fan-out job:
import { job, t, task } from '@ultimat3/jobs';
declare const listHosts: () => Promise<readonly { readonly id: string }[]>;
declare const probe: (hostId: string) => Promise<void>;
// jobs/poll-host.ts — the unit of retry: one row
export const pollHost = job({
input: t.object({ hostId: t.uuid, occurrenceMs: t.number.int() }),
idempotencyKey: ({ hostId, occurrenceMs }) => `poll-host:${hostId}:${occurrenceMs}`,
tenant: 'none',
retry: { attempts: 3, backoff: 'exponential' },
async run({ input }) {
await probe(input.hostId);
},
});
// jobs/poll-hosts.ts — the fan-out: list the rows, enqueue one child per row
export const pollHosts = job({
input: t.object({ occurrenceMs: t.number.int() }),
idempotencyKey: ({ occurrenceMs }) => `poll-hosts:${occurrenceMs}`,
tenant: 'none',
retry: { attempts: 3, backoff: 'exponential' },
async run({ input, step }) {
const hosts = await step.run('list', () => listHosts());
for (const host of hosts) {
// One step per child, keyed by the row: a replayed attempt re-enqueues nothing it already did.
await step.run(`enqueue:${host.id}`, () =>
pollHost.enqueue({ hostId: host.id, occurrenceMs: input.occurrenceMs }),
);
}
},
});
// tasks/poll-fleet.ts — the tick hands its instant to ONE job
export const pollFleet = task({
cron: '*/5 * * * *',
tz: 'UTC',
enqueue: (occurrenceMs) => [[pollHosts, { occurrenceMs }]],
});| Piece | Why it is this piece |
|---|---|
| the task enqueues one job | the tick stays cheap and deterministic; describe() names pollHosts and nothing else |
| the fan-out is a job | it reads the database, so it gets a queue row, retries, a trace and x jobs show — a task gets none of those |
| one step.run per child | at-least-once delivery would otherwise enqueue every child again on a replay; the step's name is the row's id, so the second attempt skips the ones that landed |
| the child is its own job | retry, concurrency and the dead-letter path are per row — one host being down must not retry the other forty. webhook() is the same shape: one event, one endpoint, one job |
| the child's idempotencyKey carries occurrenceMs | the same row for the same tick is one row in the queue however many times the fan-out replays |
webhook() below is this pattern shipped as a factory; a fleet poll, a per-tenant digest and a
per-subscriber notification are the same three files with different names.
One job per org, from a schedule
The per-tenant form of the same fan-out, and the three things it has to say that the untenanted one does not: the schedule belongs to no org, listing the orgs is a read across tenants, and each child runs as its org.
import { serviceActor, withChildContext } from '@ultimat3/core';
import { CROSS_TENANT_SCOPE, crossTenant } from '@ultimat3/entity';
import { cronJob, job, t } from '@ultimat3/jobs';
// A read over a tenant-scoped table — `db.orgs.orderBy('id').inBatches(500)`, collected to ids.
declare const listOrgIds: () => Promise<readonly string[]>;
declare const sendDigest: (orgId: string) => Promise<void>;
// The scheduler is no org's actor, so it names itself and holds the one scope `crossTenant()` asks.
const digestScheduler = serviceActor({ id: 'digest-scheduler', scopes: [CROSS_TENANT_SCOPE] });
// jobs/org-digest.ts — the unit of retry: one org, and the run acts AS that org
export const orgDigest = job({
input: t.object({ orgId: t.uuid, occurrenceMs: t.number.int() }),
idempotencyKey: ({ orgId, occurrenceMs }) => `org-digest:${orgId}:${occurrenceMs}`,
tenant: ({ orgId }) => orgId,
retry: { attempts: 3, backoff: 'exponential' },
async run({ input }) {
await sendDigest(input.orgId);
},
});
// jobs/org-digests.ts — the schedule and the fan-out, one declaration
export const orgDigests = cronJob({
name: 'orgDigests',
cron: '0 6 * * *',
tz: 'UTC',
input: t.object({ occurrenceMs: t.number.int() }),
payload: (occurrenceMs) => ({ occurrenceMs }),
idempotencyKey: ({ occurrenceMs }) => `org-digests:${occurrenceMs}`,
tenant: 'none',
retry: { attempts: 3, backoff: 'exponential' },
async run({ input, step }) {
const orgIds = await step.run('list', () =>
withChildContext({ actor: digestScheduler }, () =>
crossTenant('the daily digest queues one job per org, so listing them spans every org', () =>
listOrgIds(),
),
),
);
for (const orgId of orgIds) {
await step.run(`enqueue:${orgId}`, () =>
orgDigest.enqueue({ orgId, occurrenceMs: input.occurrenceMs }),
);
}
},
});| Piece | Why it is this piece |
|---|---|
| tenant: 'none' on the cron job | a schedule has no org; its body carries none, so a tenant-scoped read in it is X_TENANCY_ACTOR_ORG_REQUIRED until it says it spans tenants |
| serviceActor({ scopes: [CROSS_TENANT_SCOPE] }) | crossTenant() proves tenancy:cross on the actor in scope and a job's own actor does not hold it (X_TENANCY_CROSS_DENIED). The sweep names itself, once, at module scope |
| withChildContext, not a new context | the run's requestId and trace carry through, so the one cross-tenant read is auditable back to the occurrence that asked for it |
| crossTenant() around the LIST only | the enqueues need none: the cron job's actor has no org, so there is nothing for the payload's org to contradict |
| tenant: ({ orgId }) => orgId on the child | each row is queued under the org its payload names and executeJob installs that org's actor: every read and write in sendDigest is scoped to it, and two orgs' identical keys are two jobs |
The export name is the job's name
import { type ApiModule, defineApi } from '@ultimat3/action';
declare const postJobs: ApiModule;
declare const orgJobs: ApiModule;
declare const scheduledTasks: ApiModule;
export const api = defineApi({
jobs: [postJobs, orgJobs], // module namespaces, never a list of name strings
tasks: [scheduledTasks],
});defineApi hands each module to registerJobs/registerTasks, which stamp the export name
onto the handle the module exported and re-key the registry — import { onboardOrg } is the
object enqueue() routes through after boot, not a renamed copy of it. Hand nothing over and a
job keeps the positional name job() gave it: anonymous-job-2 on the queue row, in
x.manifest.json and in every dead-letter trace, appearing in no source file.
A definition that sets name: keeps it. A job name is the durable queue key that queued,
retrying and dead-lettered rows already carry, so renaming an export must never move where they
are delivered — @ultimat3/mail's mail.send relies on exactly that.
Registering the same handle twice is one registration seen twice, because defineApi and the
framework's module scan both reach the same declaration file. Everything else that puts two
things on one durable name is X_JOB_DUPLICATE, refused at the earliest point it is decidable:
| Collision | Refused at |
|---|---|
| two definitions setting the same name: | job() / task(), before either can seat the other out |
| two different handles under one export name | defineApi |
| one handle exported twice (export { notify as a, notify as b }) | defineApi — the second alias would move the queue key |
registerJobs/registerTasks are internal: defineApi reaches them through core's registrar
table, and they are not part of this package's public API. There is one way to register.
.as() queues; it never runs the handler inline. A job's execution surface is the queue,
so an inline run would be a second execution path next to the worker's — with no retry, no
dedupe and no dead letter. Its idempotency key is the job's own, so a manual task.enqueue()
and the scheduler's occurrence-scoped fire stay distinct rows on purpose.
One entry the scheduler cannot queue fails the whole occurrence (As of 2026-11): a tenant()
that throws or answers empty, or an empty concurrency key, on any entry of a task's enqueue.
Nothing is queued and the watermark stays; jobs.scheduler.entry-refused (error) names the task,
the job and the entry index. The next tick owes the same occurrence and logs it again, until the
declaration or the data is repaired — then that tick queues every entry. Never a partial fire.
With no facade installed, enqueue publishes straight to jobDriver(); with none of those
either, it is X_DRIVER_UNAVAILABLE at the call, not a silently dropped job.
idempotencyKey is required by the type
Not a convention, not a lint rule — a non-optional field on JobDefinition. Queues deliver
at least once (partition, lease expiry, outbox replay), so every job is asked "have you
already run?" whether or not its author thought about it. Optional means the answer is
usually "nobody thought about it", and the bug — two charges, two welcome emails, two
provisioned orgs — shows up in production under load and never in a test. There is no way
to define a job in Ultimate that cannot be deduped.
tenant is required by the type
The same shape, for the same class of bug. A job body runs with no request behind it, so nothing
can read the acting org off a caller — and @ultimat3/entity's tenant guard derives from the
ambient context, so a job that declared nothing used to run with no tenant at all: a row naming
another org was refused over HTTP as X_TENANCY_ACTOR_MISMATCH and accepted through the queue.
tenant: (input) => input.orgId // the run acts under this org
tenant: 'none' // this job belongs to no tenantexecuteJob derives the org, puts it on the run's actor and installs that context, so
ctx.actor.orgId inside the body is the tenant the job declared — and every tenant-scoped read and
write is checked against it, exactly as it is on every other surface. 'none' carries no org,
so a tenant-scoped read inside such a job() is X_TENANCY_ACTOR_ORG_REQUIRED: a job body that
genuinely spans tenants says so with crossTenant(reason, fn) around its own reads. (A
backfill() is the one exception, and it is not a loophole — its source is a lazy chain, so the
author has nothing to wrap and the pass opens the scope itself. See the backfill section below.)
Omitting the field is a type error, and
X_JOB_TENANT_REQUIRED for generated code and JS callers.
The declared tenant is checked at the enqueue. A payload whose tenant(input) names org A,
enqueued with tenantId B — explicitly, or by .as(actorOfB, …) — or under an ambient actor of
org B, is X_JOB_TENANT_MISMATCH before anything is staged, on enqueue and enqueueMany. A row
already queued that way is refused at its run, terminally, before the body. An actor with no org,
and tenant: 'none', are never compared. The ambient half has one escape, @ultimat3/entity's:
inside crossTenant('<why>', () => onboardOrg.enqueue({ orgId: newOrg })), by an actor holding
tenancy:cross, the enqueue is admitted (read through entity's own write guard, re-proved at the
call). An explicit tenantId or .as() that contradicts the payload is never admitted.
A row is queued for the org its payload names when the enqueue states none: a plain
enqueue(input) stamps tenant(input), so two orgs' identical idempotency keys are two jobs and
perTenant / ratePerTenant count the org. An explicit tenantId or .as() still wins — and the
refusal above guarantees they agree.
A single boot-supplied service actor would have closed the same hole with one identity for every job in the app — which is a cross-tenant read waiting for the first job that takes an org id in its input. The tenant is a fact about the work, so the job declares it.
Durable steps
| Call | Behaviour |
|---|---|
| step.run(name, fn) | runs once ever; result persisted before the next step starts, and it answers what it persisted: StepOutput<T>, the JSON form, on every attempt. fn receives an AbortSignal |
| step.run(name, fn, { compensate }) | compensate(output, { signal }) undoes it if the run fails FOR GOOD; needs job({ compensates: true }) |
| step.run(name, fn, { once: true }) | at most once: started persisted before fn; a replay without completed is terminal X_STEP_OUTCOME_UNKNOWN |
| step.sleep(name, '3d') | suspends the run, requeues it for the wake time |
| step.sleep('3d') | same, step name derived from the duration |
| step.waitForEvent(name, event, { schema, match, timeout }) | suspends until publishEvent() matches; answers the payload parsed by the required schema |
| A step answer | Is |
|---|---|
| a Date, anything with a toJSON() | what that returns: new Date(value) at the read, a compile error otherwise |
| undefined, a function or a symbol at the top, or in an array | null: compare === null |
| undefined or a function on a member | absent |
| a bigint, a cycle | X_STEP_OUTPUT_UNSERIALIZABLE, terminal: String(id), the ids rather than the object graph |
| more than a declared job({ stepOutputMax }) bytes of JSON | X_STEP_OUTPUT_TOO_LARGE, terminal, nothing stored: every attempt loads every output of its run, so persist the payload and return its key or cursor |
| more than STEP_OUTPUT_MAX_BYTES (256 KiB), no stepOutputMax declared | stored, and logged once per job and step: jobs.step.output-too-large, code: 'X_STEP_OUTPUT_TOO_LARGE', with the fix. Refused by default from the next major |
| a stored event the wait's schema refuses | X_JOB_EVENT_INVALID, terminal, on a hit or a replay. The error carries the issues, never the payload |
A boot's bus runs on the open transaction's connection (currentTx() ?? client, as the outbox):
publishEvent inside a transaction commits and rolls back with it. An event committed after a
wait began is that wait's, whatever its stamp. published_at is the INSERT's time and the row is
visible at COMMIT, so a new wait records the snapshot it began under (EventLookup.mark(),
SQL_EVENT_MARK, persisted on the waiting step) and also matches every event whose transaction
(x_job_events.xact) that snapshot could not see. A rolled-back publish matches nothing. A
waking bus published inside withTransaction wakes again once it COMMITS (SQL_EVENT_COMMIT_WAKE,
run from Tx.onCommit on the pool): a run that parked while the transaction was open is resumed
at the commit, not at the 15 min backstop.
Events are consumed in (published_at, id) order, stamps truncated to the millisecond; the cursor a
refused event leaves is that pair, compared and never looked up (events-cursor.ts, both buses),
so a purged cursor still excludes what it excluded. A refusal only moves it FORWARD, under the
horizon of the search that found the event; an event refused behind it (owed through the horizon)
is excluded by id. The wait's own line — startedAt and the mark's horizon (EventSince) — rides
every search and is never moved by a refusal, so no event committed before the wait is handed out.
resetEventBus() is the test seam beside resetJobDriver(), both on @ultimat3/jobs/adapter: an
event is matchable until it expires, so on a bus shared by one bun test process an answer one test published resumes the
next test's wait — call it between tests.
The event bus has ONE clock. postgresEventBus({ executor }) stamps publishedAt and the expiry
with the database's now() — it takes no clock — and bus.now() answers that same clock. A
consumer that wants "published after I asked" (@ultimat3/scraping's eventPrompt) reads its
"asked at" from bus.now(), never from its own process: a skew between two pods must not decide
which answers count. step.waitForEvent stamps a new wait from that clock (EventLookup.now(), required) and asks it
again before declaring a timeout, so a worker running ahead of the database still matches an event
published after it asked and does not give up early. eventsPurgeTarget(bus) is the bus as a
purge() target: purgeExpired() is awaited and answers the rows it removed.
A publish wakes its waiters on postgresEventBus({ executor, wakes: true }) — what boot
installs over its own postgresJobDriver: SQL_EVENT_PUBLISH_WAKE inserts the event, makes every
suspended run with a matching waiting step due, and notifies each of their queues, in ONE
statement (a rollback undoes all three; x_job_steps_waiting_idx keeps it a seek). A waiting step
then parks for WAKING_EVENT_POLL_MS (15 min) — the backstop and the timeout's clock — instead of
DEFAULT_EVENT_POLL_MS (30 s), and asks find once more after writing waiting, so an event
committed in between is not left to the backstop. A declared eventPoll wins.
Compensation and once
import { job, t } from '@ultimat3/jobs';
type Order = { readonly orgId: string; readonly orderId: string };
declare function charge(order: Order): Promise<{ id: string }>;
declare function refund(chargeId: string): Promise<void>;
declare function ship(order: Order): Promise<void>;
declare const vendor: { pay(order: Order): Promise<void> };
export const checkout = job({
input: t.object({ orgId: t.uuid, orderId: t.uuid }),
tenant: ({ orgId }) => orgId,
idempotencyKey: ({ orderId }) => `checkout:${orderId}`,
compensates: true,
retry: { attempts: 3 },
run: async ({ input, step }) => {
await step.run('charge', () => charge(input), { compensate: (c) => refund(c.id) });
await step.run('ship', () => ship(input));
await step.run('payout', () => vendor.pay(input), { once: true });
},
});| Rule | Behaviour |
|---|---|
| when | only once the run fails for good (!decision.retry); never a retry, cancel, drain or suspension |
| order | last-in first-out, each as step compensate:<name>, so a replay skips what ran |
| durable | unwinding is written first; any later attempt replays to its first incomplete step (UnwindReached) and unwinds — x jobs retry too |
| crash on the final attempt | rows are enqueued with UNWIND_MARGIN (2) attempts past retry.attempts (enqueuedAttempts); the claim re-offers the lapsed row and it unwinds |
| a compensator throws | handed back while the unwind has attempts; then dead, X_JOB_COMPENSATION_FAILED |
| once unknown | x jobs resolve-step <id> <step> --ran --output '<json>' or --not-ran (resolveJobStep), then x jobs retry <id> |
| reserved | unwinding, compensate:* as a body's step name: X_JOB_DECLARATION_INVALID |
Step names are the replay key, so they must be deterministic and unique in a run — a
duplicate is X_STEP_DUPLICATE, not a silent overwrite. Suspension is control flow
(StepSuspension), never a failure: it does not burn a retry attempt.
What a crash does to an effect left outside a step is proven, not reviewed: x exercise kills
every job it reaches at every step boundary (crashProof, @ultimat3/testing), and an effect a
killed run makes more often than a clean one is X_JOB_CRASH_DIVERGED, red in x verify. A job
test asks the same with crashProof(job, input).
Testing.
Rollups and materialized views are jobs
rollup({ name, into, table, key, lookback, bucket, source, map, tenant }) re-aggregates every
bucket from the one holding now - lookback on, read from that bucket's first instant in
bucket.timeZone, into the app's table with one upsertAll on key (a unique index on into, checked at
declaration: X_JOB_ROLLUP_INVALID). refreshView({ name, view, concurrently? }) refreshes a
materialized view entity (X_JOB_REFRESH_VIEW_INVALID). Both are factories over job(); the
schedule is the app's task. Reference: Jobs and workflows.
Backfills are jobs
backfill() is a factory over job(), not a ninth primitive — one pass over every row a
chain matches, with the retry policy, the queue, the cancellation and the dead-letter path a job
already has.
import { backfill } from '@ultimat3/jobs';
import { db } from '@postly/db';
export const rewriteSlugs = backfill({
name: 'rewrite-slugs', // REQUIRED: a durable key
batch: 1_000, // rows per statement and per step
rate: 5, // batches/sec — the default
tenant: 'none', // every tenant — the pass scopes itself
source: () => db.posts.where({ published: true }),
async handle({ rows }) {
await db.posts.upsertAll(rows.map(slugged), { onConflict: ['id'] });
},
});
await rewriteSlugs.enqueue({}); // it is a JobHandleThe source is read through inBatches() — one statement per page, keyset, never OFFSET — and
each page is handled inside its own step.run, named batch:0, batch:1, … A run killed
mid-pass therefore resumes on the page it stopped at: completed steps replay from storage
without a statement, and the iteration reopens at the cursor they left behind.
| Rule | Why |
|---|---|
| the checkpoint is a cursor and a count, never the page | a completed step's output is retained for the whole run — checkpointing rows would hold every processed row until the job ends |
| handle is given no step | a step name minted inside it collides with itself on batch 2 (X_STEP_DUPLICATE) |
| handle is given a signal | the run's deadline composed with the batch's own ceiling — hand it to whatever the body calls |
| handle runs at least once per page | an attempt cancelled between the last row and the checkpoint replays it — write through upsertAll / updateWhere, never count + 1 |
| idempotencyKey is the backfill's name | re-enqueueing a live pass is the same pass, not a second writer on one table |
| tenant is required, exactly as on job() | a backfill IS a job. tenant: () => orgId scopes every page to one org; tenant: 'none' sweeps every tenant, and the PASS opens that cross-tenant scope — source is a lazy chain, so the author has nothing to wrap |
| batch is refused at declaration | 0, 1.5 and a NaN from an env var fail the build, not the fourth attempt |
| rate throttles, and there is no way off | a sweep shares its pool with the requests the app is still serving; to go faster raise the number |
| the pause is spent inside the step | a resumed attempt replays 500 checkpoints and re-pays none of their pauses |
A remote source, and one pass per scope
pages: async ({ ctx, cursor, signal, input }) => ({ rows, next }) beside source — exactly one
of the two, or X_BACKFILL_SOURCE_INVALID. One page per step, checkpointed { cursor, rows: n };
next: null ends the pass. input + scope(input) makes one pass per scope: the ledger row and
the live idempotency key are <name>:<scope>. An input with no scope is refused.
The throttle
rate is batches per second, defaulting to DEFAULT_BACKFILL_RATE (5) — 5,000 rows/sec at the
default batch, one statement every 200ms, so the pool spends the rest of each interval on the
app. A rate above what the batches can actually achieve produces no wait, which is why there is
no unthrottled mode to reach for: rate: 200 is the fast sweep. Fractions are rates too
(rate: 0.5 is one batch every two seconds), a rate that is not finite and positive is refused
where it was written, and the wait unwinds on the run's cancellation (X_ABORTED) rather than
sitting in a timer nobody is waiting for. rate is not part of the definition checksum, for
the reason batch is not: pacing is tuning, and changing it does not make a completed sweep a
different sweep.
The x_backfills ledger
What has already been swept, the twin of x_migrations. It ships in the same DDL as x_jobs,
hangs off the queue driver as driver.backfills, and carries one row per pass: name,
definition checksum, status, app version, rows processed, last cursor, started/completed.
// The PASS is the no-op, never the enqueue. The one-live-run index covers `ready`/`delayed`/
// `running`/`suspended`, and a completed job is in none of them — so this creates a real job row,
// a worker runs it, it reads the ledger and reports what it found.
import { type JobHandle } from '@ultimat3/jobs';
declare const rewriteSlugs: JobHandle<{ force?: boolean }>;
const again = await rewriteSlugs.enqueue({}); // → { deduped: false, … }
// the run's own result:
// → { name: 'rewrite-slugs', batches: 0, rows: 0, skipped: true, previousRunId: '…' }
await rewriteSlugs.enqueue({ force: true }); // sweeps again, into a NEW row| Rule | Why |
|---|---|
| only a completed row blocks | a running row is this pass resuming, a failed one is an attempt the queue is about to retry |
| force writes a new row | reruns are history, never an edit of the row they rerun |
| a moved checksum warns | it hashes function source text, which a bundler moves without behaviour changing — @ultimat3/db throws on the same fact because SQL text is what it applied |
| the row is a report, never a resume source | where a resumed pass restarts is the step checkpoints' answer, and there is only one |
| a retry adopts its own row | started_at is when the pass began, not when this attempt did |
| a driver without a ledger runs the pass anyway | the same degradation introspect has — no bookkeeping, never a refusal |
Three surfaces read it, all through one projection (inspectBackfills()), so none of them can
report a different number:
| Surface | Shows |
|---|---|
| x db backfill --list | the whole ledger, --name / --status / --limit, and --json |
| x jobs list | the passes in flight — rows so far and cursor, beside the queue depth |
| x jobs show <id> | the ledger row for that run, under backfill (null for any other job) |
| /_x → jobs | the whole ledger plus a live count, alongside the queues and the step traces |
What was DECLARED — the other half of the ledger
As of 2026-08.
The ledger says which passes have run. registeredBackfills() says which ones exist, and the
diff between them is the alarm: a sweep merged, deployed and never enqueued had no row and showed
up on no surface at all.
import {
isBackfill,
type JobHandle,
pendingBackfills,
registeredBackfills,
} from '@ultimat3/jobs';
declare const rewriteSlugs: JobHandle<{ force?: boolean }>;
declare const runs: Parameters<typeof pendingBackfills>[0]['runs'];
declare const environment: Parameters<typeof pendingBackfills>[0]['environment'];
const declarations = registeredBackfills();
registeredBackfills(); // [{ kind: 'backfill', name, checksum, requires, environments, counts }]
isBackfill(rewriteSlugs); // true — a plain job() is false, and so is a look-alike
pendingBackfills({ declarations, runs, environment });
// → { environment, rows, pending, orphaned }backfill() stamps its own handle through the origin WeakMap task() already uses — an app
registers nothing, because a declaration that has to be registered a second time is a declaration
half the apps will forget. x db backfill --pending is the command, and it exits non-zero when
anything is unswept so a cron or a deploy check can read the exit code alone.
| State | Means | In pending |
|---|---|---|
| pending | declared, no row under this name | yes |
| failed | the newest pass failed — the queue may have dead-lettered it | yes |
| running | a pass is in flight | no — a check red for the whole of every sweep gets muted |
| completed | a completed row exists, so nothing re-runs without --force | no |
| excluded | environments does not include this one | no |
Three optional declarations, all of them DATA
import { backfill } from '@ultimat3/jobs';
import { database, entity, timestamp, uuid } from '@ultimat3/entity';
const posts = entity('posts', {
tenant: 'orgId',
columns: { id: uuid().primaryKey(), orgId: uuid(), publishedAt: timestamp().nullable() },
});
const db = database({ posts });
export const dropLegacy = backfill({
name: 'drop-legacy',
tenant: 'none', // required, exactly as on job() — see the table above
requires: '20260814120000_add_publish_at', // a migration id, checked against x_migrations
environments: ['staging', 'production'], // omitted = every environment
count: ({ ctx }) => db.posts.where({ publishedAt: null }).count(),
source: ({ ctx }) => db.posts.where({ publishedAt: null }),
handle: async ({ rows }) => { /* … */ },
});| Field | Rail | Enforced where |
|---|---|---|
| requires | X_BACKFILL_MIGRATION_PENDING — the migration is not applied | x db backfill, which is where x_migrations is readable; this package holds no @ultimat3/db dependency and will not grow one to read a ledger |
| environments | X_BACKFILL_ENVIRONMENT | the pass (backfillPass) — the rail, because .enqueue() from app code reaches no command — and again in gateBackfill() as the CLI's pre-check, so x db backfill refuses before it queues work that would only dead-letter |
| count | X_BACKFILL_STALLED — the source ran out and this still matches rows | the pass, once, after the last batch |
environments ships as declared data and never as a hardcoded "cleanups are production": a staging
rehearsal is correct practice, so which deploys a sweep belongs to is the app's convention and this
is only the mechanism carrying it. There is deliberately no dependsOn graph over other
backfills — the real dependency is almost always "after code tolerating both shapes is serving",
which the framework cannot observe.
count is the same predicate source selects on, counted. It is what makes a dry run honest and
"did it converge" arithmetic: a pass that exhausts its source while count() still answers above
zero has two predicates that disagree, which is an authoring bug and not something a retry fixes.
Its result is parsed rather than trusted — a non-negative safe integer or X_INVARIANT, because
NaN > 0 and -1 > 0 are both false and would complete the sweep the detector exists to fail.
Running one
x db backfill --pending --json # declared minus completed; non-zero when anything is unswept
x db backfill drop-legacy # DRY RUN — --write is never implied
x db backfill drop-legacy --write # gate, then enqueue; the workers sweep
x db backfill --all --write # every pending one, isolated per name
x db backfill drop-legacy --write --force # a completed name, again, into a NEW ledger row--write enqueues; it never runs the pass inline, because the queue is a job's execution
surface. That is what makes the backfill deploy role a trigger rather than a gate: it runs after
the new pods serve, puts the sweeps on the queue and exits, and a slow UPDATE never holds a release
open against a database still serving the previous build. --all isolates per name and continues
past a failure, so one wedged cleanup cannot block every later one forever.
Rebuilding a search index: reindex()
reindex({ name, entity, source, tenant, index? }) is a backfill() in two phases, one durable
step per page. Rows: each row's document goes to the searchIndex port — entity's one builder,
searchDocumentOf, so only .searchable() columns leave and each document keeps its tenant.
Sweep: every document the index lists whose row source no longer reads — deleted while the
index was down, moved to another tenant — is removed, tombstoned one millisecond above the version
listed, so an id written again meanwhile keeps its newer document. source is therefore the WHOLE
table: a narrowed one empties the index of the rest. tenant: 'none' sweeps every tenant's
documents; a declared tenant, its own. Run it after moving from the built-in Postgres index to
Meilisearch or Typesense, or after an index lost data. An entity with no searchable column is
refused at declaration. The index keeps only the NEWER version of each id, so neither a replayed
batch nor a stale read can overwrite a newer write or bring a deleted row back.
import { database, entity, text, timestamp, uuid } from '@ultimat3/entity';
import { reindex } from '@ultimat3/jobs';
const posts = entity('posts', {
columns: {
id: uuid().primaryKey(),
title: text().searchable(),
updatedAt: timestamp().defaultNow().onUpdateNow(), // each document's version
},
});
const db = database({ posts });
export const reindexPosts = reindex({
name: 'reindex-posts',
entity: posts,
tenant: 'none',
source: () => db.posts,
});Partition maintenance is a job too
partitions({ name?, cron?, tz?, clock? }) keeps every entity({ partitionBy }) table ready: one
step per partitioned entity runs @ultimat3/db's partitionMaintenance(description, now) — the
function the migration also calls — creating ahead partitions past the current one and
dropping those retain expired. It is a job plus a .schedule task() (<name>.schedule,
default DEFAULT_PARTITIONS_CRON, 03:17 UTC daily), the shape consumer()'s .supervisor has.
now is the job's clock, never the server's, so a test moves it; a second run at one instant
changes nothing (create … if not exists). Entities are read per run, so one declared later is
maintained from its first tick. isPartitionsJob(handle) answers whether partitions() minted a
handle — by identity, so a cronJob() (the same <name>.schedule shape) is not one; x verify
reads it for X_PARTITIONS_UNMAINTAINED.
import { partitions } from '@ultimat3/jobs';
export const maintainPartitions = partitions(); // list it in defineApi({ jobs })Before a backfill() copies rows older than the first partition, enqueue it once with { from:
'<oldest row ISO>' }: that run creates every partition back to that row's period and drops
nothing. Every DDL statement runs under a lock_timeout, failing fast with X_DB_LOCK_TIMEOUT
(retryable — the job's retry absorbs it) rather than queueing behind a long transaction.
A job on its own cron: cronJob()
cronJob({ name, cron, tz, input?, payload?, catchUp?, maxCatchUp?, …job }) declares a job and the
task that fires it at once: the handle is the job, .schedule the task() (<name>.schedule).
name and tz are required; input comes with payload(occurrenceMs), which builds one
occurrence's input from its instant, or neither (each occurrence enqueues {}); idempotencyKey
defaults to () => name. Listing the job in defineApi({ jobs }) is enough — the task registers
with it.
import { cronJob } from '@ultimat3/jobs';
export const sweepSessions = cronJob({
name: 'sweepSessions',
cron: '15 * * * *',
tz: 'UTC',
tenant: 'none',
retry: { attempts: 3 },
async run({ step }) {
return step.run('sweep', () => 0);
},
});Consumers are jobs too
consumer() reads a queue, a change stream or a vendor's cursor: a factory over job() plus a
.supervisor task(). One running body per key, idempotencyKey: consumer:<name>:<key>, no
timeout, the cursor saved in the batch's own transaction, the drain honoured.
import { consumer } from '@ultimat3/jobs';
interface Order { readonly id: string }
declare const feed: { since(cursor: string | null, signal: AbortSignal): AsyncIterable<Order> };
declare function upsertOrders(rows: readonly Order[]): Promise<void>;
declare const cursors: {
of(key: string): Promise<string | null>;
save(key: string, next: string): Promise<void>;
};
export const syncOrders = consumer<Order, string>({
name: 'sync-orders',
tenant: 'none',
keys: () => ['orders'],
open: ({ cursor, signal }) => feed.since(cursor, signal), // the app's AsyncIterable
handle: async ({ items }) => {
await upsertOrders(items);
return items[items.length - 1]?.id ?? '';
},
cursor: { load: (key) => cursors.of(key), save: (key, next) => cursors.save(key, next) },
});| Rule | Why |
|---|---|
| handle returns the next cursor; the framework saves it in the same withTransaction | cursor and effect commit together or not at all |
| .supervisor (<name>.supervisor, every rearm, UTC) enqueues <name>.arm, which enqueues each of keys() | a live key's re-arm is deduped; a settled or dead one restarts from its saved cursor |
| a self-.enqueue from inside the run is X_CONSUMER_SELF_ENQUEUE | it would dedupe onto the running row and arm nothing |
| no cursor, a timeout, a bad batch or rearm is X_CONSUMER_INVALID | refused at declaration |
| at least once per item | a drained or failed batch is delivered again: handle is idempotent per item |
Retention sweeps are jobs too
purge() is the second factory over job(), and it exists because three framework stores
shipped a purgeExpired() with no caller — x_idempotency, x_rate_limit and the auth pair each
kept every row they ever took. x_rate_limit takes one upsert per HTTP request the web role
serves, assets included, so its growth follows total traffic and not traffic that hit a limit.
import { DEFAULT_PURGE_CRON, purge, task } from '@ultimat3/jobs';
declare const store: { purgeExpired(nowMs: number): Promise<number> };
export const sweep = purge({
name: 'x.purge',
// Read once per ATTEMPT, never captured: a host declares the sweep at boot, and some of the
// stores behind it are built later.
targets: () => [{ name: 'x_rate_limit', purgeExpired: (nowMs) => store.purgeExpired(nowMs) }],
});
export const hourly = task({
name: 'x.purge.hourly',
cron: DEFAULT_PURGE_CRON,
tz: 'UTC',
enqueue: () => [[sweep, {}]],
});| Rule | Why |
|---|---|
| PurgeTarget is structural | the stores live in @ultimat3/action, @ultimat3/http and @ultimat3/auth; importing them would put the HTTP pipeline on this package's graph |
| one step.run per target | a killed attempt resumes at the table it stopped on, not at the first |
| one clock reading per pass | postgresRateLimitStore.purgeExpired(nowMs) needs the CALLER's clock — the server's read a 20,000,000-second refill against a frozen one and deleted a live bucket |
| at least once is safe here | a replayed delete removes rows that are already gone, and a row a purge deleted answers exactly as one that was never there |
| two targets under one name | X_INVARIANT, before the first delete — step.run would raise X_STEP_DUPLICATE after one table was already empty |
The stored event bus is a target too: eventsPurgeTarget(bus) answers
{ name: EVENTS_PURGE_TARGET, purgeExpired } over bus.purgeExpired(), which is awaited and
answers the rows it removed — x_job_events only grew while nothing called it. Add it to
targets: targets: () => [eventsPurgeTarget(eventBus())].
Finished jobs are one too: jobsPurgeTarget({ executor, doneRetentionMs, deadRetentionMs })
deletes done rows past the first window and dead, failed and cancelled rows past the
second, each with its x_job_steps once no row of the run still stands. A pass runs at most
maxBatches (50) batches of batchSize (1,000) rows, skip locked; a batch is one statement, plus a
follow-up when a row it could not see deleted still shared a run (two sweeps that split a run settle
its steps after both commit). Each batch walks its partial index (x_jobs_done_idx,
x_jobs_ended_idx) from the newest row the batch before it deleted — a keyset, kept across passes
and forgotten once a day — so it never re-reads the index entries earlier deletes left for vacuum
(As of 2026-11-14: a walk from the start read most of the heap to delete nothing). After the batches, one more statement removes up to batchSize step
records whose run has no row left, what a sweep that died before its follow-up stranded. A live row is never deleted, nor one an
unpublished x_outbox row or a running x_backfills row still names. The windows come from
app.config.ts (jobs.doneRetentionMs, 14 days, and jobs.deadRetentionMs, 90 days).
outboxPurgeTarget({ executor, publishedRetentionMs }) is the same for x_outbox: published
rows only, measured against the job's clock (the relay stamps published_at from its own), at
jobs.outboxRetentionMs (7 days). An unpublished row is a job not yet handed over, never deleted.
@ultimat3/cli's boot declares both halves over the three tables it owns, so an app gets the sweep
without writing any of the above. It needs a worker to run it and a scheduler to fire it: a
deployment with neither has no background work at all, and this is one more thing it does not do.
Exporting a large dataset is a job too
exportRows() is a factory over job() that streams a paged read to object storage with a
resumable cursor. It exists for one reason: const all = await repo.all(); await disk.put(key,
csv(all)) works on 200 rows and OOM-kills the pod on two million.
import type { ReadBuilder } from '@ultimat3/entity';
import { exportRows, t } from '@ultimat3/jobs';
import { formatMoney, type Money } from '@ultimat3/money';
import { disk } from '@ultimat3/storage';
import { formatDate, instant } from '@ultimat3/time';
interface Order {
readonly id: string;
readonly placedAt: Date;
readonly total: Money;
}
// The app's own chain: `source` takes whatever `db.orders.where(…)` answers.
declare const db: {
readonly orders: { where(filter: { readonly orgId: string }): ReadBuilder<Order> };
};
export const exportOrders = exportRows({
name: 'orders.export',
input: t.object({ orgId: t.string, exportId: t.string }),
// The security boundary of the whole feature — an export concentrates one tenant's rows into a
// single downloadable object.
tenant: ({ orgId }) => orgId,
prefix: ({ orgId, exportId }) => `exports/${orgId}/${exportId}`,
source: ({ input }) => db.orders.where({ orgId: input.orgId }),
format: 'csv',
columns: ['id', 'placedAt', 'total'],
row: (order) => ({
id: order.id,
// A date gets its zone and a Money its currency HERE, where the app knows which it means.
// `instant()` is the check that turns a stored `Date` into one nothing can format zone-less.
placedAt: formatDate(instant(order.placedAt), { locale: 'en', zone: 'UTC' }),
total: formatMoney(order.total, 'en'),
}),
sink: () => disk('exports'), // a thunk: read per write, after defineStorage() — never at import
});The artifact is one object per page plus a manifest:
exports/<orgId>/<exportId>/part-00000.csv
exports/<orgId>/<exportId>/part-00001.csv
exports/<orgId>/<exportId>/manifest.json| Rule | Why |
|---|---|
| one object per PAGE, never one per export | put() buffers by construction — its own header says the server-side path "is for objects that FIT IN MEMORY" — so a single-object export holds the whole dataset, which is the failure this exists to prevent |
| the part key is the page INDEX | so a page that runs twice REWRITES its part. At-least-once needs no idempotency argument about your rows here: a duplicate part cannot be expressed |
| a step persists the CURSOR and two counters | never the page — steps.ts retains a completed step's output for the whole run, so checkpointing rows keeps every exported row until the job ends |
| every line ends in a newline, header in part 0 only | cat part-* is one valid file, which is what makes the parts an artifact rather than fragments |
| maxPartBytes is a heap bound, not a file-size preference | one page is encoded whole before it is written; X_EXPORT_PART_TOO_LARGE names the batch to lower |
| a row() key columns does not carry is REFUSED | both encoders would drop it in silence, and row: (r) => ({ ...r }) picks up every column the entity gains from the next migration on |
| csv cells leading =, +, -, @, TAB or CR are neutralised | Excel, Sheets and LibreOffice EVALUATE them, so a user-named record is code execution in the reviewer's spreadsheet. Strings only — a negative number stays a number |
| the manifest COUNTS parts, never lists them | exportPartKey(prefix, i, format) rebuilds every key, and a list is the one thing in the pass that would grow with the export |
| tenant: 'none' gets no cross-tenant escape | backfill() does (backfill-scope.ts) because its lazy chain leaves an author nothing to wrap. An export does not, and the difference is the direction of the data: a sweep rewrites rows under audit, an export writes every tenant's rows into one downloadable object |
| rate has no default, unlike a backfill's | a backfill competes for WRITE capacity on rows the app is still serving; an export is a bounded read somebody is usually waiting for. Declare it for an export big enough to matter to the pool |
ExportSink is a seam and not a @ultimat3/storage import, for the reason PurgeTarget is one:
this package holds no storage dependency, and taking one so a queue could name a disk would put the
object store on tier 3's import graph.
Importing a large file is a job too
importRows() is exportRows()'s twin: a factory over job() that reads one object from storage
a page at a time, through the app's schema, into the app's handle. It exists because
parse(await disk.get(key)) holds the whole upload, and a retried job re-applies every row from
zero. Which columns mean what, and who may import, stay the app's.
import { importRows, t } from '@ultimat3/jobs';
import { disk } from '@ultimat3/storage';
interface Order {
readonly id: string;
readonly orgId: string;
readonly total: number;
}
// The app's own table: `handle` takes whatever `db.orders.upsertAll(…)` answers.
declare const db: {
readonly orders: {
upsertAll(rows: readonly Order[], args: { onConflict: readonly string[] }): Promise<unknown>;
};
};
export const importOrders = importRows({
name: 'orders.import',
input: t.object({ orgId: t.uuid, key: t.string }),
tenant: ({ orgId }) => orgId,
source: () => disk('imports'), // a thunk; a StorageDriver IS an ImportSource
key: ({ key }) => key,
format: 'csv',
columns: ['id', 'total'],
schema: t.object({ id: t.uuid, total: t.number.int() }),
handle: ({ rows, input }) =>
db.orders.upsertAll(rows.map((row) => ({ ...row, orgId: input.orgId })), {
onConflict: ['orgId', 'id'],
}),
errors: { sink: () => disk('imports'), prefix: ({ orgId }) => `imports/${orgId}/errors` },
});| Rule | Why |
|---|---|
| one step per page; its output { offset, line, rows, rejected, errorPart, header } is the checkpoint | a killed attempt resumes at the byte offset. Never the rows: a step's output is retained for the whole run |
| no carry between steps | bytes after the last complete record are re-read by the next page; a record boundary is found on BYTES (0x0A outside "), which no UTF-8 sequence contains |
| handle runs at least once per page | upsertAll is the idempotent spelling, as for backfill() |
| pageBytes (1 MiB) must exceed maxRecordBytes (64 KiB) | so every window holds a whole record; past maxRecordBytes is X_IMPORT_RECORD_TOO_LARGE |
| a page uses its whole pageBytes read, handed to handle batch (500) records at a time | bytes read are O(file) and steps about file ÷ pageBytes, while one call is still one bounded statement. Measured: a 10 MB file of a\n rows is 10 reads, 10,000,004 bytes and 10 page steps |
| csv: header = columns, any order; empty cell null, quoted "" the empty string; cells coerced as an HTTP form is (coerceInput) | X_IMPORT_HEADER_MISMATCH names missing and undeclared |
| ndjson: a key outside columns refuses the row | record.undeclared, naming the key |
| a refused row is { line, field, code } in <prefix>/<runId>/errors-NNNNN.ndjson (importErrorKey); the result's errorPrefix names it, so a re-import never mixes runs | the code is a format rule (IMPORT_REJECTIONS) or the schema's rule; never the value |
| past maxRowErrors (1,000) the run fails X_IMPORT_TOO_MANY_ERRORS | the batch that crossed it unhandled, its report written; 0 stops at the first bad batch |
| the report is { rows, rejected, parts, bytes, errorPrefix } | bounded, for x jobs show |
| a csv with no first line — empty, a BOM, blank lines — is X_IMPORT_HEADER_MISMATCH | zero rows from a file that never named its columns is not a success |
| a header mismatch prints the DECLARED names whole and the file's as a count plus five escaped, cut names | a header cell is file content: raw, it forges a log line or prompts the agent reading x jobs show |
| tenant: 'none' gets no cross-tenant escape | a scoped write in handle fails closed with X_TENANCY_ACTOR_ORG_REQUIRED |
| no formula guard is undone | an import cannot know a leading ' was the exporter's |
Measured As of 2026-11-03 (pageBytes 1 MiB, batch 5,000): a 200 MB csv imported with the
heap up 42 MB, a 20 MB one with it up 24 MB — a page and the garbage behind it, not the file.
ImportSource is a seam for ExportSink's reason; scripts/export-sink.test.ts compiles
StorageDriver into both. memoryImportSource() is the test source.
One person's data is a job too
defineSubject(entity, { driver, key, tables, targets?, columns?, batch? }) declares the person
once; subjectExport({ name, input, tenant, subject, sink, prefix, format }) and
subjectErase({ name, input, tenant, subject }) are factories over job() that take it. The
reach is planned when a run starts (planSubject, pure), from every registered entity's foreign
keys, continued only through tables the erase deletes; the first refusal of the declaration
throws before a row is touched (X_SUBJECT_TABLE_UNDECLARED, X_SUBJECT_TREATMENT_INVALID,
X_SUBJECT_CYCLE, all terminal).
A parent's <table>_history (entity({ history })) names its row by row_id, no foreign key, so
the walk alone never finds it. It is reached when its parent is deleted or anonymized — both write
the person's data into a before image — and needs a line like any table:
| tables: { posts_history: … } | Does |
|---|---|
| 'delete' | in the parent's own step and transaction, after the write: the rows' ids read, the write made, every history row of them deleted — the image that write just recorded included — under x.purge naming the table, the one delete its guard lets through. The memory driver deletes the same rows through the history repository, inside purgingHistory(<history table>, …) — its in-process twin of x.purge (@ultimat3/entity's history-purge.ts) |
| { retain: '<why>' } | a step of its own before the parent's, counted by row_id |
| { anonymize } | refused, X_SUBJECT_TREATMENT_INVALID: history is never rewritten |
| Piece | Does |
|---|---|
| subject-plan.ts | reach, children-first order, loop-closing keys to clear first, every refusal |
| subject-plan-history.ts | which history tables a written parent reaches, and how each is treated |
| subject-erase-history.ts | a parent's page and its history's rows, one transaction under x.purge |
| subject-select.ts | a table's rows of the subject a page of parent keys at a time, through database() over the app's driver |
| subject-erase-pass.ts | targets (fresh subject row each step), cleared keys, then each table; one step per page, each write deleteWhere/updateWhere on one key |
| subject-export-pass.ts | one object per page per table and target, index.json last; sealed columns left out, instants as ISO UTC |
| subjectEraseTables(subject, key, step) | the table passes alone, under the caller's context — what @ultimat3/testing's subjectProof drives |
SubjectTarget (name, columns, exportPage, erase) is structural, as PurgeTarget is:
authSubjectTarget, auditSubjectTarget and storageSubjectTarget satisfy it from their own
packages. { target, retain: '<why>' } exports a target and never erases it.
personalData() coverage
.personalData(kind) on a column (@ultimat3/entity) marks it as a person's data. It adds no
second export/erase path: it is the proof that the declared subjects cover every marked column.
| Check | Refuses |
|---|---|
| unerasedPersonalData(plan) | a reached table whose { anonymize } names fewer than every marked column (X_PERSONAL_DATA_UNERASED). 'delete' clears the row; { retain: '<why>' } is a stated reason |
| unreachedPersonalData(plans) | a marked entity no subject's walk reaches (X_PERSONAL_DATA_UNREACHED) |
| personalDataProblems() | both, over registeredSubjects() and every marked entity — what x exercise lists |
Enforced twice: plannedSubject() throws the first X_PERSONAL_DATA_UNERASED when a run starts, so
subjectExport/subjectErase refuse before a row is touched, and x exercise lists both codes
as findings. An erase is audited: with an auditSink installed, subjectErase writes one
allowed record per completed erase and a failed record per attempt that threw: name the job,
primitive: 'action', surface: 'job', input: { subject, run } — the entity and the run id,
never the subject's key, which an app may make an email. At least once: a sink dedupes on
idempotencyKey (<job>:<runId>). A sink that refuses fails the run; one refusing every attempt
can hold no record, and the dead-lettered run is the trail.
gdpr.job.test.ts proves the property, not the shape: a covered erase leaves no marked value of the
person in any marked table, and a declaration missing one column is named and does leak it.
Outbound webhooks are jobs too
webhook() is a factory over job() and delivers one event to one endpoint. Retry with
backoff, disable-after-N and the ledger are all per-endpoint facts, so the endpoint is the unit: a
job that fanned out inside one body would retry every subscriber because one of them was down.
Which endpoints exist is the app's — the fan-out is your own for loop over your own
subscription table, one enqueue per endpoint.
import { memoryWebhookLedger, webhook } from '@ultimat3/jobs';
declare const db: {
endpoints: {
byId(id: string): Promise<{ id: string; orgId: string; url: string; secret: string } | null>;
};
events: { byId(id: string): Promise<{ topic: string; body: string } | null> };
};
export const deliver = webhook({
name: 'partner.webhooks',
// The org that owns the endpoint, carried on every enqueue — or `tenant: 'none'` for endpoints
// no tenant owns. `tenant` is synchronous over the input, so the org rides beside the two ids.
tenant: ({ orgId }) => orgId,
// Read once per ATTEMPT and never checkpointed: the endpoint carries a secret, and a step's
// output is written to `x_job_steps`.
endpoint: ({ endpointId }) => db.endpoints.byId(endpointId),
event: ({ eventId }) => db.events.byId(eventId),
ledger: memoryWebhookLedger(), // dev only — a bounded ring in one heap
disableAfter: 10,
});
// The fan-out is yours, because the subscription table is yours.
declare function subscribersOf(topic: string): Promise<readonly { id: string; orgId: string }[]>;
declare const event: { readonly id: string };
for (const endpoint of await subscribersOf('orders.paid')) {
await deliver.enqueue({ endpointId: endpoint.id, eventId: event.id, orgId: endpoint.orgId });
}The delivery carries three headers beyond content-type, and the signature is over
v1:<timestampSeconds>:<eventId>:<topic>:<body>:
x-ultimate-webhook-id: evt_01HZ
x-ultimate-webhook-topic: orders.paid
x-ultimate-webhook-signature: t=1700000000,v1=<hex hmac-sha256>The receiving half is verifyWebhookSignature(request, { secret }) in @ultimat3/http. The format
itself — the canonical string, the mac and the header names — is one module in @ultimat3/core
(webhook-signature.ts), imported from @ultimat3/core by both packages and re-declared by
neither: this package signs, http verifies, and neither may import the other, so the one copy
lives at the tier both can reach. A receiver or a test imports WEBHOOK_SIGNATURE_HEADER,
webhookSignature and the rest from @ultimat3/core — 25.0.0 dropped this package's
re-exports (X_HELPER_COPY). Same argument timing-safe-equal.ts makes for itself.
| Rule | Why |
|---|---|
| the timestamp is inside the mac | a captured delivery re-dated to slip back into a receiver's freshness window no longer verifies |
| the timestamp is SEND time, not event time | a retry three days later signs again now, so the window measures the request rather than the age of the fact |
| : is refused in an id or a topic | one mac over v1:t:evt:01HZ:orders.paid:<body> would otherwise authenticate two different id/topic splits — the same delivery under a label the sender never wrote |
| the endpoint's own headers merge under the framework's | an endpoint row that could set x-ultimate-webhook-signature is an endpoint row that can forge one |
| redirect: 'manual' | following a 3xx would re-POST a body signed for one host to whatever the receiver named |
| the endpoint is never checkpointed | a step.run output lands in x_job_steps, and the endpoint carries the secret |
| every attempt is recorded before the throw | a failure the ledger cannot see is a failure the consecutive count cannot see, which is an endpoint that never gets disabled |
| a Retry-After the receiver names is honoured | X_WEBHOOK_DELIVERY_THROTTLED carries meta.retryAfterSeconds, which the nack waits out — read by core's retryAfterSecondsOf (delta-seconds, or an HTTP-date against the response's own Date; 0 or a past date is unstated), clamped by retry.maxDelay, plus core's jitterStatedDelay spread so deliveries handed one instant do not wake together |
| WebhookLedger.isDisabled(endpointId) is asked before ev
