# Streams, logs and traces

> Stream tokens and progress to a UI, write logs, and record spans with token counts.

Source: https://cairnflow.dev/docs/develop/streams-logs

Streams, logs and traces run **beside** the journal. Writing to them adds no command to the
journal and no durable wait to the turn, and nothing is sent again on replay.

```ts
async run(ctx: Context, prompt: string) {
  const ui = ctx.stream("ui");
  ctx.log.info("starting", { prompt_len: prompt.length });
  return ctx.trace.span("llm", async (span) => {
    span.set({ model: "m-1" });
    return ctx.run("llm", async () => {
      let text = "";
      for await (const tok of model.stream(prompt)) {
        ui.append({ tok });
        text += tok;
      }
      span.set({ input_tokens: 1200, output_tokens: text.length });
      return text;
    });
  });
}
```

## Streams

`ctx.stream(name, opts?)` returns a writer:

| Method | Meaning |
|---|---|
| `append(record)` | Add a JSON record. Does not wait, does not throw, skipped on replay |
| `close()` | No more records after this |

Stream names are 1 to 128 bytes and cannot start with `$`. An invocation can have up to 16 streams.

### Ephemeral or durable

| | `ctx.stream("ui")` (default) | `ctx.stream("events", { durable: true })` |
|---|---|---|
| Stored | In memory of the node running the invocation, 1 MiB per stream (oldest records drop first) | With the invocation, on the next durable write |
| Lives | While the current step runs; readable for 60 seconds after the invocation finishes or pauses | Until the invocation is purged |
| On node change | Lost: readers get `moved` then `reset`, and the retried step streams again from the start | Kept |
| Limit | 1 MiB per stream | 8 MiB for all durable user streams of one invocation |

Use the ephemeral stream for tokens and progress a UI shows live; the full output of a step still
comes from the `ctx.run` result. Use a durable stream for records someone must be able to read
later.

Append ephemeral records from **inside** the `ctx.run` closure that produces them: the closure runs
only when the step really executes, so a replay does not re-emit old tokens.

:::note
Records reach readers as they are appended only in streaming mode (`BIDI_STREAM`). In
request-response mode, the default for `https://` endpoints on Cairnflow Cloud, the records of a
turn travel with its response and reach readers together when the turn ends. See
[Deployments](/docs/cloud/deployments#transport).
:::

### Reading a stream

Streams are served as Server-Sent Events:

```sh
curl -N "$CAIRN_URL/invocations/$ID/streams/ui?from=0" \
  -H "authorization: Bearer $CAIRN_KEY" -H "accept: text/event-stream"
```

| Event | Data |
|---|---|
| `record` | `{offset, durable, step, attempt, k, data}` — `data` is what you appended |
| `gap` | `{offset, dropped}` — records dropped by a limit, or overwritten while the reader lagged |
| `superseded` | `{offset, step, attempt}` — that attempt of that step was replaced by a retry |
| `end` | `{next}` — the stream is sealed and fully read |
| `moved` | `{leader}` — the node serving the stream changed; reconnect |
| `reset` | After `moved`, ephemeral streams only: clear what you displayed, the step streams again |

Resume with `?from=<offset>` or the `Last-Event-ID` header. Reading a stream needs a key that can
invoke handlers.

In TypeScript, `readStream` from `@cairnflow/sdk/client` handles reconnects, node changes and
connection lifetimes, and yields every event (including `reset`, which a UI needs):

```ts

for await (const e of readStream(process.env.CAIRN_URL!, id, "ui", {
  headers: { authorization: `Bearer ${process.env.CAIRN_KEY}` },
})) {
  if (e.kind === "reset") clearOutput();
  if (e.kind === "record") render(e.data);
}
```

Options: `from` (start offset, default 0), `headers`, `signal` (an `AbortSignal`), `retries`
(consecutive failures before giving up, default 10). It throws `StreamError` (with `status` and
`code`) when the stream cannot be read, for example `404`.

## Logs

`ctx.log.debug|info|warn|error(message, attrs?)` writes to the invocation's durable log. Each record
is tied to the step and attempt that wrote it.

- The minimum level is `info`; set `logLevel` in the handler options to change it.
- Like streams, log calls do not wait, do not throw, and are not repeated on replay.
- Records become durable with the invocation's next durable write (a step result, a suspension,
  the end). Set `logFlushMs` in the handler options to also flush on a timer during a long step, at
  the cost of one write per flush.
- The log keeps up to 1 MiB per invocation; past that, records are dropped and a `gap` is recorded.

Read logs with an admin key:

```sh
curl "$CAIRN_URL/invocations/$ID/logs?level=warn&limit=100" \
  -H "authorization: Bearer $CAIRN_KEY"
```

The answer is `{"records": [...], "next": ...}`; each record has `offset`, `step`, `attempt`, `ts`,
`level`, `msg` and `attrs`. Fetch the next page with `from=<next>`, or add `follow=1` to receive new
records as Server-Sent Events. Filters: `level`, `attempt`, `from`, `limit` (default 1000).

## Traces

`ctx.trace.span(name, fn, attrs?)` records a span around `fn`. Spans nest by call scope, and
`span.set(attrs)` adds attributes that are written when the span ends. If `fn` throws, the span ends
with status `error` and the error is rethrown.

```ts
const plan = await ctx.trace.span("plan", async (s) => {
  s.set({ model: "my-model", input_tokens: 1200 });
  return ctx.run("llm", () => callModel());
});
```

Read the span tree with an admin key:

```sh
curl "$CAIRN_URL/invocations/$ID/spans" -H "authorization: Bearer $CAIRN_KEY"
```

The answer is `{"spans": [...], "tokens": {"input": ..., "output": ...}}`. Each node has `span_id`,
`parent_id`, `name`, `start_ts`, `end_ts`, `status`, `attrs` and `children`; `unfinished: true`
marks a span whose process died before it ended. `tokens` sums the `input_tokens` and
`output_tokens` attributes of every span, so set them on your model-call spans.

- Span IDs are deterministic, so a replay that closes a span opened earlier matches it.
- The trace keeps up to 1 MiB per invocation.
- Set `trace: "runtime"` in the handler options to add spans from the runtime itself: one per turn
  and one per `ctx.run`.

The [Vercel AI SDK adapter](/docs/agents/vercel-ai-sdk) writes these spans and the `ui` stream for
you.
