Skip to Content
Runlane
ReferenceApplication API

Runs and waits

Read and control runs, send signals, and resolve wait tokens.

These APIs belong to the runtime returned by createRunlane(). Import their types and enums from @runlane/core. All operations use that runtime's environment.

Stored JSON strings and object keys must contain valid Unicode without U+0000 (NUL). Leading U+FEFF remains legal. Invalid payloads reject before submission; invalid task and step results fail before saving an output. Log messages and attributes reject synchronously with configuration_invalid; invalid metadata patches reject before changing the run or its history. Earlier successful calls are not rolled back.

Read runs

CallReturn value and behavior
runs.get(runId)Promise<RunRecord | undefined>. Reads a run with its payload, status, and stored result.
runs.get(task, runId)A promise of a typed run or undefined. Requires a task with an output schema. Validates successful output and checks that the run belongs to that task.
runs.watch(runId, options?)AsyncGenerator<RunRecord, void>. Follows subscription snapshots without stream reads until the run finishes or the watch is aborted.
runs.watch(task, runId, options?)The same iterator with successful output parsed through the task's output schema. Producer definitions work too.
runs.list(options?)Promise<Page<RunSummary>>. Returns one page of run summaries.
runs.events(runId, options?)Promise<Page<RunEventRecord>>. Returns one page of the run's event history.
runs.readStream(runId, name, options?)Promise<RunReadPage<RunStreamRecord>>. Reads named starts, chunks and derived attempt closes. See streams.
runs.subscribe(runId, options?)AsyncGenerator<RunSubscriptionEvent, void>. Resumes snapshot/status/meta/stream delivery from source checkpoints and drains chunks before terminal status.
runs.logs(runId, options?)Promise<RunReadPage<RunLogEntry> & { readonly truncated: boolean }>. Reads durable application logs by log sequence.
runs.timeline(runId, options?)A RunReadPage<RunTimelineEntry> with partiallyPruned: boolean. Merges bounded causal summaries.
runs.attempts(runId)Promise<readonly RunAttemptSummary[]>. Reads the run's history and groups it into attempts. This can read multiple event pages.
runs.findActive({ task, idempotencyKey?, singletonKey? })Promise<RunRecord | undefined>. Finds an active run. Supply at least one key.
runs.findCurrent({ task, idempotencyKey })Promise<RunRecord | undefined>. Finds the current key owner, including a retained terminal run.

A run can be scheduled, queued, running, retrying, released, cancellation_requested, succeeded, failed, cancelled, or expired. Use the matching RunStatus enum member in TypeScript. Terminal runs have finished: succeeded, failed, cancelled, or expired. An expired run missed its first-attempt start deadline. An attempt timeout is a failure with code task_timed_out; timed_out is a wait token status.

Check for undefined before reading a result. Check RunStatus.Succeeded before using successful output. A typed read can throw validation_failed for the wrong task or task_output_invalid if retained output no longer matches the task schema.

findActive() needs a lane with operator read support. See choose a lane for supported capabilities.

RunAttemptSummary.failure also keeps handler errors on cancelled and shutdown-released attempts. It is absent when no error was thrown, except when an oversized return value under cancellation records storage_limit_exceeded. This does not set RunRecord.failure.

RunAttemptSummary.output also keeps a handler return value when cancellation wins. This is attempt diagnosis only: the run has no output, and joins still return ok: false.

RunAttemptSummary.release describes a saved pause. Its optional stepKey identifies a keyed sleep, signal wait, or timed token window. Keyless waits and explicit releases omit it. The release can also contain delay, resumeAt, reason, and wait, as supplied by the saved outcome.

In event history, every released event has type: RunEventType.Released and a required releaseType. RunReleaseType.Time carries delay, resumeAt, and an optional stepKey. RunReleaseType.External carries an external wait condition, such as a signal, token, or child join. It cannot carry delay or resumeAt. Import RunReleaseType from @runlane/contracts or @runlane/core.

Subscribe to changes

runs.subscribe(runId, { after?, signal?, streams? }) yields RunSubscriptionEvent snapshots and deltas. streams defaults to every name. Pass false to skip all stream reads, or a readonly string[] to read only those names. Excluded names are never read or placed in the cursor. A resumed cursor drops positions outside the current selection; newly included names start at position zero. The list is bounded by contractDefaults.streams.maxNames, and each name uses the stream-name rules.

for await (const event of runlane.runs.subscribe(runId, { streams: false })) {
  // Snapshot, status, and metadata only; no stream chunks are read.
}

runs.watch() is a simple snapshot view built on the same subscription engine. Both use lane push hints when available and polling otherwise. Choose watch for complete current run records, including tags and typed output. Choose subscribe for resumable status/meta deltas and selected stream chunks. Watch can skip intermediate states and has no cursor.

Only selected stream tails must drain before terminal status. after is the last applied subscription cursor, and signal stops pending waits. See streams for ordering and cursor scope, and realtime for authorized browser delivery.

Run counters

RunRecord and RunSummary both expose counters: RunCounters:

FieldMeaning
attemptsTotal saved run.started events, including recovery and wait resumptions.
failuresSaved attempt failures, including failures that schedule a retry.
retriesAutomatic retries scheduled after failures.
releasesSaved releases and waits.
interruptionsConsecutive counted interruptions without a new checkpoint. See stop crash loops for reset and failure rules.

startedAt records the runtime clock's observation of run.started, not the exact instant the first line of handler code executes. Eligibility uses storage time; clock skew can make direct comparisons with startedAt misleading.

startedAt is absent between a recovery claim and its next saved run.started event. Earlier starts remain in event history. Every counter, including interruptions, is required. A stored record missing one fails to decode. See stop crash loops for the limit and recovery steps.

Watch a run

runs.watch() is a simple snapshot view built on subscriptions with streams: false; it never reads stream names, headers, or chunks. It uses lane push hints when available and a polling fallback otherwise. Use the run ID returned by trigger():

for await (const run of runlane.runs.watch(runId, { signal: AbortSignal.timeout(60_000) })) {
  console.log(run.status, run.meta)
}

This example stops watching after one minute or after the run finishes. It does not cancel the run. To validate successful output, use runs.watch(taskDefinition, runId, options?); its task and output checks match runs.get(taskDefinition, runId).

WatchRunOptions accepts two optional fields:

FieldType and behavior
pollIntervalDurationString. Overrides the subscription fallback wait, including the timeout for missed hints. When omitted, uses the runtime’s streams.pollInterval, whose default is contractDefaults.streams.pollInterval. Hints can wake the watcher sooner. Must resolve to positive whole milliseconds no greater than the timer limit owned by maxTimerDelayMs.
signalAbortSignal. Stops waiting and ends the iterator. An already-aborted signal produces no snapshots.

Work starts when the loop requests its first value. The watcher reads the current run, then yields a new snapshot when its eventSequence changes. This includes metadata and tag updates, but not lease heartbeats. It yields a terminal snapshot once and ends. A failed, cancelled, or expired run is a normal snapshot, not a watch error.

Snapshot reads can skip intermediate states. It is not a complete event stream; use runs.events() for history. Reads never overlap within one watcher. While your loop handles a snapshot, the watcher performs no background work and buffers no updates. Each pending read interval keeps the process alive. Many watchers increase storage traffic; use a longer interval when you need fewer reads.

Use break to leave the loop after receiving a snapshot. Use signal to stop a pending next() call; calling the iterator's return() alone does not interrupt that pending call. A storage read already in flight must settle before the iterator ends. Storage errors still surface, including after an abort. Stop and await your watch loops before closing the runtime; runlane.close() does not own these caller-started iterators.

A missing or pruned run rejects with run_not_found. Invalid options reject with configuration_invalid. Read and output-validation errors end the iterator; they are not retried in the background. Starting a new watch reads the latest stored snapshot, not missed history. Watching does not retain runs, start workers, or change execution.

This backend API reads the stored run directly, even without an operator read model. Authorize access in your application before forwarding snapshots: they include payload, output, and metadata.

Run filters and pagination

ListRunsOptions accepts these optional fields:

FieldType
queuesreadonly QueueDefinition[]
statusesreadonly RunStatus[]
taskIdsreadonly TaskId[]
idempotencyKey, singletonKeyString keys
versionNon-default first-start version; supports creation-time order.
batchIdRaw batch submission ID, including reused members
sourceRunIdRun ID of the source run
tagOne exact, case-sensitive label. See run tags.
createdAt, updatedAt, runAtTime ranges: { from?: Date, to?: Date }
sortByRunSortField
sortDirectionSortDirection.Asc or SortDirection.Desc
cursorCursor string returned by the previous page
limitPositive integer page size

Time range endpoints are inclusive. If both are set, from must not be later than to.

ListRunEventsOptions accepts cursor, limit, sortDirection, occurredAt (a time range), types: readonly RunEventType[], and sortBy: RunEventSortField. Every field is optional.

Run and event ID ties use ascending Unicode code-point (UTF-8 byte) order, including when timestamps sort descending. List cursors carry an order version; old or unsupported versions reject with validation_failed.

Lists return { data, nextCursor? }. Continue with nextCursor and the same filters and sort order. Stop when it is absent. Read default limits and sort order from defaults.

Batch pagination

runs.list({ batchId }) reads bounded membership pages and returns distinct visible runs in creation order. It includes reused idempotent and debounced runs, even when their birth batchId differs or is absent. Run records and summaries expose the birth identity; membership owns inclusion in this filter.

Use RunSortField.CreatedAt or omit sortBy; other sort fields reject with configuration_invalid. Other filters, including status, task, queue, version, and time ranges, apply through bounded point reads. A page may be empty and still have nextCursor. Continue until that cursor is absent.

A cursor belongs to its environment, batch, filters, and direction. Keep those values unchanged between pages. The cursor skips the complete creation-time/run-ID prefix, so duplicate item memberships cannot repeat a run on later pages. Membership disappears when its run is pruned.

Control runs

CallReturn value and behavior
runs.cancel(runId, options?)Promise<RunRecord & DeliveryOutcome>. Cancels waiting work or requests cooperative cancellation of a running attempt.
runs.updateMeta(runId, patch, options?)Promise<RunRecord>. Commits a top-level metadata patch on a non-terminal run.
runs.addTags(runId, tags, options?)Promise<RunRecord>. Adds indexed labels to a non-terminal run.
runs.retry(runId, options?)Promise<RunRecord & DeliveryOutcome>. Creates a new linked run from a failed run and atomically acquires its idempotency key.
runs.rerun(runId, options?)Promise<RunRecord & DeliveryOutcome>. Creates a new linked run from a terminal run and atomically takes over its idempotency key.
runs.prune(options)Promise<PruneRunsResult>, containing prunedCount and optional nextCursor. Removes eligible terminal runs from normal reads.
idempotencyKeys.reset(task, { key })Promise<void>. Accepts an executable task or producer definition. Clears a retained idempotency key so a later trigger can create a new run.

CancelRunOptions accepts optional actor, meta: JsonObject, traceCarrier, and reason: string.

Linked retries and reruns use the source key in the same task and environment. Source records retain their audit history. Another run's live or retained owner rejects with storage_conflict; no new run is created. A rerun preserves its source owner's captured TTL when present. Keys without a remaining source owner use the current task TTL or shared default. Active-key retention and saved final results follow the normal idempotency rules. Linked runs preserve the source singleton key and reject singleton conflicts.

Cancellation, retry, and rerun follow saved changes and delivery errors. Cancellation reports a failed immediate parent resume after saving the cancellation; unrelated queue refills remain logged.

Retry and rerun accept CreateLinkedRunOptions: optional actor, meta, traceCarrier, queue: QueueDefinition, and runId. An explicit runId must be unused; an existing ID rejects with run_id_conflict, even for the same task. They are explicit operator actions, separate from a task's automatic retry policy.

Cancellation does not force JavaScript to stop. The handler must cooperate through context.signal or context.isCancellationRequested(). See cancel runs and retry and rerun runs.

PruneRunsOptions requires olderThan: Date | DurationString. Optional fields are actor, cursor, limit, and a nonempty list of terminal statuses. Follow its cursor to process more eligible runs. Related stored data can require later cleanup passes. See prune old runs before setting a retention policy.

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.

Reset rejects with storage_conflict while the key's owner is active. It does not cancel that run. See prevent duplicate runs for reset rules and key retention.

Awaited-child cancellation

When a parent moves into cancelled, it also cancels unfinished children the parent created and awaited. This includes concurrent named siblings admitted in the same park, even when only one sibling is the current wait source. This covers single and group context.join() waits, step.triggerAndWait(), and step.triggerBatchAndWait(). Every member of a group wait is included. Each cancelled child applies the same rule to its awaited children. Named awaited siblings are also covered when a time, signal, or token pause wins their park.

A child is protected when another run remains registered on it after the parent departs, or another parent holds a pending or held named step binding to it. These holds show that someone else still needs the result. A reused idempotent or debounced child keeps its original creator; a different parent cannot cancel it through this cascade. Legacy counter bindings also keep children running when their owners cannot be proved. Custom providers with eventual indexes retain children whose exclusive ownership cannot be proved.

A raw context.join() from another run does not guarantee protection from the creator's cancellation. A raw group registers only its current member. Later members can be cancelled even though that group lists them. The joiner receives a normal unsuccessful result with run.status: RunStatus.Cancelled; it does not stay stuck waiting. Use a named step trigger or an idempotent child of your own when you need shared-child protection.

Children that the parent has not awaited keep running. This includes fire-and-forget context.trigger(), context.triggerBatch(), and context.step.trigger() calls without a join. Queued, retrying, scheduled, and running parents also cancel their unfinished named awaited children when cancellation finalizes. Already finished children stay unchanged.

Child cancellation uses the system actor with a reason naming the cancelled parent. Queued children become cancelled. Running children receive cancellation_requested and use the same cooperative cancellation rules as a direct request.

The parent cancellation is durable before child processing starts. Child processing runs in bounded pages. Nested cascades share the remaining pass budget; they do not start a fresh budget. An interrupted or failed cascade remains saved for MaintenancePhase.RunFinalization to finish. A child-processing failure logs run_cancellation_cascade_failed without failing the already saved parent cancellation. Retention and manual pruning keep the parent until its cascade marker is cleared. A successful cancel response therefore does not mean every child has already stopped. Keep maintenance enabled.

Update metadata

Use meta for progress and other small JSON values. Inside a task:

const updated = await context.updateMeta({ phase: 'processing', completed: 10 })

From application code, use await runlane.runs.updateMeta(runId, { completed: 10 }). Both calls return a new RunRecord after the write commits. context.run stays the snapshot from the start of that handler; use the returned run for the updated values.

The patch: JsonObject merges top-level keys. Unmentioned keys stay intact. A nested object or array replaces the old value at that key; null is a value, not deletion. Dates, functions, undefined, non-finite numbers, and top-level arrays are rejected. Concurrent patches preserve unrelated keys. When they write the same key, the last committed patch wins.

Each accepted call, including an empty or repeated patch, appends RunEventType.MetaUpdated (run.meta_updated). RunMetaUpdatedEvent.patch changes the run's meta. The optional operator RunOperatorActionOptions fields—actor, meta, and traceCarrier—describe that event; its audit meta does not change run metadata. Read patches through runs.events(runId, { types: [RunEventType.MetaUpdated] }).

Task-side updates require the same unexpired lease and must precede the attempt deadline, when configured. Cancellation or lost ownership rejects the write. Operator updates work on any non-terminal run in the runtime's environment. A missing or pruned run rejects with run_not_found; a terminal run rejects with validation_failed. Authenticate and authorize callers in your application before exposing operator writes.

Metadata updates do not change status, retry budgets, queue capacity, or waits. They are not saved steps: replaying a handler can apply the patch again. Await each update before returning a result or awaiting a wait. Updates do not automatically propagate to children or parents.

Metadata and tag updates preserve a queued run's ready time. If runAt was absent, the update saves that existing time in runAt before changing updatedAt. This keeps an update from delaying the run or moving it behind newer work.

There is no background buffer. Each call adds durable history. The merged run and event must fit the product record limit, and the complete transaction must fit the driver's atomic capacity. An oversized update fails with storage_limit_exceeded and no partial write. Keep updates small and avoid using metadata as a log stream. Updates read and project the current run inside the write transaction. The storage driver replays conflicting transactions up to its configured maxTransactionAttempts; exhausted contention rejects with the driver’s storage_conflict error. Sanitized observation exports include the event type and sequence, not the patch or metadata.

See Upgrade Runlane before adding metadata updates to an existing deployment.

Tags are short labels for finding related runs across tasks. Add known labels at creation. Later additions, such as reviewed below, require a run that has not finished:

const { run } = await runlane.trigger(
  sendEmail,
  { userId: 'user_123' },
  {
    tags: ['customer:123', 'import:456'],
  },
)

await runlane.runs.addTags(run.id, ['reviewed'])
const page = await runlane.runs.list({ tag: 'customer:123' })

Inside a handler, use await context.addTags(['processed']). Both addition methods return a new RunRecord after committing. context.run stays the snapshot from handler entry. Run records and list summaries expose tags?: RunTags; absence means no labels. Use meta for structured progress values and tags for indexed lookup.

Labels are nonempty, case-sensitive strings. Spaces are preserved; Runlane does not trim or lowercase them. NUL and invalid Unicode are not allowed. Limits come from contractDefaults.tags.maxCount and contractDefaults.tags.maxLength; see current values. Length uses JavaScript's string.length, so many emoji count as two units. Duplicate labels count once, and first-seen order is preserved. Inputs must be arrays, even for one label. Invalid inputs or an addition that exceeds the run's distinct-label limit reject with configuration_invalid; nothing is silently dropped.

Concurrent additions merge without losing labels. Each accepted call, including an empty or duplicate-only addition, appends RunEventType.TagsAdded (run.tags_added). Its RunTagsAddedEvent.tags contains the requested distinct labels. Optional RunOperatorActionOptions (actor, meta, and traceCarrier) describe the audit event, not the run's labels or metadata. Read history with runs.events(runId, { types: [RunEventType.TagsAdded] }). Sanitized observation exports omit label values; exact reads, history, and watchers can expose them. Do not put secrets in tags.

Await additions before returning a handler result or awaiting a wait. Task writes require an active, unexpired lease and must precede the attempt deadline. Operators can add tags only to non-terminal runs in their runtime's environment. Missing or pruned runs reject with run_not_found; terminal runs reject with validation_failed. Conflicting transactions use the storage driver’s configured maxTransactionAttempts. Tags do not grant access: authorize callers in your application.

Tags do not affect queues, priority, idempotency, retries, or waits. They remain on the same run through retries and releases. Idempotency, debounce, and named replay retain the run's current tags; repeating trigger options never adds labels to an existing run. New children, scheduled runs, manual retries, and reruns do not inherit tags. There is no task-level tag default or removal API. Raw and named batch items and runNow() accept explicit tags through their existing options.

runs.list({ tag }) applies the label alongside all other filters. Continue with the same tag and cursor to read more pages. It is one exact label, not a prefix, substring, OR, or full-text search. Pruned runs disappear from results. Tag queries require an operator read model. Local storage indexes matching run keys in memory; PostgreSQL indexes the stored tag array. Common labels can still match many runs and require sorting. Index maintenance adds memory, storage, and write cost.

See Upgrade Runlane for package, stored-reader, and tag-index migration requirements.

Signals

signals.send(signalKey, { limit? }) returns Promise<readonly (RunRecord & DeliveryOutcome)[]>. The result contains only the runs this call successfully resumed.

signalKey is a nonempty string. By default, one send resumes all current waiters in bounded storage batches. The call freezes the last indexed wait position before scanning, so new arrivals cannot keep extending the scan. Waiters registered after that point may be included if their position sorts before the frozen end; later positions wait for another signal. Signals are not saved for future waiters.

limit is an optional positive integer that caps how many runs this call resumes. Runs are selected in wait-registration order, oldest waiter first, with the run ID breaking timestamp ties. A result shorter than limit means no waiters were left in the scan. A result equal to limit may leave waiters; send again to continue. Concurrent processes can also resume or register waits.

A new signal wait stores wait.registeredAt, the time of its waiting transition. Metadata and tag writes keep that time unchanged. It is cleared when the wait ends; another wait gets a new registration time.

Runs that started waiting before the upgrade have no registration timestamp. They keep sorting by updatedAt, using the same stored index encoding. A metadata or tag update during a send can still move such a waiter outside the frozen scan. This remaining edge lasts only until that existing wait ends. No migration or backfill is needed.

Signal results follow saved changes and delivery errors. A committed resume with a failed wakeup returns its run and deliveryError; a failure before commit still rejects after all attempts settle. Storage conflicts are retried while the run still waits on the same condition. If those retries are exhausted, the call rejects with a retryable storage_conflict error.

A signal wakes runs already waiting on that key. In a handler, await context.step.waitForSignal(stepKey, signalKey, { timeout? }). Its WaitPromise<WaitResult, void> resolves to { ok: true } when signaled or { ok: false, error } with wait_timed_out after a timeout; replay returns the same result. .unwrap() returns nothing or throws a non-retryable timeout error. It does not save a value or keep a message for future waiters. Use a wait token when one result must reach a run that may not be waiting yet. Save the application state first, then send the signal. A timeout lets a waiting task recheck state if it misses the signal. See wait without failing.

Wait tokens

Tokens store one external result and an optional fixed deadline. Their status is WaitTokenStatus.Pending, WaitTokenStatus.Completed, or WaitTokenStatus.TimedOut.

CallReturn value and behavior
wait.createToken(options?)Promise<CreateWaitTokenResult>, containing outcome and token. Outcome is created or returned_existing.
wait.getToken(tokenId)Promise<WaitTokenRecord | undefined>. Returns stored JSON output on a completed token.
wait.completeToken(definition, tokenId, output, options?)Validates through the shared definition before saving. Invalid output rejects with wait_token_output_invalid and leaves a pending token open. options accepts actor and meta.
wait.completeToken(tokenId, options)Promise<CompleteWaitTokenResult & DeliveryOutcome>, containing outcome and token. Outcome is completed, timed_out, or already_resolved.
wait.listTokens(options?)Promise<Page<WaitTokenSummary>>. Summaries omit output, metadata, and the completion actor.
wait.pruneTokens(options)Promise<PruneWaitTokensResult>, containing prunedCount and optional nextCursor. Prunes eligible terminal tokens with no retained run links.

Create a token

CreateWaitTokenOptions has only optional fields:

FieldType and behavior
timeoutDurationString. Sets a fixed deadline when the token is created. Omit it for no deadline.
idempotencyKeyString key that reuses a token in the same environment. Use a stable key when creation may repeat.
idempotencyKeyTTLDurationString. Requires a key. Unlike task keys, token keys do not accept IdempotencyKeyTTLMode.Active.
metaJsonObject describing the token.

Inside a handler, keyless context.wait.createToken() uses an automatic replay key. Outside a handler, keyless runlane.wait.createToken() creates a new token on every call. See handler token creation.

If creation returns an existing token, read its current status. It may already be completed or timed out. Without a key TTL, ownership remains until pruning removes the token.

Complete and read a token

CompleteWaitTokenOptions requires output: JsonValue. Optional actor and meta: JsonObject record who completed it and why. Authenticate and authorize the caller in your application before completing a token.

The first terminal result wins. Completion after the deadline can return timed_out. Repeating a completion can return already_resolved; it does not replace the stored output. Always use the returned token to decide what happened.

Token completion follows saved changes and delivery errors. deliveryError reports a failed eager resume after the token was saved. Maintenance finishes it; do not complete the token again to recover delivery.

Define a shared contract with waitToken({ id, output: schema }) from @runlane/core. Pass it to context.wait.forToken(tokenId, definition) or spread it into wait options to add a timeout. Output types come from the schema. The id is an application label, not a stored kind check. Typed completion validates every call, including repeats. Completion validates schema input but stores raw JSON, so transforms run once on each consumer read.

The two-argument completeToken(tokenId, { output, actor?, meta? }) is an operator escape hatch. It skips application schema validation; use the shared definition in application routes.

The runtime's wait.getToken() returns raw JSON. Inside a handler, context.wait.forToken(tokenId, { output: schema, timeout? }) returns WaitPromise<TokenWaitResult<TOutput>, TOutput>. Await it for { ok: true, output, token } after completion or { ok: false, error, token } on expiry or wait timeout. It validates completed output and parks while pending. Invalid stored output returns ok: false with wait_token_output_invalid; the handler can wait for a new token. The resolved token cannot be corrected. .unwrap() returns output or throws a non-retryable error with the token ID. context.wait.getToken(tokenId, { output: schema }) reads without waiting. Both retain the token as a dependency of the run. Maintenance resumes waiting runs after the token resolves.

The optional handler timeout limits one wait window. wait_timed_out leaves the token pending and completable. The token's creation deadline still produces wait_token_expired. Saved window timeouts replay in call order per token, even after completion; the following call can read that completion. See handler wait tokens for exact replay and error rules.

Use context.wait.until(date, { reason?, meta? }) for an absolute time. It needs no key and resolves at once after the date has passed. See wait until a date.

List and prune tokens

ListWaitTokensOptions accepts optional createdAt: { from?: Date, to?: Date }, cursor, limit, sortDirection, and one status: WaitTokenStatus.

PruneWaitTokensOptions requires olderThan: Date | DurationString, with optional cursor and limit. Pending tokens and tokens still linked to retained runs are not eligible.

See build a human-in-the-loop flow for a complete task and completion service.

Run versions and patch history

RunRecord.version and RunSummary.version are the immutable starting RunVersion; they are absent before first start. A child carries versionConstraint from its parent's baseline at acceptance, but has no starting version until first start. Unstarted children are excluded from version lists, just like unstarted roots. Each RunEventType.Started event records baseline version and actual workerVersion. This records code identity without worker routing.

runs.list({ version, ...filters }) reads only visible started runs through RunsByVersion. Only versions set through createRunlane({ version }) are indexed; listing the default unversioned value rejects with configuration_invalid, because indexing it would add an index write to every run update in apps that never set a version. It requires RunSortField.CreatedAt; other sort fields reject with configuration_invalid. sortDirection still accepts both directions. Extra filters examine one bounded cohort per page, so an empty data array can have nextCursor. Continue until that cursor is absent. List unstarted queued and scheduled work separately during a deployment drain.

Read markers with runs.events(runId, { types: [RunEventType.PatchRecorded] }). Each event contains patchId, boolean value, deciding worker version, and attempt. Marker creation advances history without consuming another attempt, retry, or release. Retention removes markers with their run. See deploy task changes.

Current hook delivery state

runs.get() includes optional hooks: pending_discovery, pending, claimed, done, or failed, with bounded callback states, storage-authored createdAt, and storage-sealed updatedAt. The discovery wait starts at the earliest pending callback’s availableAt, or createdAt when none is pending. A later lapsed claimExpiresAt restarts the wait; recovery wakeups do not reset it. Aggregate lastFailure records an expired-discovery reason even when no callback was known. Callback entries show scope, kind, stable deliveryId, attempts, and bounded failure code/message/retryable details. Private claim tokens are never returned. Known absence has no hook state. Result reads and completion waits use the terminal task outcome even while hooks retry.

Schedule run sources contain scheduleId and fireAt. Runtime schedule sources also snapshot revision and any externalId. These fields describe the accepted occurrence; later schedule updates and deletion do not change an accepted run. See schedules.

Named child waits admitted before an attempt’s first pause commit their children and bindings with that pause’s release, including sleep, signal, token, and explicit releases. Only a child-first pause registers a child completion waiter. See named child waits.

Logs and causal timeline

runs.logs() includes context.logger entries and console output captured during task attempts. Capture is on by default and preserves normal console printing. Prefer context.logger for structured attributes; console arguments become one formatted message. Set logs: { captureConsole: false } in createRunlane() to opt out. See the task logger contract for severity mapping, formatting, limits, and draining.

Log pages also include truncated: boolean, reporting whether the run’s storage quota dropped entries. This flag applies to the whole run, including pages before the truncation marker. Storage quotas do not limit entries sent to the telemetry logger.

Both readers accept { after?: RunCursor | string, limit?: number } and return { records, cursor, hasMore }. Limits use contractDefaults.pagination. Continue with cursor while hasMore is true; an empty page can still advance a bounded scan. Missing or pruned runs throw run_not_found. Malformed, wrong-kind, wrong-run, wrong-environment, future, and reused-run-instance cursors throw run_cursor_invalid.

RunLogEntry contains its stable id, sequence, level, message, optional JSON attributes, occurredAt, and afterEventSequence. Task entries identify attempt; hook entries identify hookDeliveryId and hookAttempt. Correlation includes bounded trace/span IDs when available. The run head keeps log watermarks and effective writer times nondecreasing by sequence, clamping a backward writer clock to the preceding log time.

Timeline events stay in sequence order. Between event N and N+1, records whose afterEventSequence is N are ordered by writer time, source, and source position/ID. Sources are run_event, step_completed, log_entry, stream_record, and hooks. No storage-time field or extra clock sample is added to run events or steps.

Completed-step summaries include the key, attempt, completion time, and optional child binding, but omit output. Stream summaries use only index references and contain name, attempt, firstPosition, lastPosition, count, and occurredAt. Consecutive references for one name in one gap form a range; a bounded range can continue on the next page. Counts include source records such as attempt starts. The attempt comes from event history. Use runs.readStream() for full records and chunk values.

The hooks entry is a bounded current-state projection captured in the first cursor. It keeps its original terminal sequence and update time throughout that page series. It is not a hook-attempt audit. partiallyPruned is true when outgoing step cleanup has begun while retention still keeps the run visible.

These are operator views, not lossless export checkpoints. Concurrent late commits can appear behind a page already read. Refresh from the beginning to include them. Authorize access in your application: logs and metadata may contain application data.

Public IDs and keys accept plain strings but reject . and .. in the shared identifier schema. This keeps run IDs addressable over HTTP. Runtime close interrupts live subscriptions and watchers with a retryable operation_cancelled error; it does not mean the run finished.

run.released also supports RunReleaseType.Handoff, an immediate checkpoint handoff with no wait or delay. Shutdown releases may carry interruptionCause and interruptions. Takeover recovery records its count on run.attempt_abandoned. If recovery exhausts the allowance, run.failed records the count in failure.meta.interruptions. These decisions let event replay work without reading step records. Older events without a decision keep their original counting behavior.

On this page