Skip to Content
Runlane
ReferenceApplication API

Streams

Write durable named output and resume readers from source cursors.

Declare named schemas on the task, then use context.stream(name) inside its handler. Chunks are finite JSON values stored with the run. The task's returned output remains separate.

import { task } from '@runlane/core'
import * as z from 'zod'

const writeAnswer = task({
  id: 'answer.write',
  schema: z.undefined(),
  streams: { answer: z.string().trim() },
  async run(_input, context) {
    const answer = context.stream('answer')
    await answer.append('Hello')
    await answer.appendBatch([' ', 'world'])
  },
})

Write chunks

stream(name) returns a RunStreamWriter. Names must be nonempty valid Unicode, contain no NUL or leading U+FEFF, exclude . and .. because URL parsing removes these path segments, and fit streams.maxNameLength UTF-16 code units. Colons and other punctuation are allowed.

MethodBehavior
append(chunk)Atomically commits one chunk before resolving.
appendBatch(chunks)Commits capacity-sized atomic groups. A rejected group leaves earlier cohorts committed. Failure metadata includes accepted, the confirmed chunk count from this call.
pipe(source)Consumes an AsyncIterable with backpressure. Flushes by count, serialized bytes, or delay, including while awaiting a slow source. An empty source still opens the attempt.

Each declared schema validates and normalizes chunks once before storage. The writer accepts that schema's input type; readers receive its output type. No explicit type arguments are needed.

task() checks the declaration at authoring time. Names must pass runStreamNameSchema and fit contractDefaults.streams.maxNameLength. The map can contain at most contractDefaults.streams.maxNames names, and every value must be a Standard Schema. Producer definitions carry the same map. Reuse those schema instances when adding a worker handler.

The handler and task middleware use the same declared names and schema input types. TypeScript rejects undeclared names, including every name on a task with no streams. At runtime, an undeclared name throws configuration_invalid at the call. The message names the task and lists its declared streams. It is not retried by default. Runtime limits can be lower than the declaration ceilings; they still apply when opening or appending a stream.

Normalized chunk strings and object keys must contain valid Unicode without U+0000 (NUL). A lone UTF-16 surrogate is an unmatched half of a character pair, such as \ud800. Runlane rejects lone surrogates and NUL with configuration_invalid after your stream schema runs. An appendBatch() containing one rejects before writing any chunks from that call. Valid surrogate pairs, such as emoji, remain supported.

A successful append has crossed the lane's storage commit boundary. Postgres keeps it across process restarts; the local lane keeps it only while runlane dev runs. Use createTestLane() for process-only stream tests without dev. Each deliberate call appends again. Internal retries after an ambiguous commit response preserve command and member identities and do not duplicate records. If a group commits but every response is lost, accepted can omit those chunks. Read retained records before making another deliberate append.

The attempt stops accepting new writes and waits for admitted writes to finish before saving its outcome, including calls that the handler did not await. A write failure prevents an otherwise successful attempt from succeeding and follows the run's retry policy. Cancellation, timeout, suspension, and an existing handler failure retain their normal precedence. Calls made after suspension stay parked. A closed writer rejects later calls. A retained write failure makes later calls reject with a structured error naming the failed source; see the task logger contract.

pipe() rejects with operation_cancelled on cancellation and calls the source iterator's return() when it stops early. A source whose pending next() never resolves cannot hold up cancellation. Chunks already committed stay readable.

Read a named stream

const page = await runlane.runs.readStream(runId, 'answer', {
  after: savedCursor,
  limit: 50,
})

The result is { records, cursor, hasMore }. Save cursor even for an empty page. hasMore describes the bounded scan observed by this call; an active run can append later.

RunStreamRecordType has three values:

  • attempt_started: this attempt first used the name.
  • chunk: includes normalized value, UTF-8 JSON bytes, and zero-based chunkIndex within that attempt and name.
  • attempt_closed: derived from closing history; includes reason and boundarySequence.

Every record includes id, environment, runId, name, attempt, position, occurredAt, and afterEventSequence. Positions are opaque unsigned-64-bit decimal strings. A derived close shares its attempt's last source position; its boundary sequence makes its named cursor distinct. Close reasons are completed, failed, released, cancelled, expired, and abandoned. Recovery saves RunEventType.AttemptAbandoned before a replacement attempt starts, so a lost worker still has a visible close.

occurredAt is the writer's clock sample. afterEventSequence is the maximum of the attempt watermark and the stored run sequence read by the append transaction. These fields describe causal placement, not a global commit order.

Subscribe to run changes

for await (const event of runlane.runs.subscribe(runId, {
  after: savedCursor,
  signal: abortController.signal,
})) {
  savedCursor = event.cursor
}

Pass streams: false to skip stream reads, or streams: ['answer'] to read and cursor only selected names. The default includes all names. See runs and waits.

Without after, the subscription yields a snapshot, then reads retained named records from position zero and run events after the snapshot. These two sources have no total order. An already-terminal snapshot waits until retained stream tails drain. With after, it resumes each source strictly after its supplied position without inserting a newer snapshot ahead of older events.

RunSubscriptionEventType includes snapshot, status, meta, and stream. Status carries the event sequence, attempts, version when known, and permitted terminal output or failure. Metadata deltas contain the actual top-level patch. Stream deltas carry stored starts and chunks; use the named reader for derived closes. Heartbeats do not produce status deltas.

There is no total order across event and stream sources. Every committed chunk is delivered before terminal status. A terminal observation captures all selected named tails and drains them before ending.

Subscriptions use lane.runSignal when provided and fall back to streams.pollInterval after a missed hint. Abort or runtime close stops the wait. Retained backlogs drain without waiting between pages. See subscription read cost for provider details.

Cursors are opaque and bind the reader kind, environment, run, and retained creation-event identity. Never exchange named, subscription, log, or timeline cursors. Malformed, future, mismatched, and reused-run-instance cursors raise run_cursor_invalid. Missing or pruned runs raise run_not_found.

Limits and retention

Configure limits under createRunlane({ streams: { ... } }). Read defaults from contractDefaults.streams; see defaults.

Body quotas count normalized UTF-8 JSON bytes, including quotes and escapes. Run-wide record quotas count stored starts and chunks across names and attempts; derived closes do not count. Names, bytes, and records are admitted transactionally. stream_limit_exceeded reports quota failures; storage_limit_exceeded reports an infeasible record envelope or provider transaction.

Run pruning owns stream records, headers, and the name registry. Streams have no independent TTL. Saved steps do not re-emit chunks on resume. A later attempt may produce a different answer; use attempt boundaries when displaying it.

Serve these readers to browsers with realtime. See set up realtime for authorization and client wiring.

On this page