Storage contract details
Implement durable records, transaction replay, cursors, pruning, and limits without weakening core invariants.
Use this page while implementing or reviewing a StorageDriver. Start with build a storage provider for the shorter guide.
Keep logical records in core
NewStorageRecord contains a logical key, a JSON document, and all index entries. The provider assigns a new opaque positive-decimal StorageRecordVersion only when a mutation commits.
Storage drivers must declare profile.contractVersion: 2. Runtime construction rejects a missing or unsupported version before accepting work. Every current logical document has this envelope:
{ "schemaVersion": 2, "value": {} }Only schema version 2 is accepted. There is no compatibility reader for another version. A malformed value or a mismatch between the document, key, and derived indexes is durable corruption.
Keep documents opaque unless the provider has a contract-aware projection. Use the exported codecs and table definitions. Do not maintain another schema for runs, events, steps, outbox messages, schedules, owners, queue capacity, observations, leases, tombstones, or wait tokens.
JSON boundaries reject non-finite numbers and reference cycles during parsing and encoding. Parsed records and materialized appends own their nested JSON values. Reuse those owned values within the boundary instead of parsing or copying them again; new caller inputs and returned provider data still require validation at their respective boundaries.
encodeStorageDocument(codec, value) applies the owning document codec and produces an immutable canonical JSON document. parseNewStorageRecord() returns an immutable record, and parseAppendRecordsCommand() owns immutable appended values. Treat these write inputs as readonly. The helpers can reuse snapshots they previously validated and froze, including their UTF-8 byte measurements. Freezing an arbitrary caller value does not establish validation. Mutable caller inputs are reparsed, and ordinary stored-record reads retain independent caller-owned copies.
This reuse is an in-process optimization tied to the snapshot's lifetime. Durable state and transaction fences remain in storage. A fence is an atomic condition that rejects stale ownership or state. Drivers own physical limits and can use the shared measurement helpers. No provider-specific trust flag or additional transaction method is required.
The codecs also check identities that JSON shapes cannot express alone. These include:
- deterministic step tokens and schedule occurrence ids;
- nested environment and run ownership;
- observation source identity and unsigned 64-bit positions;
- complete outbox claim state;
- wait-token resolution, link counters, and reciprocal idempotency ownership.
Use shared format primitives
environmentKey defines the storage namespace. isoDateCodec defines ordered timestamp strings. getRunWaitTokenIdempotencyKey defines the reserved token identity shared with its parser. getRunStartExpiryAvailableAt and isRunDebouncePending provide canonical lifecycle rules for checking provider projections. runlaneDateArithmeticOptions supplies the shared structured-error policy for date arithmetic.
Completion-source selection, token wait-window keys, and parsed debounce policy belong to core. Providers preserve the supplied documents and index entries.
Recover completion waits
Preserve the child-wait counters, stored member order, cursor, and recovery indexes supplied by core. A pending wait parks its handler: Runlane saves the wait and frees execution capacity while the current promise stays pending.
context.join() uses child_completion and child_group_completion for both child references and known run IDs. Each source must exist. Wait registration and departure change the source's childWaiterCount atomically with the parent's wait. A positive count retains the source.
A terminal source with waiters has childCompletionResumeAt. RunCompletionsNeedingResume indexes it by environment, resume time, and run ID. An empty discovery page does not prove that registered waiters are gone. Only the exact count reaching zero clears recovery state; incomplete work must remain discoverable without starving other sources.
A group stores unique runIds and a zero-based cursor; RunsWaitingForCompletion indexes the active source. Store those values as supplied. Core may order stored members differently from the caller's result order. Moving the cursor, changing source counts, and appending run.wait_advanced commit together. Progress alone does not request parent delivery or change attempts, releases, or capacity. The parent resumes when the full group is terminal. Recovery must survive missed completion notifications.
Preserve cancellation cascades
Core saves a parent's private cancellationCascade marker with its cancellation and waiter departure. Preserve the tagged children marker with the current wait's runIds and member cursor, the steps marker, and the sparse RunsCancellationCascade entry. Cancellation clears the original wait. Other awaited children remain discoverable through their bindings. Cancellation step progress is recorded by removing awaited from each processed binding. The next pass reads the sparse index head. Cursor updates use the parent's storage version. No marker may be dropped before all child positions have been processed. Retention must keep parents with markers; finalization maintenance finishes interrupted cascades. See storage values.
A cascade's shared-child check uses the strongly read child and the supplied pending/held binding index. New registrations and bindings replace the child even if its flag is unchanged. Keep those version fences: an advisory empty query alone cannot exclude a concurrent binding. Eventual indexes and legacy counter holds conservatively protect children whose exclusive ownership cannot be proved.
Preserve child bindings and sparse counters
RunSteps requires a type from RunStepType: Output selects output, Child selects child, and Wait selects wait. The nested wait.type still selects sleep, signal, or token outcomes. Read and write the tag through runStepStorageValueCodec; missing tags and fields from another variant are rejected. The string values are listed in infrastructure values. Child references use the same parent, step key, and deterministic token identity as callback steps. Creation, binding, token ownership, and child retention commit atomically under the parent's lease.
retainingStepCount counts legacy child bindings without settlement. New bindings on strong-index providers use RunChildStepsByChild and the private one-way boundByStep flag; see storage values. childWaiterCount counts registered child waits. New documents omit either counter when zero; runStorageValueCodec restores zero on read. Nonzero values remain explicit. Generic providers preserve the supplied document; projections use the codec when reconstructing it. These fields do not appear in public run records. For stored children, eventual-index providers keep the counter binding path: an empty advisory index page cannot prove absence of a committed hold. A run already marked boundByStep remains held when read through an eventual-index provider.
runStorageValueCodec is a bidirectional codec. Use parse/encode operations or encodeStorageDocument() rather than object-only .shape, .pick(), or .extend() helpers. Follow Upgrade Runlane before changing stored readers.
Commit child waits and raw batch chunks
First-use triggerAndWait() and triggerBatchAndWait() save missing children, initial events/outbox and owners, bindings, retention, the parent's exact completion waiter, release/history, and both capacity releases in one transaction. No child may be visible before that release. Preserve the complete invariant on Local and durable backends. Reject the whole attempt with storage_limit_exceeded when it cannot fit; core never splits this transition. Publication starts after commit, and existing outbox and completion recovery handle later failures.
Released event documents require releaseType: RunReleaseType.Time for delay/resume fields or RunReleaseType.External for an external wait. Use storageRunEventCodec; the tag does not add SQL columns. Runlane 0.5 requires fresh storage, so no history migration is supported.
Raw batches use the same transaction mechanics for independent backend chunks. Core splits only a rolled-back size rejection and retains prepared identities. Never return a size error for an ambiguous or partly committed attempt. Native mutation grouping must retain every expected-absence and version dependency across collections.
BatchMembers keys are (environment,batchId,inputIndex). batchMemberStorageValueCodec owns runId, taskId, runCreatedAt, and storage-sealed acceptedAt. BatchMembersByBatch partitions by (environment,batchId) and sorts by (runCreatedAt,runId,inputIndex). BatchMembersByRun partitions by (environment,runId) and sorts by (batchId,inputIndex). Encode tuples, dates, and input indexes with the shared codecs. These records have no TTL and are removed with their run through bounded pruning.
Runs and creation events preserve optional birth batchId; reuse never replaces it. A sparse internal batchMemberRecordCount is advanced with accepted memberships and preserved through lifecycle changes. Tombstones carry remainingBatchMemberRecords only for runs with memberships. This lets ordinary runs skip membership reads and index work entirely. Do not derive membership from the birth ID.
Checkpoint keyed waits during resume
Preserve RunWaitStepRecord values through runStepStorageValueCodec from @runlane/contracts. RunStepWaitType.Sleep saves one completed pause. Signal saves the signal key and RunWaitResolution.Satisfied or TimedOut. Token saves the token ID and a timed-out window. Wait records keep the same step-key and deterministic-token identity as other steps. Internal window keys are core-owned; handler keys cannot contain : or #.
A keyed wait's resolution commits its checkpoint, token owner, step count, run.wait_resolved, and enabled observation with the resume or claim. attempt identifies the releasing attempt; completedAt uses sealed storage time. Pruning uses the existing step index.
Timed token conditions pair stepKey with timeoutAt. The transaction reads the token and waiting link before sealing time. A window timeout saves the checkpoint and leaves the token pending while changing the run link to connected and reducing waiter count. Shared-token batches combine departures into one replacement. Token completion or token expiry needs no window checkpoint; the earlier token deadline takes precedence.
Saved windows retain their token dependency. Replay can read it without adding another attachment. Immediate terminal reads still attach a dependency when none was retained. wait.until() uses storage claim time without creating a step record. See Upgrade Runlane for unsupported stored formats.
Support start expiry
Preserve optional startBefore, RunStatus.Expired, RunEventType.Expired, and StorageIndexName.RunsStartExpiry. The index covers visible active runs with a deadline and zero attempts, excluding requested cancellations. Its partition is the environment and its sort tuple is the ISO deadline followed by run ID. Store complete index entries supplied by core.
A claim gives a worker time-limited ownership; it does not itself count as an attempt. First-start admission and expiry use sealed storage time. Expiry, history, projections, owned capacity/singleton release, idempotency retention, and child-completion recovery commit atomically. Never release a capacity slot now owned by another run. Follow the upgrade procedure before introducing these records.
Support durable debounce
Preserve StorageCollectionName.DebounceOwners, run debounce policy, and RunEventType.Rescheduled. DebounceOwnerStorageValue contains the environment, task ID, key, and run ID. Its ID encodes task and debounce key with storageTupleCodec; its partition is the environment.
The run owns the first accepted debounce.key, delayMs, and optional absolute maxRunAt. Only runAt holds its current due time. Core supplies rescheduling decisions and complete index changes. Commit owner replacement, history, due indexes, observations, and any named binding atomically. Use conditional creation or exact-version replacement so a concurrent winner cannot be overwritten.
Named replay keeps its binding without rescheduling. Coalescing that changes no due time adds no history. An owner can remain after the window closes; a later trigger replaces it. Pruning removes it only while it still points at that run. See debounce and the upgrade procedure.
Support admission priority
Preserve optional run and creation-event priority. runPrioritySchema owns validation; missing priority means contractDefaults.run.priority. Core stores only non-normal values.
RunsRunnableByQueue keeps normal runs in the encoded environment/queue partition. High and low add priority as a third tuple component. Sort entries stay [actualEligibilityTime, createdAt, runId] with canonical ISO dates. Never persist a boosted due time or derive priority from the broker queue.
Enabled queues discover bounded candidates from three streams. Exclusive selection can lock unselected heads too; selection does not promise global start order. Core rechecks due time and current records. Eventual indexes can hide or misorder work until later scans recover it. Preserve per-stream cursors and complete index entries.
Register matching queue policies in every process. Finish or cancel all non-terminal high/low runs before removing priorityBoost, including delayed and waiting runs. See priority for ordering and Upgrade Runlane for compatibility.
Preserve execution-policy snapshots
Preserve executionPolicy on every run and creation event. runExecutionPolicySchema and resolvedRetryPolicySchema own their normalized shape. Providers must not normalize the policy again, merge task defaults, or add an empty snapshot when one is missing.
Every snapshot requires the effective maxInterruptions, including when the task used the shared default. Accepted runs retain that value if defaults change. Missing snapshots or interruption counters fail to decode. Omitted retry and duration settings disable automatic retries and task-level deadlines. Retry counting follows the task retry policy; providers need no extra counter or index. The creation event owns the accepted policy and the run carries its unchanged projection.
Policy uses existing JSON columns and atomic creation transitions, including child binding and idempotency ownership. Existing record and atomic capacity limits still apply. See stored policy for overrides and manual retries, and Upgrade Runlane before reusing history.
Preserve metadata updates
RunEventType.MetaUpdated carries patch: JsonObject. Core merges top-level keys into run metadata and advances eventSequence and updatedAt. The event's separate meta is audit data. Providers do not perform that merge or change lifecycle rules.
Persist history, run, projections, and enabled observations atomically. A token wait also updates its link's releaseSequence while preserving the same wait, counts, deadlines, and retention. Task writes check the lease, cancellation, and attempt deadline against storage time. Terminal runs remain immutable.
Preserve core's lease, version, and sequence fences on every write. Record limits apply to merged metadata. See metadata updates and Upgrade Runlane.
Preserve indexed tags
runTagsSchema owns bounded, deduplicated labels. Initial tags come from run.created; RunEventType.TagsAdded carries additions. Core merges labels and checks the final distinct count. Providers do not decide whether an addition is allowed.
Tags use the same atomic history, projection, observation, lease, and token-link rules as metadata. The run owns labels; indexes are derived. Change index membership in the same commit when documents change, become hidden, or are deleted. Opaque or malformed records cannot appear in operator tag results.
RunFilter.tag selects one exact, case-sensitive label within an environment. Apply every other filter, bind the label into cursor scope, and return defensive copies including optional RunSummary.tags. Tags are not authorization scopes. Local indexes membership in memory; PostgreSQL uses the canonical tag array without another table or generic index name. See run tags and Upgrade Runlane.
Keep operator reads separate
OperatorReadDriver is an optional read model with getRun(), listRuns(), and listRunEvents(). A driver can execute tasks without it. Core can fall back to the typed raw-record path for one exact run lookup, but ordinary list and history queries require the read model. Core owns indexed version and batch lists through the raw record indexes.
When a provider adds a projection, update it in the same atomic commit as the raw records. A visible run must appear with its exact summary and event history. A tombstoned run and its events must disappear in that same commit. Raw child cleanup may continue later.
The read-model boundary does not prescribe a second physical document copy. A provider may keep indexed metadata beside, or linked to, the canonical records. A joined read must return one consistent view of the metadata and documents, remain bounded, and preserve the same filtering and cursor semantics. Projections are derived from canonical records and are not independently writable state.
Bind every filter and sort input into the cursor scope. Return defensive copies of run records, summaries, events, nested values, and dates.
Use these exports from @runlane/contracts for operator list cursors:
| Export | Role |
|---|---|
PaginationCursorKind | Selects run, event, version, batch, or schedule lists. ScheduleList uses schedule_list with a source and optional position. |
PaginationCursorScope | Normalized environment, filters, and sort order for the selected list. |
PaginationCursorPosition | Nonempty array of numeric, string, or null keyset values. The provider owns their meaning and validates its tuple. |
encodePaginationCursor({ kind, scope, position }) | Encodes the order-versioned envelope as base64url JSON. |
decodePaginationCursor({ cursor, expectedKind, scope }) | Validates the envelope and exact scope, then returns the position. An omitted cursor returns undefined. |
parseListRunEventsQuery(query) | Checks that RunEventSortField.Sequence has a runId filter and returns the query. |
Malformed envelopes reject with validation_failed. Wrong list kind and wrong query scope share the same mismatch error. Normalize dates and absent filter values before encoding and decoding. Providers keep their own keyset ordering and tuple validation; raw named-index cursors use the separate storage query cursor contract.
An opaque document that does not decode as a canonical run or event remains a valid raw record. Do not guess at its fields or add it to the operator projection. Core's typed table boundary owns logical validation.
Treat each transaction callback as a new attempt
A provider may replay the callback after a supported conflict. Only the committed attempt's return value may escape.
get()reads records or confirms that they are absent. Both results join the validated read set.queryCandidates()returns index references, optionally holding exclusive ownership. Core point-reads every candidate that affects a decision.- The first
now()call seals the read set and returns one frozen time for that attempt. create(),replace(),delete(), and optionalappend()stage mutations.- The provider validates the read set and commits all staged mutations atomically.
Reject get() and queryCandidates() after now() or the first mutation. Reject overlapping reads. Roll back the attempt if the callback throws or a staged condition loses a race.
create() is a conditional insert. It may target an unread key or a key read as absent. It must reject a key read as present, and commit only while the key remains absent.
replace() and delete() require the unchanged record and version returned by the same attempt. A key may be mutated at most once. A replacement cannot change the key. Replacing a record replaces all index entries in the same commit. Deleting it removes them.
Providers may group staged mutations into native bulk statements without adding another batch method. Grouping does not change per-record conditions: all expected creates, replacements, and deletions must succeed, and any mismatch rolls back every group, projection, and append in the attempt. Never report a partially applied batch as a successful transaction.
Do not run user code, network calls, random id generation, or externally meaningful logging inside the callback. Prepare stable identities before entering it.
Add optional ordered append
StorageTransaction.append(command) stages one ordered batch of opaque JSON objects. The command selects a StorageStreamName, a partition, and a non-empty values array. Storage assigns positions during commit; input values must omit the stream's position field. The method returns no allocated positions.
Core owns observation contents and lifecycle rules. Providers translate the canonical storageStreamLayouts and document codecs. materializeStorageAppend() defines the persisted head, records, keys, and indexes for a starting position. readStorageStreamPosition() validates the existing head; an absent head starts at position 1. Corrupt or exhausted heads must fail without changing durable state.
For StorageStreamName.Observations, the partition is the environment name. Positions are positive unsigned 64-bit decimal strings. Every batch is contiguous and follows previously committed batches in that partition. The next-position head must also fit the unsigned 64-bit range. Do not convert positions to JavaScript numbers.
The allocator, appended records, point mutations, and projections commit atomically. Aborted or replayed attempts consume no stream positions and leave no records. Coordinate through durable storage across provider instances and processes. Native append and existing point writers use the same head and record layout; protect absent-record dependencies as well as present versions.
An attempt may stage only one append batch. It cannot also point-read or mutate the appended stream's head or records in the same partition. Appending ends the read phase just like a point mutation. Copy the supplied values at the boundary and reject use after the attempt ends.
The head and every appended record count toward the driver's atomic capacity, together with point dependencies and mutations. measureStorageAppend() measures bytes using the maximum position width before allocation. Core checks the shared record size before staging the append. Reject oversized atomic work with storage_limit_exceeded; never split it into commits.
Providers may omit append. Core then uses the existing head read and conditional point mutations. Application APIs and persisted documents are the same on either path.
Add optional exclusive candidates
A provider may advertise profile.exclusiveCandidates: true and accept queryCandidates(command, { mode: StorageCandidateMode.Exclusive }). Omitted mode, Advisory, and ordinary query() retain advisory behavior.
Exclusive selection skips records held by another exclusive attempt and holds every returned record until the current attempt commits or rolls back. Ownership must work across provider instances and processes. Core still point-reads selected records before making decisions; selection does not replace version checks, lease fences, or capacity rules.
Lock only returned records. Do not lock an extra lookahead row to determine pagination. A full exclusive page may return a cursor even if the next page is empty. Rows skipped because they were busy may require a fresh scan after their owner finishes; an empty exclusive page is not proof that the index is empty.
Do not advertise this capability if selection remains advisory. Core requests exclusive mode only from providers that advertise it.
Use the closed index catalog
query() and queryCandidates() accept only StorageIndexName values. Map each value to a native query plan. Do not expose a generic predicate or scan API through StorageDriver.
Storable identifier strings must be well-formed Unicode, contain no U+0000 (NUL), and not start with U+FEFF (the byte-order mark). This one rule applies to public IDs, environment names, stream names, schedule external IDs and deduplication keys, storage tuple/key components, index entry partitions and sorts, query partitions, and all range bounds. An interior U+FEFF and paired surrogates are valid. Fields that require a name remain nonempty; an explicitly empty range bound remains valid. The owning schemas reject invalid strings before writes, discovery, or cursor encoding. Do not normalize or replace characters. isStorableIdentifierString() and storableIdentifierStringSchema expose the canonical rule.
Providers must sort natively in Unicode code-point order, equivalent to UTF-8 byte order for well-formed strings. Use the same order for ranges, cursor seeks, equal-sort key ties, and operator ID ties. Do not fetch and re-sort results in JavaScript or encode UTF-16 to imitate JavaScript string order. Core may merge bounded partition pages using compareStorageIndexPositions(), preserving the native order of each page. U+E000 sorts before U+10000 and 😀. Tuple encoding stays lowercase UTF-8 hex; it already preserves this order.
JSON strings and object keys must be well-formed Unicode without NUL. Provider publish failures are diagnostics: Runlane replaces NUL and unmatched surrogate halves in their messages, metadata strings, and metadata keys before persisting a failed or dead-lettered outbox outcome. The same sanitizers protect handler failures. JSON may contain leading U+FEFF; these are not identifier strings. A provider that cannot store an otherwise valid value must return a non-retryable validation error, not retry it as a conflict or availability failure.
Index results contain only { key, sort }. Order them by encoded sort, then encoded record key. Treat every result as a candidate because a provider may report eventual index consistency.
Use the public cursor functions:
encodeStorageQueryCursor()to return a continuation;decodeStorageQueryCursor()before applying one;parseQueryRecordsResult()in boundary tests.
A version-2 raw cursor binds its schema version, index, partition, range, direction, last sort, and last record key. Reject it when any part of the query scope differs.
Use the canonical encodings
Use storageTupleCodec for tuple components and storageRecordKeyCodec for keys stored in maps or native provider representations. Compare two validated key objects with haveEqualStorageRecordKeys() instead of encoding both. The encoding is lowercase hexadecimal UTF-8 with / between components. Its lexical order matches component-wise UTF-8 byte order.
Use compareStorageEncodedValues() for the same comparison in memory. Use isoDateCodec for ordered timestamps and storageUnsignedIntegerCodec for unsigned 64-bit positions.
For an inclusive tuple-prefix range, call encodeStorageTuplePrefixUpperBound() and use its exclusive result. Do not append a Unicode sentinel. There is no maximum arbitrary Unicode string, so a value starting with U+10FFFF can still have more bytes.
Preserve saved idempotency results
Preserve optional finalRun in IdempotencyOwners through the owning codec. Core supplies the final snapshot and the sparse IdempotencyFinalRunExpiry entry only when that snapshot exists. Partition by environment and sort by (retainedUntil, runId) with an inclusive due-time range. Do not substitute IdempotencyRetention, which also contains owners whose runs remain stored forever.
Commit saving the result and deleting or tombstoning the run atomically. Keep owner point-version fences during repeat triggers, resets, and expiry cleanup. A stale expiry candidate cannot delete a replacement owner. Core owns liveness and size decisions; custom drivers must not add a shorter owner TTL or repeat those rules. The encoded owner must fit within contractDefaults.storage.maxRecordBytes; otherwise core holds the run until expiry.
A saved result can outlive its run: exact run reads return undefined, while triggers return the snapshot. Manual prune releases the key. A caller-chosen runId has no TTL and becomes available after deletion. Saved results reused by a named step are written as settled bindings in the bind transaction without a child-row hold. Raw batch reuse of a saved result adds no membership to an already deleted run.
Preserve pruning invariants
Run pruning does not trust the size of an advisory index. A visible run stores exact counts for events, outbox messages, steps, and wait-token links. Tombstoning copies those counts. It also removes the run from operational reads in one transaction.
Run records require waitTokenLinkRecordCount; tombstones require remainingWaitTokenLinkRecords. Missing counts fail to decode rather than defaulting to zero. These counts prevent pruning while reciprocal token links remain.
Cleanup then works in bounded transactions. Each pass point-reads child candidates, deletes exact step-token owners and reciprocal token links, and reduces durable counters. The run and tombstone disappear only after every counter reaches zero. An empty eventual-index page is not proof that cleanup finished.
Pending and held child bindings block deletion through the sparse step index. Deleting a legacy binding decrements the child's retention count in the same transaction. A terminal parent eligible for pruning may release its saved steps while another run still retains its result. This lets terminal dependency cycles be collected without deleting results needed by active parents.
Automatic handler token keys are owned by core and counted in call order. Public keys reserve :, so explicit keys cannot collide. Preserve canonical token-key encoding through the supplied codec. See Upgrade Runlane before changing token creation in active handlers.
Wait-token pruning is separate. It point-reads a terminal candidate, keeps it while any run link remains, and deletes the token with its exact idempotency owner. A missing or non-reciprocal owner is an invariant failure, not permission to orphan either record.
Report a profile that is true
The profile describes mechanics:
- durability is
processordurable; - clock authority is
client,server_sampled, ortransaction_authoritative; - index consistency is
strongoreventual; - optional
exclusiveCandidatesdeclares transaction-owned candidate selection.
Physical limits are not part of the profile. get() accepts any key count, preserves positions, and chunks internally. query() and queryCandidates() accept any positive safe-integer limit and may cap their pages. Return a cursor whenever more records may exist; no cursor means the scan is exhausted. Direct reads and index discovery never throw a storage-limit error.
Reject an attempt the driver cannot commit with createStorageLimitError(), at or before commit. The error is storage_limit_exceeded, is non-retryable, and has meta: { actual, limit } in records or bytes. Leave no durable effect and do not replay the callback for this error. Core may split its own independent batches after rollback; it never splits a user-atomic transition or replays a transport publish.
Every driver must commit the capacity floors from contractDefaults.storage, including ordered append when supported. Core checks maxRecordBytes when staging a create, replacement, or append. It does not calculate driver capacity.
Use transaction_authoritative only when the full point-read set is sealed or locked before sampling a shared advancing clock. With client or server_sampled time, version and ownership fences still protect writes. Clock skew can still cause early duplicate execution or brief capacity oversubscription. Document that risk.
Use Local as the executable reference
createLocalStorageDriver() from @runlane/local-adapters uses one shared record map with optimistic read-set validation, sorted indexes updated in place at commit, non-repeating versions, and a client clock. Commits avoid copying the full record map and re-sorting whole index partitions. Sorted-array insertion and removal can still move the rest of a partition.
Local development storage bridge
@runlane/local-adapters also exports serveLocalStorage({ storage, workSignal?, onFailure? }) and createLocalStorageBridgeClient(addressOrResolver). LocalStorageServer exposes an authenticated address and idempotent close(). LocalStorageAddress contains version, port, and token; localStorageProtocolVersion identifies the supported protocol. The server binds an ephemeral port on 127.0.0.1. onFailure receives structured errors with internal causes; responses contain public fields only. Keep tokens private.
LocalStorageBridgeClient implements raw storage, operator reads, runSignal, and workSignal. Its profile matches the in-process driver. Each transaction callback runs on the client and submits one optimistic commit. The server reuses the in-memory driver's validation and atomic application path; it keeps no transaction between requests. Confirmed conflicts replay the callback within the driver's attempt budget. Limit errors and transport failures do not replay it. A lost response may follow a successful commit.
The in-memory driver's commitAttempt() accepts a validated point-read set, staged record mutations, and an optional append. now() samples the owning clock without retaining a transaction. Its monotonic revision closes the long-poll registration gap. Each client attempt pins one session token, so it cannot apply reads from an old host to fresh memory after a restart.
createLocalStorageUnavailableError(cause?) builds the shared retryable failure used when the dev connection or live session is unavailable; the cause stays internal.
Development tooling normally uses lane-local's host and discovery APIs. Applications use createLocalLane() to connect to dev; storage operations fail when dev is absent. In-process tests use createTestLane(), which never uses this bridge. The bridge is not a durable storage service.
Its profile is process-local and strongly indexed. It accepts no physical limits option. maxTransactionAttempts defaults to 16, and tests may inject a clock. Use withStorageLimits() from @runlane/testing to simulate a bounded provider.
This driver is a reference and development implementation. It is not durable production storage.
Know the Redis Cluster limit
A single MULTI, pipeline, or script cannot commit atomically across Redis Cluster hash slots, so it cannot meet the storage contract alone.
The Redis storage driver keeps all keys for one explicit namespace in one slot. A namespace can contain multiple environments. Its Lua commit validates and changes records and indexes on that slot's primary. Independent namespaces can use different slots; a single namespace cannot scale across primaries.
Verification checklist
Before publishing a driver, prove:
- exact point-read positions, including duplicates and misses;
- large point reads, capped query pages with cursors, and the shared atomic capacity floors;
- defensive copies for objects, dates, and bytes;
- conditional create, exact replace/delete, atomic rollback, and callback replay;
- conflict detection for present, absent, read-only, and blind-create dependencies;
- frozen attempt time and rejection of reads after sealing;
- ascending and descending order, every range bound, tie-breaking, and cursor-scope rejection;
- atomic index movement and explicit limit failures;
- immediate tombstone visibility and operator-query parity when
OperatorReadDriveris present; - wait-token completion, timeout, reciprocal links, pruning, and all token index mappings;
- injected failure paths with no partial writes.
When implemented, also prove atomic ordered append, mixed-writer compatibility, position bounds, and disjoint exclusive selections across independent instances. Enable the corresponding optional conformance suites explicitly.
Use test a provider for the conformance harness and storage contract values for the closed names.
Preserve versions and durable patch markers
Runs.version is immutable after first start. versionConstraint records an accepted child's parent baseline. Started events require baseline version and actual workerVersion. Providers preserve these values; they do not route workers by version.
Map StorageCollectionName.RunPatches with key (environment, runId, patchId) and the immutable RunPatch shape through storageRunPatchCodec. RunPatchesByRun partitions by storageTupleCodec.encode([environmentKey, runId]) and sorts by storageTupleCodec.encode([patchId]). RunsByVersion partitions by [environmentKey, version] and sorts by [isoCreatedAt, runId], using storageTupleCodec. It includes visible started runs whose version differs from contractDefaults.run.version; runs on the default version have no entry.
Marker absence, run ownership, and the unexpired lease are point dependencies. Commit the boolean marker, run.patch_recorded, event sequence, sparse patchRecordCount, enabled observations, and any token-link sequence update atomically. Concurrent calls for one ID converge on the committed marker. Storage failure must expose no decision. Core supplies the branch policy and complete index entries.
Tombstoning removes version index membership and copies the optional patch count into remainingPatchRecords. Bounded cleanup deletes markers through RunPatchesByRun; an empty advisory page cannot clear a positive remaining count. Runs without patches have no patch records or patch counter field.
Preserve queue admission controls and pools
QueueControls has point-read identities (environment,queue,scope,key?). Queue controls own pause and queue overrides; keyed controls own a per-key override. Every admission strongly reads the relevant controls, including absence, before sealing transaction time. A concurrent control change invalidates the admission read set. Override expiry uses sealed storage time; no expiry index or maintenance phase is needed.
Each QueueCapacityPools record at (environment,queue,poolKind,key?) stores exact ownedCount and unsigned decimal nextSlotOrdinal. QueueCapacitySlots is canonical ownership. The pool count is a projection changed only with slot creation, transfer, renewal, deletion, or reclamation in the owning run transaction. Total, keyed, and unkeyed pools use distinct tags. A run carries up to two capacitySlots references with pool, ordinal, and owner token.
Acquire both declared pools or neither. Transfer reservations without increasing counts. Renew both expiries. Delete released slots and decrement their pools atomically. Reclaim only strongly read expired ownership in bounded pages. Stale run, token, or phase fences cannot delete a successor's slot or decrement its count. Lock multiple pools in a consistent order. Lower limits compare against all owned slots, including high ordinals and unreclaimed expired slots; never filter ownership by ordinal.
QueueCapacitySlotsByExpiry partitions by (environment,queue,poolKind,key?) and sorts by (expiresAt,ordinal). RunsDispatchHeadByKey partitions by (environment,queue,key-kind,key,priority) and sorts by (dispatchAvailableAt,createdAt,runId). Membership requires a visible run with boundedQueue: true, current dispatch eligibility, and dispatchExpiresAt === undefined. Remove it on reservation or tombstone and update it on claim. Core queries each priority band in ordinary advisory mode, strongly reads the selected heads, and rechecks due time, start expiry, controls, and capacity at sealed time. An unseen concurrent insertion is outside this advisory guarantee.
The internal boundedQueue: true run marker is derived once at creation from the registered declaration. It is absent for unbounded runs and removed from public RunRecord reads. Preserve it through every later transition. A queued run keeps its creation-time marker if a deployment changes its queue between bounded and unbounded. An originally unbounded run then lacks the per-key head check, but admission still reads the current declaration and enforces every declared pool. The marker controls only index membership and ordering. Runs created on unbounded queues gain no dispatch-head index entries. Continued bounded polling claims use the same advisory head check; fresh polling claims do not add a head query.
Preserve runtime schedule ownership
Schedules contains runtime definitions only. Preserve the normalized definition/payload, active state, internal revision, due time, creation/update times, and optional deletion time. ScheduleOverrides stores persistent declared active overrides by schedule ID. ScheduleDeduplicationOwners stores environment-scoped keys; external IDs are nonunique labels. Definition/key mutations commit atomically.
Map SchedulesByDue from environment to (workAt,id), where workAt is deletion time for cleanup, otherwise active nextFireAt. Map SchedulesByCreatedAt, SchedulesByTask, and SchedulesByExternalId to (createdAt,id) in their environment/filter partitions. Those list indexes exclude deleted definitions. Each schedule keeps one occurrence record, keyed by environment and schedule ID. Its id and fireAt describe the pending or latest processed fire. Preserve lastProcessedAt, the last accepted or skipped fire; it is absent until the first processed fire. Arming can move the pending fire earlier or later without changing this boundary. Arming and acceptance reject fires at or before it. Add ScheduleOccurrencesDue: include only Armed records, partition by environment, and sort by (fireAt, scheduleId). Completed records have no entry in this sparse index. Acceptance moves an armed fire directly to Completed. Completed records keep claimedAt, claimedBy, and claimToken to identify the worker that accepted the fire; they have no claim expiry. Completed fires may have an empty runIds array when skipped. Use canonical tuple/date codecs and preserve the index entries supplied by core.
Armed records carry taskId and optional queue, the explicit schedule queue name. Preserve both in document round trips. The task queue comes from current code. Core resolves the explicit queue by name at fire time and uses the registered policy. Create, update, and activation stage arming and fresh routing in the same transaction as their schedule write. All reads finish before transaction.now(). Runtime maintenance arming also checks the definition revision.
Run acceptance atomically completes the deterministic occurrence, advances the runtime definition, and arms a nearby following fire, together with its run, initial history, and owners/outbox. Exact-version dependencies reject concurrent update/deactivation/deletion. Declared acceptance point-reads the override. Occurrences may carry a runtime revision; run source snapshots add fire time, external ID, and revision. Processes can own different catalogs in one environment. Due scans disarm armed declarations only when the stored taskId is registered locally but its schedule ID is no longer declared. Core then writes a completed record for lastProcessedAt, or deletes a record that has none. Records for unregistered tasks remain. Runtime schedules whose stored definition is gone are also eligible for occurrence deletion. Cleanup batches re-read records before deletion and preserve concurrently changed task/fire routing. Due scans skip fires outside the local catalog within their bounded page allowance. Do not add schedule work to generic run transitions.
Persist and fence terminal hooks
Optional Runs.hooks holds at most four callback slots, their attempts/status, retry availability, independent claim expiry, and bounded last failures. The claim token is storage-only and is omitted from public runs. Terminal transitions save this state with the outcome, including cancellation and expiry before first start. Known absence saves no state. Producer definitions without handlers require discovery by a worker with that task registered.
Project both RunsHooksPending and RunsHooksPendingByQueue only while hook work remains. The first partitions by environment; the second partitions by the environment and queue tuple. Both use the same sort. Never invent an entry on read or return an empty page for an unsupported index. The sort key uses the next retry time, claim expiry, or lost-wakeup recheck time. A hook claim replaces one run row without a task lease or capacity slot. Settlement must check the exact hook token, live expiry, and visible run; rollback must preserve all prior state. Done and failed state removes both pending index entries and no longer retains the run.
Outbox intents distinguish run_wakeup from run_hooks_wakeup; in-flight probes must filter by purpose. Hook wakeups contain no callback body or code.
Preserve named output
Implement RunStreamNames, RunStreams, and RunStreamRecords through the logical record contract. The capped registry serializes aggregate quotas; per-name headers allocate uint64 positions. Appends validate the exact run/attempt/lease/tombstone read set at sealed storage time, then commit source records, header, and quota projection atomically. They never replace the run. Steps, logs, and streams share the same attempt fence: attempt number, lease token, lease expiry, and attempt deadline. CancellationRequested still admits cleanup writes while that fence holds. Source appends do not read capacity pools or slots.
Map RunStreamRecordsByStream for named delivery and RunStreamRecordsByEventSequence for causal timeline summaries. The latter sorts (afterEventSequence, occurredAt, name, position). occurredAt is the writer-clock sample. Sparse RunAttemptBoundaries entries identify stream-closing events and rare external attempt recovery. Ordinary attempts without streams add no boundary entry. Derived closes require no per-name writes.
Full record accounting includes the document, point key, and all indexes. Stream creation preflights the maximum envelope through the real codec. Keep provider capacity errors atomic so core can split batches without losing exact-retry identities. Existing run tombstones own bounded source deletion.
Delivery recovery membership
RunsDeliveryRecovery partitions by environment and sorts by (deliveryRecoveryAvailableAt, createdAt, runId). Include only visible eligible queued, scheduled, retrying, released, or running runs with a defined recovery time. Exclude queued runs with outboxRecordCount === 0; polling-only queued work has no lost transport delivery to recover. Use getRunDeliveryRecoveryAvailableAt() and preserve core's supplied entries.
Awaited child cancellation
Custom drivers must preserve RunAwaitedChildStepsByParent entries supplied by core. They cover unfinished awaited child steps, partitioned by (environment, parentRunId) and sorted by (stepKey). Settled and held steps have no entry. Update the sparse entry atomically with its step, including changes to wait intent and settlement. An empty parent page completes the cancellation step cursor in one read. RunsCancellationCascade sorts by (updatedAt, runId).
Whole-run deletion requires matching child counters. A mismatch raises an invariant error.