Upgrade Runlane
Upgrade handlers, packages, stored records, and PostgreSQL together.
Before 1.0, any release can change APIs or behavior, and a minor release can require a fresh PostgreSQL schema. Pin exact versions of every @runlane/* package in production, and read this page before you change them.
Operator retry and rerun key ownership
Changed in 0.10: runs.retry() and runs.rerun() create a new run that takes over the source's idempotency key in the same task and environment. Later same-key triggers return the new run. The source keeps its historical key field but no longer owns the key. A different live or retained owner causes storage_conflict; no new run is created. Handle that conflict by inspecting the current owner rather than repeating the operator action. See retry and rerun runs.
Required HTTP lifetime
Breaking in 0.10: createHttpDeliveryProvider() and the http options of postgresHttpLane() and redisHttpLane() now require lifetime. There is no default.
Choose HttpLifetimeMode.InRequest on serverless or per-request hosts. It works on every supported host, but the sending request and await runlane.trigger() wait for the attempt. Set publishTimeout above maxDuration plus contractDefaults.delivery.outboxSettlementReserve. Nested child publication needs maxConcurrentPublishes above the number of concurrent in-request parents, with spare incoming and queue capacity. Otherwise parents stall until the publish timeout; avoid nested triggers if you cannot bound their concurrency and nesting.
Choose HttpLifetimeMode.Process only on long-lived servers. It replies 202 at claim and continues the task in the app process. On Next.js/Vercel, this background behavior requires a host lifetime callback through after or waitUntil instead of bare process. In-request execution needs neither hook. See HTTP delivery for configuration examples.
Worker maintenance default (breaking)
createDeliveryWorker() and runlane work now run maintenance by default. Set maintenance: false or --no-maintenance to keep a separate maintenance service as the sole owner. Leases coordinate maintenance bands across workers, so running both is safe. Polling delivery handlers retain their maintenance default; SQS Lambda delivery handlers still never run maintenance in-handler.
runlane work --drain now runs one maintenance pass before draining due work. Use --drain --no-maintenance to drain without that pass.
Workers start default maintenance only after their delivery worker is ready. A failed worker startup leaves no worker-created maintenance running. Automatic maintenance drains when the last participating worker closes; worker close waits for its storage work and lease releases. Explicitly started maintenance remains runtime-owned. Calling start({ maintenance: true }) afterward is a no-op when the existing services use defaults. For custom options, call start({ maintenance: options }) before creating workers, or create workers with maintenance: false before starting custom services. Conflicting options reject with this guidance.
Custom workers can opt into SIGTERM/SIGINT handling with handleSignals: true. The default is false. Dev now warns when no retention rules are configured; production startup stays quiet. New setup examples retain successful, cancelled, and expired runs for seven days and failed runs for thirty days. Retention is still opt-in for existing runtimes.
Signal broadcasts and queued resends
signals.send() now resumes all current waiters by default, using bounded storage reads. Pass an explicit limit to cap a call. See signals for concurrent arrival rules.
New signal waits store wait.registeredAt to keep metadata and tag writes from changing their position during a send. Limited sends select the oldest registration first. The timestamp/run-ID index encoding is unchanged, so existing Postgres and Redis entries remain valid without a migration or backfill. A pre-upgrade wait without the timestamp still sorts by updatedAt; an update during a send can move it outside the frozen scan until it leaves that wait.
Replace contractDefaults.maintenance.queuedDeliveryRecoveryDelay with contractDefaults.maintenance.resendQueuedRunsAfter. Set createRunlane({ resendQueuedRunsAfter }) to override the 15-minute default. Use the same setting in every process: each run follows the value of its last writer. Non-default policies add an optional internal resendQueuedRunsAfterMs field to stored run documents. Upgrade all stored-value readers before enabling a non-default setting. Existing documents use the default until rewritten; no database migration is needed. The option also sets hook-wakeup resend intervals using the maintenance process's value; callback retries still use hooks.retry.
Handle saved mutation results
Breaking: contractDefaults.run.eventConflictAttemptLimit and contractDefaults.operator.cancellationConflictAttemptLimit are removed. Remove references to these defaults. Metadata updates, cancellation, and result persistence now read current history inside the write transaction. Configure the storage driver’s maxTransactionAttempts to bound transaction replay. Exhaustion surfaces the driver’s storage_conflict error. No storage migration is needed for this change.
Breaking: batch successes expose run, outcome, and optional deliveryError directly. After checking item.ok for each item in outcomes, replace item.result.run with item.run and item.result.outcome with item.outcome.
Breaking: triggers and linked retries and reruns no longer reject after a confirmed save, and signals.send() no longer rejects after it resumes a waiting run. These calls and token completion now return success even if immediate delivery fails. Check deliveryError and keep maintenance running. Do not repeat saved work to recover delivery. Queue controls, cancellation, and direct execution also expose delivery errors. Atomic child and token waits stay suspended after their release is saved. See saved changes and delivery errors for affected calls and metadata. A lost commit response is still ambiguous; inspect storage before retrying.
During a transport outage, alert on runlane.outbox.failed.count, rather than wakeup_publish_failed log volume. An outage can produce one warning per run.
Breaking: hooks now use hooks.retry with the same RetryPolicy as tasks. Replace hooks.maxAttempts: N with hooks.retry.maxRetries: N - 1. Move retryDelay to retry.backoff.delay and maxRetryDelay to retry.backoff.maxDelay, with type: RetryBackoffType.Exponential. The matching contractDefaults.hooks fields are replaced by contractDefaults.hooks.retry. Removed keys fail with configuration_invalid. Set hooks: { retry: { maxRetries: 0 } } to turn retries off.
The default changes from five to ten attempts and from a 1-minute to a 5-minute cap. To keep the 0.9.0 schedule exactly, use:
import { createRunlane, RetryBackoffType } from '@runlane/core'
// Use your application's lane, queues, and task catalog.
const runlane = createRunlane({
lane,
queues,
tasks,
hooks: {
retry: {
maxRetries: 4,
backoff: { type: RetryBackoffType.Exponential, delay: '1s', maxDelay: '1m' },
},
},
})When backoff is omitted from a supplied policy, it uses the fixed 30-second delay from contractDefaults.retry.backoff. Changing only maxAttempts: N to retry.maxRetries: N - 1 changes the backoff curve. To keep the new default curve while changing the count, spread contractDefaults.hooks.retry and override maxRetries. Alert on runlane.hook.exhausted.count. It counts every callback that ends failed; the hook_delivery_failed log's reason says why. drain() now waits for due hook callbacks without spending its run budget. See lifecycle hooks.
Breaking: hook callbacks now stop after a non-retryable failure, even when retries remain. A thrown RunlaneError uses its own retryable flag, which defaults to false. Plain thrown errors use the hook policy and are retryable, even when the task has no retry policy. Hook timeouts and delivery-signal cancellation remain retryable. Runlane also stops callbacks when saved output fails the task's current output schema (task_output_invalid). Invalid log entries stop with configuration_invalid. An oversized individual log body stops with log_limit_exceeded. Run-wide entry and byte quotas save one truncation marker without failing the callback. A deploy that tightens an output schema can stop a pending success hook for a run saved by the old code. Stopped callbacks log reason: not_retryable and count in runlane.hook.exhausted.count.
Breaking: createRetryPolicySchema and createRetryBackoffSchema are removed from @runlane/contracts. Use retryPolicySchema to parse task or hook retry input. RetryPolicy is derived from that schema's input type. resolvedRetryPolicySchema still validates resolved policies.
Breaking: runNow() now saves nothing when a queue is paused or full. It previously saved a queued run and rejected with storage_conflict. Handle queue_paused (retryable: false) or queue_at_capacity (retryable: true), or use trigger() to queue the work. To let work through, use queues.resume() or temporarily raise capacity with queues.setLimit(queue, { total, perKey, expiresAt }). Existing-run reuse still wins. See inline execution.
Breaking: delivery retries on a paused or full queue now report queue_paused or queue_at_capacity instead of storage_conflict. Update onDeliveryFailure filters and alerts that match the old code.
Native delivery providers can now pass DeliveryAttempt.deliveryCount, a positive integer starting at 1. Core requests a fast claim retry only on delivery 1. Later and unknown counts keep native backoff. One fast SQS retry spends one receive toward the dead-letter policy; Lambda timing stays unchanged. Custom providers should pass their native count when available. See delivery providers.
These changes require the pending hook queue index migration. See pending hook storage. Keep the existing deployment migration procedure and upgrade all @runlane/* packages together.
Pending hook storage
Breaking: pending hook callbacks now use a per-queue storage index, and runs saved by an earlier release do not have that entry. A run that still has pending callbacks when the new release starts never delivers them, and the maintenance delivery recovery phase fails with invariant_violation when it reaches that run. Let those callbacks finish before you upgrade.
Upgrade the whole package set in this order:
- Stop producers. Keep workers and maintenance running until no hook callbacks are pending.
- Stop every old process, including workers and maintenance.
- Apply the single
0003_run_retention_deadlines.sqlwithrunlane adapter postgres migrate. It includes both the retention changes and the pending hook queue index. Follow the retention cutover steps below before starting new processes. - Start the upgraded processes.
On PostgreSQL, this query must return 0 before you stop the workers:
SELECT count(*) FROM "runlane_runs" WHERE "record_hooks_pending_partition" IS NOT NULL;On other stores, check that no recently finished run has a runs.get(runId).hooks.status of pending_discovery, pending, or claimed. A run without hooks has no callbacks to deliver.
For hook polling, the migration adds two nullable columns, a partial index, and a pair check to runlane_runs. The same migration also adds retention and child-result indexes and clears old per-fire schedule occurrence rows. It holds an exclusive table lock through the index build and check validation. Reads and writes block until the transaction commits; allow a maintenance window that accounts for table size. Redis and Valkey need no migration. Restart in-memory stores.
Custom storage drivers must map StorageIndexName.RunsHooksPendingByQueue before deployment. Store exactly the entries core sends. Reject unsupported indexes and run the storage conformance suite. The document envelope and storage driver contract version stay unchanged.
Use shared observation exporter backoff
Breaking: observation exporters replace retryDelay and maxRetryDelay with backoff. For example, convert retryDelay: '2s', maxRetryDelay: '2m' to:
import { RetryBackoffType } from '@runlane/core'
import { createRunlaneObservationExporter, type RunlaneObservationExporterOptions } from '@runlane/observability'
export function createExporter(options: RunlaneObservationExporterOptions) {
return createRunlaneObservationExporter({
...options,
backoff: { type: RetryBackoffType.Exponential, delay: '2s', maxDelay: '2m' },
})
}The old options reject with configuration_invalid; there are no aliases. The default schedule stays exponential, from 1 second to a 1-minute cap, through contractDefaults.observability.exporter.backoff. Its old retryDelay and maxRetryDelay fields are removed. Use a duration string for fixed waits. Exponential backoff must include maxDelay, and all timing values must fit a Node.js timer. Retryable failures keep retrying with downward jitter; there is no retry budget.
@runlane/core and @runlane/contracts export retryBackoffSchema and its readonly input type, RetryBackoff. Task, hook, and exporter backoff use this parser. getRetryDelayMilliseconds accepts { backoff } without maxRetries. After a non-retryable failure rejects start(), another start() on the same exporter resumes from its saved checkpoint. Only close() is permanent. See observation export.
Upgrade checkpoint-aware interruption readers together
Upgrade runtimes, contracts, storage readers, CLI, and event consumers together before using 'unlimited' or handoff events. Numeric executionPolicy.maxInterruptions values still parse. New accepted runs may save 'unlimited'. Existing runs retain their saved allowance.
New shutdown events include their cause and decided interruption count. Recovery events save the same decision. Old events without those fields replay with their original behavior. The optional storage-only checkpointCountAtClaim baseline is saved in the existing claim write. A legacy active lease without a baseline keeps the old no-progress recovery behavior until its next claim.
See Stop crash loops for when interruptions count. Event consumers must accept RunReleaseType.Handoff. Lambda's default reserve has changed. See Run long jobs on Lambda for the new default. Explicit reserves are unchanged.
The unlimitedShutdownGrace export is removed. Import unlimited from @runlane/contracts instead; it has the same 'unlimited' value.
Adopt cancellation and interruption handling
Upgrade producers, workers, and readers together. Do not mix running versions, and roll back all processes as one unit. Runlane 0.9 rejects unknown event fields: it cannot read the new optional failure on run.cancelled and shutdown run.released, or output on run.cancelled. After these events are saved, 0.9 cannot read those runs' histories. Rolling back packages does not remove these fields.
context.isCancellationRequested() is true only after the worker sees a cancel request. Replace code that used it to detect any abort with context.signal.aborted.
An error after a cancel request now ends the run as cancelled. It invokes onCancel instead of onFailure. Update hooks and alerts that relied on a failed status.
Aborting the signal passed to executeNext(), runNow(), or executeDelivery() requeues an attempt that throws, without spending a retry. Receipt and visibility loss do the same. See Stop crash loops for the interruption allowance. If the signal is already aborted, runNow() rejects with operation_cancelled and saves nothing. Use runs.cancel() to stop a run for good.
On SQS Lambda and HTTP time limits, signal.reason is the task_interrupted Runlane error instead of an AbortError. Check context.signal.aborted to detect an abort. The CLI now labels interrupted attempts interrupted.
Custom storage drivers must reject with storage_conflict only when the transaction committed nothing. If the commit outcome is unknown, reject with storage_unavailable and do not replay the transaction callback.
Rename storage hint options
Breaking: PostgreSQL and Redis storage drivers now use the same hint names as lanes. Rename raw driver options as follows. There are no aliases; removed names fail with configuration_invalid.
| Removed | Use |
|---|---|
runSignalNotifications | runHints |
workSignalNotifications | workHints |
Both drivers now default runHints to contractDefaults.realtime.runHints (true), previously false on raw drivers. Postgres start() opens a run listener; Redis run waits can open a pub/sub connection. Set runHints: false explicitly on raw drivers that must avoid it. Ready-made lane defaults stay the same.
postgresPollingLane() and redisPollingLane() accept optional workHints, using contractDefaults.delivery.workHints (true). Set it to false when workers cannot keep a LISTEN or pub/sub connection. This disables both work publications and the native work listener. Commits in the same runtime still wake workers immediately; other work waits for polling with idle backoff. Disable runHints too when run readers cannot keep a listener.
Postgres/SQS, Redis/SQS, and Redis/Streams accept only top-level runHints. Remove any work-hint option from their nested storage options; these lanes force it off and reject workHints at either level because the transport delivers work. Unlike before, Postgres/SQS cannot opt into unused work publications.
Hints only lower latency. Polling guarantees progress while storage and worker capacity are available. Delays, retries, schedules, and lease expiry always depend on polling and maintenance. This option rename does not change stored records.
Compare whole records in custom storage drivers
replace() and delete() must reject a record whose document, indexes, key, or version changed after this attempt returned it. The @runlane/testing storage-driver conformance suite now checks a document edit. If your driver compares only the key and version, compare the whole record, or keep its write rules in createStorageMutationStaging() from @runlane/contracts. See Share transaction write rules.
Use one storage codec name per logical record
Each logical storage record now has one codec export, named after its table. The duplicate names are removed:
| Removed | Use |
|---|---|
storageRunEventRecordCodec | runEventStorageValueCodec |
storageOutboxMessageCodec | outboxMessageStorageValueCodec |
storageScheduleOccurrenceCodec | scheduleOccurrenceStorageValueCodec |
storageRunlaneObservationRecordCodec | observationRecordStorageValueCodec |
storageRunlaneObservationCheckpointCodec | observationCheckpointStorageValueCodec |
storageMaintenanceLeaseCodec | maintenanceLeaseStorageValueCodec |
storageRunLogCodec | runLogStorageValueCodec |
Each pair was the same value, so encoded records do not change.
Adopt native Unicode storage order
The PostgreSQL migration takes an ACCESS EXCLUSIVE lock on runlane_runs while rebuilding three indexes. It blocks reads and writes on that table; schedule downtime for the rebuild.
Storage comparisons now use Unicode code-point order (UTF-8 byte order), rather than JavaScript UTF-16 order. For example, U+E000 sorts before U+10000 and 😀. Local indexes, core page merges, outbox claims, and operator ID ties use the same order as native stores. Existing UTF-8 tuple and record-key bytes do not change. storageDriverContractVersion remains 2.
Stop old processes before switching all producers, workers, and readers to the new package set. Discard raw query cursors from version 1 and operator cursors without order version 2. Start those lists again without a cursor; old tokens now fail with the existing structured cursor error. Do not mix old and new cursors or running versions. Restart Local stores to rebuild in-memory indexes.
Public identifiers, environment and stream names, schedule external IDs and deduplication keys, tuple/key components, index strings and query bounds now reject NUL, lone surrogates, and a leading U+FEFF. Empty range bounds remain legal. JSON now rejects lone surrogates and U+0000 (NUL) in values and object keys in every lane. Leading U+FEFF remains legal in JSON. Invalid trigger payloads fail with validation_failed before creating a run. Stream chunks, logs and metadata patches reject at their calls with configuration_invalid; task and step outputs fail with task_output_invalid. Remove or encode NUL in application data before submission. Existing records containing NUL in JSON strings or object keys no longer pass record validation; export and clean those values before upgrading. Failure diagnostics replace invalid characters with U+FFFD so runs can still record their failures.
Check retained custom-provider records for newly invalid identifiers, index strings, or JSON surrogates before upgrading. New schemas reject those records on read as well as write. Clean them up with the old release or move to a fresh namespace; there is no automatic normalization or data rewrite.
Apply the additive 0001_native_string_order.sql migration before starting the new processes:
runlane adapter postgres migrateIt rebuilds the three operator run-list indexes with COLLATE "C". It takes index/table locks and needs space for rebuilt indexes; schedule a maintenance window for large installations. A schema with the matching published initial migration can upgrade in place without rewriting records. Modified or older incompatible initial migrations still require the storage replacement procedure below.
Start maintenance and export scheduled handlers
startServices(), StartServicesOptions, and RunlaneServiceHandle have been removed. Replace the separate handle with await runlane.start({ maintenance: options }), or use maintenance: true for defaults. Remove the service signal option. Call await runlane.close() for shutdown: it stops maintenance, releases leases, drains attempts, waits for committed observers, and closes lane resources.
Runtime shutdownGrace replaces contractDefaults.runtime.observerShutdownTimeout. It defaults to contractDefaults.worker.shutdownGrace and sets the close deadline for committed observers and direct executions. Workers and drains inherit it unless overridden. Observers committed during draining get only the remaining time. Worker and drain overrides govern their own drain, even when longer than runtime grace. Close waits for the longest active worker grace, including unlimited. A timeout logs observer_shutdown_timed_out and releases the observer wait.
Only one set of maintenance loops can run per runtime. A second start({ maintenance }) rejects with configuration_invalid. Plain start() remains idempotent. A closed runtime cannot restart.
Scheduled polling workers can export runlane.createDeliveryHandler({ maxDuration: '50s' }). The required budget covers startup, maintenance, and draining. Set it below the platform timeout to leave time for cleanup.
Scheduled maintenance can export runlane.createMaintenanceHandler() directly, without a prior start(). Handlers now ignore invocation arguments. Move per-call tick options to createMaintenanceHandler(options), or use runMaintenanceOnce(options) for options that change on each call.
Upgrade from 0.5.1 to 0.5.2
Move local tests to the test lane
createLocalLane() now requires runlane dev. It no longer accepts runs into private app memory. Without dev, the first storage operation fails with storage_unavailable, names the config path, and tells you how to start dev. Retry after dev starts; no app restart is needed.
Replace createLocalLane() with createTestLane() in in-process tests. Both come from @runlane/lane-local. Keep using drain() or executeNext() to control execution. Same-name test handles share one store until the last closes; use distinct names for isolated tests. Pass a shared clock: () => clock.now() function when storage needs controlled time. Different clock functions for the same name reject with configuration_invalid.
In a shared app runtime, use process.env.NODE_ENV === 'test' ? createTestLane() : createLocalLane(). Confirm your test runner sets NODE_ENV=test. Start runlane dev for local app and CLI operations. Only dev owns local run memory, and restarting dev clears it. runlane work needs that dev store too. Production lanes are unchanged.
Do not trigger or read runs inside a CLI config's runtime() function. runlane dev calls it before it starts serving runs, so those calls now fail with storage_unavailable. Trigger work from the app or the CLI after dev starts.
The raw local driver no longer has a hasRecords flag. Providers should read records through the storage contract instead.
Upgrade from 0.5.0 to 0.5.1
0.5.1 keeps the 0.5 storage format. There is no migration and no planned stop. Install the same 0.5.1 version of every @runlane/* package, then deploy as usual.
Check these two behavior changes:
| Change | Who it affects | What to do |
|---|---|---|
useRun no longer returns run.streams | React code that reads run.streams | Read stream data with useRunStream. |
| A worker skips runs for tasks it doesn't have | Alerts that watch for task_not_found during deploys | Those runs now stay queued until a worker with the task claims them. Watch worker_task_missing instead, and use startBefore to limit how long a run may wait. See change tasks safely. |
Also in 0.5.1:
- Since 0.5.1, maintenance services can run in the worker process.
runlane workstarts them by default; use--no-maintenanceto opt out. runlane devrunscontractDefaults.worker.devConcurrencyattempts at once by default.--concurrencystill overrides it.client.subscribe(runId, { streams: false })leaves stream records out of a subscription.- Resuming a subscription of a finished run, right after its last stream record, now delivers the final status. Before, the reader ended without it.
Upgrade from 0.4 to 0.5
The rest of this page covers this upgrade.
Runlane 0.5 requires a fresh PostgreSQL schema. It replaces returned wait instructions with awaited waits and changes stored record formats. Upgrade all processes during one planned stop. Compatible notification payloads do not make mixed-version operation safe.
Stop admission and drain
- Stop new triggers and scheduled admission. Keep the old workers and the maintenance phases needed to finish accepted work running.
- Drain work that the old version can finish. Include delayed runs, retries, releases, child waits, and token waits. Resolve external waits through the old application where possible. Inspect stored run states and pending outbox work; an empty transport queue does not prove that work has drained.
- If work cannot finish, keep it with the old deployment and its isolated storage. There is no converter for carrying incompatible runs into the new deployment.
- Stop every old producer, worker, maintenance service, scheduler, CLI watcher, and operator reader. Disable automatic restarts and scheduled invocations during the upgrade.
- Back up the database and record the matching package versions, application code, configuration, and transport bindings before applying migrations.
Draining active work does not make retained terminal history compatible. Choose the storage path below before restarting anything.
Upgrade the package set together
Install the same release of every @runlane/* package used by the application, including core, contracts, lanes, storage and transport providers, CLI, and testing helpers. Rebuild producers, workers, maintenance, and reader applications against that set.
Update handlers and imports as described below. Use matching task and queue definitions in every process. Keep the old deployment stopped until storage validation and application checks pass.
Choose compatible storage
The published 0000_initial.sql baseline builds the schema from scratch. Additive migrations follow it; this release adds 0001_native_string_order.sql. Matching baseline ledgers upgrade in place. A 0.4 schema or an initial migration with a different checksum remains incompatible: the runner reports unrecognized and refuses an in-place upgrade. Earlier schemas also need replacement. Stop all old processes before replacing a schema; old and new lock namespaces must not share records.
With all old application processes stopped:
- Back up the old schema if its records or history are needed. Keep matching old binaries to read that backup; 0.5 readers cannot decode all old records.
- Rename the old dedicated Runlane schema, or drop it after confirming the backup. For example,
ALTER SCHEMA runlane RENAME TO runlane_04preserves a dedicated schema. If Runlane shares a schema with application tables, leave those tables intact and configure 0.5 to use a new dedicated schema instead. - Run the 0.5 migrations against the fresh target, then check its status with the commands below.
There is no supported converter for stored JSON or pending work. Do not copy old records into the new schema or add guessed policy snapshots and pruning counts. Finish pending work with the old deployment before retiring it, or explicitly abandon it.
Review console capture and log quotas
console.log, console.info, console.warn, console.error, and console.debug output inside tasks is now stored by default. Normal console output is preserved. Captured records count toward the run's shared log quotas, including maxRunEntries and maxRunBytes. The default entry limit is 10,000 (contractDefaults.logs.maxRunEntries). When a run reaches its entry or byte quota, Runlane stops storing application entries and saves one Logs truncated: run log quota reached. marker. The marker is outside the run quota. Quota exhaustion never fails an attempt or hook. Structured logger entries use the same quota.
To opt out, set logs: { captureConsole: false } when creating the runtime. This leaves console methods untouched and keeps structured logging enabled.
Update worker shutdown
worker.close() now stops acquisition and drains attempts through shutdownGrace before aborting. Its default comes from contractDefaults.worker.shutdownGrace. Errors after the abort release work immediately through run.released with releaseType: shutdown; update event consumers to accept this value. Aborting the worker's signal remains the immediate-stop path. CLI workers support --shutdown-grace and a second Ctrl+C to skip grace. Set the platform termination window above grace plus cleanup time.
runlane.close() applies default grace to admitted direct executions and each worker's configured grace to its worker and drain calls. Platform handler shutdown remains platform-owned. This change needs no SQL migration; release events and run projections remain JSON records.
Read interruption counts
Every run requires counters.interruptions and an effective executionPolicy.maxInterruptions. Missing values fail to decode. New runs resolve the task allowance, runtime allowance, or contractDefaults.run.maxInterruptions at acceptance and keep it even if the default changes. Do not infer these values for retained runs.
Older workers kept the previous start time when they claimed another lease. Drain those pre-start leases before upgrading. If one crosses the upgrade, its first recovery can count an extra interruption.
Upgrade workers and maintenance together so every recovery path applies the crash budget. Update operator tools for the new task_interrupted error code and interruption counter. See stop crash loops.
Apply and validate PostgreSQL migrations
Use the upgraded package's migration tooling while all application processes remain stopped. From the application directory, with the CLI config pointing at the intended database and schema:
pnpm exec runlane adapter postgres migrate
pnpm exec runlane adapter postgres statusReady-made Postgres lanes register this adapter. A deployment script may instead call applyPostgresStorageMigrations() from @runlane/postgres-storage; see apply migrations.
The baseline migration creates the tables, constraints, record-version sequence, and initial indexes. Additive migrations update that schema, including the Unicode-order indexes. It installs runlane_assert_record_write for atomic write checks and runlane_lock_record_versions for dependency validation after locking. runlane_read_queue_controls reads present and absent controls under shared locks so concurrent claims can proceed together; control mutations still take exclusive locks. Record versions remain opaque equality tokens, not ordered counters.
The migration and its ledger entry apply in one transaction. The runner serializes migration jobs with a schema-scoped advisory lock and validates migration order and ledger checksums. Do not edit the ledger or generated SQL to bypass a rejection. Recreate incompatible schemas as described above. Driver startup neither applies nor inspects migrations.
A successful status command confirms the fresh schema's installed history. Start 0.5 processes only after this check passes.
For other storage providers, check their schema and index migration procedure before restart. Preserve the logical records and complete index entries supplied by core.
Update batch consumers
Raw triggerBatch() and batch.trigger() now return { batchId, outcomes }. Read outcomes before iterating old array-based callers. Each position is { ok: true, run, outcome, deliveryError? } or { ok: false, error }; branch on ok before reading its run or error. Empty batches return a new identity. Outer concurrency bounds backend chunks, and a semantic conflict rejects its whole chunk. Accepted earlier chunks remain saved. Use runs.list({ batchId }) to inspect reused and new members after uncertain responses. Named step batches retain their ordered run-array result and whole-call atomicity.
First-use trigger-and-wait calls now commit missing children and the parent release together. An oversized complete plan fails before exposing children, instead of saving children and failing a later release. Check provider capacity and use raw chunked batches with explicit joins for larger fan-out. Deploy the BatchMembers collection, its two indexes, and updated pruning readers through the fresh 0.5 schema before starting producers.
Update stored-value readers
Every stored step requires type: RunStepType.Output, RunStepType.Wait, or RunStepType.Child. Every released event requires releaseType: RunReleaseType.Time or RunReleaseType.External. Update custom readers to branch on these tags and use the current codecs. Untagged records are rejected. These are JSON document changes; the PostgreSQL tables are unchanged. The fresh-schema requirement above still applies.
Update handlers
Cleanup around a pending wait will not run. Finish work that holds connections or locks before waiting, and follow the wait safety rules when updating handlers.
Replace release results with awaited waits
Before, a handler returned a TaskRelease to wait for a known run:
run(payload, context) {
return context.waitForRun(payload.childRunId)
}After, await its result or unwrap the output:
async run(payload, context) {
return context.join(payload.childRunId).unwrap()
}For newly created children, use context.step.triggerAndWait() or context.step.triggerBatchAndWait() to save their identities and wait for completion. Raw context.trigger() calls do not create named replay bindings.
Replace the removed methods as follows:
| Previous call | Current call |
|---|---|
context.waitForRun(runId) | await context.join(runId) or .unwrap() |
context.waitForSignal(signalKey, options) | await context.step.waitForSignal(stepKey, signalKey, options) |
return context.wait.forToken(tokenId) | await context.wait.forToken(tokenId, { output: schema }) |
return context.release(delay) | Keep return context.release(delay); it now returns Promise<never> |
For a saved signal wait, before:
run(_payload, context) {
return context.waitForSignal('account_123', { timeout: '1h' })
}After:
async run(_payload, context) {
await context.step.waitForSignal('approval', 'account_123', { timeout: '1h' }).unwrap()
return { resumed: true }
}A signal carries no approval result. Recheck saved application state after it wakes the task. Use a wait token when the external action must return data. For a pause that completes once, use await context.step.sleep(stepKey, delay). Use context.wait.until(date) for an absolute time.
Change retry budgets
Before:
retry: {
maxAttempts: 3
}After:
retry: {
maxRetries: 2
}In general, replace maxAttempts: N with maxRetries: N - 1. The new value counts automatic retries after failures. Waits, releases, and expired-lease recovery neither spend nor reset it; attempt timeouts do spend it. It no longer caps all handler starts.
Each accepted run saves its retry settings, effective interruption allowance, and task-level attempt duration. Later deployments do not replace that snapshot. Manual retries and reruns create new runs with current settings. Handler code and output schemas remain current.
Preserve counted-key replay
Repeated calls to any context.step.* method share one counter per key. The first call stores key, then key#2, key#3, and so on. Handler keys cannot contain : or #. Existing loops that previously repeated one checkpoint may now create separate saved steps.
Keyless handler context.wait.createToken() calls now reuse tokens by call order within the run. Explicit keys keep their existing rules; keyless calls outside a handler still create fresh tokens. Drain active runs before moving token creation from an explicitly keyed saved step to direct keyless creation, or keep the explicit key.
Keep repeated calls in the same order across attempts. The replay guide explains how to save changing lists and branch decisions.
Handle wait results
| Wait | Success | Failure |
|---|---|---|
context.join() | { ok: true, output, run } | { ok: false, error, run } |
context.wait.forToken() | { ok: true, output, token } | { ok: false, error, token } |
context.step.waitForSignal() | { ok: true } | { ok: false, error } |
error is a RunFailure. Group joins return results in input order, including duplicates. .unwrap() returns output, ordered outputs for groups, or nothing for signals. It throws a non-retryable RunlaneError for an unsuccessful result.
A token's own expiry returns wait_token_expired. A per-call token window returns wait_timed_out while leaving the token pending. Saved window timeouts replay in call order even if the token later completes. See wait results for the exact types.
Distinguish invalid token output from timeouts
context.wait.forToken() now returns ok: false with wait_token_output_invalid when stored output fails validation. It previously threw. A handler written as if (!result.ok) return 'timed_out' now silently treats invalid output as a timeout. Branch on the error code instead:
import { ErrorCode, RunlaneError } from '@runlane/core'
const result = await context.wait.forToken(tokenId, definition)
if (!result.ok) {
if (result.error.code === ErrorCode.WaitTimedOut || result.error.code === ErrorCode.WaitTokenExpired) {
return 'timed_out'
}
throw new RunlaneError(result.error)
}
return result.outputTo throw on every unsuccessful result, including invalid output, use await context.wait.forToken(tokenId, definition).unwrap(). A resolved token cannot be corrected. If the handler recovers from invalid output, it must create and wait for a new token.
Rebuild imports and stored readers
@runlane/core now exports task-author APIs. Import surviving provider contracts, record codecs, and parsers from @runlane/contracts, including StorageDriver, TransportDriver, and DeliveryProcessor.
Remove imports of TaskRelease, its delay/wait variants and schemas, and TaskReleaseType. RunCompletionWaitCondition, completion-presence and event-ID-owner types/codecs, RunEventBase, unused run-reference types, and several internal schema/projection helpers are removed from the package roots. Use the supported application API and provider contracts rather than importing private source files.
runStorageValueCodec is a bidirectional codec and runStepStorageValueCodec is a union. Their object-only .shape, .pick(), and .extend() surfaces are gone. Use parse/encode operations or encodeStorageDocument().
Storage profiles no longer advertise limits. Remove StorageDriverLimits, storageDriverLimitsSchema, and both Local and PostgreSQL driver limits options. Drivers own physical chunking and atomic capacity. Replace getStorageDriverRecordsInBatches from @runlane/testing with driver.get(); the driver chunks reads.
Update exhaustive readers for RunStatus.Expired; RunEventType.Expired, MetaUpdated, Rescheduled, TagsAdded, WaitAdvanced, and WaitResolved; child/group wait conditions; and keyed wait-step variants. Provider catalogs remove StorageCollectionName.RunCompletionWaitPresence and RunEventIdOwners, add DebounceOwners, and add the RunCompletionsNeedingResume and RunsStartExpiry indexes. Read these values through the current codecs rather than reproducing their schemas.
ErrorCode.ScheduleNotFound is removed. Handle storage_limit_exceeded, wait_timed_out, and wait_token_expired where relevant. See error values.
Review stored error messages
Messages and metadata from handler-thrown RunlaneError values are now stored and visible to operators and result readers. Keep secrets and private request bodies out of both. Review the stored failure message rules, including Unicode-safe message and stack bounds. Ordinary errors now retain their real messages too; browser projections never include failure metadata or stacks.
Check and restart
Before enabling admission, run your application checks against an isolated fresh schema with representative new records. Confirm migration status, matching catalogs and queue policies, and updated status/event readers. Exercise a saved step, a child join, a token completion, and a timeout through the upgraded deployment.
Start upgraded maintenance and workers, then restore producers and scheduled admission. Confirm that test runs reach their expected terminal states and that pending delivery work drains. Keep every old process stopped.
Roll back as one unit
Stop admission and all upgraded processes first. Restore compatible database/schema state, application binaries, package versions, and configuration together. Do not run old readers against newly written records or bypass migration checksums. There are no down migrations; restore the matching old schema or backup.
Reconcile transport messages and external effects before resuming the restored deployment. A database restore cannot undo an email, payment, or other external action. Preserve provider idempotency keys so replay can identify work that already happened.
Add version and patch readers
Started events now require version and workerVersion. Update exhaustive event readers for RunEventType.PatchRecorded (run.patch_recorded). Update provider catalogs for RunPatches, RunPatchesByRun, and RunsByVersion, and preserve sparse patch pruning counts. Regenerate fresh-schema deployments with the current migration; do not copy old records or guess missing version fields.
Runtime version defaults to contractDefaults.run.version. Choose a distinct identity for production replay changes and follow deploy task changes. Version tracking does not add worker routing or make incompatible package formats safe to mix.
Translate queue policy and operator reads
Replace concurrencyLimit with concurrency: { total?, perKey? }. The old option is rejected. To preserve the old per-partition behavior, use perKey; use total for one shared bound across every key. Review keyed and unkeyed traffic before choosing both. Missing keys share a separate tagged unkeyed pool when perKey is declared.
Move reads of the public runlane.queues array to runlane.queueDefinitions. runlane.queues now contains durable operator methods. Upgrade CLI configs that expose a narrowed runtime surface too.
Custom storage providers must support QueueControls, QueueCapacityPools, the new pool-tagged QueueCapacitySlots, and RunsDispatchHeadByKey. Remove QueueCapacityCursors. Slots carry monotonic unsigned ordinals and are deleted on release; counts and slot changes commit atomically with the run. Stop old processes and recreate the PostgreSQL schema before starting upgraded producers, workers, and maintenance. Old and new slot formats cannot share storage.
Update schedule readers and declarations
Reserve runtime_schedule_ for generated runtime schedule IDs. Rename any declared IDs using that prefix before registration. Task-colocated declarations keep their current options and code ownership. Activation overrides persist by declaration ID, so review overrides when renaming or reusing IDs.
Provider catalogs add Schedules, ScheduleOverrides, ScheduleDeduplicationOwners, and four SchedulesBy* indexes. Preserve optional occurrence revisions and run-source fire time, external ID, and revision. Apply the package PostgreSQL migrations; incompatible pre-baseline schemas still require replacement. CLI runtime adapters must expose the schedules namespace. Handle the new schedule_conflict error for conflicting keyed creates and updates.
Enable automatic run retention
Apply the installed PostgreSQL migrations before starting the upgraded runtime. The additive migration creates runlane_record_retention_sweeps and preserves existing history. Custom storage providers must add StorageCollectionName.RetentionSweeps (retention_sweeps) to their point-read and atomic-write mappings. This collection has no named indexes.
Automatic deletion requires a task rule or createRunlane({ retention: { succeeded: RunRetention.deleteAfter('7d') } }). Set the same fallback rules on every maintenance owner in the environment. Once configured, existing maintenance entry points start bounded, resumable sweeps. You can then remove application-owned prune wrappers. See automatic retention.
Upgrade task retention and packed cleanup
Upgrade from 0.9 with a coordinated cutover. New child settlements and private run flags are not readable by strict 0.9 codecs, even without outcome rules. Drain or stop all 0.9 processes before 0.10 processes write shared storage. Existing 0.9 bindings remain readable and keep their counter holds until cleanup removes them.
Before you upgrade, let runs that use named child steps finish. Then use runs.prune() on 0.9 to delete them. Named child steps include context.step.trigger(), context.step.triggerAndWait(), and named batches. 0.10 cannot read the child steps that 0.9 stored, so replay, pruning, and retention fail on those runs.
- Stop producers, let pending hook callbacks finish, then stop every old process. Apply the single
0003_run_retention_deadlines.sqlin a maintenance window. It adds the deadline, child-binding, and cancellation-cascade indexes and blocks reads and writes onrunlane_runs,runlane_record_run_steps,runlane_record_idempotency_owners, andrunlane_record_schedule_occurrencesuntil the migration commits. - Deploy 0.10 providers and runtimes to every producer, worker, and maintenance process with no runtime or task outcome rules. Remove
retention.runs; leaveretentionunset or configure onlyretention.cleanup. Confirm that no 0.9 process remains. - Add runtime and task outcome rules in a second deploy. Register the same task definitions on producers and workers, and use consistent runtime fallback rules on maintenance owners.
The migration adds nullable index columns and sparse indexes to runlane_runs, runlane_record_run_steps, runlane_record_idempotency_owners, and runlane_record_schedule_occurrences, including the per-queue pending hook index. It clears old per-fire schedule occurrence rows without backfilling run rows. Existing 0.9 runs use the maintenance runtime's rule for their final status, and existing tombstones continue draining.
Drizzle applies pending migrations in one transaction. Adding columns takes ACCESS EXCLUSIVE locks on all four tables. Those locks stay held through the index builds and check-constraint scans until the transaction ends. Reads and writes on all four tables block during that time. Larger tables take longer. Plan a maintenance window for large tables; low traffic alone does not prevent blocking. See PostgreSQL table locks.
Custom storage drivers must support StorageIndexName.RunsCancellationCascade, StorageIndexName.RunChildStepsByChild, StorageIndexName.RunAwaitedChildStepsByParent, StorageIndexName.RunChildStepsByParentChild, StorageIndexName.RunsByRetentionDeadline, and both partitions of TerminalRunsByFinishedAt. Run the provider conformance suite before deployment. The storage contract version stays at 2. Existing runs and tombstones need no conversion.
Existing records and index entries stay valid, and Redis keeps its existing namespace. Drivers with explicit mappings must add the new index before deployment. Postgres rejects a missing physical mapping at catalog construction; an upgraded provider querying a schema without 0003 fails on missing columns instead of returning an empty page. Automatic retention reports that storage failure as RetentionPassStatus.Failed; it does not reject the full maintenance call. Custom drivers must reject unsupported index names rather than silently dropping entries or returning empty pages.
In the second deploy, runtime and task retention use the same per-outcome object and explicit values. Replace bare durations with RunRetention.deleteAfter(duration). Replace the task single-value shorthand with explicit outcome keys. Replace retention.runs with the outcomes you want to delete; move interval, batchLimit, maxBatches, and leaseDuration into retention.cleanup.
Rule changes affect new runs only. A runtime with retention rules decides every outcome; outcomes it does not list are kept forever. A task overrides the outcomes it lists. Runs without a copied final-status rule use the maintenance runtime's rule; this includes 0.9 runs and unset outcomes from runtimes without outcome rules. See rule resolution.
The stored rule tags are delete_immediately, delete_after, and keep_forever. RetentionScope.RunRule (run_rule) names copied-rule discovery and the marked TerminalRunsByFinishedAt partition. RetentionScope.RuntimeRule (runtime_rule) names fallback discovery; its environment partition remains unchanged for 0.9 rows. Checkpoint IDs use those scope values.
MaintenancePhase.Retention now owns maintenance physical cleanup, even without runtime rules. MaintenancePhase.RunFinalization no longer collects tombstones. Keep retention enabled in maintenance phase lists, or give it a dedicated handler. Manual runs.prune() still attempts cleanup and rejects on failure.
Simple runs are deleted in packed transactions; complex runs keep tombstone cleanup. retention.cleanup.maxBatches bounds discovery pages shared by both scopes and, separately, collection batches. Review timeout margins under representative load. DeleteImmediately deletes simple, unheld runs after durable completion and waiter notification. It also retries deletion after the last hook settles. Complex or otherwise held runs, crashes, and deletion failures keep the maintenance fallback. A deletion failure never changes the saved outcome. Execution calls return the saved record. Deletion removes reads, CLI history, and retry/rerun sources. Automatic retention preserves live idempotency keys and saved results; lagging watchers can receive run_not_found.
Upgrade the provider catalog
Custom drivers must declare profile.contractVersion: storageDriverContractVersion (2). Store documents through createStorageDocumentCodec(), which writes schemaVersion: 2. Import storageDriverContractVersion from @runlane/contracts; the document version is internal. An unsupported driver version fails runtime construction before accepting work. The document version is separate from postgresStorageSchemaVersion, the PostgreSQL migration-runner version. It is 4 after the additive retention-deadline migration.
- Rebuild your collection and index mappings from
StorageCollectionName,StorageIndexName, andstorageIndexCollections. - Add every collection and index below. Preserve the complete index entries supplied by core, including sparse membership rules. Point-only collections still need exact reads and atomic writes.
- Replace the old mappings listed below. Recreate incompatible stored records; there is no converter.
- Run storage-driver conformance, including every named index's ordering, continuation, and rollback cases, before declaring contract version 2.
| Collection or owner | Required 0.5 indexes and changes |
|---|---|
Runs | Add RunsDispatchHeadByKey, RunsByVersion, and RunsHooksPending; preserve sparse membership. Also implement RunsStartExpiry and RunCompletionsNeedingResume. |
RunEvents | Add sparse RunAttemptBoundaries; retain RunEventsBySequence. |
RunSteps | Re-key RunStepsByCompletion to (afterEventSequence, completedAt, stepKey). |
OutboxMessages | OutboxByRun sorts by (state, deliveryIntent.type, id); retain OutboxAvailable. |
QueueControls, QueueCapacityPools | New point-only records. Remove QueueCapacityCursors. |
QueueCapacitySlots | Replace slot identity with tagged pools and unsigned ordinals; update QueueCapacitySlotsByExpiry. |
RunPatches | Add RunPatchesByRun. |
BatchMembers | Add BatchMembersByBatch and BatchMembersByRun. |
Schedules | Add SchedulesByDue, SchedulesByCreatedAt, SchedulesByTask, and SchedulesByExternalId. |
ScheduleOverrides, ScheduleDeduplicationOwners | New point-only records. |
ScheduleOccurrences | Keep one occurrence record per schedule, keyed by environment and schedule ID. |
RunLogHeads | New point-only records. |
RunLogs | Add RunLogsByRun. |
RunStreamNames | New point-only name registries. |
RunStreams | Add RunStreamsByRun. |
RunStreamRecords | Add RunStreamRecordsByStream and RunStreamRecordsByEventSequence. |
DebounceOwners | Add point-only debounce ownership. |
RunTombstones | Preserve cleanup counts and cursors for patches, batch members, logs, stream records, headers, and names. |
Remove completion-presence and event-ID-owner collections and their indexes. Use the current storage values and provider rules as the complete catalog.
For PostgreSQL, these baseline changes are in 0000_initial.sql; later additive migrations, including the Unicode-order indexes, apply after it. Stop 0.4 processes, preserve or replace the old dedicated schema, and run exactly:
pnpm exec runlane adapter postgres migrate
pnpm exec runlane adapter postgres statusUpgrade transport envelopes together
Delivery envelopes now require version: 3 and an explicit type: run_wakeup, run_hooks_wakeup, or schedule_wakeup. Earlier message versions are permanently rejected. Upgrade every producer, worker, transport provider, and Lambda consumer together. Drain or isolate old queues before enabling new admission. Do not send old envelopes into the new consumers.
Hook wakeups use the same disposition and outbox recovery paths as execution wakeups. A worker that lacks the task acknowledges only hook wakeups with reason hook_handler_missing; execution wakeups keep retrying. Registered workers handle republished hook work. Include eager hooks and log drain in SQS visibility and Lambda invocation budgets.
Remove workflow-helper root imports
The contracts root no longer exports these helpers:
getRunCompletionSourceIdgetTokenWaitStepKeyParsedDebounceOptions
They have no public replacement imports. Use task and wait APIs instead of reconstructing internal keys or parsed option types. The runSubscriptionEventSchema root export is also removed; use the documented subscription types and browser wire schema for their intended boundaries.
Remove unused API imports
Use RunlaneObservationType for observation tags and durable source kinds. RunlaneObservationSourceKind is removed; its string values are unchanged.
Use PostgresConnectionOptions for migration connection options. PostgresStorageMigrationConnectionOptions is removed.
Start long-running SQS delivery through runtime.createDeliveryWorker() on your configured SQS lane. The direct createSqsDeliveryConsumer() function and its SqsDeliveryConsumer and SqsDeliveryConsumerOptions root types are removed. The native onDeliveryFailure callback remains available on createSqsLambdaHandler().
Use storageRunPatchCodec for patch values. runPatchStorageValueCodec is removed. Use createStorageDocumentCodec() for the document envelope; storageDocumentVersion is no longer a root export.
The unused root exports DeliveryIntent, DebounceKey, RunlaneObservationConsumerId, MaintenanceLeaseToken, RunLogId, StreamRecordId, and scheduleOccurrenceSchema are removed. Use the owning event, observation, lease, log, or stream types. Provider code that needs an occurrence parser can use createScheduleOccurrenceSchema().
Review hooks, middleware, and readers
Terminal hooks now save durable state and retry independently of the task outcome. runNow(), executeNext(), and delivered execution await eager callbacks after saving the outcome. Review latency and timeout budgets. Pending discovery and callbacks retain runs. Unresolved work without an executable registration fails after waiting unclaimed for hooks.discoveryTimeout, on a worker scan or delivery-recovery pass. Read hooks.lastFailure before retiring task code; see task removal.
Middleware must call and await next() exactly once. It observes { payload, context } and an attempt result; it cannot replace output. A pending wait keeps the application handler parked while middleware cleanup runs.
Run IDs and stream names . and .. now reject before use. Rename those identifiers before rebuilding clients. Every runs.* run-ID argument accepts a plain string and validates it before use. Realtime and React use RunlaneError and the shared ErrorCode enum. Handle validation_failed as a permanent HTTP 400 failure. Invalid construction options use configuration_invalid; resume checkpoints are in error.meta.cursor.
Rename CLI and hint options
Replace trigger-batch --concurrency with --chunk-concurrency. Replace queue commands' --key with --concurrency-key. There are no aliases. Reader checkpoints use --after; list and prune continuation uses --cursor. See the tested CLI reference.
Use runHints on raw drivers and polling lanes, or at the top level of transport lanes. Nested postgres.runHints and redis.runHints are rejected on transport lanes. Set runHints: false in serverless consumers to avoid a dedicated listener connection.
The discovery wait starts at the earliest pending callback’s availableAt, or hooks.createdAt when none is pending. A lapsed claim restarts the wait at hooks.claimExpiresAt if that is later. These times come from storage; writer clock skew cannot extend the wait. Retry backoff does not consume this budget.
The realtime subpath also removes unused RunSubscriptionWireInput, RunStreamRecordWireInput, RunStreamWireInput, RunStreamWireOutput, and runStreamRecordWireSchema exports. Use the documented runSubscriptionWireSchema and runStreamWireSchema; derive JSON input or decoded output types from those schemas when needed.
A runtime schedule whose task is missing stays armed until a registered worker can accept it. Deletion removes the schedule’s one occurrence record by key.
Update stream writers and realtime imports
Declare stream schemas on task({ streams }) and call context.stream(name) in handlers. The context.stream(name, { schema }) form is removed.
The consolidated entry replaces createRunlaneRealtimeHandler, RunlaneRealtimeHandlerOptions, createRunToken, CreateRunTokenOptions, and RunTokenVerificationOptions. Use createRunlaneRealtime, RunlaneRealtimeOptions, RunlaneRealtimeTokenOptions, and CreateRealtimeTokenOptions. The client option getToken is replaced by refreshAccessToken; it no longer runs on every reconnect.
Read trigger and join snapshots
TriggerRunResult.run and RunWaitResult.run now use RunSnapshot, the public run record without payload. Remove payload reads from trigger and join results. Use runs.get(id) when you need the full record and retention still keeps it. Named step replays and joins can return a saved result after that call returns undefined. See child result retention.
Steps and their token owners now qualify for packed deletion. A run with any legacy child binding keeps chunked cleanup; wait-token links and streams also keep that path. New child results can therefore be deleted at completion without waiting for parent cleanup.
Cancel awaited children with their parent
Breaking: cancelling a parent parked on a child wait now cancels unfinished children it created, unless another registered waiter or another parent's pending or held named binding protects them. This includes concurrent named awaited siblings and every group member, and applies recursively within one shared pass budget. Unjoined children and reused children from another creator keep running. A raw join from another run does not guarantee protection for later group members; those members can return cancelled. Use a named step trigger or an idempotent child of your own for shared-child protection. See awaited-child cancellation.
Update tests and operator flows that relied on awaited children continuing after parent cancellation. No trigger option disables this behavior. Running children still receive cooperative cancellation requests.
Apply migration 0003_run_retention_deadlines.sql before starting upgraded processes, using the coordinated cutover above. It includes the sparse RunsCancellationCascade index on runlane_runs. Custom providers must preserve the private tagged cancellationCascade marker and index entries supplied by core. Keep MaintenancePhase.RunFinalization enabled to finish saved cascades after a restart. Retention keeps a parent while that marker is set. Storage catalog and document envelope versions remain 2; existing records need no rewrite.
Migration 0003 also adds RunChildStepsByParentChild on runlane_record_run_steps. It keeps settled bindings searchable by parent and child ID. New child steps may store private awaited: true; cancellation markers move the current wait's child IDs and cursor into a children marker, then continue with a steps marker. Cancellation clears the original wait. Cancellation step progress is recorded by removing awaited from each processed binding. The next pass reads the sparse index head. These changes are part of the coordinated 0.10 cutover. Do not mix pre-release 0.10 builds with different private schemas.
Automatic retention now preserves live idempotency keys with an optional finalRun snapshot. Migration 0003 also adds IdempotencyFinalRunExpiry on the owner table. Custom drivers must support that sparse index before deployment. Strict older readers cannot read owners with finalRun; include this change in the coordinated cutover. A repeat trigger can return the saved result after runs.get() and runs.findCurrent() stop finding the run. Oversized owner snapshots hold the run until key expiry. Caller-chosen run IDs have no TTL and become free again after deletion.
Each schedule now keeps one occurrence record for its pending or latest processed fire, keyed by environment and schedule ID. Preserve lastProcessedAt separately: it tracks accepted or skipped fires and prevents replay when the pending fire moves earlier or later. Custom providers must use this key and remove the old occurrence-by-schedule index. Migration 0003_run_retention_deadlines deletes existing per-fire occurrence rows. Clear those rows on other providers during the coordinated cutover too. A fire whose run is still stored is recorded as processed and does not run again. If that run was already deleted, a runtime schedule's latest due fire can run one extra time.
Review SQS Lambda schedule cadence
In 0.10, SQS Lambda handlers default to leaving the next schedule fire to maintenance. Keep the timer running and review schedules that fire faster than that timer. Import LambdaRecursiveLoop from @runlane/transport-sqs or either SQS lane; the SQS default is sqsLambdaDefaults.recursiveLoop. The optional recursiveLoop setting restores eager arming only for functions configured with AWS RecursiveLoop: Allow. See recursive loop detection before opting in.
Create schedule runs at fire time
Upgrade transport readers and writers together. Delivery envelopes are now version 3. DeliveryMessage is tagged by type: run wakeups carry runId; schedule_wakeup carries scheduleId and fireAt. Old envelopes are rejected. Drain old broker messages before switching package versions.
Custom storage providers must add the sparse ScheduleOccurrencesDue index over Armed occurrences. Partition by environment and sort by (fireAt, scheduleId). Keep one record per schedule, including its separate lastProcessedAt replay boundary. Do not delete a declared occurrence because it is absent from a process’s catalog. Migration 0003_run_retention_deadlines adds its Postgres index columns and clears old occurrence records at the end. Migrations 0000–0002 are unchanged. Clear old occurrence records on other providers during the coordinated cutover. Clearing history can allow one extra runtime fire.
scheduleLookahead now arms wakeups instead of creating future runs. Both schedule sources use run_${occurrenceId} as their run ID. Singleton conflicts skip the fire permanently. Remove code that expects revision-based runtime run IDs or stale early runs to be cancelled at acquisition.
Review declared fires during the 0.10 cutover
Breaking: cron and interval schedules now follow the schedule start rule. Migration 0003_run_retention_deadlines clears occurrence records, so every declared recurring schedule starts fresh at its first discovery after the upgrade. A declared fire that came due while processes were stopped does not run. Trigger its task by hand if that work is needed. Runtime schedule definitions survive the migration and still catch up when their occurrence record is missing. Once schedules keep their unprocessed fire, including a past runAt.