Tasks and context
Task definitions, queues, retry rules, schedules, and handler APIs.
Import task, queue, the enums, and the types on this page from @runlane/core.
Task definitions work with both local and test lanes. createLocalLane() stores runs in runlane dev and fails on storage use without dev. Use createTestLane() with drain() or executeNext() for in-process task tests.
Where each call lives
| Namespace | Meaning | Calls |
|---|---|---|
context.step | Saved under a key you choose | run, trigger, triggerBatch, triggerAndWait, triggerBatchAndWait, sleep, waitForSignal |
context.wait | Waits on something that already exists; no key | until, forToken, plus createToken and getToken |
context.logger | Durable application logs | debug, info, warn, error |
context.stream(name) | Durable named output | append, appendBatch, pipe |
context | Runs | trigger, triggerBatch, join, release |
Task definition
task(options) returns a reusable task definition. Include run in each process that executes the task. Producers can share its schema and defaults without importing the handler.
| Option | Type and behavior |
|---|---|
id | Required, nonempty task ID. Keep it stable across deployments. Colons are reserved. |
schema | Required Standard Schema for the payload. The handler receives the validated output. |
run | Worker handler: run(payload, context). Required for execution; omit it for a producer definition. Return JSON output, undefined, or a promise of either. Await waits to suspend the attempt. |
output | Optional Standard Schema for successful output. Enables typed reads with runlane.runs.get(task, runId). |
streams | Optional map of names to Standard Schemas with JSON output. context.stream(name) accepts only declared names and types appends by the schema input. |
queue | Optional registered QueueDefinition. Falls back to the runtime's default queue. |
retention | Optional TaskRetention: an object with per-outcome rules, using the same values as runtime retention. See task retention. |
retry | Optional retry policy. Omit it to disable automatic retries. |
maxInterruptions | Optional non-negative safe integer or 'unlimited'. Allowance for consecutive interruptions without a new checkpoint. See Stop crash loops. |
maxAttemptDuration | Optional DurationString that limits each attempt. Execution options can override it. |
schedule | Optional static schedule or list of schedules, described below. |
idempotencyKey | Optional string or (payload) => string | undefined. Reuses a run with the same key. |
idempotencyKeyTTL | Optional DurationString or IdempotencyKeyTTLMode.Active. Requires an idempotency key. |
singletonKey | Optional string or payload resolver. Allows only one active run for the key. |
singletonConflict | Raw-trigger policy: SingletonConflict.Reject or SingletonConflict.ReturnExisting. Call options override it; omission uses contractDefaults.run.singletonConflict. Reuse requires an active holder of the same task. Schedules, linked retries/reruns, and named child steps still reject conflicts. |
concurrencyKey | Optional string or payload resolver. Shares capacity within a bounded queue. |
TaskContext<TStreams> and TaskHandler<TPayload, TStreams> carry the declared stream map. The handler and task middleware infer it from streams. A bare TaskContext does not describe a particular task's names. Let task() infer the context to keep TypeScript checks for names and chunk inputs.
Key resolvers receive the validated payload. Trigger options can override the task's key settings.
Payloads and outputs must be JSON-compatible, or undefined where the schema allows it. Output schemas may accept a different input shape, including omitted defaulted fields. The handler return is still checked for JSON compatibility before storage. Payload validation and transforms run when the run is created. Later attempts reuse the stored payload. Changing a task's schema does not migrate old runs.
A successful handler's output is validated before storage. A typed read validates the stored output against the supplied task's current output schema. Keep that schema compatible with retained results.
See define and trigger tasks for a complete example.
Task retention
Task retention uses the same outcome names and three rule values as runtime retention:
import { RunRetention, task } from '@runlane/core'
import * as z from 'zod'
export const sync = task({
id: 'integrations.sync.scheduled',
schema: z.object({ integrationId: z.string() }),
retention: {
succeeded: RunRetention.DeleteImmediately,
failed: RunRetention.deleteAfter('7d'),
},
})This overrides successful and failed outcomes. cancelled and expired inherit the creating runtime's rules, including KeepForever for omitted outcomes when that runtime defines any rule. If the runtime has no outcome rules, unlisted task outcomes have no copied rule. See rule resolution and snapshots. Producer definitions accept the same option. Tasks do not accept cleanup or a single-value shorthand.
When DeleteImmediately deletes
Runlane deletes the run right after it saves the final result and notifies any runs waiting on it. Calls such as runNow() and executeNext() still return the saved run. Some runs are deleted later:
- A run with pending lifecycle hooks is deleted after its last hook finishes. A failing hook first retries on the hook retry schedule.
- A run whose child result cannot fit in a saved step stays held. See child result retention.
- A run with legacy child bindings, wait-token links, streams, or too many records for one transaction is deleted by maintenance.
- If deletion fails, Runlane logs
run_completion_deletion_failedand maintenance deletes the run later. The saved result does not change.
Keep maintenance running so these runs are cleaned up.
What deletion removes
After deletion, runs.get(), the CLI, runs.retry(), and runs.rerun() cannot find the run. A runs.watch() that has not yet seen the final state can end with run_not_found. A raw context.join() wait is rejected with configuration_invalid if any final status has a DeleteImmediately rule. Use context.step.trigger(stepKey, task, payload) and join its result, or use RunRetention.deleteAfter(duration). Named steps preserve results through child result retention. If someone needs to read the run after it ends, use a short duration such as RunRetention.deleteAfter('1h') instead. See automatic 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.
Validation
Unknown keys, bare duration strings, malformed or non-positive durations, and durations too large to store reject with configuration_invalid. An empty object sets no task overrides. Messages name the field, such as retention.failed.duration. Runlane checks durations against the runtime clock when it registers the task. Producer definitions accept the same option.
Producer definitions
Runlane copies retry, maxAttemptDuration, and maxInterruptions from the triggering runtime into the run. Put these policies in the shared definition. Worker-only policy changes do not affect accepted runs. A worker logs worker_task_policy_mismatch once per task per runtime when its retry or duration policy differs, naming the fields.
Keep a shared definition in a module that does not import handler code or worker-only dependencies:
import { task } from '@runlane/core'
import * as z from 'zod'
export const greet = task({
id: 'greet',
schema: z.object({ name: z.string() }),
output: z.string(),
retry: { maxRetries: 2 },
})The worker imports that definition and adds its handler:
import { task } from '@runlane/core'
import { greet as definition } from './greet-definition.js'
export const greet = task({
...definition,
run: ({ name }) => `Hello ${name}`,
})Register the shared greet in the producer's tasks and the executable greet in the worker's tasks. Both runtimes must use the same environment, storage, and queue policies. With the local lane, separate processes share runs through runlane dev when they find the same config file and use the same lane name.
Use trigger(), triggerBatch(), or batch.trigger() with the shared definition. Payload validation, key resolvers, and accepted execution policy work the same way as executable tasks.
A shared output schema supports typed runs.get(definition, runId) and joins without importing the handler. Raw and named child triggers accept shared definitions too.
TaskDefinition<TPayload, TInput> describes the shared shape. Task requires a handler. A runtime can resolve a shared definition to its registered implementation only when their normalized schemas and settings match. Streams must have the same names and the same schema instances; name order does not matter. Reuse the shared schemas, resolvers, and defaults. Registering a matching producer definition before its implementation, or after it, resolves to the implementation. Two implementations with the same ID remain invalid.
runNow() requires an executable task. Do not start workers on a producer-only catalog. A worker claims a run by taking time-limited ownership in storage. It only claims runs for tasks it has a handler for. Runs of other tasks stay queued until a worker with a handler claims them, and the skipping worker logs worker_task_missing. See change tasks safely. Sharing a definition does not pin a deployment version.
Retry policy
Task retry and runtime hooks.retry accept the same RetryPolicy fields:
| Field | Type and behavior |
|---|---|
maxRetries | Required non-negative safe integer. Maximum automatic retries after failures, excluding the initial attempt. 0 disables automatic retries. |
backoff | Optional DurationString for a fixed delay, or the object below. Defaults to contractDefaults.retry.backoff. |
A backoff object requires type and delay:
| Field | Type and behavior |
|---|---|
type | RetryBackoffType.Fixed or RetryBackoffType.Exponential. |
delay | DurationString for the base delay. Fixed backoff uses it for every retry. Exponential backoff uses delay × 2^(retryNumber - 1) before applying the cap, starting with retry number 1. |
maxDelay | Optional DurationString that caps the delay. Must be at least delay. |
For tasks, the durable run.counters.retries count determines the remaining allowance and the next retry's delay. Releases, joins, wait resumptions, and expired-lease recovery do not spend or reset this allowance, or advance backoff. Attempt timeouts are failures and use the same retry budget. Neither tasks nor hooks add automatic jitter.
With a retry policy, an ordinary thrown Error is retryable. A RunlaneError uses its own retryable field, which defaults to false. A retry still requires a policy and remaining retries; maxRetries: 0 never schedules one.
For the maxAttempts to maxRetries conversion, follow Upgrade Runlane.
See retry failed work for a task that retries temporary failures and stops on a permanent failure.
Task interruptions use a separate budget. See stop crash loops.
retryPolicySchema from @runlane/core or @runlane/contracts is the canonical input parser for tasks and hooks. Its readonly input type is RetryPolicy. It resolves durations and default backoff into ResolvedRetryPolicy. retryBackoffSchema and its readonly input type, RetryBackoff, parse a standalone backoff value. They are available from the same package roots. resolvedRetryPolicySchema validates an already resolved policy. getRetryDelayMilliseconds(policy, retryNumber) returns the fixed or capped exponential delay in milliseconds for a one-based retry number.
Hooks use contractDefaults.hooks.retry when the entire policy is omitted. A supplied policy with no backoff uses contractDefaults.retry.backoff, just like a task. Each hook callback gets at most maxRetries + 1 attempts. Claims spend these attempts, including claims that expire before invocation or settlement. A claim aborted before invocation refunds its attempt. A non-retryable failure stops that callback at once. The saved lastFailure.retryable reflects the hook policy, independently of the task policy. See hook delivery and retries.
Stored execution policy
Every accepted run saves its task's retry settings, maxAttemptDuration default, and effective maxInterruptions allowance. Workers and timeout recovery use that snapshot across deployments. Ordinary, child, batch, scheduled, and runNow() creation all save it.
runs.get() exposes executionPolicy: RunExecutionPolicy; run.created stores the same policy. Every snapshot requires maxInterruptions. Omitting retry or maxAttemptDurationMs disables that setting. Missing optional fields never inherit later task settings.
| Field | Stored meaning |
|---|---|
maxInterruptions | Required non-negative safe integer or 'unlimited'. The effective allowance resolved at acceptance. |
maxAttemptDurationMs | Optional positive safe integer in whole milliseconds. Omission disables the task-level deadline. |
retry | Optional ResolvedRetryPolicy. Omission disables automatic retries. |
retry.maxRetries | Required non-negative safe integer with the failure-only counting behavior above. |
retry.backoff | Required object with type: RetryBackoffType, delayMs, and optional maxDelayMs. Durations are positive safe integers in whole milliseconds. |
Retry defaults and the effective crash allowance are resolved before storage. Accepted runs keep that allowance even if the shared default later changes. runExecutionPolicySchema and resolvedRetryPolicySchema validate these shapes, including backoff bounds. getRetryDelayMilliseconds(policy, retryNumber) computes the delay for a one-based retry number within the validated budget, using the same calculation as runtime execution.
Idempotency reuse, debounce, named replay, retries, and releases retain the accepted policy. Each new child uses its own task settings. runs.retry() and runs.rerun() create new runs with current settings.
Execution options can override the saved duration for one attempt, including with a longer duration. The attempt stores its resulting absolute deadline. This does not rewrite the snapshot or carry the override to another worker.
Handler code and output schemas remain current. The snapshot pins execution policy, not a deployment version.
Runs and creation events without executionPolicy fail to decode. See storage compatibility before reusing retained history.
Queue definition
queue(options) returns a QueueDefinition.
| Option | Type and behavior |
|---|---|
name | Required, nonempty queue name. Colons are reserved. |
default | Optional boolean, default false. At most one registered queue may be the default. |
concurrency | Optional { total?, perKey? } with at least one positive safe integer. Caps total capacity, per-key capacity, or both. Omit it for an unbounded queue. |
dispatchTimeout | Optional DurationString. Requires concurrency; controls recovery of a dispatched capacity reservation. |
priorityBoost | Optional positive DurationString. Requires concurrency; enables high, normal, and low admission priority. See priority for ordering and the coordinated upgrade. |
Use matching queue definitions in producers, workers, and maintenance processes. A task's concurrencyKey requires a bounded queue. See limit concurrency for capacity behavior.
Schedules
Set schedule on the task to one schedule or a list. Each entry needs a stable id and a payload accepted by the task. Omit the payload only when the task schema accepts undefined. All entries also accept queue?: QueueDefinition and enabled?: boolean.
Choose one timing form per entry:
| Form | Fields |
|---|---|
| Once | runAt: Date |
| Interval | every: DurationString, with optional startsAt: Date and endsAt: Date |
| Cron | cron: string, with optional timeZone: string |
Interval schedules without startsAt use the Unix epoch (1970-01-01 UTC) as their cadence origin.
These are static task definitions, not a runtime schedule editing API. Maintenance must register the tasks and run to create due occurrences. See schedule tasks.
Handler context
Every handler receives a TaskContext as its second argument. A resumed attempt starts it again from the beginning. To park a handler means to leave its promise pending while Runlane saves the wait and frees execution capacity.
| Member | Behavior |
|---|---|
logger | Synchronous TaskLogger; accepted writes drain before the attempt outcome. |
stream(name) | Returns an attempt-owned RunStreamWriter. Declare chunk schemas on task({ streams }). See streams. |
run | RunRecord snapshot at handler entry, including the run ID, payload, and metadata. |
updateMeta(patch) | Returns Promise<RunRecord>. Commits top-level JSON metadata keys under the active lease. See metadata updates. |
addTags(tags) | Returns Promise<RunRecord>. Adds indexed labels under the active lease. See run tags. |
attempt | Current attempt number. A resumed release starts another attempt. |
signal | AbortSignal for cancellation, attempt deadlines, lease loss, worker shutdown, and platform time limits. Pass it to fetch() and other work that supports it. |
isCancellationRequested() | Returns true once the worker has seen a cancellation request for this run. It can stay false briefly after the request. Other abort causes leave it false. See cancel runs. |
trigger(task, payload, options?) | Returns Promise<TriggerRunResult>. Creates a child run linked to the current run. Takes the runtime trigger options. |
triggerBatch(items, options?) | Submits linked children using the runtime batch contract. No named replay binding is created. |
batch.trigger(items, options?) | Alias of triggerBatch(), with the same options and behavior. |
join(childOrRunId) | Returns WaitPromise<RunWaitResult, JsonValue | undefined>. Parks while active, then resolves with ok, output or error, and run. |
join(task, child) | Applies the supplied task's output schema to successful raw output, matching typed run reads. Requires the matching task and environment. |
join(children) | Accepts child references or run IDs. Returns a WaitPromise of results in input order, including duplicates, after every member is terminal. An empty group returns []. |
join(task, children) | Applies one matching task's current output schema to every successful result in the group. |
release(delay, options?) | Returns Promise<never>. Ends the attempt so the handler runs again from the top after the delay. delay is a DurationString; options are reason?: string and meta?: JsonObject. |
Plain context.trigger() has no replay binding. Handlers restart from the top on retries, after waits resume, and after lease recovery. A plain child trigger runs again and can create another child. Use context.step.trigger() or an idempotencyKey when the child must be reused.
Wait safety
Await every wait. A pending wait records a pause. Its promise never settles in that attempt. Surrounding catch and finally blocks do not run. The next attempt starts from the top. Code after the await runs only after the wait resolves. release() always parks and never resolves. Pauses record no failure, spend no retry budget, and do not increase retry backoff. Every new attempt still increases the attempt count.
When an output-typed handler ends by releasing, write return context.release(...). TypeScript does not treat a final await context.release(...) as the end of the function.
An attempt can stop at any wait, the same way it stops when a worker crashes. Do not hold a connection, lock, or open span across a wait. Open them inside step.run.
Promise.all over several waits runs them one after another across attempts. Use join(children) or a batch call for children. Runlane waits for admitted work to settle before recording the release. Invocation handoff can defer unsaved work to the next attempt.
Do not race a wait against your own promise with Promise.race. If your promise wins, your code continues after the pause was recorded. Use the wait's timeout option when it has one. A recorded pause still wins over a handler return or throw; Runlane warns once if the handler settles before the release is stored.
After a pause, new context operations also park. After an attempt ends without a pause, late context operations reject with operation_cancelled. A pause leaves the attempt's abort signal unchanged. Operator cancellation and attempt deadlines take precedence; a lost lease abandons the attempt.
A signal carries no stored application result. On every resumed attempt, read the saved application state before deciding whether to wait again. A signal sent before a waiter exists is not saved. See wait without failing for a complete example with a timeout that recovers from a missed signal.
Wait results and unwrap
Every run, token, or signal result uses ok to separate success from failure. The exported types are defined once in contracts:
// TSuccess contains fields available only after success.
type WaitResult<TSuccess extends object = Record<never, never>> =
Readonly<{ ok: true } & TSuccess> | { readonly ok: false; readonly error: RunFailure }
type RunWaitResult<TOutput extends JsonValue | undefined = JsonValue | undefined> = WaitResult<{
readonly output: TOutput
}> & { readonly run: RunSnapshot<TOutput> }
// A completed token has parsed output. Failure can carry a pending, expired, or completed token.
type TokenWaitResult<TOutput extends JsonValue> =
| {
readonly ok: true
readonly output: TOutput
readonly token: Omit<CompletedWaitToken, 'output'> & { readonly output: TOutput }
}
| { readonly ok: false; readonly error: RunFailure; readonly token: WaitTokenRecord }
interface WaitPromise<TResult, TOutput> extends Promise<TResult> {
unwrap(): Promise<TOutput>
}TriggerRunResult.run and RunWaitResult.run use RunSnapshot: the public run record without payload. This applies to every trigger and join API, including batches and named steps. Use runs.get(result.run.id) for the full record while it still exists.
For a join, ok: true means the run succeeded. A failed result carries the run's stored RunFailure; cancellation uses operation_cancelled, and start expiry uses task_timed_out. A typed join exposes TOutput after if (result.ok). Untyped joins expose raw stored JSON. Failure has no output field; success has no error field.
const child = await context.step.trigger('index', indexDocument, payload)
const result = await context.join(indexDocument, child)
if (result.ok) return result.output
// result.error is a RunFailure; result.run contains the terminal run.unwrap() returns output for runs and tokens, nothing for signals, or an array of outputs for a group. On failure it throws a non-retryable RunlaneError. Its message includes the unsuccessful run or token and the reason. Metadata includes runId and status, or tokenId. A group names its first unsuccessful run in input order. The parent stores this message and metadata if the handler lets the error escape. Both the result promise and unwrap() park while the wait is pending.
Durable steps
context.step.run(stepKey, { output: schema }, callback) returns a promise of the schema's output. The callback receives { token }.
The first successful call saves its validated result under that key within the run. Later attempts reuse that result and skip the callback. The callback can still run again if the process stops before the result is saved. Pass token as the external service's idempotency key when it supports one. The token is unique to the run and step key and stays the same on every attempt. See make side effects safe to repeat.
All context.step.* calls share one counter per key per attempt: run, trigger, triggerAndWait, each triggerBatch or triggerBatchAndWait item in item order, sleep, and waitForSignal. Each trigger-and-wait call counts its key once. The first call keeps the plain key. Later calls use key#2, key#3, and so on. Runlane assigns the number synchronously at call time, before any await. Keys written by handlers cannot contain : or #.
A call that fails without saving a result gives its number back if it still holds the highest number for that key. A manual retry after a caught failure can then use the same stored key, and a later attempt can replay it. Saved or replayed results keep their numbers if later delivery or observation fails.
Keep repeated calls in the same order on every attempt. Follow the replay rules when a list or branch can change.
Saved callback results are reused without applying a new schema transform. See save step results.
context.step.sleep(stepKey, delay, options?) returns Promise<void>. It pauses once under a stable key. Replay resolves immediately from its saved checkpoint. Options are reason?: string and meta?: JsonObject.
context.step.waitForSignal(stepKey, signalKey, options?) returns WaitPromise<WaitResult, void>. Its saved result is { ok: true } when signaled or { ok: false, error } with wait_timed_out when timed out. Use .unwrap() to fail the parent on timeout. Options add timeout?: DurationString to the same audit fields. A timeout starts when this wait is first recorded. Signals have no payload and do not retain messages sent before a waiter exists.
A loop can reuse a wait key. Its calls use pause, pause#2, then pause#3, so each pass waits once. A wait and a result step can use the same handler key in either order because their counted calls have different stored keys. Keep each call's step kind the same across attempts; storage rejects a saved key that holds another kind.
A resolved keyed wait saves its checkpoint with the resume or claim. If the run paused for the wait, that checkpoint does not count as progress for the next attempt. See Stop crash loops for the interruption rules and wait without failing for examples.
context.step.trigger(stepKey, task, payload, options?) returns Promise<TriggerRunResult>. It atomically creates a child and saves the binding under the parent's active lease. It accepts the runtime trigger options. Later attempts return the bound child before validating a new payload. The first accepted payload and options win; another task or an incompatible explicit run ID is rejected.
context.step.triggerAndWait(stepKey, task, ...args) accepts the same arguments as step.trigger, requires an output schema, and returns WaitPromise<RunWaitResult<TOutput>, TOutput>. It triggers one counted child and performs a typed join. Replay reuses that child.
const output = await context.step.triggerAndWait('index', indexDocument, payload).unwrap()Callback results, child bindings, and waits share the same counted key namespace. Child failure, cancellation, or idempotency-key expiry does not reset a binding. Shared business idempotency may bind an existing child without changing its creation source. Named bindings preserve results as described under child result retention.
context.step.triggerBatch(items) accepts NamedTriggerBatchItem values: ordinary batch items plus a stable stepKey. Its alias is context.step.batch.trigger(items); both spellings share the same function and saved bindings. It returns one TriggerRunResult per input in the same order. Existing bindings replay their accepted children without validating their payloads again. Runlane validates every missing child, then accepts all missing bindings and children in one storage transaction.
context.step.triggerBatchAndWait(items) and context.step.batch.triggerAndWait(items) create missing named children and park the parent in one transaction, then return every terminal child result. They return WaitPromise<TaskBatchWaitResults<TTasks>, { readonly [K in keyof TTasks]: TaskBatchWaitOutput<TTasks[K]> }>. Tuple inputs preserve each item's output type where its task has an output schema; other items use raw JSON. Results keep input order. .unwrap() returns all outputs or throws for the first unsuccessful run.
When the parent pauses, Runlane saves children prepared by admitted triggerAndWait() and triggerBatchAndWait() calls with the parent release. One transaction saves the children, their bindings, and result retention, and frees the parent's capacity. This applies to sleep, signal and token waits, and explicit releases. Runlane registers a completion waiter only when the first pause waits for a child.
If a named wait rejects with task_output_invalid, the handler can catch it before a pause is selected. If a pause has already been selected, Runlane waits for the started output validations and uses the failure to settle the attempt.
See Invocation handoff for how handoff affects named child waits.
Concurrent callers keep their input order. Replay reuses bindings before validating new payloads. Terminal children resolve without another release. The whole plan must fit storage. A limit rejection exposes no children and does not save a release. Use raw batches and explicit joins for larger fan-out.
Duplicate stepKey values are counted in item order, so each item has its own binding. The call rejects without committing any missing child if a missing item is invalid, conflicts with a binding, or repeats another missing item's requested runId. Runlane sets no count cap on named batches. If the complete transaction exceeds the driver's capacity, it fails with storage_limit_exceeded and no partial write. Effective idempotency, debounce, and singleton owner keys must also be distinct among missing items. Submit those operations separately when two steps intentionally share one owner. Existing bindings remain saved.
Eager delivery runs after the storage transaction commits. Affected children report deliveryError for failed publication or admission under saved changes and delivery errors; the parent can continue successfully. Named batches have no batch identity. Unlike raw batches, named step batches do not return per-item errors or accept an outer concurrency option. An empty batch returns [].
A group join resumes the parent only when every member is terminal. Results preserve caller order and duplicates. Runlane saves bounded wait progress without starting an intermediate parent attempt.
There is no separate count cap on joined lists. The stored wait must fit the product record limit and the driver's atomic capacity. If it is too large, the parent fails with non-retryable storage_limit_exceeded and the oversized wait is not saved. Joins do not create retention bindings; use named triggers when child results must survive pruning. A raw join on an already deleted run fails with run_not_found and names DeleteImmediately retention as a possible cause.
Await join() to free execution capacity while children remain active. Completion notification recovery runs during delivery maintenance and does not consume parent attempts. Normal resumed execution still advances the attempt count. Moving a parent into cancelled also cancels unfinished children it created and awaited, including concurrent named siblings and all group members, unless another registered waiter or another parent's named binding protects them. Unjoined children keep running. A raw join from another run does not guarantee protection for every group member; see awaited-child cancellation. See trigger child tasks for the complete pattern. Follow Upgrade Runlane when changing an existing deployment.
Child result retention
A named child is kept until its final result is copied into the parent's saved step. It then follows its own retention rule, even when the parent uses KeepForever. Replay and named joins read that saved result after the child is deleted. The saved RunSnapshot includes the final output or failure and the public fields read at that time, without payload; later hook or metadata changes do not update it.
A named child's ID can be saved in a step.run() checkpoint and joined after replay. Runlane resolves it through the parent's durable binding, even after the child run is deleted. Named join reads use bounded transactions and retry smaller windows when storage reports a capacity limit. Results keep caller order and duplicate positions.
Core attempts copies before completion waiters resume. Work left after the bounded completion pass keeps the child readable until maintenance finishes the copy. A snapshot that exceeds the storage record limit keeps the child held while the parent can replay. Once a terminal parent is eligible for pruning, cleanup may release its outgoing steps to break retention cycles while preserving incoming holds on its own result. Bindings written by 0.9, and bindings to stored children on custom providers with eventual indexes, keep counter holds until cleanup removes them. A named step that reuses an already deleted run saves its idempotency result when it binds, without a child hold. A very long step key can still exceed the record limit; the attempt fails with storage_limit_exceeded. These holds can require another maintenance sweep after retention.cleanup.interval.
Wait until a date
context.wait.until(date, options?) returns Promise<void>. Pass a valid Date; options are reason?: string and meta?: JsonObject. It parks until that time and resolves at once when the time has passed. It uses the later of storage claim time and the runtime clock, so a slow worker clock cannot repeatedly pause an already due run. It needs no key and saves no checkpoint. An invalid date fails with configuration_invalid and explains what to pass.
await context.wait.until(new Date(payload.sendAt), { reason: 'scheduled_send' })Context wait tokens
| Call | Return value |
|---|---|
context.wait.createToken(options?) | Promise<CreateWaitTokenResult>. Uses the same creation options as the runtime token API. |
context.wait.getToken(tokenId, { output: schema }) | A promise of a typed token or undefined. Validates a completed token's output. |
context.wait.forToken(tokenId, { output: schema, timeout?, reason?, meta? }) | WaitPromise<TokenWaitResult<TOutput>, TOutput>. Parks while pending and validates completed output. A missing token fails with wait_token_not_found. |
Without an idempotencyKey, context.wait.createToken() uses the run id and the call's position among keyless creations. The same call returns the same token on replay. Explicit keys are used as given and do not spend a call number. outcome is created for a new token and returned_existing for a reused token, including one already completed or expired. Automatically created tokens are retained until the run is pruned, so token pruning cannot change their replay identity. Set idempotencyKeyTTL only with an explicit key.
Use waitToken({ id, output: schema }) to share the schema with completion callers. Pass the definition as context.wait.forToken(tokenId, definition), or { ...definition, timeout }. Invalid stored output returns ok: false with wait_token_output_invalid; recovery needs a new token because completed tokens are immutable.
Await context.wait.forToken() and test result.ok before using result.output. Token expiry returns ok: false with wait_token_expired. .unwrap() returns parsed output or throws a non-retryable error.
The optional timeout: DurationString bounds this call only. A pending window that reaches its deadline returns ok: false with wait_timed_out; the token stays pending and can still complete. The token's own createToken timeout still expires it. Each timed call is counted per token ID in an attempt. Keep that call order stable: a saved timeout returns the same error on replay even if the token has completed since, while the next call sees the completion. Completed or expired tokens need no timeout checkpoint. See token storage obligations if you implement a provider. See runs and waits for external token operations and build a human-in-the-loop flow for the full pattern.
Durable branch decisions
context.patched(changeId: RunlaneIdInput): Promise<boolean> reads an immutable marker scoped to the run. If absent, it persists whether the run's starting version equals this worker's version. Both true and false survive releases, automatic retries, and deployments. Repeated and concurrent calls with the same ID return the saved decision; patch IDs are not counted step keys.
A new marker requires the active unexpired attempt lease and a valid ID. Invalid IDs reject with configuration_invalid; lost or expired ownership rejects with storage_conflict. Storage errors return no speculative branch. Marker creation appends RunEventType.PatchRecorded without ending the attempt or moving ready time. See deploy task changes before changing replay paths.
Terminal hooks and middleware
Task options accept onSuccess, onFailure, onCancel, onComplete, and middleware. Hooks receive saved normalized payloads and the terminal run. Success hooks also receive output parsed with the current output schema. Failure hooks include failed and expired runs. Cancellation has its own hook. Complete receives the matching terminal case. Hooks can run before any attempt starts, with run.counters.attempts === 0.
TaskHookContext supplies a stable deliveryId, callback-local hookAttempt, timeout signal, and the same synchronous logger. Hook logs use the independent hook lease. A log drain failure follows the same retryability and attempt rules as a callback failure. Retries may repeat a callback. With hooks.retry.maxRetries: 0, a callback runs at most once; a crash before invocation can lose its effect. See hook delivery and retries. Hooks have no task steps, run lease, or queue capacity. Use deliveryId as the external idempotency key. Runtime hooks use raw JSON inputs.
Middleware wraps each attempt in registration order; runtime middleware wraps task middleware. Each function must call and await next() exactly once. Its result has outcome equal to returned, failed, suspended, or abandoned. Middleware observes the saved raw output and cannot replace it. Cleanup unwinds in reverse order. Setup failure or cleanup after success fails the owned attempt. An existing task failure, suspension, or abandonment stays primary; secondary cleanup errors are logged. See Lifecycle hooks.
Durable application logger
Runlane captures console.log, console.info, console.warn, console.error, and console.debug inside task attempts by default. Output still prints normally. Messages use Node's util.format(...args); log and info map to info, and the other methods keep their severity. Async calls keep their run and attempt identity, including concurrent attempts. Calls outside an active attempt, after its boundary settles, or in independent hook deliveries are not captured.
Captured calls share context.logger storage, ordering, quotas, and draining. Console output from that writer's storage and telemetry work is excluded to prevent feedback loops. Prefer context.logger when you need structured attributes: console objects become part of the formatted message. Capture never throws into task code. A body rejection leaves the output printed but stores no record and emits a runtime diagnostic when telemetry is configured. A background persistence failure has the same settlement behavior as context.logger.
Disable console capture for a runtime with createRunlane({ lane, tasks, queues, logs: { captureConsole: false } }). This leaves context.logger available. The default is owned by contractDefaults.logs.captureConsole.
TaskLogger.debug(message, attributes?), info, warn, and error return void. message must be a string; optional attributes must be a finite, acyclic JsonObject. Messages, attribute strings, and object keys must contain valid Unicode without U+0000 (NUL). Leading U+FEFF remains legal. Runlane takes an owned snapshot before returning. Invalid shapes throw configuration_invalid at the call. An oversized body throws log_limit_exceeded; run entry and byte quotas limit storage only; every accepted entry still reaches the telemetry logger. These quotas stop storage and save one Logs truncated: run log quota reached. marker outside the quota without failing the attempt or hook; an identity that cannot fit the configured maximum log body in a record throws storage_limit_exceeded before acceptance.
One attempt writer preserves call order and batches accepted entries. Stable log IDs make exact storage retries safe. Log entries and quotas persist without rewriting the run. Before saving an owned outcome, Runlane seals and drains all admitted logs and streams. A background log failure fails an otherwise successful attempt under its normal retry policy. Cancellation, timeout, suspension, and an existing handler failure keep precedence. Runtime diagnostics report each secondary drain failure once. After a background failure is retained, later logger calls throw a RunlaneError with message Durable logs writer failed.. Stream calls reject with Durable streams writer failed.. The error keeps the source's structured code (for example, stream_limit_exceeded); an unmapped retained failure uses storage_unavailable. Its original cause stays attached internally. Catching a later call does not clear the retained failure.
Operator cancellation still allows cleanup code to log, append streams, and save steps while the attempt owns its live lease and has not passed its deadline. Middleware can log and stream after next() until the shared writer seal.
Runtime logs options are captureConsole, maxEntryBytes, maxRunEntries, maxRunBytes, and maxTelemetryEntryBytes. Defaults come from contractDefaults.logs. Byte limits count UTF-8 JSON, including escapes. maxEntryBytes cannot exceed its shared default; maxTelemetryEntryBytes must be at least 256. Run quotas include every attempt and hook callback. Keep logs small; store large results outside the log stream.
Read persisted entries with runs.logs() and causal summaries with runs.timeline(). See debug a run.