Runtime
Create a runtime, trigger work, and manage workers and maintenance.
Import createRunlane and the option types on this page from @runlane/core. A runtime joins your task definitions to a lane. The lane supplies storage and delivery.
Create a runtime
createRunlane(options) returns a RunlaneRuntime. It does not start a worker or a maintenance loop.
| Option | Type and behavior |
|---|---|
lane | Required Lane. Use a lane package that matches your deployment. |
queues | Required, nonempty list of QueueDefinition values. Register every queue used by this runtime. |
tasks | Optional list of task definitions or a named catalog, such as { sendEmail }. Workers need the tasks they execute. |
environment | Optional { name: string }. Defaults to contractDefaults.environment. Processes sharing runs must use the same name. |
dispatch | Optional { onTrigger?: TriggerDispatchMode; eagerOutboxGrace?: DurationString }. Defaults come from contractDefaults.dispatch. Eager transport runtimes attempt bounded queue admission and publish ready work after commit; deferred mode leaves admission to maintenance. |
resendQueuedRunsAfter | Optional positive DurationString. Resends still-queued runs on unbounded transport queues after this delay. Defaults to contractDefaults.maintenance.resendQueuedRunsAfter ("15m"). Use the same value in every process; queued-run recovery follows the value of the process that last wrote it. Hook-wakeup resends use the maintenance process's value. Callback retry backoff remains controlled by hooks.retry. |
lease.duration | Optional DurationString in lease?: RuntimeLeaseOptions. Sets how long a crashed worker keeps a run before another worker can take it over. Defaults to contractDefaults.lease.duration. |
version | Optional RunlaneIdInput (a plain string), an immutable code identity. Defaults to contractDefaults.run.version. See deploy task changes. |
shutdownGrace | Optional ShutdownGrace (a positive duration string or 'unlimited'). Default shutdown budget, defaulting to contractDefaults.worker.shutdownGrace. See shutdown. |
workerId | Optional worker ID. Runlane creates one when omitted. |
clock | Optional Clock with now(): Date. Defaults to the system clock. Use a controlled clock in tests. |
hooks | Optional HookOptions: retry (RetryPolicy), timeout, leaseDuration, and discoveryTimeout. Defaults come from contractDefaults.hooks. See lifecycle hooks. |
logs | Optional task console capture policy and durable application log limits. Defaults come from contractDefaults.logs. See task logger. |
streams | Optional stream limits and polling intervals. Defaults come from contractDefaults.streams. See streams. |
maxInterruptions | Optional non-negative safe integer or 'unlimited'. Sets the runtime's interruption allowance. See default interruption allowance. |
retention | Optional RetentionOptions. Per-outcome history rules plus optional cleanup budgets. Tasks accept the same rules. See automatic run retention. |
observability | Optional logging, tracing, observation, and durable export settings. See telemetry. |
TriggerDispatchMode.Eager tries to publish a stored delivery request during the trigger call. TriggerDispatchMode.Deferred leaves publishing to maintenance. Both store the run first. Storage-polling workers read due work from storage.
dispatch.eagerOutboxGrace sets the storage-time crash timeout for pending eager outbox rows. It defaults to contractDefaults.dispatch.eagerOutboxGrace. For example, createRunlane({ lane, queues, dispatch: { eagerOutboxGrace: '5s' } }) reserves those rows for five seconds. Supply a positive duration string. The eager publisher skips this timeout when claiming its row by ID. Deferred rows remain available on the next maintenance pass. See outbox ownership.
Environment names and public identifiers follow the storable string rule: valid Unicode, no NUL, and no leading U+FEFF.
The runtime exposes environment, lane, deliveryMode, queueDefinitions, and the supplied tasks catalog as read-only properties. It also exposes schedules and the runs, signals, wait, and idempotency APIs.
Use await runlane.start({ maintenance: true }) in long-running processes. Workers, drains, and delivery and maintenance handlers start lane resources lazily. Plain start() only starts lane resources. See add Runlane to your app for complete entry points.
Saved changes and delivery errors
A confirmed storage commit makes a mutation successful. If its immediate follow-up delivery fails, the result includes deliveryError?: RunlaneError through the shared DeliveryOutcome type. This covers eager wakeup publication, bounded queue admission, and resuming waiting runs. The change is saved. Keep maintenance running so it can finish delivery; do not repeat the call to recover it.
A temporary publish failure retries after contractDefaults.maintenance.outboxRetryDelay; a permanent failure, such as access denied, dead-letters that outbox message, and on an unbounded transport queue, delivery recovery requests the queued run again after contractDefaults.maintenance.resendQueuedRunsAfter (15 minutes by default). Bounded queues use dispatch recovery instead. See Run maintenance.
The error keeps a structured cause's code and retryable; an unstructured cause uses internal_error. Serialized errors contain code, retryable, and meta, without the internal cause. meta identifies what failed:
runId: the run whose follow-up delivery failed. For a completion notification, this is the waiting parent, even when the call returns the completed child. Each waiting parent keeps its own result; a shared child does not make one parent inherit another parent's failure.sourceRunId: the completed run, on completion resume failures. If finding the waiting runs fails before any target is known,metahassourceRunIdand norunId.batchId: added for raw batches. Named child batches have none.tokenId: added for resumes driven by a wait token.queue: added for bounded queue admission.queueandrunIds: used by queue controls to name the admissions that failed.
Triggers return TriggerRunResult. Linked runs and cancellation return RunRecord & DeliveryOutcome. Queue mutations return QueueState & DeliveryOutcome; their error covers the admissions that control started. Signals return an array of RunRecord & DeliveryOutcome. Token completion returns CompleteWaitTokenResult & DeliveryOutcome. Direct execution results also report failed completion notifications and storage failures during eager hook delivery. A token completion reports only its own waiters. A finished run does not inherit a capacity refill failure. Failures for unrelated admitted runs stay with the dispatcher logs.
Batches attach an error only to positions whose run had work in the failed delivery. Reusing a terminal run creates no wakeup, so another member's delivery failure does not affect it. Logs and spans still record failures. See telemetry.
runMaintenanceOnce() treats reservation storage conflicts as stale candidates; later passes retry them. Other primary dispatch scan, reservation, token lookup, or token waiter-resume failures reject the pass. Token waiter conflicts do not stop later waiters or tokens; the pass rejects with the first conflict after attempting them. These token failures do not emit wait_token_eager_resume_failed.
Completion recovery handles each completed run on its own. If finding or resuming that run's waiters fails, it logs run_completion_resume_failed and moves on. A delivery failure after a saved resume does not stop later maintenance phases.
Failures before or during a commit retain their error behavior. A lost commit response remains ambiguous: inspect storage before retrying. A signal resume that fails before commit still rejects after all started resumes settle; sending again is its recovery.
Subscribe to live observations
runlane.subscribeObservations(observer) adds a RunlaneObserver after runtime creation and returns an idempotent unsubscribe function. It observes committed events from that runtime's workers, direct execution, and services on every lane. It uses the same sanitized payloads and observability.onObserverError policy as configured observers. Callback failures cannot reject committed work. Closing waits for committed observers up to the shutdown bound.
const unsubscribe = runlane.subscribeObservations((observation) => {
applicationLogger.info(observation)
})
// Stop listening when the owning tool closes.
unsubscribe()This is a best-effort process-local hook, not a replay or export channel. Read stored run/event records for failure details. Use durable observation export for checkpointed consumers.
The runtime exposes its resolved default as runlane.shutdownGrace.
Shutdown
await runlane.close() stops acquisition and rejects new external producer and direct execution calls immediately. Maintenance, workers, direct executions, and eager outbox work drain concurrently. Running attempts can still trigger children and use their task context during grace. Close releases saved eager messages waiting to publish. It waits for outbox writes already in progress, started publishes, and their saved results. If shutdown begins while a drain is preparing schedules, that drain returns { runsExecuted: 0 } without starting a worker. It drains workers, drain() calls, and admitted runNow(), executeNext(), and executeDelivery() calls before releasing lane resources. Direct executions receive the runtime shutdownGrace, then a shutdown abort. Workers and drain() calls inherit this value. Their own shutdownGrace governs their drain, even when longer than the runtime grace. Close waits for the longest active worker grace, including unlimited. Polling hook acquisition stops immediately, including claims waiting on storage. Started hook callbacks retain their worker grace and hook deadline; unclaimed hooks remain recoverable. Errors after the abort release the run without spending a retry or an interruption. Deliveries admitted through platform handlers and their result writes are covered by shutdown admission; close still only waits for those deliveries. Platform handlers gain no shutdown hook.
Close waits for admitted external mutations, including triggers and batches, signals, token calls, operator changes, schedule changes, queue controls, idempotency resets, and manual maintenance. These calls keep storage open through their result and observers. They have no extra runtime shutdown timeout; storage operations retain their own timeouts. Closing also waits for observers of events committed before or during draining. createRunlane({ shutdownGrace }) sets the observer deadline when close begins. Workers use their own resolved grace. Observers committed during draining receive only the remaining time. The default is contractDefaults.worker.shutdownGrace; 'unlimited' removes this deadline. At the bound, Runlane logs observer_shutdown_timed_out and releases the wait. A callback that returns later cannot restart publishing a released message.
New external trigger, signal, token creation or completion, runNow(), executeNext(), and executeDelivery() calls fail with operation_cancelled once closing begins. Platform delivery calls are also refused with operation_cancelled; their task handlers do not start. The provider maps that rejection to its native retry behavior. An external batch started after closing rejects; an admitted batch can finish submitting its chunks.
A cleanup failure rejects close() after draining work and closing lane resources. Failed releases and uncertain transport results still need normal grace or claim recovery. See duplicate delivery for recovery limits.
Trigger or run now
| Call | Return value | Behavior |
|---|---|---|
trigger(task, payload, options?) | Promise<TriggerRunResult> | Stores a run and requests delivery. The result has outcome, run, and optional deliveryError. The outcome is created or returned_existing. |
triggerBatch(items, options?) | Promise<TriggerBatchResult> | Submits same-task or mixed-task items. Returns one ordered acceptance or error outcome per item. |
batch.trigger(items, options?) | Promise<TriggerBatchResult> | Alias of triggerBatch(), with the same options and behavior. |
runNow(task, payload, options?) | Promise<RunSnapshot & DeliveryOutcome> | Stores a run that already holds the caller's lease, then executes one attempt in the calling process. A lease is time-limited ownership in storage, so no worker or queue admission can start the run first. A paused queue rejects with queue_paused (retryable: false); a full total or per-key pool rejects with queue_at_capacity (retryable: true). Both save nothing. Use queues.resume() to resume the queue, queues.setLimit(queue, { total, perKey, expiresAt }) to raise its limit temporarily, or trigger() to queue the work. A retry or release needs later execution. |
When runNow() reuses an existing run ID, idempotency owner, or same-task singleton holder, it returns that run without executing it, before pause or capacity is considered. Refusal errors include meta.queue and meta.taskId. See the inline fallback example.
Omit payload only when the task's input schema accepts undefined. trigger() does not return the handler's output. Read a completed run with runlane.runs.get(task, runId) when the task has an output schema.
Trigger results follow saved changes and delivery errors, including bounded queue admission. Child triggers and named steps follow the same rule.
New runs save the task's execution policy at acceptance. Complete its coordinated upgrade before updated processes create runs.
TriggerRunOptions accepts these optional fields:
| Field | Type and behavior |
|---|---|
queue | Registered QueueDefinition. Overrides the task's queue. |
runId | Run ID chosen by the caller. Reuse for the same task returns the existing run with returned_existing in any visible status, until pruned. Another task or a conflicting idempotency owner rejects with run_id_conflict. A failed run is returned; use runs.retry() to run it again. Omit to generate an ID. |
runAt | Valid Date setting when the run first becomes eligible to execute. Omit it, or supply a past time, for immediate eligibility. It is not an execution deadline. |
startBefore | Valid Date setting an exclusive deadline for the first attempt. Omit it for no start deadline. See start expiry. |
debounce | DebounceOptions: a task-scoped key, required delay, and optional maxDelay. See debounce. |
priority | RunPriority.High, Normal, or Low. Defaults to contractDefaults.run.priority. Non-normal values require a queue with priorityBoost. See priority. |
idempotencyKey | String key used to reuse a run for the same task and environment. |
idempotencyKeyTTL | DurationString or IdempotencyKeyTTLMode.Active. Controls how long the key remains owned after the run ends. Requires an idempotency key. |
singletonKey | String key that blocks another active run with the same key in the same environment, across all tasks. Add the task name to the key when only runs of one task should compete. |
singletonConflict | SingletonConflict.Reject or SingletonConflict.ReturnExisting. Overrides the task policy; defaults to contractDefaults.run.singletonConflict. Returns an active singleton holder only for the same task. |
concurrencyKey | String key used to share capacity within a bounded queue. Requires a bounded queue; keys may select per-key capacity or ordering on a total-only queue. |
actor | Actor identifying who created the run. |
meta | JsonObject attached to the creation event. |
tags | RunTags label array for indexed grouping. No default or child inheritance. See run tags for limits and the coordinated upgrade. |
traceCarrier | TraceCarrier used to continue a trace. |
singletonConflict applies to raw triggers and runNow(). Same-task reuse returns the holder without claiming new idempotency or debounce ownership or creating run history, outbox, or delivery records. runNow() does not execute a reused run. Existing run-ID, debounce, and idempotency decisions take precedence. Schedules, linked retries/reruns, and named child steps keep their existing conflict behavior. See prevent duplicate runs.
Pruning hides a run before cleanup removes it. Its ID rejects with run_id_conflict during cleanup and becomes available after cleanup finishes.
Retry and rerun create new linked runs. Their optional runId must be unused; an existing ID rejects with non-retryable run_id_conflict, even for the same task.
Call options override matching task key settings. Without a task or call queue, Runlane uses the registered default queue. At most one registered queue may be the default. If no default exists, the task or call must choose a queue.
trigger(task, payload, { runAt }) stores the run now and leaves it ineligible until that time. For a relative delay, calculate a timestamp, for example new Date(Date.now() + 60_000). The run does not reserve queue capacity while waiting. Transport lanes keep future delivery work in the outbox until due; keep maintenance running. runAt is also accepted by child triggers and each batch item's options.
Batch items may request the same runId. For the same task, the first accepted item creates the run and later items return it. An item for another task rejects with run_id_conflict.
Each trigger copies runAt and startBefore before awaiting payload validation or storage. Changing the caller's Date objects afterward cannot change the accepted schedule or deadline.
An idempotent or named replay keeps the original run and time. It does not reschedule accepted work. You can cancel a delayed run through runs.cancel(). Delivery remains at least once: full maintenance can publish both a scheduled and a recovery wakeup when work becomes due. Storage rechecks eligibility and ownership before each attempt; duplicate wakeups do not mean duplicate runs.
See prevent duplicate runs for key ownership, expiration, and repeated requests. Use the error reference to handle rejected API calls.
Eligibility and start time
A due time is an eligibility boundary, not a promise that the handler starts at that instant. This applies to every lane and to schedules, runAt, retry backoff, and timed releases. Storage checks the due time before granting a claim. Workers still need available capacity, an unpaused queue, and any required ordering or concurrency admission.
Transport messages are advisory wakeups. Receiving one does not authorize early execution. Schedule look-ahead arms fires and publishes delayed wakeups before eligibility, but creates each run only at its fire time; ordinary delayed triggers can remain in the outbox until due. Maintenance cadence, broker delivery, storage latency, and worker load can all delay execution after eligibility. Runlane does not guarantee a maximum gap between due time and handler start.
Start expiry
Use startBefore when work is no longer useful if it starts too late:
await runlane.trigger(
sendEmail,
{ userId: 'user_123' },
{
startBefore: new Date(Date.now() + 60_000),
},
)Storage decides whether the first attempt can start. At or after startBefore, it refuses the start, including an earlier lease claim that has not started an attempt. Once the first attempt starts, this deadline no longer affects execution, releases, or retries. Use maxAttemptDuration to limit an attempt's execution time. Start expiry is not a guarantee about when the first line of user code runs after an authorized start.
The deadline is absolute: it does not restart after runAt. A deadline at or before runAt leaves no start window. A past deadline is accepted and makes the run ineligible immediately. There is no default deadline.
Keep maintenance running. The RunFinalization phase saves terminal RunStatus.Expired and RunEventType.Expired (run.expired) without consuming an attempt or retry. Before that pass, the run can still show an active status, but workers cannot start it. Maintenance also releases any capacity still owned by the run and resumes joined parents; completion recovery repairs interrupted child notifications. A cancellation already requested keeps its cancellation outcome.
Workers also finalize expired runs they read past during acquisition. When the same acquisition claims healthy work, its attempt executes before that expiry cleanup.
Child triggers and each batch item's options accept startBefore. Named or idempotent replay retains the original run and deadline, including an expired result. Expiry releases singleton ownership. Idempotency retention follows the same policy as successful or cancelled runs; expiry does not silently replace accepted work. An explicit runs.rerun() creates a new run without inheriting the old deadline.
Follow Upgrade Runlane before using start expiry in an existing deployment.
Debounce
Use debounce to combine requests while waiting for a quiet period:
await runlane.trigger(
indexDocument,
{ documentId: 'doc_123' },
{
debounce: { key: 'doc_123', delay: '5s', maxDelay: '1m' },
},
)The key is scoped to the environment and task, not the queue. Durations must be positive whole milliseconds. delay is required. maxDelay has no default; without it, continuous triggers can keep postponing the run. A cap shorter than the delay becomes the initial due time.
The first accepted call fixes the payload and options, including queue, keys, source, trace carrier, delay, cap, and startBefore. Later calls inside the window return returned_existing and move only runAt: storage time plus the first delay, capped by the first maxDelay. Later options cannot change or remove that cap. Calls that cannot move the time add no event. Fresh submissions still validate their payloads.
The window closes at runAt, even if no worker has started the run. A later trigger creates a new run. Cancellation or start expiry also closes the window. Debounce does not limit concurrent execution after the window closes; use queue capacity or singleton ownership. A singleton can reject a new run while the previous run remains active.
Debounce keeps the first, not the latest, payload. For indexing or synchronization, pass a stable resource ID and read the latest application state inside the task. There is no payload replacement mode or payload aggregation.
Debounce cannot be combined with idempotencyKey, including a task-derived key, runId, or runAt. These combinations reject with configuration_invalid; no key is silently discarded. A raw retry after the window closes can create another run. Use business idempotency for one accepted operation across retries, or a named step for parent replay.
Child triggers and batch items accept the same option. A new named step can bind an existing pending child. Replaying that step returns the bound child without postponing it, even after completion. Joined parents release their queue slots while waiting. See child tasks.
Debounced runs start as scheduled and hold no queue slot during the quiet period. Polling workers use existing due-run indexes. On transport lanes, keep DeliveryRecovery and OutboxFlush maintenance enabled: there is no initial delivery message to cancel or edit. Rescheduling records RunEventType.Rescheduled (run.rescheduled) without changing attempt or retry counters. runs.get() exposes the first policy as debounce: { key, delayMs, maxRunAt? }; runAt is the current due time. runs.rerun() does not inherit debounce.
Follow Upgrade Runlane before using debounce in an existing deployment.
Priority
Priority changes which due run gets available queue capacity. Enable it on a bounded queue:
import { queue, RunPriority } from '@runlane/core'
export const jobs = queue({ name: 'jobs', concurrency: { perKey: 4 }, priorityBoost: '30s' })
// Register jobs in the shared runtime before triggering.
await runlane.trigger(sendEmail, { userId: 'user_123' }, { queue: jobs, priority: RunPriority.High })priorityBoost is a positive DurationString in whole milliseconds and requires concurrency. There is no default boost. Without it, only normal priority is accepted. The enum values are high, normal, and low.
Let A be the run's actual eligibility time and W the queue's boost. Only work due at storage time is eligible. Runlane compares high as A - W, normal as A, and low as A + W; smaller values come first. Equal values use creation time, then run ID. These are comparison values, not changed start times. An idle low run starts when due; a high run never bypasses runAt, debounce, retry delays, or start expiry.
Each candidate uses its own queue's boost. A normal run eligible for longer than W, or a low run eligible for longer than 2W, outranks newly eligible high work in that queue. This limits overtaking by newer arrivals, not total waiting time under a backlog or unavailable capacity.
Polling claims and bounded transport dispatch use the same ordering. Keep DeliveryRecovery and OutboxFlush maintenance running on transport lanes. Priority applies among visible candidates before new capacity reservations. It cannot reorder published messages, revoke reservations, interrupt running work, or guarantee an exact start order across workers. Explicit runNow() and operator execution do not select work by priority.
Child triggers and raw or named batch items accept the same option. The first accepted priority survives idempotency reuse, debounce, named replay, releases, and retries. Children do not inherit the parent's priority. There is no task-level priority default or reprioritization API. runs.rerun() creates normal-priority work. runs.get() and creation events expose stored non-normal priority; a missing field means contractDefaults.run.priority.
Follow Upgrade Runlane before using priority. All processes must register the same queue policy. Before removing priorityBoost, finish or cancel every non-terminal high/low run, including delayed and waiting work. Later retries and releases otherwise become undiscoverable. Changing an enabled boost changes pending selection order.
Batch submission
Use runlane.triggerBatch(items, options?) or its alias runlane.batch.trigger(items, options?). Both call the same function. trigger() accepts one task, not an array. Inside a handler, context.triggerBatch() and context.batch.trigger() use this contract and link new children to the parent.
Each TriggerBatchItem contains task, its schema's input payload, and optional per-item trigger options. Omit payload only when that task accepts undefined. The item count is bounded by contractDefaults.trigger.maxBatchItems. Outer options and every item envelope are checked before writes. Invalid items keep an error at their input position and are excluded from commit plans.
const { batchId, outcomes } = await runlane.triggerBatch(
[{ task: sendEmail, payload: { userId: 'user_123' } }, { task: cleanup }],
{ concurrency: 2 },
)
for (const item of outcomes) {
if (!item.ok) throw item.error
// Read the accepted run directly. This is not the handler output.
const runId = item.run.id
if (item.deliveryError) {
// The run is saved. Maintenance finishes delivery; do not trigger again.
process.stderr.write(`Wakeup delayed for ${runId}: ${item.deliveryError.code}\n`)
}
}
const page = await runlane.runs.list({ batchId })TriggerBatchResult contains one BatchId and ordered outcomes. Each outcome is { ok: true, run, outcome, deliveryError? } or { ok: false, error: RunlaneError }. Check ok before reading its run or error. An empty batch still returns a new batchId with empty outcomes. Invalid outer options or an oversized input array reject the whole call.
Runlane prepares bounded cohorts and submits atomic backend chunks. Every accepted chunk commits its runs, initial history, outbox and ownership records, and positional batch memberships together. Singleton conflicts are per item; unrelated items can commit. Run-ID, business-key, and singleton decisions follow scalar triggers in item order. Cohorts that share a run ID or key value commit in item order. So do cohorts that use different kinds of identity, such as one with run IDs and another with idempotency keys, because those can point to the same stored run. Cohorts that use only one kind, with no shared values, may commit concurrently. An item with a caller-chosen run ID rejects with run_id_conflict when its live idempotency key belongs to a different run, including when an earlier item claimed the key. Reusing a run by ID does not claim an unused or expired key. A rolled-back run_id_conflict or singleton-conflict chunk is split to report each item in input order. Later items see singleton keys claimed by earlier items, including same-task reuse with SingletonConflict.ReturnExisting. Rolled-back chunks publish nothing. A rolled-back storage_limit_exceeded chunk is also split. Splitting reuses prepared payloads, policy, callbacks, run IDs, and event IDs. One item that still cannot fit receives the limit error.
Before publishing, a chunk with a caller-chosen run ID, idempotency key, debounce key, or singleton key using ReturnExisting retries an event-sequence or idempotency storage conflict once with fresh reads and planning. A second conflict returns positional retryable errors. Publication failures do not replay creation.
TriggerBatchOptions.concurrency bounds simultaneous chunk submissions. It is a positive safe integer and defaults to contractDefaults.trigger.batchConcurrency. It does not control handler execution or transport publish batch sizes. When every item carries more than one kind of identity, for example a runId plus a task-level idempotency or singleton key, cohorts commit one at a time whatever this value is.
A newly created run saves its birth batchId in the run and creation event. A reused idempotent or debounced run keeps its original birth identity and gains membership in the new submission. runs.list({ batchId }) includes these reused runs and lists each run once. See batch pagination.
Accepted items follow saved changes and delivery errors. Only runs implicated by failed publication or admission carry deliveryError; raw batch diagnostics include the real runId and batchId. Terminal reuse is unaffected by another member's failed delivery.
A failure before a confirmed commit returns ok: false. A lost transaction response is ambiguous: storage may have committed even though the caller received an error. These errors include batchId and the prepared run ID when known. Inspect the batch and use business idempotency before retrying. Runlane does not persist a resumable batch job or promise request-level exactly-once submission.
Inside a parent, named step batches keep their all-or-nothing contract and ordered run-array result. They have no outer concurrency option and are never split to fit storage.
Local lane and worker
Import createLocalLane, createTestLane, CreateLocalLaneOptions, and CreateTestLaneOptions from @runlane/lane-local.
createLocalLane({ name?, emptyPollDelay? }) returns a storage-polling lane connected to runlane dev. name defaults to 'local' and must be nonempty. emptyPollDelay is a positive duration string; omission uses contractDefaults.delivery.storagePollingEmptyPollDelay. Creation performs no file or network I/O and starts no worker.
Before connecting, each storage operation looks for dev by config path. No session means storage_unavailable with the config path and instructions to start runlane dev. A dev session that serves a different lane name rejects with configuration_invalid and names both lanes. A failed lookup is not sticky. Start dev and retry in the same app process. If dev is still starting or stopping, the error says so; retry after it finishes. Run and work signal waits never reject without dev. They end at their timeout, abort, or close, and the next storage read reports the error.
Dev owns the store in memory. Apps, CLI commands, and workers use its authenticated loopback HTTP bridge on 127.0.0.1; they never keep private runs. Connected lanes fail if dev stops and reconnect on later operations after it restarts. Restarting dev erases old runs. See config discovery and lifecycle.
createTestLane({ name?, emptyPollDelay?, clock? }) returns an in-process storage-polling lane. It never discovers dev or accesses the filesystem. The common options have the same validation and defaults as createLocalLane(). clock?: () => Date sets storage time. Pass the controlled clock object to createRunlane() separately when runtime time must match storage time.
Same-name test handles share one reference-counted store and work signal across module copies. Different names and dev-hosted stores are separate. Closing the last test handle releases the store; a later handle starts fresh. A same-name handle with a different clock function, including an omitted clock, rejects at creation with configuration_invalid. Both factories reject unknown options and report productionDurable: false.
Use drain() or executeNext() with test lanes to control execution. A dev-connected local lane also supports drain(); leases prevent double ownership with dev's worker. The local lane is for Node.js development, not serverless or edge hosting.
The lane package also exports CLI integration APIs. resolveLocalConfigPath(configPath?) resolves an explicit path or the nearest default config. resolveLocalSessionPath(configPath) derives its private session path. requireLocalDevAvailable(configPath) checks session ownership before the CLI loads application code. It rejects while an owner is starting or stopping, but permits loading when no dev session exists. It is not a check that dev is running; the lane rejects storage operations without dev. configureLocalLane(lane, configPath, signal?) binds a CLI runtime's discovery and cancellation before first storage use. Other lane types are unaffected.
acquireLocalLaneHost(lane, configPath?) returns LocalLaneHost for a local lane and undefined for other lanes, including test lanes. It acquires config ownership and pins storage in-process before runtime startup. After startup, host.serve(onFailure) publishes the loopback server; onFailure receives structured errors with internal causes. host.failure rejects if the ownership lock is compromised. Close the server to stop accepting clients, then close workers and the runtime before host.release() removes the session and releases ownership. These APIs serve development tooling; applications keep using createLocalLane().
Redis lanes
redisPollingLane() from @runlane/lane-redis-polling returns a storage-polling lane with drain() and a scheduled delivery handler. redisStreamsLane() from @runlane/lane-redis-streams returns a transport lane with long-running workers. redisSqsLane() from @runlane/lane-redis-sqs preserves the native SQS Lambda handler type.
Use Redis options for the exclusive connection forms, namespace, hints, and delivery settings. Setup guides cover polling, Streams, and SQS.
Execution options
RunNowOptions includes the trigger options above except debounce, priority, runAt, and startBefore, plus these fields. runNow() remains immediate-only. The execution methods below also accept the following fields unless noted.
| Field | Type and behavior |
|---|---|
leaseDuration | Optional DurationString. How long this worker owns the attempt between renewals. The call's leaseDuration overrides createRunlane({ lease: { duration } }), which overrides contractDefaults.lease.duration. |
heartbeatInterval | Optional DurationString. Must be shorter than the effective lease. An interval above half the lease leaves no room to retry a failed renewal. Defaults to one third of the effective lease duration. Refresh intervals are capped by contractDefaults.lease.maxRefreshIntervalMs; see defaults. |
maxAttemptDuration | Optional DurationString. Overrides the saved task limit for this attempt; every run uses its accepted snapshot. Without either setting, the attempt has no deadline. |
signal | Optional AbortSignal. Aborting it interrupts an attempt that throws and requeues it without spending a retry. See Stop crash loops for the interruption allowance. If the signal is already aborted, runNow() rejects with operation_cancelled before validating the payload or saving a run. Use runs.cancel() to stop a run for good. |
workerId | Optional worker ID for this execution. |
Renewal clocks start from claim and renewal send times, so reply latency does not move the retry cadence. A failed job lease refresh is recorded and retried at the normal cadence. Work continues until ownership is proven lost or the lease is within the renewal margin of expiry without a confirmed renewal. The local deadline uses the last confirmed claim or renewal's monotonic send time, plus the lease duration, minus min(heartbeatInterval, leaseDuration - heartbeatInterval). A renewal whose planned slot is at or before that deadline is sent even if its timer wakes late. Its reply may arrive after that deadline. It must confirm before the hard bound: the last confirmed send plus the full lease duration. At that bound, Runlane gives up even if the request is still in flight. A late success cannot restore ownership. Set heartbeatInterval to at most leaseDuration / 3 to tolerate a failed refresh. An effective interval above half the lease leaves no room to retry after the first refresh. The default five-minute lease remains capped at roughly 30 seconds between refreshes.
The same lease precedence applies to workers, drain(), executeNext(), runNow(), executeDelivery(), and platform delivery handlers. runlane work --lease-duration 30s supplies a per-call override.
A lease prevents two workers from owning the same attempt. It is not a time limit on the handler. maxAttemptDuration sets that limit. A timeout records task_timed_out. The run becomes retrying if its retry policy allows another attempt, or failed otherwise.
On the Postgres polling lane, start() does not open the worker wake-up listener. createDeliveryWorker() opens and confirms it before resolving; listener startup failures reject worker creation. Producers, maintenance, and drain() do not open it. Run progress hints are separate; use runHints: false to skip their listener on serverless hosts.
Workers and delivery
| Call | Return value and options |
|---|---|
createDeliveryWorker(options?) | Promise<DeliveryWorker>. Starts the lane's delivery worker. Runs leader-elected maintenance by default (maintenance: false opts out). handleSignals?: boolean defaults to false; when enabled, the first SIGTERM/SIGINT closes with resolved grace and a later signal outside the shared duplicate window aborts. Handlers are removed on close. Takes execution options, concurrency?: number, shutdownGrace?: ShutdownGrace (a duration or 'unlimited'), and queues?: readonly QueueName[]. |
executeNext(options?) | Promise<(RunRecord & DeliveryOutcome) | undefined>. Claims and executes one due run from storage, or returns a crash-budget failure without starting another attempt. Takes execution options and queues?: readonly QueueDefinition[]. Can return undefined after a bounded scan or lost claim even when other work exists. Workers and drain() resume incomplete scans. |
executeDelivery(message, options?) | Promise<ExecuteDeliveryResult>. Validates and processes one DeliveryMessage from a transport. Intended for delivery integrations. |
drain(options?) | Promise<DrainResult>, containing runsExecuted, the number of attempts executed. Crash-budget finalizations do not spend this count or maxRuns. Available on storage-polling lanes. Takes worker options and maxRuns?: number; stops when idle, cancelled, or the limit is reached. |
createDeliveryHandler(options) | On polling lanes, requires maxDuration and returns PollingDeliveryHandler. Accepts drain options except signal, plus maintenance?: false | TickOptions. On transport lanes, options remain optional and the handler type comes from the lane, such as SqsLambdaHandler. |
executeDelivery() returns materialized with the accepted run for a schedule hint. That run executes through ordinary dispatch. An ignored hint returns schedule_settled when no due fire is accepted.
Polling handlers return Promise<PollingDeliveryHandlerResult> with { drain: DrainResult, maintenance: TickResult | undefined }. They ignore platform arguments. maxDuration must not exceed 2,147,483,647 milliseconds (about 24.8 days). It starts at handler entry and covers startup, maintenance, and draining. At the deadline acquisition stops and attempt signals abort immediately. If maintenance uses the budget, draining is skipped. Settlement continues, so leave cleanup time below the platform timeout. See scheduled polling workers for when the handler can wait for an armed fire.
Worker concurrency defaults to contractDefaults.worker.concurrency. It limits this worker's parallel attempts. A queue's concurrency is a separate shared limit enforced through storage.
Worker and drain queues take queue names, such as [emails.name]. executeNext() takes queue definitions, such as [emails]. Omitted queue filters include all registered queues. Supplied worker queue lists must be nonempty and must not repeat names. Counts must be positive integers.
Default maintenance starts only after the delivery worker is ready. Failed worker startup leaves no worker-created services running. Worker-created maintenance is shared by maintenance-enabled workers on the same runtime. The last participating worker’s close() and waitUntilClosed() wait for maintenance passes and lease releases before resolving. A new worker waits for a closing maintenance generation before starting another. Runtime close() also drains these services before releasing lane resources. Maintenance created by an explicit start({ maintenance }) call belongs to the runtime and remains alive until runtime close. Reusing automatic services does not change their ownership.
Workers reuse services already started with start({ maintenance }). A later start({ maintenance: true }) is a no-op when the running services use defaults. Start custom maintenance before workers, or pass maintenance: false to createDeliveryWorker() before starting custom services. Conflicting options reject with configuration_invalid and this guidance. The defaults come from contractDefaults.worker.maintenance and contractDefaults.worker.handleSignals.
A worker handle has close(): Promise<void> and waitUntilClosed(): Promise<void>. Close stops acquisition immediately, waits up to shutdownGrace (inherited from the runtime unless overridden), then aborts context.signal with createWorkerShutdownError() from @runlane/contracts, a RunlaneError with code task_interrupted and retryable: true. With shutdownGrace: 'unlimited', close stops acquisition and waits for attempts with no abort timer. Runtime close waits for this worker’s grace, even when it exceeds the runtime grace. It waits for attempts to settle even after abort. Errors after that abort release the run; successful returns still succeed. Aborting the worker option signal skips grace. Close is idempotent. Keep its process alive until shutdown. runlane work uses this worker API, so it supports both storage polling and transport consumption for the configured lane.
drain({ signal }) uses the same immediate abort rule: it skips shutdownGrace, stops acquisition, and aborts active attempt signals. It still waits for handlers to settle and results to be saved. See scheduled drains for function timeout budgeting.
Let TypeScript infer the runtime type from createRunlane(). Replacing a concrete lane type with the broad Lane type hides methods such as drain() and the platform handler.
When the lane changes by environment, check runlane.deliveryMode before using a mode-specific API. This read-only property comes from runlane.lane.delivery.mode and narrows the whole runtime. For an application that selects between HTTP transport and local/test polling lanes, an HTTP route can return 404 on polling lanes:
import { LaneDeliveryMode } from '@runlane/contracts'
import { runlane } from '@/runlane'
const deliver =
runlane.deliveryMode === LaneDeliveryMode.Transport
? runlane.createDeliveryHandler({ maxAttemptDuration: '240s' })
: undefined
export async function POST(request: Request) {
return deliver ? deliver(request) : new Response(null, { status: 404 })
}A mixed runtime can accept createDeliveryHandler({ maxDuration: '10s' }) before narrowing because both lane modes expose that method. The call works on a polling lane, but a transport lane rejects the polling-only maxDuration option with configuration_invalid when creating the handler. For mixed runtimes, check deliveryMode before creating a mode-specific handler, even when TypeScript accepts the call.
Create the handler once at module scope; it starts the runtime lazily on invocation. The application owns the 404 policy. The transport branch retains the native handler type supplied by the lane; the polling branch exposes drain() and requires maxDuration when creating its polling handler. A mode check does not distinguish HTTP from SQS when both transport lanes are possible, or add a handler when a worker-only transport is possible. An explicit union of a handler-capable transport and a worker-only transport therefore does not expose createDeliveryHandler().
Keep the inferred lane type through application composition; annotating it as broad Lane discards that information. Untyped lane values do not establish a capability guarantee. Give the provider boundary a concrete return type instead of casting the runtime. Checking the environment name or the nested runlane.lane.delivery.mode does not narrow the whole runtime.
Process signal shutdown
waitForWorkerShutdown(worker, controller, options) shares two-stage signal shutdown with custom hosts. WorkerShutdownOptions requires shutdownGrace and accepts an abort signal, an onShutdown callback, and duplicateSignalWindowMs for launcher duplicates (default contractDefaults.worker.duplicateSignalWindowMs, 250 ms). Pass the standard AbortController whose signal you gave the worker; the function aborts it when the grace ends or a second signal arrives. The function removes handlers when the worker settles and reports close failures.
Maintenance
Maintenance starts due schedule fires, wakes due work, resolves token deadlines, and publishes pending delivery requests. It does not run task handlers.
| Call | Return value and lifecycle |
|---|---|
runMaintenanceOnce(options?) | Promise<TickResult>. Runs one bounded pass. |
createMaintenanceHandler(options?) | (...args: readonly unknown[]) => Promise<TickResult>. Starts lazily and runs one pass using creation options. Ignores event and context arguments. |
start({ maintenance: true }) | Promise<void>. Starts lane resources and maintenance loops. Pass a MaintenanceServicesOptions object instead of true to configure them. close() owns shutdown. |
TickOptions.scheduleLookahead accepts a positive duration or false. It defaults to contractDefaults.maintenance.scheduleLookahead (1m) for one-shot calls. Set it to the maintenance interval to arm future schedule wakeups. Runs are created at fire time. false keeps due-only acceptance. It is excluded from start({ maintenance: { maintenance: tickOptions } }), whose loops keep due-time timers. See run maintenance.
TickOptions accepts optional positive integer limits: cancellationFinalizationLimit, completionResumeLimit, deliveryRequestLimit, outboxClaimLimit, scheduleMaterializationLimit, startExpiryLimit, timeoutFinalizationLimit, waitTokenResumeLimit, and waitTokenTimeoutLimit. Their defaults come from the matching fields in contractDefaults.maintenance.
It also accepts clockSkewTolerance?: DurationString and phases?: readonly MaintenancePhase[]. A supplied phase list must be nonempty. Omit it to run all phases:
| Enum member | Work performed |
|---|---|
MaintenancePhase.DeliveryRecovery | Recovers missed child-completion notifications and requests delivery for due work. |
MaintenancePhase.OutboxFlush | Publishes stored delivery requests. |
MaintenancePhase.Retention | Applies run rules and runtime rules, and drains bounded physical cleanup. Always participates in service loops unless excluded. |
MaintenancePhase.RunFinalization | Expires unstarted runs and finalizes due cancellations and attempt timeouts. |
MaintenancePhase.ScheduleMaterialization | Creates due scheduled runs. |
MaintenancePhase.WaitTokenResolution | Times out tokens and resumes their waiting runs. |
TickResult.retention is present when its phase participates. It contains the RetentionPassResult described below. TickResult also contains cancellationsFinalized, completionRunsResumed, deliveryRequested, materialized, scheduleFiresSkipped, outbox, runsExpired, timeoutsFinalized, waitTokenRunsResumed, and waitTokensTimedOut. scheduleFiresSkipped contains ScheduleFireSkip entries for singleton-held fires committed during the pass, with scheduleId, fireAt, and reason: singleton_key. Start expiry uses storage time without subtracting clockSkewTolerance.
Each field reports what its own phase did in this pass. deliveryRequested lists the runs the delivery-recovery phase requested. outbox reports the outbox-flush phase. On an eager transport runtime, an earlier phase can also start ready bounded work as soon as it commits. For example, finalizing a run frees its slot, and the next waiting run is reserved and published right away. That work is not added to deliveryRequested or outbox, so these fields are not totals of everything the pass started.
Delivery recovery and outbox scans also use storage time. The outbox phase takes a fresh storage-time cutoff after earlier phases, then keeps it fixed for the sweep. This lets it publish wakeups those phases just saved, within the outbox claim limit. Pending eager rows retain their configured grace. A maintenance process with a slow clock does not postpone due delivery work or fail its eligibility check.
Delivery recovery skips queues absent from this runtime and retains scan progress across bounded passes. Unrelated queues and pending outbox wakeups cannot permanently hide later due work. Their records stay unchanged.
An enabled priority queue reads bounded candidate pages from three bands; ordinary queues read one. Priority dispatch retains up to deliveryRequestLimit candidates per band and bounded queue so a busy band does not hide another with free capacity. A full per-key pool skips that partition's remaining candidates. A pause or full total pool skips the whole queue for that pass. Queue-wide blocks count against the shared deliveryRequestLimit, as do successful and stale attempts. A per-key block leaves the attempt budget available for other keys.
Delivery recovery also re-requests queued runs on unbounded transport queues that have waited longer than contractDefaults.maintenance.resendQueuedRunsAfter, so a wakeup the broker lost is replaced. See recover lost wakeups.
completionRunsResumed contains parents resumed by completion recovery. Its completionResumeLimit is separate from deliveryRequestLimit, so neither backlog consumes the other's budget. Recovery checks storage; it does not rerun a waiting parent or consume its retry budget.
Immediate completion notifications stop when a full page makes no progress because of contention. Durable completion recovery retries the remaining parents in later maintenance passes.
Grouped waits may advance through a bounded page without resuming a parent. Those progress-only changes are not included in completionRunsResumed.
MaintenanceServicesOptions accepts a duration for each loop: deliveryRecoveryInterval, outboxFlushInterval, retentionInterval, runFinalizationInterval, scheduleMaterializationInterval, and waitTokenResolutionInterval. Each defaults to contractDefaults.maintenance.services.interval.
For retention, retentionInterval controls checks for newly due run rules and physical cleanup, and is the base retry or stalled-pass cadence. These checks pick up manual pruning from any runtime without starting a new runtime-rule sweep before nextSweepAt. Repeated failures use the existing exponential service backoff; recovery resets it. Productive pending passes continue immediately. The sweep interval comes from retention.cleanup.interval.
All loop intervals vary randomly from half to one and a half times the configured value. A loop wakes earlier for a due time found by its last pass or saved by the same runtime. Full passes that make progress continue without interval sleeps. See timer precision for limits and tuning.
Band leases renew every third of their duration. A failed renewal keeps passes running until the local renewal deadline; proven ownership loss stops new passes immediately. The deadline is the monotonic send time of the last confirmed claim or renewal, plus the lease duration, minus one renewal interval. A renewal sent by the deadline may still confirm ownership when its reply arrives later. It must confirm before the hard bound: the last confirmed send plus the full lease duration. At that bound, Runlane gives up even if the request is still in flight. A late success cannot restore ownership. In-flight passes remain fenced by storage.
Band lease refresh and standby polling cap their native timer delays at the platform timer limit. Long leases retain their configured validity; timer overflow cannot turn these waits into rapid polling or refresh writes.
MaintenanceServicesOptions.phases selects a nonempty list of phases, just like TickOptions.phases. Omit it to start all applicable loops. Use [MaintenancePhase.Retention] for a dedicated retention service.
Other service options are maintenance (tick options without phases and scheduleLookahead), maintenanceLeaseDuration, onServiceError(error, { phase }), and onServicePass(result, { phase }). start({ maintenance }) does not accept a service signal; use runtime close() for shutdown. Repeating default maintenance startup is a no-op when defaults are already running, including concurrent calls. Conflicting custom options reject with configuration_invalid and guidance to pass maintenance: false to the worker. Plain start() remains a no-op after startup. Without onServiceError, close() rejects with the first recorded service failure after cleanup. With it, the application owns the failure policy.
Independently reported retention failures remain visible through onServicePass as RetentionPassStatus.Failed. They do not call onServiceError, add a second service failure log, or cause close() to reject.
Service loops share one schedule owner per set of declared schedule IDs. Registration order and definition edits keep the same ownership group. A runtime created without a task list uses the schedules registered so far each time it claims the lease. Different sets create their own scheduled runs; overlapping schedules still create one run per occurrence. Other maintenance bands share one owner per environment. One-shot runMaintenanceOnce() calls do not take band leases. Retention also takes its own sweep lease across all entry points, including one-shot calls.
See run maintenance for deployment and recovery guidance.
Runtime close() owns maintenance shutdown; a closed runtime cannot restart.
Queue definitions and controls
runlane.queueDefinitions exposes the frozen registered queue array. runlane.queues exposes durable pause, resume, setLimit, resetLimit, and get methods. See queue operations. Queue declarations accept concurrency: { total?, perKey? }; omission is unbounded, and a present object requires a positive safe-integer bound.
Lifecycle delivery policy
createRunlane() accepts runtime onSuccess, onFailure, onCancel, onComplete, and middleware. Runtime hooks apply to tasks without task-level hooks too. The hooks options are retry, timeout, leaseDuration, and discoveryTimeout. hooks.retry uses the same RetryPolicy as task retries; maxRetries: 0 turns retries off. The timeout, leaseDuration, and discoveryTimeout defaults come from contractDefaults.hooks. The timeout must be shorter than the independent hook lease. Callback failure never changes a saved terminal outcome.
Automatic run retention
Automatic retention keeps a live idempotency key after deleting its run. A repeat trigger within idempotencyKeyTTL returns returned_existing with the saved final RunSnapshot, without creating or executing work. During that window, runs.get() and runs.findCurrent() still return undefined for the deleted run. Retention saves the owner and snapshot only when they fit within contractDefaults.storage.maxRecordBytes. Larger records keep the run until the key expires. Failed runs and IdempotencyKeyTTLMode.Active release the key when the run ends. Manual runs.prune() removes the key; idempotencyKeys.reset() also clears a saved result.
A caller-chosen runId has no TTL. Once deletion finishes, the ID is free again and the same trigger can execute new work. Use an idempotencyKey when you need a promised deduplication window.
createRunlane({ retention }) and task retention accept an object with optional succeeded, failed, cancelled, and expired rules. Each outcome accepts exactly these values:
| Value | Effect |
|---|---|
RunRetention.DeleteImmediately | Delete after the final result is saved and completion waiters are notified, when the run is simple and unheld. |
RunRetention.deleteAfter(duration) | Delete after the given duration from the final result. For example, RunRetention.deleteAfter('7d'). |
RunRetention.KeepForever | Never delete automatically. Manual runs.prune() can still delete the run. |
import { createRunlane, RunRetention } from '@runlane/core'
import { lane, queues, tasks } from './definitions.js'
export const runlane = createRunlane({
lane,
queues,
tasks,
retention: {
succeeded: RunRetention.deleteAfter('7d'),
failed: RunRetention.deleteAfter('30d'),
cancelled: RunRetention.deleteAfter('7d'),
expired: RunRetention.KeepForever,
cleanup: { interval: '12h', batchLimit: 500, maxBatches: 10, leaseDuration: '1m' },
},
})A runtime with retention rules decides every outcome; outcomes it does not list are kept forever. A task overrides the outcomes it lists. A run copies these resolved rules when it is created. If the creating runtime has no outcome rules, it copies only the task's rules and leaves other outcomes unset. Changing either level affects new runs only, including new runs created by retry or rerun. The public run record and run.created event expose that snapshot: delete_immediately, delete_after with milliseconds, or keep_forever, tagged by RunRetentionType.
For a run with no copied rule for its final status, maintenance uses its own runtime rule for that status. This covers older runs and unset outcomes on runs created by runtimes without outcome rules. An unset rule or KeepForever keeps the run. Keep fallback rules consistent across maintenance owners in the same environment.
Bare duration strings, a single-value task shorthand, retention.runs, and top-level cleanup fields are not accepted. An empty object sets no rules. Durations accept ms, s, m, h, d, w, and y; a week is exactly 7 days (604,800,000 ms), and a year is exactly 365.25 days (31,557,600,000 ms), matching ms. Months are not supported.
Only runtime retention accepts cleanup:
retention.cleanup field | Type and behavior |
|---|---|
interval | Positive duration between completed runtime-rule sweeps and between run-rule restarts. Defaults to contractDefaults.retention.interval. The first sweep starts immediately. |
batchLimit | Positive safe integer limiting candidate runs per discovery page in each scope. Defaults to contractDefaults.pruning.batchLimit. |
maxBatches | Positive safe integer limiting discovery pages shared by both scopes, with one page reserved for an active runtime-rule sweep; separately limits collection batches per invocation. Each collection batch can delete several simple runs and advance one complex run. Defaults to contractDefaults.retention.maxBatches. |
leaseDuration | Positive duration for sweep ownership. Defaults to contractDefaults.retention.leaseDuration. Checkpoints refresh ownership between pages. Cleanup checks ownership before each batch and renews when half or less of its validity remains. A slow page can outlive its lease and fail safely. |
RetentionPassResult reports status, prunedCount, collectedRunCount, deletedChildRecords, and hasMore. prunedCount counts runs that became absent, through direct deletion or tombstoning; collectedRunCount counts runs whose storage was fully removed, including direct deletion. deletedChildRecords also counts expired saved idempotency owners. The expiry sweep uses cleanup.batchLimit and cleanup.maxBatches, halves pages on storage limits, and runs even without outcome rules. These counters describe a successful invocation, not the sweep's lifetime total.
RetentionPassStatus has Busy, Idle, Pending, Completed, and Failed members with corresponding snake_case values. Busy means another caller owns the sweep. Pending means discovery or physical cleanup remains. Completed means this invocation finished discovery and no physical cleanup remains. Idle means no discovery was due and no physical cleanup remains. Failed reports an independently logged failure; committed changes remain durable, and counters are zero because the pass could not report a complete result. Both Busy and Failed return hasMore: true.
hasMore signals unresolved work. Invoke another pass promptly only for a productive Pending result. Retry Busy, Failed, or a pass with no progress on the normal schedule cadence. See the bounded drain example.
Idle checks read the checkpoint and bounded backlog indexes without claiming or refreshing the sweep lease. Lag metrics still update. When discovery or cleanup is needed, the pass claims the lease and rechecks the checkpoint before changing data.
At construction, each deleteAfter duration must produce supported creation deadlines and fallback cutoffs when applied to the configured clock. cleanup.interval and cleanup.leaseDuration must also produce supported timestamps. Out-of-range values reject with configuration_invalid and name the invalid field. A clock.now() call that throws or returns an invalid value reports a clock configuration error. Runtime writes still use storage time.
nextSweepAt, when available, is the runtime-rule sweep's next deadline; while discovery is active it remains the sweep start time. sweepStartedAt and sweepAgeMs describe only that scope. historyLagMs takes the larger of run-rule deadline lag after settling and a conservative runtime-rule lag. The runtime sample checks the oldest candidate's actual status rule; a kept or not-yet-due candidate reports zero. Held runs can contribute to lag. garbageCollectionLagMs measures the oldest indexed physical-cleanup tombstone's age. Idle run-rule probes sample after the saved cursor until restart, so holds behind it reappear in lag observations at restart. Backlog observations are bounded index reads and may change immediately under concurrent work; they are not exact backlog counts. Busy or failed passes report zero ages because they did not finish sampling progress.
Run-rule discovery continues on each pass after a one-minute settle margin, allowing for slow commits and clock differences. It keeps a durable sort position and restarts every cleanup.interval to revisit holds and delayed commits. Packed simple-run deletion uses a 500-record transaction budget and reduces it when storage rejects a batch. Automatic retention and runs.prune() share eligibility, packed simple-run deletion, and chunked tombstone cleanup. Every maintenance deletion transaction checks the shared lease after its reads. RunRetention.DeleteImmediately also deletes simple, unheld runs after durable completion and waiter notification, without that lease; failures leave the saved outcome intact for maintenance. runNow() returns a payload-free RunSnapshot; other execution calls return the saved record, while lagging watchers can receive run_not_found. Only MaintenancePhase.Retention performs maintenance physical cleanup; RunFinalization only finalizes runs. It does not prune wait tokens or the observation export stream. See pruning and recovery.
runtime.hasRetentionRules is a read-only boolean derived from runtime fallback rules and registered task rules. It reports whether any rules are configured, including explicit keep-forever rules.
Default interruption allowance
See Stop crash loops for how Runlane resolves createRunlane({ maxInterruptions }) into an accepted run's allowance.