This is the full developer documentation for cairnflow # Introduction > What cairnflow is, and when to use it. Cairnflow runs your handlers durably. Every step — a model call, a tool call, a payment — is recorded in a journal before the run moves on. When a process crashes, a deploy restarts your service or a connection drops, the run resumes from the last recorded step instead of starting over or running side effects twice. You write ordinary TypeScript with the `@cairnflow/sdk` package, Python with the [`cairnflow` package](/docs/develop/python), or Go with the [`cairn` package](/docs/develop/go). Cairnflow calls your service over HTTP, keeps the journal, the state and the timers, and decides when each run continues. ## What you can build [Section titled “What you can build”](#what-you-can-build) | Use case | What cairnflow gives you | Start with | | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | | **AI agents** | Model and tool calls as durable steps, tool approvals that wait on a durable promise, streams that reconnect after a reload, one turn at a time per chat | [Vercel AI SDK](/docs/agents/vercel-ai-sdk) | | **Durable workflows** | Multi-step processes with one run per ID, waits of minutes or weeks, signals from outside | [Workflows](/docs/workflows/workflows) | | **Stateful objects** | State per user, account or device behind a key, with one writer per key at a time | [Virtual objects and state](/docs/develop/state) | | **Sagas and payments** | Recorded side effects, idempotency keys, compensation with `TerminalError` | [Errors and retries](/docs/develop/errors-retries) | | **Schedules and background jobs** | Server-side cron with time zones, delayed sends, fan-out to child invocations | [Schedules](/docs/develop/schedules) | | **Webhooks and events** | Acknowledge once durable, deduplicate with `Idempotency-Key`, concurrency and rate limits per scope | [Flow control](/docs/reference/flow-control) | ## Where your code runs [Section titled “Where your code runs”](#where-your-code-runs) **On a long-running server** — a container, a VM or Kubernetes — with `serve()` on Node.js 22.6 or newer. This is the best fit for agents: a replay cache keeps resumes cheap, and where HTTP/2 reaches your service, one streaming connection per run carries tokens and cancellation as they happen. On Cairnflow Cloud, streaming is opt-in; see [Deployments](/docs/cloud/deployments#transport). **On a serverless function** — Vercel, Cloudflare Workers or AWS Lambda — with `fetchHandler`, the Fetch adapter, which Deno and Bun can serve too. This fits short workflows: a few steps with retries and timers, on the platform you already deploy to. See [Serverless](/docs/workflows/serverless). ## How it is built [Section titled “How it is built”](#how-it-is-built) All of cairnflow’s state lives on object storage — an S3-compatible bucket. The runtime nodes keep nothing on disk: a node takes ownership of a range of keys with a lease, and when it dies another node takes the range over from the bucket. A run is acknowledged only after its step is durable in the bucket. ## Next [Section titled “Next”](#next) * [Quickstart](/docs/quickstart) — a first durable run on your own machine. * [Concepts](/docs/concepts) — services, virtual objects, workflows and the journal. # Quickstart > Install a release binary or run Docker, start a node on your own machine, and run a first durable invocation in two minutes. This page runs everything on one machine: a cairnflow node, a small service, and the calls between them. You need: * a Cairnflow runtime — a prebuilt release archive below, or Docker (no Rust, no database); * Node.js 22.18 or newer, which runs TypeScript files directly (Node.js 22.6 to 22.17 works with `node --experimental-strip-types`) — or Python ≥ 3.11 or Go ≥ 1.25. Note Cairnflow Cloud is in early-access waitlist — [join the waitlist](/#pricing). Until it opens, you run the runtime yourself, as this page does. ## 1. Install and start a node [Section titled “1. Install and start a node”](#1-install-and-start-a-node) **Option A — Prebuilt binaries** (Linux x86_64 below; the [releases page](https://github.com/cairnflowdev/cairnflow/releases) has Linux arm64 and macOS arm64 too): ```sh A=cairnflow-v0.1.0-beta.0-x86_64-unknown-linux-musl mkdir -p ~/.local/bin # or any directory on your PATH curl -L "https://github.com/cairnflowdev/cairnflow/releases/download/v0.1.0-beta.0/$A.tar.gz" \ | tar -xz -C ~/.local/bin --strip-components=1 "$A/cairnflow" "$A/cairn" "$A/cairn-ctl" "$A/cairn-query-worker" cairnflow --no-auth # dev switch: no API key, for a machine only you reach ``` **Option B — Docker:** ```sh docker run -d --name cairnflow -p 127.0.0.1:8080:8080 \ --add-host=host.docker.internal:host-gateway \ -v cairnflow-data:/var/lib/cairnflow \ ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 --no-auth cairn() { docker exec cairnflow cairn "$@"; } # the CLI is in the container ``` Four self-contained binaries ship together: `cairnflow` (the runtime), `cairn` (the CLI), `cairn-ctl` (the operator tool) and `cairn-query-worker`. The node listens on `127.0.0.1:8080` (`8081` is for other nodes), keeps all state under `./cairnflow-data`, and serves the web console at `http://127.0.0.1:8080/ui/`. To compile from source instead, see [Build from source](/docs/self-hosting#build-from-source). ## 2. Write a service [Section titled “2. Write a service”](#2-write-a-service) In a second terminal, install `@cairnflow/sdk` (zero runtime dependencies): ```sh mkdir greeter && cd greeter npm init -y && npm pkg set type=module npm install @cairnflow/sdk ``` A service is a set of handlers. `ctx.run` journals the result of a step: after a crash or retry, the step is replayed from the journal instead of running again. service.ts ```ts import { serve, service } from "@cairnflow/sdk"; const greeter = service("Greeter", { greet: async (ctx, name: string) => { // Journaled: a retry after a crash does not run it again. const upper = await ctx.run("upper", () => name.toUpperCase()); return `Hello, ${upper}!`; }, }); await serve({ services: [greeter], port: 9080 }); ``` Start it and leave it running: ```sh node service.ts ``` `serve()` listens on `127.0.0.1` by default, which is all a node on the same machine needs. When running the runtime in Docker, pass `hostname: "0.0.0.0"` in `serve()` so the container can reach your service. It prints a warning that `identityKeys` is not set: a service that other machines can reach should check that requests really come from your node. See [Request identity](/docs/self-hosting/security#request-identity-signed-calls-to-your-services). To write the service in Python or Go, see [Python SDK](/docs/develop/python) (`pip install cairnflow`) and [Go SDK](/docs/develop/go) (`go get github.com/cairnflowdev/cairnflow/sdk/go`). On Vercel or AWS Lambda, the same service runs behind `fetchHandler`: see [Serverless](/docs/workflows/serverless). ## 3. Register and invoke [Section titled “3. Register and invoke”](#3-register-and-invoke) In a third terminal, register the deployment so Cairnflow reads its services and handlers, then invoke `greet`: ```sh cairn register http://127.0.0.1:9080 # with Docker: http://host.docker.internal:9080 cairn invoke Greeter greet --input '"world"' ``` The answer carries the invocation ID and the handler’s output, `"Hello, WORLD!"`. To fire and forget over HTTP, call `POST http://127.0.0.1:8080/invoke/Greeter/greet/send` instead: you get the invocation ID back as soon as it is durable. ## 4. Read the journal [Section titled “4. Read the journal”](#4-read-the-journal) Every step of the run is recorded. Inspect it with the `cairn` CLI: ```sh cairn journal ``` It lists the input, the step and its result, and the output. Open `http://127.0.0.1:8080/ui/` in a browser to inspect journals, timelines and traces visually, retry or cancel runs, and query invocations with SQL. ## 5. Turn authentication on [Section titled “5. Turn authentication on”](#5-turn-authentication-on) `--no-auth` is only for local development on a machine only you reach. Without it, every route except `/health` requires an API key: ```sh export CAIRNFLOW_ADMIN_KEY="cf_$(openssl rand -hex 24)" # bootstrap key, at least 32 bytes export CAIRNFLOW_TOKEN="$CAIRNFLOW_ADMIN_KEY" # key sent by the `cairn` CLI cairnflow # same directory, same data ``` For production, point the node at an S3-compatible bucket instead of a local directory: `--main-store s3://my-bucket/prefix` with the usual `AWS_*` environment variables. ## Next [Section titled “Next”](#next) * [Concepts](/docs/concepts) * [Build an agent with the Vercel AI SDK](/docs/agents/vercel-ai-sdk) * [Self-hosting](/docs/self-hosting): buckets, clusters, security and operations. # Build with AI > Copy-paste prompts and Markdown docs so your coding agent can add cairnflow to a project. These docs are written to be read by coding agents as well as people. Paste one of the prompts below into Claude Code, Cursor, Codex, Copilot or any other agent, and it will find the pages it needs and wire up the SDK. Every prompt points the agent at Markdown versions of the docs, so it reads the real API instead of guessing. ## Add cairnflow to a project [Section titled “Add cairnflow to a project”](#add-cairnflow-to-a-project) For an existing TypeScript service or a new one. The agent installs the SDK, writes a first service with durable steps, exposes it with `serve()` or `fetchHandler`, and tells you how to register and invoke it. Prompt: add cairnflow ```text You are adding cairnflow to this TypeScript project. Cairnflow is a durable execution runtime: handlers run inside my own HTTP service, and cairnflow records every step in a journal, so a crash or a deploy resumes the run where it stopped instead of starting over or repeating side effects. Read these first. They are Markdown pages written for agents: - https://cairnflow.dev/llms.txt (index of all docs) - https://cairnflow.dev/docs/quickstart.md - https://cairnflow.dev/docs/concepts.md - https://cairnflow.dev/docs/develop/durable-steps.md Then: 1. Install the SDK: `npm install @cairnflow/sdk` (Node.js 22.6 or newer; the SDK has no dependencies). Make sure `package.json` has `"type": "module"` if you run `.ts` files directly. 2. Create one service module. Use `service(name, handlers)` for stateless handlers, `service(name, handlers, { type: "VIRTUAL_OBJECT" })` when state belongs to a key (a user, an order, a chat), and `workflow(name, { run, ... })` for a process that runs once per ID. 3. Wrap every side effect (HTTP calls, database writes, payments, emails) in `ctx.run("", () => ...)`. Step names are part of the journal: do not rename them later and do not put configuration values in them. 4. Expose the service: - on a long-running server: `serve({ services, port: Number(process.env.PORT ?? 9080), hostname: "0.0.0.0", identityKeys })` - on Vercel, Cloudflare Workers or AWS Lambda: `fetchHandler({ services, identityKeys })` from `@cairnflow/sdk/fetch` (see https://cairnflow.dev/docs/workflows/serverless.md) 5. Read `CAIRN_URL` and `CAIRN_KEY` from the environment. Read `CAIRN_IDENTITY_KEY` too and pass `identityKeys: [process.env.CAIRN_IDENTITY_KEY]` when it is set; leave `identityKeys` out when it is not (a node signs its requests only when it is configured to). Never hard-code keys. 6. Finish by showing me the two commands to run: register the deployment with `POST $CAIRN_URL/deployments` and body `{"uri": ""}`, then invoke one handler with `POST $CAIRN_URL/invoke//`, both with `authorization: Bearer $CAIRN_KEY`. The URL must be reachable from the cairnflow node: with a node on the same machine, `http://127.0.0.1:` works. Rules for all handler code: - No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`. - Do not catch and swallow errors around `ctx` commands; rethrow what you do not handle. - Throw `TerminalError` for failures a retry cannot fix (bad input, a refused payment). - Keep results, state and call inputs small JSON values. Put files and images in `ctx.artifact` and return the reference; keep data that later invocations need (such as a chat history) in state, not in an artifact. - Do not invent APIs. If something is not in the docs, ask me. ``` ## Make a Vercel AI SDK agent durable [Section titled “Make a Vercel AI SDK agent durable”](#make-a-vercel-ai-sdk-agent-durable) For a chat agent that already uses `streamText` and `useChat`. The agent keeps your tools, prompts and UI, and moves the model and tool calls onto durable steps with approvals and a reconnecting stream. Prompt: durable AI SDK agent ```text This project has a chat agent built with the Vercel AI SDK v7 (`streamText` on the server, `useChat` in the browser). Make it durable with cairnflow without rewriting it: every model call and tool call becomes a journaled step, tools can wait for human approval, and the stream reconnects after a page reload. Read these first. They are Markdown pages written for agents: - https://cairnflow.dev/docs/agents/vercel-ai-sdk.md - https://cairnflow.dev/docs/agents/approvals.md - https://cairnflow.dev/docs/agents/streaming.md Server: 1. Install the SDK: `npm install @cairnflow/sdk` (Node.js 22.6 or newer; no runtime dependencies). 2. Move the `streamText` call into `chatObject("Chat", async (ctx, turn) => streamText({ ... }))`. 3. Wrap the model: `wrapLanguageModel({ model, middleware: cairnMiddleware(ctx) })`. 4. Wrap the tools: `cairnTools(ctx, tools, { approve: [] })`. 5. Pass `messages: await convertToModelMessages(turn.messages)` and `onError: turn.onError`. 6. `chatObject` stops after 5 attempts by default, so a provider that keeps failing does not retry forever. To change it: `chatObject("Chat", run, { options: { retryPolicy: { maxAttempts: 3, onMaxAttempts: "PAUSE" } } })`. 7. Serve it: `serve({ services: [chat], port: Number(process.env.PORT ?? 9080), hostname: "0.0.0.0", identityKeys })`, with `identityKeys: [process.env.CAIRN_IDENTITY_KEY]` when that variable is set and left out when it is not. Browser: 8. Create `const transport = cairnChatTransport({ baseUrl: "", service: "Chat" })` and add the same-origin proxy route described in the guide. 9. Load the history when rendering the page with `await transport.messages(chatId)`, then call `useChat({ id: chatId, transport, messages: initial, resume: true })`. 10. Approve tools with `transport.approve(chatId, approvalId, { approved })`, not with `addToolApprovalResponse`. Keep the existing tool definitions, prompts and UI components. Do not call the model or a tool outside `cairnMiddleware` and `cairnTools`. `maxRetries` has no effect here: cairnflow retries a failed step itself. On Cairnflow Cloud the browser gets each model step's text when the step finishes, not token by token, unless the deployment is registered with `"transport": "declared"` (see the streaming guide); do not promise live tokens without it. Do not invent APIs; if something is not in the guide, ask me. ``` ## Keep your agent on the rules [Section titled “Keep your agent on the rules”](#keep-your-agent-on-the-rules) Add this block to the instructions file your agent reads on every task (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules/cairnflow.mdc`, `.github/copilot-instructions.md`). It keeps later changes inside cairnflow’s rules, such as never renaming a step that running invocations depend on. AGENTS.md ```md ## cairnflow This project uses cairnflow for durable execution. Docs for agents: https://cairnflow.dev/llms.txt (append `.md` to any https://cairnflow.dev/docs/ URL to get the page as Markdown). - Every side effect inside a handler goes through `ctx.run("", fn)`, or through `cairnTools` / `cairnMiddleware` for Vercel AI SDK tools and models. - Step names are part of the journal. Renaming a step breaks in-flight invocations; see https://cairnflow.dev/docs/develop/versioning.md before renaming or reordering steps. - No `Date.now()`, `Math.random()` or random IDs outside `ctx.run`. - Never swallow errors around `ctx` commands. Throw `TerminalError` for failures a retry cannot fix. - State (`ctx.get`, `ctx.set`) and durable promises exist only on virtual objects and workflows. - Keep journaled values small; put files and images in `ctx.artifact` (its references are only readable by the invocation that wrote them, so do not keep them in state for later turns). ``` ## Docs in Markdown [Section titled “Docs in Markdown”](#docs-in-markdown) | What | Where | | -------------------------------- | ----------------------------------------------------------------------- | | Any page as Markdown | add `.md` to its URL, e.g. [`/docs/quickstart.md`](/docs/quickstart.md) | | Copy a page for your agent | the **Copy page** button next to every page title | | Index of all pages | [`/llms.txt`](/llms.txt) | | All docs in one file | [`/llms-full.txt`](/llms-full.txt) | | A shorter version without asides | [`/llms-small.txt`](/llms-small.txt) | Tip Agents work best with a narrow task and the one or two pages that cover it. Give it the Markdown link of the page you are reading (**Copy page → Copy Markdown link**) rather than the whole site. # Concepts > Services, virtual objects, workflows, the journal and the three rules of handler code. ## Invocations and the journal [Section titled “Invocations and the journal”](#invocations-and-the-journal) Each call to a handler is an **invocation**. While it runs, every `ctx` command — a step, a sleep, a call to another handler, a state write — is appended to the invocation’s **journal**. When the handler has to run again (after a crash, a deploy, or a wait), cairnflow replays it: commands that are already in the journal return their recorded result instead of running again, and the handler carries on from the first step that is not. ## Three kinds of service [Section titled “Three kinds of service”](#three-kinds-of-service) | Kind | Declared with | Has state | Runs | | -------------- | ----------------------------------------------------- | -------------------- | --------------------------------------- | | Service | `service(name, handlers)` | No | Any number at once | | Virtual object | `service(name, handlers, { type: "VIRTUAL_OBJECT" })` | Yes, per key | One exclusive handler per key at a time | | Workflow | `workflow(name, { run, … })` | Yes, per workflow ID | `run` once per ID | A **virtual object** is addressed by a key — a chat ID, a user ID, an order number. Its state belongs to that key, and two exclusive handlers on the same key never run at the same time. That makes it the natural home for a conversation: the agent’s history lives in the object’s state. State (`ctx.get`, `ctx.set`) and durable promises exist only on virtual objects and workflows. A plain service gets a `ServiceContext` without them. ## Durable steps [Section titled “Durable steps”](#durable-steps) ```ts const receipt = await ctx.run("charge", () => chargeCard(amount)); ``` `ctx.run` runs the closure once and records the result. On replay the closure is not called again. The step’s name is part of the journal: renaming a step between two deploys stops in-flight invocations that reach it, so keep names stable and put configuration (model IDs, prompt versions) in span attributes instead. ## Waiting [Section titled “Waiting”](#waiting) `ctx.sleep`, calls to other handlers, durable promises and signals end the current turn instead of holding a connection. The invocation is suspended in storage and resumes when the result is there — seconds or weeks later. Nothing runs and nothing is billed as compute while it waits. ## Errors and retries [Section titled “Errors and retries”](#errors-and-retries) * A normal error thrown from a `ctx.run` closure fails the turn, and cairnflow retries it under the handler’s retry policy: completed steps are replayed, only the failed step runs again. * `TerminalError` is for failures a retry cannot fix (bad input, a refused payment). It is recorded and can be caught, so you can compensate and carry on. ## The three rules of handler code [Section titled “The three rules of handler code”](#the-three-rules-of-handler-code) 1. **Every side effect goes through `ctx.run`** (or a cairnflow wrapper such as `cairnTools`). The handler body runs again on every replay. 2. **No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`.** Replay must take the same path as the first run. 3. **Do not catch and swallow errors around `ctx` commands.** A suspended or failed turn stays suspended or failed whatever your `catch` does. # Artifacts > Keep large bytes out of the journal with ctx.artifact, and pass references between steps. Step results, state and call inputs live in the journal, and the journal is replayed on every turn. Large values there make every turn slower and more expensive. **Artifacts** keep the bytes in object storage and put only a small reference in the journal. ```ts const ref = await ctx.run("render", async () => ctx.artifact.put(await renderChart(data), { contentType: "image/png" }), ); // ref = { sha256: "…", size: 48213, contentType: "image/png" } ``` Return the reference from `ctx.run`, not the bytes. The journal then holds a few dozen bytes, and the step is not re-run on replay. ## API [Section titled “API”](#api) ```ts interface ArtifactRef { readonly sha256: string; // hex SHA-256 of the content readonly size: number; readonly contentType: string; } ctx.artifact.put(bytes: Uint8Array | string, opts?: { contentType?: string }): Promise; ctx.artifact.get(ref: ArtifactRef | string): Promise; ``` * `put` accepts bytes or a string (encoded as UTF-8). `contentType` defaults to `application/octet-stream`. * The reference is computed locally from the content; cairnflow stores the bytes before it processes the invocation’s next command. * Content-addressed: putting the same bytes twice gives the same `sha256`. * `get` accepts a reference or a bare `sha256` string. ## Limits [Section titled “Limits”](#limits) * One artifact can be at most 16 MiB minus 1 KiB. The SDK exports this as `ARTIFACT_MAX_BYTES`; `put` throws a `RangeError` above it. * Your environment may also cap the total artifact bytes it keeps; on Cairnflow Cloud, see [Beta limits](/docs/cloud/limits). ## Reading an artifact back [Section titled “Reading an artifact back”](#reading-an-artifact-back) `ctx.artifact.get(ref)` first looks in the SDK process’s own memory (a 64 MiB cache of recent artifacts). On a different process — after a restart, or on another replica — it fetches the artifact from cairnflow, which you must configure once at startup: ```ts import { configureArtifacts } from "@cairnflow/sdk"; configureArtifacts({ baseUrl: process.env.CAIRN_URL!, headers: { authorization: `Bearer ${process.env.CAIRN_KEY}` }, }); ``` Use a key that can invoke handlers. Without this, `get` throws when the artifact is not in memory. Caution `ctx.artifact.get` reads artifacts of the **current** invocation. To hand an artifact to another invocation, pass the bytes through a new `put` there, or read it over HTTP with the ID of the invocation that created it. ## Reading artifacts over HTTP [Section titled “Reading artifacts over HTTP”](#reading-artifacts-over-http) With a key that can invoke handlers: ```sh # List the artifacts of an invocation. curl "$CAIRN_URL/invocations/$ID/artifacts" -H "authorization: Bearer $CAIRN_KEY" # -> {"artifacts": [{"sha256": "...", "size": 48213, "contentType": "image/png"}]} # Download one. curl "$CAIRN_URL/invocations/$ID/artifacts/$SHA256" \ -H "authorization: Bearer $CAIRN_KEY" -o chart.png ``` The response carries the content type given to `put` and is served as inert content: HTML, SVG, XML and PDF artifacts are always sent as downloads, never rendered in place. ## Lifetime [Section titled “Lifetime”](#lifetime) Artifacts belong to the invocation that created them. When the invocation is purged — explicitly or when its retention period ends — its artifacts go with it, and the HTTP routes answer `404`. ## When to use them [Section titled “When to use them”](#when-to-use-them) * Files and images produced or consumed by a step. * Documents and model outputs that later steps of the same invocation, or a UI, read back. Not for values carried from one invocation to the next, such as a chat history kept in state: `ctx.artifact.get` cannot read another invocation’s artifacts, and artifacts are purged with the invocation that wrote them. Keep such values in state; large ones are stored as segments automatically (see [Virtual objects and state](/docs/develop/state#state-api)). On serverless platforms (`fetchHandler`), where the journal travels on every request, this matters even more — see [Serverless](/docs/workflows/serverless). # Calling other handlers > Durable request-response calls, one-way sends, idempotency keys, scopes, and attaching to invocations. A handler can call any other handler in your environment. Calls are commands in the journal: they are made exactly once per invocation, and their results survive crashes and deploys. ```ts // Wait for the result. const plan = await ctx.call("Planner", "plan", task); // Fire and forget. ctx.send("Email", "welcome", { userId }); // A virtual object: pass the key. const total = await ctx.call("Counter", "add", 5, { key: "user-42" }); ``` ## ctx.call [Section titled “ctx.call”](#ctxcall) ```ts call(service: string, handler: string, input: unknown, opts?: CallOptions): DurableFuture; ``` * The callee runs as its own invocation, with its own journal and retries. * When the result is not there yet, the caller **suspends**; nothing waits in memory. It resumes when the callee finishes. * If the callee fails, `await` throws a `TerminalError` with the callee’s code and message. The callee’s outcome is final, so retrying the caller would not change it. * The returned `DurableFuture` combines with `ctx.all` and `ctx.race`, for example to fan out: ```ts const notes = await ctx.all( sections.map((section) => ctx.call("Researcher", "dig", { topic, section }, { name: `dig/${section}` }), ), ); ``` ## ctx.send [Section titled “ctx.send”](#ctxsend) ```ts send(service: string, handler: string, input: unknown, opts?: CallOptions): void; ``` `ctx.send` records a one-way call and returns at once. It never suspends the caller. Use `delay` (ms) to run the callee later: ```ts ctx.send("Reminders", "remind", { userId }, { delay: 3 * 24 * 3600_000 }); ``` The callee of a send is detached work: it is not cancelled when the caller is cancelled. ## Options [Section titled “Options”](#options) | Option | Meaning | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `key` | Key of the target virtual object or workflow | | `idempotencyKey` | At most one invocation for the same target and key — see below | | `name` | Label of the call in the journal and the console (default `service/handler`) | | `delay` | `ctx.send` only: run the callee this many ms later | | `scope` | Run the callee in a scope (see [Scopes](#scopes)). Absent: inherit the caller’s scope | | `limitKey` | `l1` or `l1/l2`: concurrency bucket inside the scope. Requires a scope | | `placement` | `"spread"`: deliberately spread unkeyed callees across partitions — see below | | `tags` | Up to 8 `key: value` tags on the callee invocation. Keys match `[a-z0-9_.-]{1,32}`, values are at most 64 bytes; invalid tags are dropped and the call still runs | ## Idempotency keys [Section titled “Idempotency keys”](#idempotency-keys) Calls from a handler are already deduplicated by the journal: a replay never sends the same call twice. An `idempotencyKey` goes further: calls to the same target with the same key, from any invocation, refer to the **same** callee invocation. A second call returns the first call’s result (or waits for it) instead of running the handler again. ```ts await ctx.call("Payments", "charge", order, { idempotencyKey: `charge-${order.id}` }); ``` Deduplication lasts as long as the finished invocation is retained. After it is purged, the same key starts a new invocation. ## Scopes [Section titled “Scopes”](#scopes) A scope groups a tree of invocations that belong together — usually one user or one tenant of your product. Set it once at the root; every call below inherits it. ```ts const agent = ctx.scoped(`user-${userId}`); const plan = await agent.call("Planner", "plan", task); // Inside Planner.plan, ctx.call("Search", ...) stays in the same scope. ``` * `ctx.scoped(scope, limitKey?)` returns a view with `call` and `send` only. Scope names use `[A-Za-z0-9_.-]`, 1 to 36 characters; a bad name throws a `TypeError` immediately. * **A scope is part of identity.** `Cart/a` in scope `bob` is a different object, with different state, from `Cart/a` without a scope. Idempotency keys and durable promises are per scope too. * **Everything in a scope lives together**, so calls within it stay local and fast. The price is that one scope is bounded by what a single partition can process. One scope per user or tenant is right; one per request, or one for the whole system, is not. * A call can switch to another scope (`ctx.scoped("other")`), but cannot leave a scope for “no scope”. ## Spreading fan-out [Section titled “Spreading fan-out”](#spreading-fan-out) Unkeyed calls (no scope, no `key`, no `idempotencyKey`) are placed next to their caller by default, which keeps a whole call tree local. For a CPU-heavy fan-out you may want the opposite: ```ts await Promise.all(files.map((f) => ctx.call("Resize", "run", f, { placement: "spread" }))); ``` `placement` only changes where the callee runs, not its identity. It is ignored when the call has a scope (including an inherited one), a `key` or an `idempotencyKey`. Any other value than `"spread"` throws a `TypeError`. ## Attaching to another invocation [Section titled “Attaching to another invocation”](#attaching-to-another-invocation) If you have the ID of an invocation — from the client, from `/send`, or passed in the input — a handler can wait for its result or peek at it: ```ts const result = await ctx.attach(reportInvocationId); // waits durably const maybe = await ctx.getOutput(reportInvocationId); // null if not finished yet ``` Both throw a `TerminalError` if the target failed. `ctx.invocationId` is the current invocation’s ID, in the same format the HTTP API uses. ## Calls and cancellation [Section titled “Calls and cancellation”](#calls-and-cancellation) A hard cancel of an invocation also cancels the invocations it created with `ctx.call` and is still waiting for, all the way down the tree. Invocations created with `ctx.send` are not touched; cancel them by ID. See [Cancellation](/docs/develop/cancellation). # Cancellation > Cooperative cancel that lets your code clean up, hard cancel as the fallback, and how steps react. There are two ways to cancel an invocation. | | Cooperative (`mode=signal`) | Hard | | --------------------- | ---------------------------------------------------------------------- | --------------------------------- | | HTTP | `POST /invocations/{id}/cancel?mode=signal` | `POST /invocations/{id}/cancel` | | Client | `handle.cancel()` (the default) | `handle.cancel({ mode: "hard" })` | | Key needed | One that can invoke handlers | An admin key | | Your code | Gets a `TerminalError` (code `409`) at its next wait, and can clean up | Gets no further turn | | Ends as | Whatever your code does — usually `failed` with `409` | `failed` with code `572` | | Needs your service up | Yes | No | Both answer `{"cancelled": true|false, "status": ...}` once the invocation has stopped; `cancelled` says whether it really stopped. Cancelling an invocation that already finished is a no-op: `{"cancelled": false, "status": "completed"}`. ## Cooperative cancel [Section titled “Cooperative cancel”](#cooperative-cancel) Cairnflow delivers a cancel signal to the invocation. From then on, every **wait point** throws `TerminalError` with code `409`, so your `try/catch/finally` can undo what was done: ```ts async run(ctx: Context, order: Order) { const undo: Array<() => PromiseLike | void> = []; try { const charge = await ctx.run( "charge", (signal) => payments.charge(order, { signal }), { cancellable: true }, ); undo.push(() => ctx.run("refund", () => payments.refund(charge.id))); await ctx.promise("shipped").get(); return "done"; } catch (e) { if (e instanceof TerminalError) { for (const step of undo.reverse()) await step(); ctx.send("Email", "orderCancelled", { orderId: order.id }); } throw e; } } ``` Each undo step is registered only after its forward step has a result, and the list is rebuilt the same way on every replay. In streaming mode (`BIDI_STREAM`, which `serve()` declares), a cancel that arrives in the middle of a turn reaches the handler at once. In request-response mode there is no channel into a running request: the cancel takes effect from the next turn. That is always the case with `fetchHandler`, and on Cairnflow Cloud also with `serve()` unless the deployment is registered with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)). ### What is and is not a cancellation point [Section titled “What is and is not a cancellation point”](#what-is-and-is-not-a-cancellation-point) | Command | After a cooperative cancel | | ------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `await` on something not finished yet: `ctx.sleep`, `ctx.call`, `ctx.promise(...).get()`, `ctx.signal`, an awakeable, `ctx.all`, `ctx.race` | Throws `TerminalError` 409 | | `ctx.run(name, fn)` (default) | **Runs normally.** Compensation steps are `ctx.run`, and they must work after a cancel | | `ctx.run(name, fn, { cancellable: true })` | Does not start; throws 409. If the cancel arrives while the closure runs (streaming mode only), its `AbortSignal` fires | | `ctx.send`, `ctx.set`, `ctx.clear` | Run normally | | A result already in the journal | Returned normally | This is why compensation code should use only `ctx.run` (not cancellable) and `ctx.send`: a `ctx.call` or a sleep in a `catch` block throws again at once. ### Cancellable steps [Section titled “Cancellable steps”](#cancellable-steps) Mark forward work that is expensive or pointless after a cancel — model calls, tool calls, long fetches — as `cancellable`: ```ts const page = await ctx.run( "fetch", (signal) => fetch(url, { signal }).then((r) => r.text()), { cancellable: true }, ); ``` * If the invocation is already cancelled and the step has no result yet, the closure does not run and `ctx.run` throws 409. * If the cancel arrives while the closure runs (streaming mode only), the `AbortSignal` passed to the closure fires. Whatever the closure throws afterwards becomes a 409; nothing is recorded. * If the closure ignores the signal and returns normally, its result is recorded as usual. ### The service must be reachable [Section titled “The service must be reachable”](#the-service-must-be-reachable) Cooperative cancel needs your code to run. If your service is down, the invocation keeps waiting for it. That is what the hard cancel is for. ## Hard cancel [Section titled “Hard cancel”](#hard-cancel) A hard cancel writes the terminal state directly, without asking your code: * The invocation ends `failed` with code `572`. Callers waiting on it with `ctx.call` get that failure. * If it held a virtual object’s key, the next invocation in the queue runs. * A turn already running on your service is not cut off. It runs to its next natural stop; its steps have run (and cost what they cost), and its state writes still apply. Only its outcome is discarded. * Pending timers and retries are discarded when they come due. * Your `catch` blocks never run: a saga does not compensate on a hard cancel. ### Propagation to children [Section titled “Propagation to children”](#propagation-to-children) A hard cancel also cancels every invocation it created with `ctx.call` and is still waiting for, recursively down the tree. Calls not yet dispatched are never sent. Invocations started with `ctx.send` are detached work and are **not** cancelled; cancel them by ID. ## Choosing [Section titled “Choosing”](#choosing) Use cooperative cancel by default: it lets you refund, release and notify. Fall back to the hard cancel when the service cannot answer, or when you need the invocation stopped regardless of what its code does. # Typed client > Call services, objects and workflows from your app with @cairnflow/sdk/client. `@cairnflow/sdk/client` calls your handlers from an application, a script or an edge function. It imports nothing from `node:*`, follows the cluster’s redirects, retries safely, and takes its types from your service definitions. app.ts ```ts import { connect, InvocationFailed } from "@cairnflow/sdk/client"; import type { orders, signup } from "./services.ts"; const c = connect({ url: process.env.CAIRN_URL!, apiKey: process.env.CAIRN_KEY! }); // Call and wait for the result. const receipt = await c.service("OrderService").submit({ amount: 5 }); // Send and get a handle back at once. const h = await c.service("OrderService").send.submit({ amount: 5 }); const result = await h.attach({ timeoutMs: 60_000 }); ``` ## Types from your services [Section titled “Types from your services”](#types-from-your-services) Export the definitions from the module that declares them and import them with `import type`. Only types cross over, so the client bundle does not pull in your service code or `node:http`: services.ts ```ts import { service, type ServiceContext } from "@cairnflow/sdk"; export const orders = service("OrderService", { async submit(ctx: ServiceContext, input: { amount: number }) { return { receipt: await ctx.run("charge", () => charge(input.amount)) }; }, }); ``` `c.service("OrderService")` then exposes `submit(input, opts?)`, typed with the handler’s input and returning a promise of its output. The name string must match the service name; the type parameter only describes it. ## Targets [Section titled “Targets”](#targets) | Call | For | | ---------------------------------------- | ------------------------ | | `c.service(name, opts?)` | A plain service | | `c.object(name, key, opts?)` | A virtual object, by key | | `c.workflow(name, workflowId, opts?)` | A workflow, by ID | | `c.invocation(id)` | Any invocation, by ID | `opts` is `{ scope }` to address the target inside a [scope](/docs/develop/calls#scopes). Each target exposes one function per handler, which calls and waits, plus `send.`, which returns an `InvocationHandle` as soon as the invocation is durable. ### Workflows [Section titled “Workflows”](#workflows) ```ts const wf = c.workflow("UserSignup", "u-1"); await wf.send.run({ email: "a@example.com" }); // start without waiting await wf.click({ secret }); // a shared handler const verified = await wf.attach(); // wait for run's result const now = await wf.output(); // { ready: false } or { ready: true, value } ``` Calling `run` a second time for the same ID throws `AlreadyInvoked`, with the ID of the existing run. ## Invocation handles [Section titled “Invocation handles”](#invocation-handles) | Method | Meaning | | --------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | `id` | The invocation ID | | `attach({ timeoutMs?, signal? })` | Wait until it finishes; returns the output | | `output()` | `{ ready: false }` or `{ ready: true, value }`, without waiting | | `status()` | Status, timestamps, and failure details | | `signal(name, value?)` | Deliver a [signal](/docs/develop/promises-signals#signals) | | `cancel({ mode? })` | Cooperative cancel by default; `{ mode: "hard" }` needs an admin key — see [Cancellation](/docs/develop/cancellation) | Waiting uses long polls of 25 seconds each (`attachWaitMs`), below the idle timeout of common load balancers. A `503`, or a `429` that names no invocation, is retried after a backoff (honouring `Retry-After`). If `timeoutMs` runs out first, `attach` throws `AttachTimeout`; the invocation keeps running and you can attach again by ID. ## Call options [Section titled “Call options”](#call-options) | Option | Meaning | | ---------------- | --------------------------------------------------------------------------------------------------------------- | | `idempotencyKey` | Idempotency key for this call. Absent: generated once and reused across the client’s retries. `null`: send none | | `timeoutMs` | Give up waiting after this long (calls only) | | `signal` | `AbortSignal` to stop waiting | | `limitKey` | Limit key, for calls in a scope | | `logLevel` | Minimum `ctx.log` level for this invocation: `"debug"`, `"info"`, `"warn"` or `"error"` | | `headers` | Extra request headers | ## Idempotency [Section titled “Idempotency”](#idempotency) Every call carries an `Idempotency-Key`. When you do not pass one, the client generates a random key and keeps it across its own retries, so a lost response or a network error never creates a second invocation. Pass your own key to deduplicate across processes or restarts: ```ts await c.service("OrderService").submit(order, { idempotencyKey: `order-${order.id}`, }); ``` The same key returns the same invocation: its result if it has finished, or a handle to wait on. `send.` returns a handle to that invocation even when it has already failed or is paused. Deduplication lasts as long as the finished invocation is retained. A workflow’s `run` needs no key: the workflow ID already makes it run once. ## Errors [Section titled “Errors”](#errors) | Error | When | | ------------------ | ------------------------------------------------------------------------------------------------- | | `InvocationFailed` | The invocation ended `failed`. It is a `TerminalError`, with `code`, `message` and `invocationId` | | `InvocationPaused` | The invocation is `paused` (for example, retries exhausted). Has `code` and `invocationId` | | `AlreadyInvoked` | A workflow `run` was called again for the same ID | | `AttachTimeout` | `timeoutMs` ran out; the invocation is still running | | `CairnHttpError` | Any other HTTP error (`400`, `401`, `403`, `404`, …), with `status` and `code` | ```ts try { await c.object("Cart", userId).checkout(); } catch (e) { if (e instanceof InvocationFailed && e.code === 409) { // business failure reported by the handler } else { throw e; } } ``` ## Connect options [Section titled “Connect options”](#connect-options) | Option | Default | Meaning | | -------------- | -------------- | ------------------------------------------------------------------ | | `url` | — | Your environment’s endpoint | | `apiKey` | — | Sent as `Authorization: Bearer` | | `headers` | — | Extra headers on every request | | `maxAttempts` | `8` | Attempts per request | | `maxElapsedMs` | `30000` | Time budget per request, including waits between attempts | | `attachWaitMs` | `25000` | Length of each long poll while waiting for a result | | `followLeader` | `true` | Follow the cluster’s redirect to the node that owns the invocation | | `fetch` | global `fetch` | Custom `fetch` implementation | The client also exposes `c.promise(...)` and `c.awakeable(id)` for [promises and awakeables](/docs/develop/promises-signals), and `c.schedules` for [schedules](/docs/develop/schedules). Caution An API key in a browser bundle is visible to every user. Call cairnflow from your backend, or from an edge function that holds the key, and expose only what the browser needs. The client has no delayed send; to run something later, use `ctx.send(..., { delay })` inside a handler. # Durable steps > ctx.run, what it guarantees, and what has to go inside it. `ctx.run` runs a piece of code once and records its result in the invocation’s journal. When the handler replays — after a crash, a deploy or a wait — the step returns the recorded result and the closure is not called again. ```ts const receipt = await ctx.run("charge", () => chargeCard(order.amount)); ``` ```ts run( name: string, fn: (signal: AbortSignal) => Promise | T, opts?: { cancellable?: boolean }, ): Promise; ``` ## What it guarantees [Section titled “What it guarantees”](#what-it-guarantees) 1. The closure runs. 2. The SDK sends the result to cairnflow and **waits until it is durable** before the handler goes on. Only then do later steps run. 3. On every later replay, `ctx.run` returns the recorded result. If the process dies **while the closure is running**, the result is unknown, so the closure runs again on the next attempt. This is the at-least-once part no runtime can remove: nobody knows how far a network call got. Make the work inside a step idempotent — for example, pass an idempotency key to the payment API derived from `ctx.invocationId` and the step name. If the process dies **after** the result is durable, the step never runs again. ## The result is JSON [Section titled “The result is JSON”](#the-result-is-json) Results are stored with `JSON.stringify` and read back with `JSON.parse`, and the handler always continues with the stored value. Return plain data: * `undefined` becomes `null`. * A `Date` becomes a string; `Map` and `Set` become `{}`; class instances lose their methods. * A result whose encoded frame is over 16 MiB is not sent: the step fails for good with a `TerminalError` of code `413`, recorded like any other result, so the closure does not run again. * Put files and images in an [artifact](/docs/develop/artifacts) and return the reference. Large JSON results are stored as segments rather than inline; see [Payload](/docs/cloud/limits#payload) for the limits on Cairnflow Cloud. Caution Do not return secrets (API tokens, keys) from a step. Results are stored in the journal and shown in the console. Read secrets from the environment inside the closure instead. ## Step names are part of the journal [Section titled “Step names are part of the journal”](#step-names-are-part-of-the-journal) On replay, the SDK checks each command against the journal: its kind, its name (for `ctx.run`, the step name), and every other field it records, such as a call’s target, key and input. If a deploy renames a step, an in-flight invocation that reaches it stops in the `paused` state with code `570` (journal mismatch) instead of running the wrong code. * Keep names stable across deploys. * Do not put configuration in names (model IDs, prompt versions). Put them in [span attributes](/docs/develop/streams-logs) instead. * Names built from data are fine when the data is deterministic, for example ``ctx.run(`dig/${section}`, ...)`` inside a loop over the input. See [Deploying new versions](/docs/develop/versioning) for how to change step names safely. ## Errors inside a step [Section titled “Errors inside a step”](#errors-inside-a-step) | The closure throws | What happens | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | A normal `Error` | Nothing is recorded. The current turn fails and is retried under the handler’s retry policy; on retry, completed steps replay and this closure runs again. Any `ctx` command after the failure throws `TurnFailed`, even if your code catches the error | | `RunFailure(message, code)` or `TerminalError(message, code)` | The failure **is** recorded, and the SDK waits until it is durable. `ctx.run` then throws a `TerminalError` with that code and message, now and on every replay. The step never runs again. Catch it to compensate, or let it fail the invocation | Use `RunFailure` or `TerminalError` when your code decides that a failure is permanent — a `410 Gone` from the other side, a vendor that has not answered after several attempts: ```ts import { RunFailure } from "@cairnflow/sdk"; const note = await ctx.run(`dig/${section}`, async () => { if (ctx.attempt >= 5) { throw new RunFailure(`vendor did not answer after ${ctx.attempt} attempts`, 503); } return callVendor(section); }); ``` More in [Errors and retries](/docs/develop/errors-retries). ## Deterministic helpers [Section titled “Deterministic helpers”](#deterministic-helpers) The handler body outside `ctx.run` must take the same path on every replay. Use these instead of non-deterministic sources: | Instead of | Use | | -------------------------- | ---------------------------------------------------------------------------------- | | `Math.random()` | `ctx.random()` — a seeded generator that replays the same sequence | | `Date.now()`, `new Date()` | `await ctx.run("now", () => Date.now())` | | `crypto.randomUUID()` | `await ctx.run("id", () => crypto.randomUUID())` | | Your own invocation ID | `ctx.invocationId` | | Retry counter | `ctx.attempt` — attempts since the handler last made progress (0 on the first run) | Waits have their own deterministic form: `ctx.sleep` computes its wake-up time once and records it. ## What must go inside ctx.run [Section titled “What must go inside ctx.run”](#what-must-go-inside-ctxrun) Anything whose result can differ between two runs, or that touches the outside world: * HTTP calls, model calls, tool calls, database reads and writes, sending email. * Reading the clock or generating random IDs. * Reading anything that can change between attempts (files, environment-dependent lookups) when the handler’s path depends on it. Pure computation on the handler’s input and on previous step results can stay outside. ## Long steps and parallel steps [Section titled “Long steps and parallel steps”](#long-steps-and-parallel-steps) * Only the streaming transport (`BIDI_STREAM`) keeps the connection alive while a closure runs, so a long closure is not cut there. In request-response mode each turn is one HTTP request and must finish within the handler’s `inactivityTimeout`, and on a serverless platform within the platform’s time limit too. That is always the case with `fetchHandler`, and on Cairnflow Cloud it is also the case for `serve()` unless you register the deployment with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)). * A step that runs past that limit is cut and retried: its closure runs again from the start, and without a retry policy the retries do not stop. Split long work into several shorter steps, or declare a longer `inactivityTimeout` for the handler ([Handler options](/docs/develop/services#handler-options)). The default and the upper bound on Cloud are in [Turn time limit](/docs/cloud/limits#turn-time-limit). * Several steps can run at once with `Promise.all([ctx.run(...), ctx.run(...)])`. Results reach your code in the order they were recorded in the journal, so parallel branches take the same path on every replay. Code after `await ctx.run(...)` never runs in the same turn as that step’s closure: do not make a closure wait for something only that later code would do. ## Cancellation [Section titled “Cancellation”](#cancellation) By default a step is not interrupted by a cooperative cancel, so compensation steps still run. Mark forward steps (model calls, tools) with `{ cancellable: true }`: they do not start once the invocation is cancelled, and their closure receives an `AbortSignal` that fires if the cancel arrives mid-step (streaming mode only). See [Cancellation](/docs/develop/cancellation). ```ts const page = await ctx.run( "fetch", (signal) => fetch(url, { signal }).then((r) => r.text()), { cancellable: true }, ); ``` # Errors and retries > Terminal errors, retried errors, retry policies and paused invocations. A handler can end in three ways besides returning a value: fail for good, be retried, or pause until someone fixes the cause. Which one you get depends on what you throw. | You throw | Outcome | Journal | | ------------------------------ | --------------------------------------------------------------- | ------------------------------------------------------------- | | `TerminalError(message, code)` | Invocation ends `failed` with `code` and `message`. Not retried | Kept; the failure is the result | | Any other error | The turn fails and is **retried** with backoff | Kept; completed steps replay, only unfinished work runs again | | `PauseError(message, code)` | Invocation is `paused`, waiting for an operator | Kept; `resume` continues from the same point | All three are exported from `@cairnflow/sdk`. ## TerminalError [Section titled “TerminalError”](#terminalerror) Use it for failures a retry cannot fix: invalid input, a refused payment, a missing record. ```ts import { TerminalError } from "@cairnflow/sdk"; if (typeof input?.amount !== "number") { throw new TerminalError("amount must be a number", 400); } ``` * `code` defaults to `500`. Use HTTP-style codes; the code and message reach the caller. A code that is not an integer from 0 to 2³²−1 becomes `500`. * A caller using `/invoke` gets `500` with `{"status": "failed", "code": 400, "message": ...}`; the [typed client](/docs/develop/client) throws `InvocationFailed`, which is itself a `TerminalError`. * A handler that called the failed one with `ctx.call` gets a `TerminalError` with the same code and message. * You can catch a `TerminalError` and carry on — that is how you write compensation (sagas). * Thrown inside a `ctx.run` closure, it becomes the step’s recorded result: the closure does not run again, and `ctx.run` throws the same error on every replay. ## Retried errors [Section titled “Retried errors”](#retried-errors) Any error that is not a `TerminalError` or `PauseError` fails the current **turn**. Cairnflow schedules another attempt with backoff. On the next attempt, steps already in the journal return their recorded results; only the work that did not finish runs again. Inside a `ctx.run` closure the rule is strict: once a closure throws a normal error, the turn is dead even if your code catches the error. The next `ctx` command throws `TurnFailed`, and the turn ends as a failure to retry. Continuing past the error would let later steps depend on a result the retry is about to replace. If you want a step’s failure recorded so it never runs again, throw `RunFailure` or `TerminalError` from the closure — see [Durable steps](/docs/develop/durable-steps#errors-inside-a-step). ### Retry policy [Section titled “Retry policy”](#retry-policy) Without a policy, retries are unlimited with backoff starting at 100 ms, doubling, capped at 60 seconds. Set a policy per service or per handler: ```ts service("Payments", { charge }, { options: { retryPolicy: { initialInterval: 200, maxInterval: 30_000, exponentiationFactor: 2, maxAttempts: 5, onMaxAttempts: "PAUSE", }, }, }); ``` | Field | Default | Meaning | | ---------------------- | --------- | ---------------------------------------------------------------------------- | | `initialInterval` | `100` | First backoff, ms | | `maxInterval` | `60000` | Largest backoff, ms | | `exponentiationFactor` | `2` | Multiplier between attempts; must be at least 1 | | `maxAttempts` | unlimited | Total attempts **including the first**; at least 1 | | `onMaxAttempts` | `"PAUSE"` | `"PAUSE"` keeps the invocation for an operator; `"KILL"` ends it as `failed` | When attempts run out, the invocation ends `paused` (or `failed` with `KILL`) with code `575`, and the message includes the last attempt’s error. `POST /invocations/{id}/resume` gives a paused invocation another round of attempts. The policy is captured when the deployment is registered; changing it means registering a new deployment. ### Giving up on purpose [Section titled “Giving up on purpose”](#giving-up-on-purpose) `ctx.attempt` counts the attempts since the handler last made progress: `0` on a first run, and it resets every time the journal grows. Use it to stop retrying a dependency that is down for good: ```ts import { RunFailure } from "@cairnflow/sdk"; const result = await ctx.run("call vendor", async () => { if (ctx.attempt >= 3) { throw new RunFailure("vendor did not answer after 3 attempts", 503); } return callVendor(); }); ``` ## Paused invocations [Section titled “Paused invocations”](#paused-invocations) An invocation is `paused` when it cannot continue without a person: | Code | Cause | What to do | | --------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | | `570` | Journal mismatch: the code no longer matches the recorded steps | Fix the code or move the invocation — see [Deploying new versions](/docs/develop/versioning) | | `575` | Retry attempts exhausted | Fix the cause, then resume | | your code | You threw `PauseError` | Fix the cause, then resume | Throw `PauseError` for problems that will not fix themselves but are worth keeping the work for — stock that must be restocked, a quota that must be raised: ```ts import { PauseError } from "@cairnflow/sdk"; const inStock = await ctx.run("check stock", () => stock.count(sku)); if (inStock < input.quantity) { throw new PauseError(`missing ${input.quantity - inStock} of ${sku}`); } ``` `POST /invocations/{id}/resume` continues the invocation from where it stopped. The answer carries the status after continuing: it can complete, suspend, or pause again if nothing changed. Caution A paused invocation on a virtual object **keeps its place in the key’s exclusive queue**. Other exclusive invocations on that key wait until it is resumed, cancelled or finished. A caller waiting with `/invoke` gets `409` with `{"status": "paused", "code": ..., "message": ...}`; the typed client throws `InvocationPaused`. ## Don’t swallow control flow [Section titled “Don’t swallow control flow”](#dont-swallow-control-flow) When your code awaits something that is not ready yet (a timer, a call, a signal, a step result not yet durable), the promise simply stays pending until the turn ends; nothing is thrown. The SDK throws its own errors only in a few cases, and none of them is an error of your code: | Error | When | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `TurnFailed` | A `ctx` command after a step’s closure threw a normal error; the turn will be retried | | `JournalMismatch` | A command does not match the journal; the invocation pauses with `570` | | `Suspend` | A `ctx` command after the turn has already suspended, for example from code still running after it awaited something outside the SDK | Catching them changes nothing: the turn still suspends, fails or pauses. If you need a broad `catch`, rethrow them: ```ts import { JournalMismatch, Suspend, TurnFailed } from "@cairnflow/sdk"; try { await doWork(ctx); } catch (e) { if (e instanceof Suspend || e instanceof TurnFailed || e instanceof JournalMismatch) throw e; // handle your own errors here } ``` For the full list of failure codes, see [Errors reference](/docs/reference/errors). # Go SDK > Write services, virtual objects and workflows in Go with the cairn package, serve them, and call them with the Go client. The Go SDK, module `github.com/cairnflowdev/cairnflow/sdk/go` (package `cairn`), has the same model as the TypeScript SDK: handlers replay from a journal, side effects go through `cairn.Run`, and results reach your code in the order they were recorded. It needs Go 1.25 or newer and has no dependencies: `go.mod` has no `require`. It is licensed under Apache-2.0 and is in beta. The rest of these docs show TypeScript. The concepts, limits, error codes and HTTP routes are the same in Go; this page lists what is spelled differently. ## Install [Section titled “Install”](#install) ```sh go get github.com/cairnflowdev/cairnflow/sdk/go ``` Releases are tagged `sdk/go/vX.Y.Z` (the current beta is `v0.1.0-beta.0`: `go get github.com/cairnflowdev/cairnflow/sdk/go@v0.1.0-beta.0`). To work against a local checkout instead: ```sh go mod edit -replace=github.com/cairnflowdev/cairnflow/sdk/go=../cairnflow/sdk/go ``` ```go import ( cairn "github.com/cairnflowdev/cairnflow/sdk/go" "github.com/cairnflowdev/cairnflow/sdk/go/client" // calling services from an app or a script ) ``` ## A first service [Section titled “A first service”](#a-first-service) main.go ```go package main import ( "context" "fmt" "log" "os" "os/signal" "syscall" "time" cairn "github.com/cairnflowdev/cairnflow/sdk/go" ) type Order struct { Amount int `json:"amount"` } type Receipt struct { Receipt string `json:"receipt"` Total int `json:"total"` } // charge is the side effect: a payment provider in real life. func charge(ctx context.Context, amount int) (string, error) { log.Printf("charging %d", amount) return fmt.Sprintf("receipt-%d", amount), ctx.Err() } func submit(ctx cairn.ObjectContext, order Order) (Receipt, error) { if order.Amount <= 0 { return Receipt{}, cairn.TerminalErrorf(400, "amount must be positive") // bad data: retrying is useless } total, _, err := cairn.Get[int](ctx, "total") // false (and 0) = the key does not exist if err != nil { return Receipt{}, err } if err := cairn.Sleep(ctx, time.Second); err != nil { // durable: the timer lives in the store return Receipt{}, err } receipt, err := cairn.Run(ctx, "charge", func(rc cairn.RunContext) (string, error) { return charge(rc, order.Amount) // runs once per durable result; rc is a context.Context }) if err != nil { return Receipt{}, err } if err := cairn.Set(ctx, "total", total+order.Amount); err != nil { return Receipt{}, err } return Receipt{Receipt: receipt, Total: total + order.Amount}, nil } // total runs in parallel with other handlers of the same key and only reads state. func total(ctx cairn.ObjectSharedContext) (int, error) { t, _, err := cairn.Get[int](ctx, "total") return t, err } var orders = cairn.NewObject("OrderService", cairn.Exclusive("submit", submit), cairn.Shared("total", cairn.NoInput(total))) func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() // Listens on every interface; 127.0.0.1:9080 is unreachable from outside a container. err := cairn.Serve(ctx, ":9080", orders, cairn.IdentityKeys(os.Getenv("CAIRN_IDENTITY_KEY"))) if err != nil { log.Fatal(err) } } ``` Register and invoke it exactly as in the [Quickstart](/docs/quickstart): `POST /deployments` with the service’s public `https://` URL, then `POST /invoke/OrderService/submit?key=order-42`. Every durable step is a function of the package that takes the context (`cairn.Get(ctx, …)`, `cairn.Run(ctx, …)`), so it can be generic in the type of its value. A step that can fail returns an `error`: return it from the handler as it is. ## Services and handlers [Section titled “Services and handlers”](#services-and-handlers) | Declared with | Kind | | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cairn.NewService(name, handlers...)` | A plain service: no key, no state. Handlers are `cairn.Handler(name, fn)` with `fn func(cairn.Context, I) (O, error)` | | `cairn.NewObject(name, handlers...)` | A virtual object: state per key. `cairn.Exclusive(name, fn)` takes a `cairn.ObjectContext`; `cairn.Shared(name, fn)` takes a `cairn.ObjectSharedContext` and only reads state | | `cairn.NewWorkflow(name, handlers...)` | A workflow: exactly one `cairn.Main(name, fn)` taking a `cairn.WorkflowContext`, which runs once per workflow ID, plus any number of `cairn.Shared` handlers. Name the main handler `run`, as the other SDKs do by default | * A handler without input is wrapped with `cairn.NoInput(fn)`; one without output returns `cairn.Void`. * Input and output are JSON through `encoding/json`. An input that does not decode into the handler’s input type fails the invocation with a terminal error `400` before the handler runs. * Writing state from a shared handler does not compile, and neither does `cairn.Get` on a plain service’s context. * A mistake in a declaration (no handler, two handlers with one name, a workflow without one `Main`) panics at declaration time. Handler options are trailing arguments of a handler, or `.With(...)` on the whole service: `WithRetryPolicy`, `WithInactivityTimeout`, `WithJournalRetention`, `WithLogLevel`, `WithRuntimeTrace` and `WithLogFlush`. Durations are `time.Duration` values. Their meaning is in [Handler options](/docs/develop/services#handler-options). As in TypeScript, a service that sets no inactivity timeout declares 15 minutes. ```go signup := cairn.NewWorkflow("Signup", cairn.Main("run", func(ctx cairn.WorkflowContext, email string) (string, error) { // Waits, durably, until the shared handler below completes the promise. return cairn.Promise[string](ctx, "code").Get() }), cairn.Shared("verify", func(ctx cairn.WorkflowSharedContext, code string) (cairn.Void, error) { return cairn.Void{}, cairn.Promise[string](ctx, "code").Resolve(code) }), ).With(cairn.WithRetryPolicy(cairn.RetryPolicy{ InitialInterval: time.Second, MaxInterval: time.Minute, ExponentiationFactor: 2, MaxAttempts: 10, OnMaxAttempts: cairn.PauseOnMaxAttempts, })) ``` ## The context [Section titled “The context”](#the-context) | | Go | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | State | `cairn.Get[T](ctx, k)` returns `(value, found, err)`; `cairn.Set(ctx, k, v)`, `cairn.Clear(ctx, k)`, `cairn.ClearAll(ctx)`, `cairn.StateKeys(ctx)` | | Steps | `cairn.Run(ctx, name, func(rc cairn.RunContext) (T, error))`, `cairn.RunAsync(...)` (a future); option `cairn.Cancellable()` | | Timers | `cairn.Sleep(ctx, d)`, `cairn.After(ctx, d)` (a future) | | Calls | `cairn.Service[O](ctx, svc, handler)`, `cairn.Object[O](ctx, svc, key, handler)`, `cairn.Workflow[O](ctx, svc, id, handler)`, then `.Request(in)`, `.RequestFuture(in)` or `.Send(in, cairn.WithDelay(d))`; options `WithIdempotencyKey`, `WithScope`, `WithLimitKey`, `WithSpread` | | Signals | `cairn.Signal[T](ctx, name)` (a future), `cairn.SendSignal(ctx, invocationID, name, v)` | | Awakeables | `awk := cairn.Awakeable[T](ctx)`, `awk.ID()` for the outside system, then `awk.Result()` | | Promises | `p := cairn.Promise[T](ctx, name)`: `p.Get()`, `p.GetFuture()`, `p.Peek()`, `p.Resolve(v)`, `p.Reject(code, msg)` | | Other invocations | `cairn.Attach[T](ctx, invocationID)` (a future), `cairn.GetOutput[T](ctx, invocationID)`, `cairn.ContinueAsNew(ctx, input)` | | Combinators | `cairn.WaitFirst(ctx, futs...)`, `cairn.Wait(ctx, futs...)`, `cairn.All(ctx, futs...)`, `cairn.Race(ctx, futs...)`; on a future, `f.Result()` and `f.Done()` | | Streams, logs, traces | `s, err := ctx.Stream(name)` (`cairn.Durable()` to keep it), `s.Append(record)`, `s.Close()`; `ctx.Log()` is a `*slog.Logger`; `cairn.WithSpan(ctx, name, fn, attrs...)` | | Artifacts | `ref, err := rc.Artifacts().Put(bytes, contentType)` inside a `Run` closure, `ctx.Artifacts().Get(ref.SHA256)` | | Identity | `ctx.Key()`, `ctx.InvocationID()`, `ctx.Attempt()`, `ctx.Schedule()`, `ctx.Rand()`, `ctx.Random()`, `cairn.UUID(ctx)` | A command is journaled when its future is created; waiting happens only in `Result` or in a combinator. That is how several steps run at once on one goroutine. When several futures are ready, the combinators pick by journal order, never by arrival time, so a replay takes the same path. The rules of handler code are the same as in TypeScript. In Go they read as follows, with two additions (rules 1 and 4): 1. **Stay on the handler’s goroutine.** No `go` statements, channels, `sync` or `time.Sleep` in handler code to coordinate durable work: parallel work is futures plus a combinator. Concurrency inside a `Run` closure is fine. 2. Use `ctx.Rand()`, `ctx.Random()` or `cairn.UUID(ctx)`, not `math/rand`, `crypto/rand` or `time.Now`. Read the clock only inside `cairn.Run`. 3. **Do all I/O inside `cairn.Run`.** A `cairn.Context` is not a `context.Context`; a `Run` closure gets one, and must not touch the handler’s `ctx`. 4. **Issue the same commands in the same order.** Ranging over a map visits keys in a random order, so sort the keys before a loop that issues commands. ## Errors [Section titled “Errors”](#errors) | Returned from a handler | What happens | | ---------------------------------------------- | ---------------------------------------------- | | `cairn.TerminalErrorf(code, format, args...)` | The invocation fails without a retry | | `cairn.PauseErrorf(format, args...)` | The invocation pauses until someone resumes it | | `cairn.RetryableErrorf(code, format, args...)` | Retried like any other error, with a code | | Any other `error`, or a panic | The turn fails and is retried with backoff | Returned from a `Run` closure, a `*cairn.TerminalError` is recorded as the step’s result: the closure does not run again, and `cairn.Run` returns the same error on every replay. Check for one with `errors.As` or `cairn.IsTerminalError(err)`. See [Errors and retries](/docs/develop/errors-retries) for codes and retry policies. ## Serving [Section titled “Serving”](#serving) | Entry point | Where | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | | `cairn.Serve(ctx, addr, services...)` | The built-in server, until `ctx` ends. It serves HTTP/1.1 and cleartext HTTP/2 on one port | | `cairn.HTTPHandler(services...)` | An `http.Handler` for a server of your own | | `cairn.LambdaHandler(services...)` | AWS Lambda (Function URL or API Gateway HTTP API, payload v2), request-response mode only. Pass the handler to `lambda.Start` in your own `main` | Unlike `serve()` in TypeScript, these default to request-response mode. For streaming mode pass `cairn.Bidi()`. On Cairnflow Cloud an `https://` endpoint is called in request-response mode unless you register it with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)). Services and options are passed together, in any order: | Option | Default | Meaning | | --------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `cairn.IdentityKeys(keys...)` | none | Identity keys of your environment; unsigned requests get `401`. Required by Cairnflow Cloud. Without it, a warning is logged once and the endpoint keeps no replay cache | | `cairn.IdentityHosts(hosts...)` | none | The public hosts you registered, as `identityHosts` in [serve() options](/docs/develop/services#serve-options) | | `cairn.Bidi()` | off | Declare streaming mode | | `cairn.WithoutCompression()` | compression on | Stop accepting gzip request bodies and compressing large responses | | `cairn.ReplayCache(...)`, `cairn.WithoutReplayCache()` | on with `IdentityKeys` (off on Lambda) | Keep the journal of running invocations in memory so only new entries are sent | | `cairn.MaxProtocolVersion(v)` | `6` with `IdentityKeys`, else `5` | Pin an older protocol version | | `cairn.SegmentOrigins(...)`, `cairn.ValueCacheBytes(n)`, `cairn.MaxValueBytes(n)`, `cairn.MaxTurnValueBytes(n)` | as in TypeScript | Downloading large values stored as segments | ## Client [Section titled “Client”](#client) app.go ```go c := client.Connect(os.Getenv("CAIRN_URL"), client.WithAPIKey(os.Getenv("CAIRN_KEY"))) // Waits for the result. r, err := client.Call[Receipt](ctx, c.Object("OrderService", "order-42"), "submit", Order{Amount: 100}) // Returns once the invocation is durable. h, err := client.Send(ctx, c.Object("OrderService", "order-42"), "submit", Order{Amount: 5}) out, err := client.Attach[Receipt](ctx, h, client.Timeout(time.Minute)) ``` * Targets: `c.Service(name)`, `c.Object(name, key)`, `c.Workflow(name, workflowID)`, `c.Awakeable(id)`, `c.Promise(service, key, name)`, `c.Schedules()`. * `client.Call` waits; `client.Send` returns an invocation handle with `Status`, `Signal` and `Cancel`; `client.RunWorkflow` starts a workflow and waits for it. * Every call carries a generated `Idempotency-Key`, kept across the client’s own retries (`client.IdempotencyKey(k)` sets one, `client.NoIdempotencyKey()` sends none). The client follows the `leader` of a `503` and waits for the `Retry-After` of a `429`. * A handler’s terminal error arrives as `*client.InvocationFailed`; a wait that runs out is a `*client.AttachTimeout`, and the invocation keeps running. * `c.ReadStream(ctx, invocationID, name)` iterates over a stream’s events and reconnects on its own, like `readStream` in [Streams, logs and traces](/docs/develop/streams-logs). ## Testing handlers [Section titled “Testing handlers”](#testing-handlers) The package `github.com/cairnflowdev/cairnflow/sdk/go/cairntest` runs a handler in the test process over the SDK’s real turn machine, with no runtime. Every turn replays the whole journal so far, so a test exercises replay too: ```go inv := cairntest.New(orders, "submit", Order{Amount: 100}, cairntest.Key("o-1")) st, err := inv.Run() // cairntest.Completed, Waiting, Failed, Paused or ContinuedAsNew if err != nil || st != cairntest.Completed { t.Fatal(st, err) } var r Receipt if err := inv.Output(&r); err != nil { t.Fatal(err) } ``` ## Not in the Go SDK [Section titled “Not in the Go SDK”](#not-in-the-go-sdk) * The Vercel AI SDK adapter (`chatObject`, `cairnMiddleware`, `cairnTools`, `cairnChatTransport`): it is specific to that TypeScript library. # Local development > Run your service on your own machine against a dev environment in Cairnflow Cloud, through an HTTPS tunnel whose URL does not change. Cloud is in waitlist This page is about developing against Cairnflow Cloud, which is not open yet — [join the waitlist](/#pricing) for early access. Today you can run the runtime yourself: with a node on your own machine, as in the [Quickstart](/docs/quickstart), you register `http://127.0.0.1:` and need no tunnel. Cairnflow Cloud does not run your code: it calls your service over HTTPS. While you develop, that service can run on your own machine, as long as Cloud can reach it. This page covers that setup. To run the runtime itself on your machine instead, install a release binary or run Docker: see [Self-hosting](/docs/self-hosting). ## 1. Use a separate environment [Section titled “1. Use a separate environment”](#1-use-a-separate-environment) Create an environment for development, for example `dev`, next to `prod`. Each environment has its own endpoint, API keys, identity key and data, so nothing you register or run in `dev` touches `prod`. How many environments an organization can have is in [Account limits](/docs/cloud/limits#account-limits). On the `dev` environment’s page, copy its endpoint and identity key, and create an Admin API key: ```sh export CAIRN_URL="" export CAIRN_KEY="" export CAIRN_IDENTITY_KEY="" ``` ## 2. Run the service on your machine [Section titled “2. Run the service on your machine”](#2-run-the-service-on-your-machine) service.ts ```ts import { serve, service } from "@cairnflow/sdk"; const greeter = service("Greeter", { greet: async (ctx, name: string) => { const upper = await ctx.run("upper", () => name.toUpperCase()); return `Hello, ${upper}!`; }, }); await serve({ services: [greeter], port: Number(process.env.PORT ?? 9080), identityKeys: [process.env.CAIRN_IDENTITY_KEY!], }); ``` Start it the way you run TypeScript in your project. `serve()` listens on `127.0.0.1` by default, which is all a tunnel on the same machine needs, and nothing else on your network can reach it. Keep `identityKeys`: the tunnel makes the service public, and the identity key is what refuses requests that do not come from your environment. Cloud refuses to register an endpoint without it. ## 3. Give it a public HTTPS URL that does not change [Section titled “3. Give it a public HTTPS URL that does not change”](#3-give-it-a-public-https-url-that-does-not-change) Cloud calls only `https://` endpoints on the public internet, so put a tunnel in front of the service. Choose one whose URL stays the same every time you start it: a deployment remembers the URL it was registered with, and invocations stay on the deployment they started on (see [When the URL changes](#when-the-url-changes)). ### Cloudflare Tunnel, named, on your own domain [Section titled “Cloudflare Tunnel, named, on your own domain”](#cloudflare-tunnel-named-on-your-own-domain) With a domain whose DNS is on Cloudflare, create a named tunnel once and give it a hostname: ```sh cloudflared tunnel login cloudflared tunnel create cairn-dev cloudflared tunnel route dns cairn-dev cairn-dev.example.com ``` Point it at the service in `config.yml` in your `.cloudflared` directory: config.yml ```yaml tunnel: credentials-file: url: http://127.0.0.1:9080 ``` Then run it whenever you work: ```sh cloudflared tunnel run cairn-dev ``` The URL is `https://cairn-dev.example.com`, every time. ### ngrok with your dev domain [Section titled “ngrok with your dev domain”](#ngrok-with-your-dev-domain) Every ngrok account, including a free one, has a dev domain that does not change when the agent restarts, and `ngrok http` uses it unless you pass another domain with `--url`: ```sh ngrok http 127.0.0.1:9080 ``` The URL is your dev domain, shown when the agent starts. ### What to avoid [Section titled “What to avoid”](#what-to-avoid) * **Tunnels that get a new URL every time**, such as Cloudflare’s quick tunnels (`cloudflared tunnel --url …`, a new `trycloudflare.com` hostname on each start). * **Long turns through a tunnel.** In request-response mode each turn is one HTTP request, and a tunnel or proxy can have its own limit on how long a request may take, on top of the [turn time limit](/docs/cloud/limits#turn-time-limit). ## 4. Register the tunnel URL [Section titled “4. Register the tunnel URL”](#4-register-the-tunnel-url) ```sh curl -X POST "$CAIRN_URL/deployments" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"uri":"https://cairn-dev.example.com"}' ``` Leave `transport` out: Cloud then calls the tunnel URL in request-response mode, which works through any tunnel. Invoke a handler to check the round trip: ```sh curl -X POST "$CAIRN_URL/invoke/Greeter/greet" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '"world"' ``` The console of the `dev` environment shows each invocation step by step. ## Day-to-day [Section titled “Day-to-day”](#day-to-day) * **Restart the service freely.** A turn cut by a restart is retried, and the invocation replays from its journal. While your machine sleeps or the tunnel is down, invocations that need your service are retried with backoff until it answers again, or until their retry policy gives up. * **Changing code in place affects running invocations.** They replay against whatever code answers at the URL. Renaming, adding, removing or reordering steps, or changing a call’s target or input, before the point an invocation reached pauses it with code `570`; see [Deploying new versions](/docs/develop/versioning). * **Register again when you change services, handlers or their options** (retry policy, `inactivityTimeout`): they are read at registration. Each registration creates a new deployment, even for the same URL, and counts toward the environment’s [deployment limit](/docs/cloud/limits) until you remove it. `DELETE /deployments/{id}` removes one that is no longer current and has no invocations left on it. ## When the URL changes [Section titled “When the URL changes”](#when-the-url-changes) Every invocation stays on the deployment it started on, for its whole life, and a deployment always calls the URL it was registered with. If the tunnel’s URL changes (a quick tunnel, another ngrok domain, a new hostname) and you register the new URL, new invocations go to the new deployment, but the ones already running keep calling the old URL. They cannot reach it, so they are retried with backoff, and without a [retry policy](/docs/develop/errors-retries#retry-policy) they keep retrying until the old URL answers again. Caution Do not leave invocations on a URL you no longer control. Every attempt sends the invocation’s journal (its input and step results) to that URL, so whoever answers there next receives them. Find them with `GET /deployments/{id}` of the old deployment (`pinnedInvocations` counts them), or list them with SQL on the console’s **Query** page or through [`POST /query`](/docs/query): ```sql SELECT id, service, handler, class, last_failure_message FROM sys_invocation WHERE class IN ('active', 'paused') AND pinned_deployment = 'dp_…' ``` Then pick one way out for each: * **Bring the old URL back.** Start a tunnel on the old hostname again; the invocations continue on their next retry. The code behind it must still match their journals. * **Move them to the new deployment:** `POST /invocations/{id}/migrate?deployment=`. Cloud first replays the invocation on the new deployment and refuses with `409` if the code there no longer matches its journal; `&force=true` skips that check. In the console: **Migrate…** on the invocation. * **Run them again on the new deployment:** `POST /invocations/{id}/restart?deployment=`. This starts a new invocation from the old one’s input (add `&from=` to keep the first `n` journal entries and their results); the old one ends, and callers waiting on it get the new one’s result. A workflow’s `run` cannot be restarted. In the console: **Restart from step…**. * **End them:** a hard cancel, `POST /invocations/{id}/cancel`, does not need your service. In the console: **Cancel now**, also available as a bulk action. Once no invocation is left on the old deployment, remove it with `DELETE /deployments/{id}`. ## Next [Section titled “Next”](#next) * [Deployments](/docs/cloud/deployments) * [Deploying new versions](/docs/develop/versioning) * [Beta limits](/docs/cloud/limits) # Durable promises, signals and awakeables > Wait for a person or an outside system, and complete the wait from another handler or over HTTP. Three primitives let an invocation wait for something that happens outside it — an approval, a webhook, a click in an email. All three suspend the invocation durably: it can wait for weeks without holding a process. | Primitive | Addressed by | Available in | Completed by | | --------------- | ---------------------------- | -------------------------- | ------------------------------------------------------------- | | Durable promise | service + key + promise name | Virtual objects, workflows | Another handler on the same object, or `POST /promises/...` | | Signal | invocation ID + signal name | Every handler | `POST /invocations/{id}/signal`, `ctx.sendSignal`, the client | | Awakeable | an opaque `awk_...` ID | Every handler | `POST /awakeables/{id}/resolve` | Pick a **promise** when the outside system knows the object (a workflow ID, an order number). Pick an **awakeable** when you hand an ID to a third party and want nothing else exposed. Pick a **signal** when the sender already knows the invocation ID. ## Durable promises [Section titled “Durable promises”](#durable-promises) A promise is a named value that belongs to one object (a virtual object key or a workflow ID). signup.ts ```ts import { type Context, workflow } from "@cairnflow/sdk"; const signup = workflow("UserSignup", { async run(ctx: Context, user: { email: string }) { const secret = await ctx.run("secret", () => crypto.randomUUID()); await ctx.run("mail", () => sendVerification(user, secret)); const clicked = await ctx.promise("email-link-clicked").get(); return clicked === secret; }, async click(ctx: Context, req: { secret: string }) { await ctx.promise("email-link-clicked").resolve(req.secret); }, }); ``` | Method | Meaning | | ------------------------ | ------------------------------------------------------------------------------ | | `get()` | Wait until the promise is completed. A rejected promise throws `TerminalError` | | `peek()` | `null` if not completed yet, without waiting | | `resolve(value)` | Complete with a value. Throws `TerminalError` if already completed | | `reject(message, code?)` | Complete with a failure. Throws `TerminalError` if already completed | ### Completing a promise over HTTP [Section titled “Completing a promise over HTTP”](#completing-a-promise-over-http) No extra handler is needed: an outside system can complete the promise directly with an API key that can invoke handlers. ```sh # Resolve: the body is the value. curl -X POST "$CAIRN_URL/promises/UserSignup/u-1/email-link-clicked/resolve" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" -d '"s3cr3t"' # Reject: waiters get a terminal error with this code and message. curl -X POST "$CAIRN_URL/promises/UserSignup/u-1/email-link-clicked/reject" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" -d '{"code": 403, "message": "link expired"}' # Has it been completed yet? curl "$CAIRN_URL/promises/UserSignup/u-1/email-link-clicked" \ -H "authorization: Bearer $CAIRN_KEY" ``` For an object in a scope, prefix the path with `/scope/{scope}`. With the [typed client](/docs/develop/client): `c.promise("UserSignup", "u-1", "email-link-clicked").resolve(value)`. Properties you can rely on: * **Completing twice is a no-op, not an error.** The second HTTP call answers `completed: false`. Webhook retries are safe without an extra idempotency key. * **Completing before anyone waits still works.** The promise is durable; a `get()` that runs later returns the value at once. ## Signals [Section titled “Signals”](#signals) A signal is a named message delivered to one invocation. `ctx.signal(name)` returns a future you can await or race against a deadline: ```ts const approval = await ctx.race([ ctx.signal<{ by: string }>("approve"), ctx.sleep(24 * 3600_000), ]); if (approval === undefined) throw new TerminalError("approval timed out", 408); ``` Send it from outside with the invocation ID: ```sh curl -X POST "$CAIRN_URL/invocations/$ID/signal" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"signal": "approve", "value": {"by": "alice"}}' ``` From the client: `await c.invocation(id).signal("approve", { by: "alice" })`. From another handler: `ctx.sendSignal(invocationId, "approve", { by: "alice" })` — one-way, it does not wait. * A signal without a value resolves to `null`. * **A delivered signal stays delivered.** Sending the same signal again is a no-op. And once `approve` has arrived, every later `ctx.signal("approve")` in that invocation resolves at once with the same value — use a new name for a new round of waiting (`approve-2`). * Signals sent to an invocation that has already finished are ignored. ## Awakeables [Section titled “Awakeables”](#awakeables) An awakeable is a wait point with a generated ID. Hand the ID to an outside system — inside a `ctx.run`, so it is sent once — then await the promise: ```ts const { id, promise } = ctx.awakeable<{ approved: boolean }>(); await ctx.run("request approval", () => mailer.send(approver, id)); const answer = await ctx.race([promise, ctx.sleep(7 * 24 * 3600_000)]); ``` The outside system completes it with an API key of the same environment that can invoke handlers: ```sh curl -X POST "$CAIRN_URL/awakeables/$AWAKEABLE_ID/resolve" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" -d '{"approved": true}' curl -X POST "$CAIRN_URL/awakeables/$AWAKEABLE_ID/reject" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" -d '{"message": "denied", "code": 403}' ``` With the client: `c.awakeable(id).resolve(value)` or `c.awakeable(id).reject(message, code)`. A rejected awakeable throws `TerminalError` in the handler. ## Starting work that waits for a person [Section titled “Starting work that waits for a person”](#starting-work-that-waits-for-a-person) Start the invocation with `/send` (or `send.` in the client), not `/invoke`: holding an HTTP request open until someone clicks a button is what `/send` avoids. For a workflow, fetch the result later with `POST /workflow/{service}/{key}/attach` — it needs only the workflow ID, so the outside system does not have to store an invocation ID. # Python SDK > Write services, virtual objects and workflows in Python with the cairnflow package, serve them, and call them with the Python client. The Python SDK, package `cairnflow`, has the same model as the TypeScript SDK: handlers replay from a journal, side effects go through `ctx.run`, and results reach your code in the order they were recorded. It needs Python 3.11 or newer and has no runtime dependencies. It is licensed under Apache-2.0 and is in beta (version `0.1.0b0`). The rest of these docs show TypeScript. The concepts, limits, error codes and HTTP routes are the same in Python; this page lists what is spelled differently. ## Install [Section titled “Install”](#install) ```sh pip install cairnflow ``` To install from a local checkout of the repository instead: `pip install ./sdk/python`. Two optional extras: | Extra | Adds | Needed for | | ------------------- | -------------- | ----------------------------------------------------------------------------- | | `cairnflow[bidi]` | `h2` | Streaming mode (`BIDI_STREAM`) in the built-in server | | `cairnflow[crypto]` | `cryptography` | Faster verification of request signatures; a pure-Python fallback is built in | ## A first service [Section titled “A first service”](#a-first-service) service.py ```python import asyncio import os from dataclasses import dataclass from cairnflow import Context, TerminalError, VirtualObject, serve orders = VirtualObject("OrderService") @dataclass class Order: amount: int def charge(amount: int) -> str: return f"receipt-{amount}" # a payment provider in real life @orders.handler() async def submit(ctx: Context, order: Order) -> dict: if order.amount <= 0: raise TerminalError("amount must be positive", 400) # retrying bad input is useless total = (await ctx.get("total")) or 0 # None: the key does not exist await ctx.sleep(1) # durable timer, in seconds receipt = await ctx.run("charge", charge, order.amount) ctx.set("total", total + order.amount) return {"receipt": receipt, "total": total + order.amount} @orders.handler(kind="shared") # runs alongside the exclusive handlers, reads state only async def get_total(ctx: Context) -> int: return (await ctx.get("total")) or 0 asyncio.run( serve( [orders], host="0.0.0.0", # the default, 127.0.0.1, is unreachable from outside a container port=int(os.environ.get("PORT", "9080")), identity_keys=[os.environ["CAIRN_IDENTITY_KEY"]], ) ) ``` Register and invoke it exactly as in the [Quickstart](/docs/quickstart): `POST /deployments` with the service’s public `https://` URL, then `POST /invoke/OrderService/submit?key=order-42`. ## Services and handlers [Section titled “Services and handlers”](#services-and-handlers) | Declared with | Kind | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | `Service(name)` | A plain service: no key, no state | | `VirtualObject(name)` | A virtual object: state per key; handlers are exclusive unless declared `kind="shared"` | | `Workflow(name)` | A workflow: exactly one `@wf.main()` handler (named `run` by default) that runs once per workflow ID, plus `@wf.handler()` shared handlers | * A handler is `async def h(ctx)` or `async def h(ctx, input)`. The handler name defaults to the function name; pass `@svc.handler("name")` to choose another. * Input and output are JSON. An input annotated with a dataclass or a Pydantic model is converted for you, and dataclasses and Pydantic models are serialized on the way out. * Shared handlers must not write state; the runtime rejects their writes with code `571`. Handler options go in `options=HandlerOptions(...)` on the service or on one handler. Durations are a `timedelta` or a number of **seconds** (the TypeScript SDK uses milliseconds): ```python from datetime import timedelta from cairnflow import HandlerOptions, RetryPolicy, Service agent = Service( "Agent", options=HandlerOptions( inactivity_timeout=timedelta(minutes=10), retry_policy=RetryPolicy(max_attempts=5, on_max_attempts="PAUSE", initial_interval=0.2), ), ) ``` `HandlerOptions` fields: `inactivity_timeout`, `retry_policy`, `journal_retention`, `log_level`, `trace`, `log_flush`. `RetryPolicy` fields: `initial_interval`, `max_interval`, `exponentiation_factor`, `max_attempts`, `on_max_attempts`. Their meaning is in [Handler options](/docs/develop/services#handler-options). As in TypeScript, the SDK declares an `inactivity_timeout` of 15 minutes when you set none. ## The context [Section titled “The context”](#the-context) | | Python | | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | State | `await ctx.get(k)`, `ctx.set(k, v)`, `ctx.clear(k)`, `ctx.clear_all()`, `await ctx.state_keys()` | | Steps | `await ctx.run(name, fn, *args, cancellable=False, **kwargs)`; `fn` can be sync or async | | Timers | `await ctx.sleep(seconds_or_timedelta, name="sleep")` | | Calls | `await ctx.call(service, handler, input, key=..., idempotency_key=..., placement="spread")`, `ctx.send(..., delay=...)`, `ctx.scoped(scope, limit_key).call(...)` | | Signals | `await ctx.signal(name)`, `ctx.send_signal(invocation_id, name, value)` | | Awakeables | `awk_id, fut = ctx.awakeable()`, then `await fut` | | Promises | `await ctx.promise(name).get()`, `.peek()`, `.resolve(v)`, `.reject(message, code)` | | Other invocations | `await ctx.attach(invocation_id)`, `await ctx.get_output(invocation_id)`, `ctx.continue_as_new(input)` | | Combinators | `await ctx.all([f1, f2])`, `await ctx.race([f1, f2])`; `asyncio.gather` over branches works too | | Streams, logs, traces | `ctx.stream(name, durable=False).append(record)`, `ctx.log.info(msg, attrs)`, `async with ctx.trace.span(name) as s:` | | Artifacts | `ref = ctx.artifact.put(data, "image/png")`, `await ctx.artifact.get(ref)`, `configure_artifacts(base_url, headers)` | | Identity | `ctx.key`, `ctx.invocation_id`, `ctx.attempt`, `ctx.schedule` (a `(name, at_ms)` tuple or `None`), `ctx.random()` | The rules of handler code are the same as in TypeScript, with one addition: 1. Use `ctx.random()`, not the `random` module. 2. Read the clock only inside `ctx.run`. 3. **Do all I/O inside `ctx.run`.** Handler code runs on a deterministic event loop that refuses network I/O on purpose; `ctx.run` functions run on the server’s normal event loop. ## Errors [Section titled “Errors”](#errors) * `TerminalError(message, code=500)` fails the invocation without a retry. * `PauseError(message, code=500)` pauses it until someone resumes it. * Any other exception fails the turn, which is retried with backoff. * Raised inside a `ctx.run` function, `TerminalError` or `RunFailure` is recorded as the step’s result: the function does not run again, and `ctx.run` raises a `TerminalError` with the same code and message on every replay. See [Errors and retries](/docs/develop/errors-retries) for codes and retry policies. ## Serving [Section titled “Serving”](#serving) | Entry point | Where | | --------------------------------------------------------------- | -------------------------------------------------------------------------------- | | `await serve(services, host="127.0.0.1", port=9080, **options)` | The built-in server. `start(...)` does the same and returns the `asyncio.Server` | | `app(services, **options)` | An ASGI application for uvicorn, hypercorn or any ASGI server | | `cairnflow.aws_lambda.lambda_handler(services, **options)` | AWS Lambda (Function URL or API Gateway HTTP API, payload v2) | Unlike `serve()` in TypeScript, these default to request-response mode. For streaming mode pass `protocol_mode="BIDI_STREAM"`: the built-in server then needs the `bidi` extra, and under ASGI it needs a server that speaks cleartext HTTP/2 on the same port as HTTP/1.1, such as hypercorn (uvicorn has no HTTP/2). On Cairnflow Cloud an `https://` endpoint is called in request-response mode unless you register it with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)). Options, as keyword arguments: | Option | Default | Meaning | | --------------------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `identity_keys` | none | Identity keys of your environment; unsigned requests get `401`. Required by Cairnflow Cloud. Without it, a warning is emitted once per process | | `identity_hosts` | none | The public hosts you registered, as `identityHosts` in [serve() options](/docs/develop/services#serve-options) | | `protocol_mode` | `"REQUEST_RESPONSE"` | Or `"BIDI_STREAM"` | | `compression` | `True` | Accept gzip request bodies and compress large responses | | `replay_cache` | `True` (`False` on Lambda) | Keep the journal of running invocations in memory so only new entries are sent | | `max_protocol_version` | `6` | Pin an older protocol version | | `segment_origins`, `value_cache_bytes`, `max_value_bytes`, `max_turn_value_bytes` | as in TypeScript | Downloading large values stored as segments | ## Client [Section titled “Client”](#client) app.py ```python import asyncio import os from cairnflow import InvocationFailed, connect async def main() -> None: c = connect(os.environ["CAIRN_URL"], api_key=os.environ["CAIRN_KEY"]) order = c.object("OrderService", "order-42") print(await order.call("submit", {"amount": 100})) # waits for the result h = await order.send("submit", {"amount": 5}) # returns once the invocation is durable try: print(await h.attach(timeout=60)) except InvocationFailed as e: print("failed:", e.code, e) asyncio.run(main()) ``` * Targets: `c.service(name)`, `c.object(name, key)`, `c.workflow(name, workflow_id)`, `c.invocation(id)`, `c.awakeable(id)`, `c.promise(service, key, name)`, `c.schedules`. Each target takes `scope=` where it applies. * `call(handler, input, ...)` waits; `send(handler, input, ...)` returns an invocation handle with `attach`, `output`, `status`, `signal` and `cancel`. A workflow client adds `run`, `attach` and `output`. * Every call carries a generated `Idempotency-Key`, kept across the client’s own retries; `idempotency_key=None` sends none. The client follows the `leader` of a `503` and waits for the `Retry-After` of a `429`. * Errors: `InvocationFailed` (a `TerminalError`), `InvocationPaused`, `AlreadyInvoked`, `AttachTimeout`, `CairnHttpError`, as in the [typed client](/docs/develop/client). * `connect` options: `headers`, `follow_leader`, `max_attempts` (8), `max_elapsed` (30 s), `attach_wait` (25 s), `timeout`, `connect_timeout` (10 s), `ssl_context`. Durations are in seconds. * `read_stream(base_url, invocation_id, name, offset=0, headers=...)` is an async iterator over a stream’s events, like `readStream` in [Streams, logs and traces](/docs/develop/streams-logs). Schedules use keyword arguments in snake case: ```python await c.schedules.put( "nightly-report", cron="0 2 * * *", time_zone="Europe/Berlin", target={"service": "Report", "handler": "build"}, input={"full": True}, ) ``` ## Not in the Python SDK [Section titled “Not in the Python SDK”](#not-in-the-python-sdk) * The Vercel AI SDK adapter (`chatObject`, `cairnMiddleware`, `cairnTools`, `cairnChatTransport`): it is specific to that TypeScript library. * A typed client generated from your service definitions: the Python client addresses handlers by name. # Server-side schedules > Run a handler on a cron expression or a fixed period, managed by cairnflow. A schedule invokes a handler on a cron expression or every N milliseconds. Cairnflow stores the schedule and fires it; your service does not need a timer process or a cron host. setup.ts ```ts import { connect } from "@cairnflow/sdk/client"; const c = connect({ url: process.env.CAIRN_URL!, apiKey: process.env.CAIRN_KEY! }); await c.schedules.put("nightly-report", { cron: "0 2 * * *", timeZone: "Europe/Berlin", target: { service: "Report", handler: "build" }, input: { full: true }, }); ``` `put` creates or updates. Calling it again with the same definition is a no-op that does not move the next tick, so it is safe to call on every application start. ## Definition [Section titled “Definition”](#definition) Exactly one of `cron` or `everyMs` is required. | Field | Meaning | | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cron` | Five fields: minute, hour, day of month, month, day of week. Supports `*`, `,`, `-`, `/` and month and weekday names. Day of month and day of week combine with OR. No seconds field, no `L`, `W` or `#` | | `timeZone` | IANA time zone for `cron`, default `UTC` | | `everyMs` | Fixed period in ms, aligned to the Unix epoch. Must be at least the server’s minimum period (10 seconds unless your operator changed it) | | `target` | `{ service, handler }`, plus `key` for a virtual object | | `input` | JSON input for each run, at most 64 KiB encoded. Absent: no input | | `overlap` | `"skip"`: if the previous run has not finished, skip this tick (default for targets without a key). `"allow"`: always fire (the only option for keyed or scoped targets) | | `paused` | Create the schedule paused | | `jitterMs` | Spread the fire time by a deterministic offset below this value, kept before the next tick | | `limitKey` | Limit key passed to each run | Schedule names are 1 to 128 characters from `[A-Za-z0-9._-]`, unique within the environment (and scope). ## Managing schedules [Section titled “Managing schedules”](#managing-schedules) ```ts await c.schedules.pause("nightly-report"); // no ticks until resumed await c.schedules.resume("nightly-report"); // next tick counted from now, no catch-up const run = await c.schedules.trigger("nightly-report"); // fire once now await run.attach(); const s = await c.schedules.get("nightly-report"); // undefined if it does not exist const all = await c.schedules.list(); await c.schedules.delete("nightly-report"); // false if it did not exist ``` * **`trigger`** fires once immediately, ignoring `paused` and `overlap`, and does not move the next tick. It returns an invocation handle. Pass `{ idempotencyKey }` to make retries safe: the same key gives the same run. Without one, the client generates a key and keeps it across its own retries. * **`resume`** computes the next tick from the current time. Ticks missed while paused are not fired. * **`delete`** removes the schedule. Runs it already started are not affected. * **Changing a definition** with `put` recomputes the next tick from the current time. * Every method takes an optional `{ scope }` for schedules inside a [scope](/docs/develop/calls#scopes). `get` returns the definition plus: | Field | Meaning | | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | | `nextAt` | Next nominal tick (ms), `null` while paused | | `fireAt` | When `nextAt` will actually fire, after jitter | | `upcoming` | The next 10 ticks | | `last` | Up to 10 recent ticks, newest last: `at`, `id` of the run, `outcome` (`fired` or `skipped`), and sometimes the run’s `status` | | `fired`, `missed`, `skipped` | Counters | `list` returns `{ schedules, partial, missing, missingRanges }`; `partial: true` means some part of the environment could not be read and the list may be incomplete. Managing schedules needs a key that can invoke handlers. The same operations exist over HTTP under `/schedules/{name}` — see the [HTTP API reference](/docs/reference/http-api). ## Inside the handler [Section titled “Inside the handler”](#inside-the-handler) `ctx.schedule` tells a run which tick it belongs to: ```ts const report = service("Report", { async build(ctx, input: { full: boolean }) { const tick = ctx.schedule; // { name, at } or undefined const day = tick ? new Date(tick.at).toISOString().slice(0, 10) : "manual"; return ctx.run(`build ${day}`, () => buildReport(day, input.full)); }, }); ``` * `at` is the nominal tick time in ms (for `trigger`, the time it was triggered), not the moment the run actually started. Use it as the business date of the run. * `ctx.schedule` is `undefined` when the handler was invoked any other way. ## Missed ticks [Section titled “Missed ticks”](#missed-ticks) If cairnflow could not fire for a while (for example, a node was down across several ticks), the schedule fires **once**, for the most recent missed tick. The others are counted in `missed`, not replayed. Make runs that must cover a period read their range from `ctx.schedule.at` and catch up on their own if needed. ## Daylight saving time [Section titled “Daylight saving time”](#daylight-saving-time) Cron times are taken literally in the schedule’s time zone: * A local time that does not exist (clocks jump forward) does **not** fire. * A local time that happens twice (clocks fall back) fires **twice**. Use `timeZone: "UTC"` (the default) for jobs that must run exactly once a day, or avoid local times between 1:00 and 3:00. ## Costs and limits [Section titled “Costs and limits”](#costs-and-limits) * Each tick is at least one durable write, so very short periods add up. Prefer minutes to seconds. * Your environment may cap the number of schedules; creating one more fails with `409`. On Cairnflow Cloud, see [Beta limits](/docs/cloud/limits). # Services and handlers > Declare services, virtual objects and workflows, choose handler types, and serve them with serve(). A **service** is a named set of handlers. Cairnflow discovers the services your endpoint exposes, and calls each handler over HTTP when an invocation needs to run or resume. service.ts ```ts import { type Context, serve, service, TerminalError } from "@cairnflow/sdk"; const orders = service( "OrderService", { async submit(ctx: Context, input: { amount: number }) { if (typeof input?.amount !== "number" || input.amount <= 0) { throw new TerminalError("amount must be a positive number", 400); } const soFar = (await ctx.get("total")) ?? 0; const receipt = await ctx.run("charge", () => chargeCard(input.amount)); ctx.set("total", soFar + input.amount); return { receipt, total: soFar + input.amount }; }, async total(ctx: Context) { return (await ctx.get("total")) ?? 0; }, }, { type: "VIRTUAL_OBJECT", handlerTypes: { submit: "EXCLUSIVE", total: "SHARED" } }, ); await serve({ services: [orders], port: 9080, hostname: "0.0.0.0" }); ``` ## Three kinds of service [Section titled “Three kinds of service”](#three-kinds-of-service) | Declared with | Kind | Context type | State and durable promises | | ----------------------------------------------------- | -------------- | ---------------- | -------------------------- | | `service(name, handlers)` | Service | `ServiceContext` | No | | `service(name, handlers, { type: "VIRTUAL_OBJECT" })` | Virtual object | `Context` | Yes, per key | | `workflow(name, { run, ... })` | Workflow | `Context` | Yes, per workflow ID | A plain service has no key, so there is no object for state to belong to. Its handlers receive a `ServiceContext`: the same as `Context` without `get`, `set`, `clear`, `clearAll`, `getKeys` and `promise`. Calling them is a compile error, and the runtime also rejects them with a terminal error (code `574`). If you need state, declare a virtual object and call it with a key — see [Virtual objects and state](/docs/develop/state). Workflows are covered in [Workflows](/docs/workflows/workflows). ## Handler types [Section titled “Handler types”](#handler-types) | Type | Where | Behaviour | | ----------- | ------------------------------------------------------------------- | -------------------------------------------------------------------- | | `EXCLUSIVE` | Virtual objects (default) | One exclusive handler per key runs at a time; others queue behind it | | `SHARED` | Virtual objects, workflows (default for every handler except `run`) | Runs alongside other invocations on the same key | | `WORKFLOW` | Workflows | Set by `workflow()` on `run`; you do not set it yourself | Set types per handler with `handlerTypes`. A handler you do not list is `EXCLUSIVE` in a virtual object and `SHARED` in a workflow. Shared handlers cannot write state. Type them with `SharedContext` (a `Context` without `set`, `clear` and `clearAll`) so the compiler catches a write; `handlerTypes` does not change the type of `ctx` for you. The runtime enforces the rule too, in virtual objects and workflows alike: a write from a shared handler fails the invocation with a terminal `571` protocol violation. ## Handler signature [Section titled “Handler signature”](#handler-signature) ```ts type Handler = (ctx: Context, input: I) => Promise | O; ``` * **Input** is the request body parsed as JSON. If the body is not valid JSON, the handler receives it as a string. The `I` type is your declaration only: nothing checks the shape at runtime, so validate it and throw `TerminalError` (for example with code `400`) when it is wrong — retrying a bad payload never fixes it. * **Output** is whatever you return, serialized with `JSON.stringify` (`undefined` becomes `null`). * `ctx.key` is the object key (or workflow ID); it is empty in a plain service. `ctx.invocationId` is the invocation’s ID, the same one the HTTP API uses. ## Handler options [Section titled “Handler options”](#handler-options) Options are part of the deployment’s contract. Set them for the whole service with `options`, or per handler with `handlerOptions` (a handler’s options override the service’s): ```ts service("Agent", { think, quick }, { type: "VIRTUAL_OBJECT", options: { inactivityTimeout: 10 * 60_000, retryPolicy: { maxAttempts: 5, onMaxAttempts: "PAUSE", initialInterval: 200 }, }, handlerOptions: { quick: { inactivityTimeout: 5_000 } }, }); ``` | Option | Meaning | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `inactivityTimeout` | How long (ms) the runtime waits on your endpoint while it is silent within one turn — in practice, the longest `ctx.run` closure on `REQUEST_RESPONSE`. Greater than 0, at most one hour. When neither the handler nor the service sets it, the SDK declares 15 minutes | | `retryPolicy` | Backoff and attempt limit — see [Errors and retries](/docs/develop/errors-retries) | | `journalRetention` | How long (ms) to keep the journal of a finished invocation | | `logLevel` | Minimum level kept by `ctx.log` (default `info`) — see [Streams, logs and traces](/docs/develop/streams-logs) | | `trace` | `"runtime"` adds runtime spans (one per turn and per `ctx.run`); default `"off"` | | `logFlushMs` | Flush durable log and stream records on this period (ms) even in the middle of a long `ctx.run`. Each flush is one extra write. `serve()` only | The values are captured when you register a deployment. Changing them means registering a new deployment. ## serve() options [Section titled “serve() options”](#serve-options) `serve()` runs a Node.js HTTP server for your services. It answers both HTTP/1.1 and cleartext HTTP/2 on one port. | Option | Default | Meaning | | ------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `services` | — | The service definitions to expose | | `port` | `9080` | Port to listen on | | `hostname` | `"127.0.0.1"` | Address to bind. Set `"0.0.0.0"` in a container, or nothing outside the machine can reach it | | `identityKeys` | none | Identity keys (`publickeyv1_...`) of your environment. When set, every request must carry a valid signature from one of them, or it is refused with `401`. Required by Cairnflow Cloud | | `identityHosts` | none | The public hosts you registered. The signature covers the request body and the host it was sent to; when this is set, the signed host must be one of these. When unset, it is compared with the request’s own `Host` header. Set it when a proxy in front of your service rewrites `Host` | | `protocolMode` | `"BIDI_STREAM"` | Streaming over HTTP/2. Set `"REQUEST_RESPONSE"` if a proxy between cairnflow and your service only speaks HTTP/1.1 | | `compression` | `true` | Accept gzip-compressed request bodies and compress responses when asked | | `replayCache` | `true` | Keep the journal of running invocations in memory so cairnflow only sends new entries each turn. `{ maxBytes, ttlMs }` tunes it (defaults 64 MiB, 15 minutes) | | `valueCacheBytes` | 64 MiB | Memory for segments of large values ([Payload](/docs/cloud/limits#payload)) the SDK has already downloaded. `0` keeps none | | `maxValueBytes` | 64 MiB | Largest single value the SDK assembles from segments. A larger one fails the turn before anything is downloaded | | `maxTurnValueBytes` | 256 MiB | Most bytes of segmented values one turn may assemble | | `segmentOrigins` | any `http(s)` origin | Origins the SDK may download segments from. Leaving it unset is safe only with `identityKeys`, which signs the download URLs | Each request body is capped at 256 MiB after decompression; a larger one gets `413`. If cairnflow speaks a newer protocol version than this SDK build supports (for example after you rolled the service back to an older SDK without registering it again), the endpoint answers `415` and the turn is retried; register the deployment again. `serve()` resolves to `{ port, url, close() }`. `close()` stops accepting connections and lets open invocation streams finish. To rotate identity keys, add the new key to `identityKeys` before it becomes active, and remove the old one after. Note On platforms that only accept a `(Request) => Promise` function — Vercel, Cloudflare Workers, AWS Lambda — use `fetchHandler` instead of `serve()`. See [Serverless](/docs/workflows/serverless). ## Registering [Section titled “Registering”](#registering) Cairnflow reads your services from the endpoint’s discovery route. Deploy the service, then register its base URL: ```sh curl -X POST $CAIRN_URL/deployments \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"uri":"https://your-service.example.com"}' ``` Each registration creates a new, immutable deployment and makes it the current revision of every service in it. Invocations already running stay on the deployment they started on — see [Deploying new versions](/docs/develop/versioning). `GET /services` lists the handlers you can call and their effective types. ## Rules of handler code [Section titled “Rules of handler code”](#rules-of-handler-code) The handler body runs again every time an invocation is replayed. Put side effects in [durable steps](/docs/develop/durable-steps), do not read the clock or `Math.random()` outside one, and do not catch and swallow errors around `ctx` commands. See [Concepts](/docs/concepts). # Virtual objects and state > Keyed objects with durable state and one writer at a time. A **virtual object** is a service whose invocations are addressed by a **key** — a chat ID, a user ID, an order number. Each key has its own state, and two exclusive handlers on the same key never run at the same time. You never create an object: calling a handler with a new key is enough. counter.ts ```ts import { type Context, serve, service, type SharedContext } from "@cairnflow/sdk"; const counter = service( "Counter", { async add(ctx: Context, n: number) { const total = ((await ctx.get("total")) ?? 0) + n; ctx.set("total", total); return total; }, async reset(ctx: Context) { ctx.clearAll(); }, async read(ctx: SharedContext) { return (await ctx.get("total")) ?? 0; }, }, { type: "VIRTUAL_OBJECT", handlerTypes: { read: "SHARED" } }, ); await serve({ services: [counter], port: 9080, hostname: "0.0.0.0" }); ``` Call it with a key: ```sh curl -X POST "$CAIRN_URL/invoke/Counter/add?key=user-42" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" -d '5' ``` `ctx.key` inside the handler is `"user-42"`. ## State API [Section titled “State API”](#state-api) | Call | Returns | Notes | | ------------------------- | ----------------------- | ------------------------------------------ | | `ctx.get(name)` | `T \| null` (awaitable) | `null` means the entry does not exist | | `ctx.set(name, value)` | `void` | Does not wait. The value is stored as JSON | | `ctx.clear(name)` | `void` | Removes one entry | | `ctx.clearAll()` | `void` | Removes every entry of this object | | `ctx.getKeys()` | `string[]` (awaitable) | Names of the object’s state entries | State reads are recorded in the journal like every other command, so a replay sees the value that was read the first time, not whatever the state holds now. Caution `null` from `ctx.get` means **missing**, which is different from an empty value. Setting a key to `""` or `0` and reading it back gives you `""` or `0`, not `null` — keep the `?? default` pattern for “not set yet” only. Values go through `JSON.stringify`: store plain data, not class instances, `Map`, `Set` or `Date` objects. A large value, such as a long chat history, is stored as segments outside the journal, and your code still reads and writes the whole value; see [Payload](/docs/cloud/limits#payload) for the limits on Cairnflow Cloud. Do not store an [artifact](/docs/develop/artifacts) reference in state to read in a later invocation: `ctx.artifact.get` reads only the artifacts of the current invocation. ## One writer per key [Section titled “One writer per key”](#one-writer-per-key) Exclusive handlers on one key form a queue. While an invocation holds the key — including while it sleeps, waits for a call, or waits for a promise — the next exclusive invocation on that key waits behind it. That is what makes a read-modify-write like `add` above safe without locks or transactions. Two consequences: * **A long wait blocks the key.** An exclusive handler that sleeps for a day holds the key for a day. If other work on the same key must keep flowing, move the waiting part into a separate invocation (a workflow, or a call to another object) and keep the exclusive handler short. * **Calling `/invoke` on a busy key can return `202 waiting`.** The invocation is accepted and durable; it runs when the key frees up. Fetch the result later with `POST /invocations/{id}/attach`, or use the [typed client](/docs/develop/client), which does that for you. ## Shared handlers [Section titled “Shared handlers”](#shared-handlers) A `SHARED` handler runs without waiting in the key’s queue, so it can answer while an exclusive handler is suspended. Use it for reads: status pages, progress, “what is in the cart”. Shared handlers only read state. They run alongside the exclusive ones, and a read-modify-write from both sides would lose updates, so the runtime rejects `set`, `clear` and `clearAll` from a shared handler with a terminal `571` protocol violation. Type shared handlers with `SharedContext`, which has no `set`, `clear` or `clearAll`, to catch the mistake at compile time. Move writes to an exclusive handler. ## Keys and scopes [Section titled “Keys and scopes”](#keys-and-scopes) * A key can be any string your callers agree on. Keep it stable: a different key is a different object with empty state. * A call made inside a [scope](/docs/develop/calls#scopes) addresses a different object from the same call without a scope: `Cart/a` in scope `bob` and `Cart/a` with no scope have separate state and separate queues. ## Durable promises live here too [Section titled “Durable promises live here too”](#durable-promises-live-here-too) Virtual objects and workflows can also use `ctx.promise(name)`: a named, durable value that another handler or an outside system completes. See [Durable promises, signals and awakeables](/docs/develop/promises-signals). # Streams, logs and traces > Stream tokens and progress to a UI, write logs, and record spans with token counts. 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 [Section titled “Streams”](#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 [Section titled “Ephemeral or durable”](#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 [Section titled “Reading a stream”](#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=` 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 import { readStream } from "@cairnflow/sdk/client"; 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 [Section titled “Logs”](#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=`, or add `follow=1` to receive new records as Server-Sent Events. Filters: `level`, `attempt`, `from`, `limit` (default 1000). ## Traces [Section titled “Traces”](#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. # Timers and sleeping > Durable sleeps, deadlines, and delayed calls. `ctx.sleep(ms)` pauses an invocation for a duration. The timer is stored durably; nothing holds a process, a connection or memory while it waits, so sleeping for a week costs the same as sleeping for a second. ```ts await ctx.sleep(24 * 3600_000); // one day ``` ```ts sleep(ms: number, name?: string): DurableFuture; ``` * The wake-up time is **absolute**: it is computed once, from the clock at the moment the sleep is first recorded, and stored in the journal. A replay does not start the timer again. * `name` (default `"sleep"`) labels the entry in the journal and the console. * When the sleep is not over yet, the turn ends and the invocation is **suspended**. It resumes when the timer fires, on whichever node owns it at that time. * A timer fires at or shortly after its due time. Do not rely on millisecond precision. ## Deadlines with ctx.race [Section titled “Deadlines with ctx.race”](#deadlines-with-ctxrace) `ctx.sleep` returns a `DurableFuture`, so it combines with calls, signals, promises and awakeables. `ctx.race` resolves with whichever finished first **in journal order**, so every replay picks the same winner. ```ts const approval = await ctx.race([ ctx.signal<{ by: string }>("approve"), ctx.sleep(24 * 3600_000), ]); if (approval === undefined) { throw new TerminalError("nobody approved within 24 hours", 408); } ``` A sleep resolves to `undefined`, which is how you tell that the deadline won. To tell two futures apart when their values could look alike, create both first, race them, then compare their positions in the journal with `order()`: ```ts const answer = ctx.promise("approval").get(); const deadline = ctx.sleep(30 * 60_000, "approval deadline"); await ctx.race([answer, deadline]); if (answer.order() > deadline.order()) { throw new TerminalError("approval timed out", 408); } const decision = await answer; ``` Do not use `ready()` for this: a late answer still lands in the journal, and from then on `ready()` returns `true` on every replay, so the same code would take a different branch. ## Waiting for many things [Section titled “Waiting for many things”](#waiting-for-many-things) `ctx.all([...])` waits for every future, like `Promise.all`, but suspends durably until all of them are done. If one of them failed, it throws that failure. ```ts const [a, b] = await ctx.all([ ctx.call("Search", "query", "a"), ctx.call("Search", "query", "b"), ]); ``` ## Delayed calls [Section titled “Delayed calls”](#delayed-calls) To run another handler later instead of waiting yourself, send it with a delay. The handler that sends it does not wait and does not hold a key: ```ts ctx.send("Reminders", "remind", { userId }, { delay: 3 * 24 * 3600_000 }); ``` Like a sleep, the due time is computed once and recorded. Delays are only available from inside a handler; the client has no delayed send. For recurring work, use [server-side schedules](/docs/develop/schedules). ## Reading the clock [Section titled “Reading the clock”](#reading-the-clock) Do not call `Date.now()` in the handler body: a replay would see a different time and could take a different path. Read it inside a step: ```ts const startedAt = await ctx.run("now", () => Date.now()); ``` ## Gotchas [Section titled “Gotchas”](#gotchas) * **A losing sleep still fires.** In a `race`, the sleep that loses keeps its timer and costs one durable write when it fires. Use long deadlines; do not poll with a loop of short sleeps. * **Sleeping in an exclusive handler holds the key.** Other exclusive calls on the same virtual object wait until the sleep is over. Put long waits in a workflow or a plain service when the key must stay available. * **Long loops grow the journal.** A loop that sleeps and polls forever adds entries every round. Restart it with a fresh journal from time to time with `ctx.continueAsNew(state)` — see [Deploying new versions](/docs/develop/versioning#long-running-loops). * Your environment may limit the number of pending timers per invocation; on Cairnflow Cloud, see [Beta limits](/docs/cloud/limits). # Deploying new versions > Change handler code without breaking invocations that are already running. Invocations can run for minutes or months, so a deploy usually happens while some are in flight. Cairnflow replays each of them against code, and the code must still match what the journal recorded. This page covers how deployments are pinned, what counts as a breaking change, and how to recover when something breaks. ## Invocations are pinned to their deployment [Section titled “Invocations are pinned to their deployment”](#invocations-are-pinned-to-their-deployment) Registering an endpoint creates a new, immutable **deployment** and makes it the current revision of every service it exposes. * **New invocations** go to the current revision. * **Running invocations stay on the deployment they started on**, for every later turn — even after the revision has moved on. A deploy never drags in-flight work onto new code by itself. The safest way to ship a change is therefore to give each version its own URL: 1. Deploy the new code at a new URL (a new container, a versioned path, a new function alias). 2. Register it: `POST /deployments {"uri": ""}`. New invocations use it from now on. 3. Keep the old version running until no invocation is pinned to it. `GET /deployments/{id}` reports `pinnedInvocations`. 4. Remove the old deployment with `DELETE /deployments/{id}`. It answers `409` while the deployment is still a current revision or still has invocations pinned to it. How you run several versions side by side depends on your platform — see [Deployments](/docs/cloud/deployments). ## What breaks a running invocation [Section titled “What breaks a running invocation”](#what-breaks-a-running-invocation) If you replace code **in place** (same URL), in-flight invocations replay against the new code. On replay, the SDK checks each command against the journal: its **kind** (a step, a sleep, a call, a state read…), its **name** (for `ctx.run`, the step name), and every other field it recorded, such as a call’s target service, handler, key and input. When they differ, the invocation stops `paused` with code `570` (journal mismatch). It does not run the wrong code, and it does not retry on its own: a retry would only hit the same mismatch. | Change | Effect on an invocation already past that point | | ----------------------------------------------------------------------------- | -------------------------------------------------------- | | Rename a `ctx.run` step | Pauses with `570` when it reaches the step | | Add, remove or reorder `ctx` commands before the point it reached | Pauses with `570` where the commands stop lining up | | Change a call’s target service, handler, key or input | Pauses with `570` at that call | | Change the body of a step that already has a result | Nothing: the recorded result is used | | Change the value written by `ctx.set`, a sleep’s duration or a send’s `delay` | Nothing: these values are recorded once and not compared | | Add code after the last command it reached | Nothing: it runs the new code from there | Not every semantic change is caught: what a recorded step returned is never checked against the new code. When in doubt, deploy at a new URL. Keep step names stable, and keep configuration (model IDs, prompt versions) out of them — put it in [span attributes](/docs/develop/streams-logs#traces). ## Check before you switch [Section titled “Check before you switch”](#check-before-you-switch) Replays can be tested without running any of the new code’s side effects. Both checks are read-only: no closure of the new code runs and nothing is written. ```sh # Replay a sample of unfinished invocations of a service against a deployment. curl -X POST "$CAIRN_URL/deployments/$NEW_DP/replay-check?service=OrderService&sample=20" \ -H "authorization: Bearer $CAIRN_KEY" # -> {"checked": ..., "matched": ..., "failures": ..., ...} # Replay one invocation against a deployment. curl -X POST "$CAIRN_URL/invocations/$ID/replay?deployment=$NEW_DP" \ -H "authorization: Bearer $CAIRN_KEY" # -> {"matches": true, "upto": 7} or {"matches": false, "mismatchAt": ..., "expected": ..., "got": ...} ``` To register a deployment without making it current, add `?activate=false`, run the checks, then move each service yourself: ```sh curl -X POST "$CAIRN_URL/deployments?activate=false" \ -H "authorization: Bearer $CAIRN_KEY" -H "content-type: application/json" \ -d '{"uri":"https://v2.example.com"}' curl -X PUT "$CAIRN_URL/services/OrderService/revision" \ -H "authorization: Bearer $CAIRN_KEY" -H "content-type: application/json" \ -d '{"deployment": "dp_new", "expect": "dp_old"}' ``` `expect` makes the move conditional: it only happens if the current revision is still `dp_old`, so two people rolling back at once cannot both win. The same call rolls back to an older deployment. ## Recovering a paused invocation [Section titled “Recovering a paused invocation”](#recovering-a-paused-invocation) An invocation paused with `570` can continue in two ways: * **Restore the code it expects** at the URL it is pinned to (for example, bring the old step name back), then `POST /invocations/{id}/resume`. * **Move it to a deployment whose code matches** with `POST /invocations/{id}/migrate?deployment=`. Migrate replays the invocation on the target first and refuses (`409`, with the report) if it does not match. `&force=true` skips that check. Migrate is also the way to move a healthy invocation onto newer code on purpose. ## Long-running loops [Section titled “Long-running loops”](#long-running-loops) An agent loop or a poller that runs forever keeps growing its journal, and every replay walks the whole journal. `ctx.continueAsNew(input)` ends the current invocation and starts a new one for the same target, with an empty journal and `input` as its input: ```ts async loop(ctx: Context, s: { step: number; done: boolean }) { for (let i = 0; i < 50 && !s.done; i++) { s = await ctx.run(`step ${s.step}`, () => next(s)); } if (!s.done) ctx.continueAsNew(s); return s; } ``` * The line after `continueAsNew` never runs. * The new invocation runs on the service’s **current revision**, which makes it a natural upgrade point for long-lived loops. * Callers waiting on the old invocation, and its idempotency key, move to the new one; they receive the final result of the chain. The old invocation ends with `{"continuedAsNew": ""}`. ## Handler options are part of the deployment [Section titled “Handler options are part of the deployment”](#handler-options-are-part-of-the-deployment) Retry policies, timeouts and other handler options are captured when a deployment is registered. Changing them means registering a new deployment; invocations already pinned to the old one keep the old options. The same goes for the SDK’s protocol version. If you roll a service back to an older SDK build at the same URL without registering it again, cairnflow may speak a newer protocol version than that build supports. The endpoint then answers `415` instead of running the handler, and the turn is retried under the retry policy. Register the deployment again. # Human approval > Make an agent wait for a person before a tool runs, and answer from the chat, an admin page or a webhook. Some tools should not run on the model’s word alone: a refund, an email to a customer, a database change. With `cairnTools(ctx, tools, { approve })` such a tool waits on a **durable promise** until someone answers. The invocation is suspended in storage while it waits, so it can wait minutes or days without holding a process, a connection or memory. If the answer is no, the tool never runs. ## Declare which tools need approval [Section titled “Declare which tools need approval”](#declare-which-tools-need-approval) agent.ts ```ts import { cairnTools } from "@cairnflow/sdk"; // A list of tool names… const guarded = cairnTools(ctx, tools, { approve: ["refund"] }); // …or a function of the tool name and its input. const byAmount = cairnTools(ctx, tools, { approve: (name, input) => name === "refund" && (input as { amount: number }).amount > 100, }); ``` Approval needs `ctx.promise`, so the tools must run in a virtual object or a workflow. A `chatObject` is a virtual object. In a plain service, a tool that needs approval fails with a terminal error instead of waiting. ## What happens during a turn [Section titled “What happens during a turn”](#what-happens-during-a-turn) 1. The model calls `refund`. `cairnTools` records the request in a step and sends a `tool-approval-request` chunk to the UI. The tool part in `useChat` gets the state `approval-requested` and an `approval.id`. 2. The tool waits on the promise named by that approval ID. The turn suspends. 3. Someone resolves the promise with `{ approved, reason? }`. 4. Approved: the tool runs as a durable step and the model sees its result. Rejected: the tool does not run, the UI part becomes `output-denied`, and the model receives `{ denied: true, reason }` as the tool result, so it can tell the user. The saved history records the decision on the tool part (`approval: { id, approved, reason }`), so a reloaded chat shows the same thing the live one did. The approval ID is derived from the tool call: `approvalIdOf(toolCallId)` returns it, and it is also the `approval.id` on the UI part. ## Answer from the chat page [Section titled “Answer from the chat page”](#answer-from-the-chat-page) chat.tsx ```tsx const transport = cairnChatTransport({ baseUrl: "/cairn", service: "Chat" }); // In your message renderer: if (part.type === "tool-refund" && part.state === "approval-requested") { const id = part.approval.id; return ( <> ); } ``` Use `transport.approve`, not the AI SDK’s `addToolApprovalResponse`. The latter belongs to the AI SDK’s own `needsApproval` flow, which ends the turn and sends the whole chat again. Here the invocation stays alive, suspended on the promise, and `approve` resolves it; every page connected to the chat sees the tool run. ## Answer from somewhere else [Section titled “Answer from somewhere else”](#answer-from-somewhere-else) The approver does not have to be the person chatting. `transport.approve` is one HTTP call, and an admin page, a Slack interaction webhook or a script can make the same call with an API key: ```sh curl -X POST "$CAIRN_URL/promises/Chat/$CHAT_ID/$APPROVAL_ID/resolve" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"approved": true}' ``` slack-webhook.ts ```ts // After verifying the Slack request and reading chatId and approvalId from your button's value: await fetch(`${process.env.CAIRN_URL}/promises/Chat/${chatId}/${approvalId}/resolve`, { method: "POST", headers: { authorization: `Bearer ${process.env.CAIRN_KEY}`, "content-type": "application/json", }, body: JSON.stringify({ approved: false, reason: "Rejected in Slack" }), }); ``` The route is `POST /promises/{service}/{key}/{approvalId}/resolve`, where `{key}` is the chat ID. An **Invoke only** key is enough. With a scope, prefix the path with `/scope/{scope}`. Properties you can rely on: * **Answering twice is a no-op, not an error.** A promise completes once; a second resolve reports that it did not complete anything (`completed: false`). Webhook retries are safe without an idempotency key. `transport.approve` checks that case: resending the same decision succeeds, and a different decision (another tab or approver answered first) throws. * **An answer that arrives early is not lost.** The promise is durable; a waiter that reaches it later reads the result. * **Reject by resolving with `approved: false`.** That is the path the adapter turns into `output-denied` and a `{ denied: true }` tool result. To check whether a request was answered: `GET /promises/Chat/{chatId}/{approvalId}`. ## Pending requests survive a reload [Section titled “Pending requests survive a reload”](#pending-requests-survive-a-reload) The `ui` stream is temporary: it lives in memory and only promises to hold the step that is running. A turn that has been waiting for approval for more than about a minute releases what it streamed, and a change of leader loses it entirely. So a page opened later cannot rely on the stream to show the approval buttons. `cairnTools` therefore also keeps each pending request in the object’s state until it is answered, and the `messages` handler of `chatObject` returns it: while a turn waits, the history ends with an assistant message (its ID is the running invocation’s ID) carrying the tool part in state `approval-requested`. Initialise `useChat` with `await transport.messages(chatId)` and the buttons are there after a reload, on another device, or a week later. ## List what is waiting [Section titled “List what is waiting”](#list-what-is-waiting) For an admin page that lists open approvals across chats, use the [query API](/docs/query). Find chats with a running turn, then read each one’s pending requests: ```sql SELECT key, id, created_at FROM sys_invocation WHERE service = 'Chat' AND handler = 'send' AND class = 'active' ORDER BY created_at LIMIT 100 ``` ```sql SELECT name, waiter_id FROM sys_promise_waiter WHERE service = 'Chat' AND key = 'chat-42' ``` `sys_promise_waiter` lists promises that someone is waiting on and that are not completed yet. `transport.messages(chatId)` gives the same requests with the tool name and input, ready to render. ## Waiting costs nothing [Section titled “Waiting costs nothing”](#waiting-costs-nothing) While it waits, the invocation runs no code and holds no connection. Nothing is billed as compute. Each approval adds one journal entry and one durable wait to the turn. ## Next [Section titled “Next”](#next) * [Streaming to the browser](/docs/agents/streaming) * [Durable promises and signals](/docs/develop/promises-signals) # Agents without chatObject > Build your own agent handler with cairnMiddleware and cairnTools, and the contract the chat transport expects. `chatObject` covers the common case: one chat per key, history in state, the browser on `useChat`. When you need something else (history in your own database, several agents behind one chat, an agent that runs without a browser) use the two building blocks directly: * `cairnMiddleware(ctx)` makes each model call a durable step and streams its UI chunks. * `cairnTools(ctx, tools, opts?)` makes each tool call a durable step, with optional approval. Both work in any handler that has a `ctx`. Approval needs `ctx.promise`, so it needs a virtual object or a workflow. ## A background agent in a workflow [Section titled “A background agent in a workflow”](#a-background-agent-in-a-workflow) No browser, no chat: a workflow runs once per ID, survives crashes and deploys, and can wait for an approval before publishing. research.ts ```ts import { stepCountIs, streamText, wrapLanguageModel } from "ai"; import { anthropic } from "@ai-sdk/anthropic"; import { cairnMiddleware, cairnOnError, cairnTools, workflow } from "@cairnflow/sdk"; const research = workflow("Research", { run: async (ctx, topic: string) => { const result = streamText({ model: wrapLanguageModel({ model: anthropic("claude-sonnet-5-5"), middleware: cairnMiddleware(ctx), }), tools: cairnTools(ctx, tools, { approve: ["publish"] }), prompt: `Research ${topic} and publish a short brief.`, stopWhen: stepCountIs(10), onError: cairnOnError(ctx), }); for await (const _ of result.fullStream) { // Drain the stream; every model and tool call is journaled as it completes. } return await result.text; }, }); ``` Start it with `POST /invoke/Research/run/send?key=`, and answer the approval with `POST /promises/Research///resolve`. The approval ID is the `approvalIdOf(toolCallId)` of the tool call; see [Human approval](/docs/agents/approvals). ## Your own chat object [Section titled “Your own chat object”](#your-own-chat-object) The browser transport does not require `chatObject`. It needs a virtual object, keyed by chat ID, with three handlers that keep this contract: | Handler | Type | Receives | Must | | -------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | | `send` (or the name in the transport’s `handler` option) | exclusive | A JSON body: `chatId`, `trigger`, and `message` (the new user message) or `messages` (with `sendHistory: true`); optional `messageId`, `after`, `body` | Write the turn’s UI chunks to the `ui` stream (`cairnMiddleware` and `cairnTools` do it). While it runs, make `active` return its invocation ID | | `active` | shared | nothing | Return the invocation ID of the running `send`, or `null` | | `messages` | shared | nothing | Return the history as `UIMessage[]` | Details the transport relies on: * It sends to `POST /invoke/{service}/{handler}/send?key=` and reads the invocation ID from the answer, then reads `GET /invocations/{id}/streams/ui`. * It emits its own `start` chunk with `messageId` set to the invocation ID, and its own `finish` chunk; `start` and `finish` records on the stream are ignored. Use the invocation ID as the assistant message ID in the history you save, so the saved message matches the one the page built. * `transport.approve(chatId, approvalId, …)` resolves the promise `approvalId` on the object `{service}/{chatId}`. Tool approvals must therefore wait on the same object that received the message, which is what `cairnTools(ctx, …)` inside `send` does. ### Example: also keep the transcript in your database [Section titled “Example: also keep the transcript in your database”](#example-also-keep-the-transcript-in-your-database) support.ts ```ts import { convertToModelMessages, stepCountIs, streamText, wrapLanguageModel, type UIMessage } from "ai"; import { anthropic } from "@ai-sdk/anthropic"; import { cairnMiddleware, cairnOnError, cairnTools, service, TerminalError, type ChatRequest, type Context, } from "@cairnflow/sdk"; const support = service( "Support", { async send(ctx: Context, req: ChatRequest) { ctx.set("active", ctx.invocationId); try { const saved = (await ctx.get("messages")) ?? []; const history = req.message === undefined ? saved : [...saved, req.message as UIMessage]; const result = streamText({ model: wrapLanguageModel({ model: anthropic("claude-sonnet-5-5"), middleware: cairnMiddleware(ctx), }), tools: cairnTools(ctx, tools, { approve: ["refund"] }), messages: await convertToModelMessages(history), stopWhen: stepCountIs(8), onError: cairnOnError(ctx), }); let final: UIMessage[] = history; for await (const _ of result.toUIMessageStream({ originalMessages: history, generateMessageId: () => ctx.invocationId, onFinish: (e) => { final = e.messages; }, })) { // The chunks already went to the `ui` stream from the middleware and tools. } ctx.set("messages", final); // A side effect, so it goes through ctx.run. await ctx.run("save-transcript", () => db.transcripts.save(ctx.key, final)); ctx.clear("active"); return { id: ctx.invocationId }; } catch (e) { // Clear only on a terminal failure. A transient error is retried from the journal, // and a state change here would make the retry's journal differ. if (e instanceof TerminalError) ctx.clear("active"); throw e; } }, async active(ctx: Context) { return (await ctx.get("active")) ?? null; }, async messages(ctx: Context) { return (await ctx.get("messages")) ?? []; }, }, { type: "VIRTUAL_OBJECT", handlerTypes: { send: "EXCLUSIVE", active: "SHARED", messages: "SHARED" }, }, ); ``` In the browser: `cairnChatTransport({ baseUrl: "/cairn", service: "Support" })`. ### What `chatObject` does that this example does not [Section titled “What chatObject does that this example does not”](#what-chatobject-does-that-this-example-does-not) If you write your own object, decide whether you need these; `chatObject` has them built in. * **Regenerate.** On `trigger: "regenerate-message"` it cuts the saved history at `messageId` before the turn. * **Stale history.** It compares `after` (the ID of the message before the new one on the page) with the saved history, and refuses the turn when the page is behind. * **History during a turn.** It keeps the turn’s input in state as soon as the turn starts, so `messages` includes the user message while the answer is still being generated. * **Pending approvals after a reload.** `cairnTools` keeps each pending request in the object’s state under a key starting with `pending-approval/` until it is answered. `chatObject`’s `messages` turns those into an assistant message with tool parts in state `approval-requested`. Without that, a page opened during a long wait shows no approval buttons. * **Approval decisions in history.** The history that `toUIMessageStream` builds shows a rejected tool as an ordinary result (`{ denied: true }`). `chatObject` marks such parts `output-denied` and records the decision on each approved or rejected part, so a reloaded chat matches what the live page showed. ## Rules that still apply [Section titled “Rules that still apply”](#rules-that-still-apply) * Model calls go through `cairnMiddleware`, side effects through `cairnTools` or `ctx.run`. An unwrapped call runs again on every replay. * No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`; use `ctx.invocationId` where you need a stable ID. * Ignore `Suspend` in any `onError` you write (`cairnOnError(ctx)` does); it is not an error of your code. * Do not change state in a `catch` for errors that are not `TerminalError`. ## Next [Section titled “Next”](#next) * [Vercel AI SDK](/docs/agents/vercel-ai-sdk) * [Durable steps](/docs/develop/durable-steps) * [Services, objects and workflows](/docs/develop/services) # Streaming to the browser > How tokens reach the page over SSE, what happens on reload, stop() and failures, and the limits of temporary streams. An agent turn writes UI chunks to a stream of its invocation while it runs. The browser reads that stream over Server-Sent Events. `cairnMiddleware` and `cairnTools` do the writing and `cairnChatTransport` does the reading, so with `chatObject` and `useChat` you write no streaming code. This page explains what happens underneath, so you can reason about reloads, stops and failures. ## The path of a message [Section titled “The path of a message”](#the-path-of-a-message) 1. `sendMessage` posts the last message to `POST /invoke/Chat/send/send?key=`. The answer comes as soon as the invocation is durable and carries its ID. The transport attaches an `Idempotency-Key`, so a resend after a network error points at the same invocation instead of starting a second turn. 2. The transport opens `GET /invocations/{id}/streams/ui` with `accept: text/event-stream`. 3. In the handler, the middleware runs the model call inside `ctx.run`. Each part of the model stream is translated into a UI chunk (`start-step`, `text-delta`, `tool-input-available`, …) and appended to the `ui` stream as it arrives. In streaming mode the page sees tokens while the step is still running; in request-response mode it sees them when the step finishes (see below). 4. Tool calls append their input, approval request, output or error the same way. 5. When the turn ends, the stream is sealed; the SSE connection receives `end`, and the transport emits `finish`. Chunks are appended only inside the step that produces them. When a handler replays, the model and tool results come from the journal and nothing is sent to the stream a second time. Live tokens need the streaming transport Chunks reach the page as they are generated only when your environment calls the service in streaming mode (`BIDI_STREAM`). On Cairnflow Cloud an `https://` endpoint is called in request-response mode unless you register it with `"transport": "declared"`, which works only when HTTP/2 reaches your app. In request-response mode the chunks of a step travel with the step’s result and reach the page together when the step finishes; the chat still works, without the typing effect. See [Deployments](/docs/cloud/deployments#transport) and the comparison in [Vercel AI SDK](/docs/agents/vercel-ai-sdk#streaming-versus-request-response). ## Reload and reconnect [Section titled “Reload and reconnect”](#reload-and-reconnect) With `resume: true`, `useChat` calls the transport’s `reconnectToStream` when the page loads. The transport asks the object’s `active` handler whether a turn is running; if so, it reads that invocation’s stream from the beginning, and the first chunk resets the message being shown. ```tsx // `initial` comes from `await transport.messages(chatId)` when the page is rendered. const { messages } = useChat({ id: chatId, transport, messages: initial, resume: true, }); ``` `messages` already includes the user message of the running turn, so the page shows the question and the answer streams in under it. The same works in a second tab or on another device. The reader also reconnects by itself when an SSE connection ends: a connection lives at most ten minutes, and the node serving the stream can change. If the stream turns out to be a new one (the step is being generated again), the transport sends a `reset-step` chunk first: the UI drops the partial step and shows it again from the start. Note In request-response mode the running turn becomes visible to `active` only after its first durable step. A reload during the very first model call finds nothing to reconnect to; the answer appears in `messages` when the turn ends. ## Stop [Section titled “Stop”](#stop) `stop()` in `useChat` stops reading and sends `POST /invocations/{id}/cancel?mode=signal`, a **cooperative** cancel. An Invoke only key may send it. * In streaming mode (`BIDI_STREAM`) the cancel reaches the running turn at once. The model or tool call in progress receives an `AbortSignal`, so the provider request is cut and stops spending tokens. No later model or tool step runs. * The model call that was cut returns **the text generated so far** as its result. The turn ends `completed`, and the saved history holds exactly what the user saw, like a “Stop” button in a hosted chat app. * In request-response mode there is no channel into a running step: the step finishes, and the cancel takes effect from the next step. A tool that should stop mid-way reads the signal from the AI SDK’s `execute` options: ```ts const tools = { research: tool({ description: "Search the web", inputSchema: z.object({ query: z.string() }), execute: async ({ query }, { abortSignal }) => search(query, { signal: abortSignal }), }), }; ``` See [Cancellation](/docs/develop/cancellation) for the hard cancel used from the console. ## When something dies mid-step [Section titled “When something dies mid-step”](#when-something-dies-mid-step) | What dies | What the page sees | | --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Your service process (deploy, crash, out of memory) | Cairnflow retries the turn. The old attempt is marked superseded on the stream, the UI receives `reset-step`, and the step streams again from the start. The model call of that step **is** made again: it had no journaled result yet | | The node leading the chat’s range | The temporary stream is lost with it. The UI receives `reset-step` and the new leader runs the unfinished step again. Completed steps do not run again | | A step completed just before the failure | The new run has nothing left to stream for it. The transport closes cleanly, the UI keeps what it received, and the full history is in `messages` | ## Temporary streams: what to expect [Section titled “Temporary streams: what to expect”](#temporary-streams-what-to-expect) The `ui` stream is a **temporary** stream: it lives in the memory of the node that leads the chat’s range, and writing to it costs no storage requests. That is what makes token streaming cheap, and it comes with limits: * **It holds the running step, not the whole history.** Each stream keeps up to 1 MiB; older records are overwritten, and a reader that falls that far behind sees a gap. * **It disappears after the turn.** A sealed stream can be read for about 60 seconds, then it is gone. Read finished turns from `messages`. * **A long wait releases it.** A turn suspended on an approval that streams nothing for about a minute releases its records. See [Human approval](/docs/agents/approvals) for how pending requests are recovered from `messages`. * **Only the leader serves it.** Another node answers `503` and names the leader; the transport follows it once. * **Each invocation has at most 16 streams.** An invocation never fails because of a stream: records over a limit are dropped. * **The console does not show temporary streams.** Its **Streams** tab lists durable streams only. The model and tool results are in the **Journal** tab. * **Open connections are capped** per environment and node; see [Limits](/docs/cloud/limits). A reader over the cap receives `429` and retries. If you need records that survive a node failure, write them to a durable stream (`ctx.stream(name, { durable: true })`) in your own code; see [Streams and logs](/docs/develop/streams-logs). ## SSE events [Section titled “SSE events”](#sse-events) You only need these if you read streams without the transport, for example with `readStream` from the SDK client. | Event | Data | | ------------ | ------------------------------------------------------------------------------------------------------------------------ | | `record` | `{offset, durable, step, attempt, k, data}`; the SSE `id` is the offset, `data` is the JSON the handler appended | | `gap` | `{offset, dropped}`: records dropped over a cap, or overwritten because the reader fell too far behind | | `superseded` | `{offset, step, attempt}`: that attempt of that step was replaced; its earlier records belong to an abandoned branch | | `end` | `{next}`: the stream is sealed and fully read; the server closes the connection | | `moved` | `{leader}`: the node stopped leading the range; ask the new leader | | `reset` | `{}`: follows `moved` for a temporary stream; what was shown is gone, and a new attempt will stream again from the start | Resume after a dropped connection with `?from=` or the `Last-Event-ID` header. The server sends a keep-alive comment every 15 seconds. ## Proxies [Section titled “Proxies”](#proxies) If a proxy sits between the browser and cairnflow, it must not buffer or compress `text/event-stream` responses, and it must pass `Last-Event-ID` through. See the proxy sketch in [Vercel AI SDK](/docs/agents/vercel-ai-sdk#keep-the-api-key-on-the-server). # Vercel AI SDK > Durable chat agents with streamText, useChat, tools and human approval. Write the agent with `streamText` and `useChat` as usual; cairnflow makes each model call and each tool call a durable step. If the process dies mid-run, the run continues from the unfinished step without calling the model again for steps that already answered. A run can wait for a human approval as long as it takes without holding a process, and its output streams to the browser: token by token in streaming mode, a step at a time in request-response mode, the default on Cairnflow Cloud (see [Streaming versus request-response](#streaming-versus-request-response)). A page reload reconnects to the same run. The adapter ships in `@cairnflow/sdk` and targets **AI SDK v7** (`ai@7`). The SDK does not depend on `ai`: install `ai`, `@ai-sdk/react` and your provider package in your app. ## What you get [Section titled “What you get”](#what-you-get) | You write | Cairnflow does | | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | | `wrapLanguageModel({ model, middleware: cairnMiddleware(ctx) })` | Each model call is a `ctx.run`: the result is journaled and replayed from the journal. A span `llm ` records input and output tokens | | `cairnTools(ctx, tools)` | Each tool `execute` is a `ctx.run` with a span `tool `; input, result and error reach the UI | | `cairnTools(ctx, tools, { approve: ["refund"] })` | The tool waits on a durable promise until someone approves; if rejected, it never runs | | `chatObject("Chat", run)` | A virtual object keyed by chat ID: history in state, one turn at a time per chat | | `useChat({ transport: cairnChatTransport(…) })` | Messages go through cairnflow, UI chunks come back over SSE; reload resumes; `stop()` cancels | | `onError: turn.onError` | Errors from `streamText` go to the invocation’s log | ## Server [Section titled “Server”](#server) agent.ts ```ts import { convertToModelMessages, stepCountIs, streamText, tool, wrapLanguageModel } from "ai"; import { anthropic } from "@ai-sdk/anthropic"; import { z } from "zod"; import { cairnMiddleware, cairnTools, chatObject, serve } from "@cairnflow/sdk"; const tools = { lookupOrder: tool({ description: "Look up an order", inputSchema: z.object({ id: z.number() }), execute: async ({ id }) => db.orders.get(id), }), refund: tool({ description: "Refund an order (needs approval)", inputSchema: z.object({ id: z.number(), amount: z.number() }), execute: async ({ id, amount }) => payments.refund(id, amount), }), }; const chat = chatObject("Chat", async (ctx, turn) => streamText({ model: wrapLanguageModel({ model: anthropic("claude-sonnet-5-5"), middleware: cairnMiddleware(ctx), }), system: "You are the support assistant of a shop.", tools: cairnTools(ctx, tools, { approve: ["refund"] }), messages: await convertToModelMessages(turn.messages), stopWhen: stepCountIs(8), onError: turn.onError, }), ); await serve({ services: [chat], port: Number(process.env.PORT ?? 9080), hostname: "0.0.0.0", // the default, 127.0.0.1, is unreachable from outside a container identityKeys: [""], }); ``` Then register the deployment (`POST /deployments`, see [Deployments](/docs/cloud/deployments)). In request-response mode, a model call that takes longer than the [turn time limit](/docs/cloud/limits#turn-time-limit) is cut and made again on the next attempt. For long generations, declare a longer `inactivityTimeout` in `opts.options` (below) and set a retry policy. ### What `chatObject` builds [Section titled “What chatObject builds”](#what-chatobject-builds) `chatObject(name, run, opts?)` returns a virtual object with three handlers. The browser transport talks to exactly these three. | Handler | Type | What it does | | ---------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `send` | exclusive | Records itself as the active turn, builds the history from state plus the new message (or cuts it at the message to regenerate), calls `run`, drains `toUIMessageStream` (the assistant message ID is the invocation ID), saves the new history, clears the active turn. Returns `{ id }` | | `active` | shared | The invocation ID of the running `send`, or `null` | | `messages` | shared | The saved history (`UIMessage[]`). During a turn: the history of that turn, including the message just sent, plus pending approval requests | Because `send` is exclusive, two messages to the same chat never run at the same time; the second waits in the object’s queue. The shared handlers answer while `send` runs. The `turn` argument of `run` carries: * `messages` — the UI history to pass to `convertToModelMessages`; * `onError` — pass it to `streamText({ onError })`; * `chatId`, `trigger` (`"submit-message"` or `"regenerate-message"`), `messageId`; * `body` — the `body` option the browser passed to `sendMessage`, if any. `opts.options` takes the handler options shared by every cairnflow handler, such as `retryPolicy`. When it sets no `retryPolicy.maxAttempts`, `chatObject` uses 5 (`CHAT_MAX_ATTEMPTS`). `opts.stream` renames the stream the UI chunks go to (default `ui`). ### The three rules [Section titled “The three rules”](#the-three-rules) These apply to every cairnflow handler, and they matter more in an agent loop: 1. **Every side effect goes through `cairnTools` or `ctx.run`.** The handler body runs again on every replay. A tool `execute` that is not wrapped calls the outside API again each time. 2. **No `Date.now()`, `Math.random()` or `generateId()` outside `ctx.run`.** 3. **Do not catch and swallow errors around `ctx` commands.** A failed turn is still retried, whatever your `catch` does. ## Browser [Section titled “Browser”](#browser) The transport implements the AI SDK `ChatTransport` interface. `useChat` uses it for sending, reconnecting and stopping; you call two extra methods yourself. chat.tsx ```tsx import { useChat } from "@ai-sdk/react"; import type { UIMessage } from "ai"; import { cairnChatTransport } from "@cairnflow/sdk"; const transport = cairnChatTransport({ baseUrl: "/cairn", service: "Chat" }); function ChatPage({ chatId, initial }: { chatId: string; initial: UIMessage[] }) { const { messages, sendMessage, stop, status } = useChat({ id: chatId, transport, messages: initial, // await transport.messages(chatId) when rendering the page resume: true, // reload mid-generation: reconnect to the running turn }); const approve = (approvalId: string, approved: boolean) => transport.approve(chatId, approvalId, { approved }); // …render messages; tool parts waiting for approval have state "approval-requested" } ``` | Option | Meaning | | ------------- | ------------------------------------------------------------------------------ | | `baseUrl` | Where cairnflow is reached. In a browser, a same-origin proxy path (see below) | | `service` | The virtual object, usually your `chatObject` name | | `handler` | The handler that receives messages (default `send`) | | `scope` | Scope of the object, if you use scopes | | `headers` | Extra headers, for example `authorization` when running server-side | | `stream` | The stream to read (default `ui`) | | `sendHistory` | Send the whole history instead of only the last message (default `false`) | | Method | Use | | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `transport.messages(chatId)` | The saved history, to initialise `useChat` after a page load | | `transport.approve(chatId, approvalId, { approved, reason? })` | Answer a tool approval request — see [Human approval](/docs/agents/approvals). Throws if the request was already answered with a different decision | By default the transport sends only the **last** message; the object keeps the history in its state. `sendHistory: true` makes the object use the client’s history instead, and adds a second copy of it to every turn’s journal. ### Stale history [Section titled “Stale history”](#stale-history) With each message the transport sends the ID of the message right before it. If the page holds an older history than the object (another tab sent a message, or the page never loaded `messages`), `send` does not run the turn and does not change the history: the UI receives an `error` chunk and `useChat` reports an error. Reload the history with `transport.messages(chatId)` and send again. Initialising `useChat` with `messages: await transport.messages(chatId)` avoids it. ### Keep the API key on the server [Section titled “Keep the API key on the server”](#keep-the-api-key-on-the-server) Cairnflow does not send CORS headers, and an API key must never reach the browser: anyone holding it can call every handler, read every chat and approve every request of the environment. Put a proxy on your app’s origin that checks your user and adds the key. app/cairn/\[...path]/route.ts ```ts // Sketch of a Next.js route handler. `auth` and `allowed` are your code. async function handler(req: Request, { params }: { params: Promise<{ path: string[] }> }) { const { path } = await params; const user = await auth(req); if (!(await allowed(user, req.method, path, new URL(req.url)))) { return new Response("forbidden", { status: 403 }); } const target = `/${path.join("/")}${new URL(req.url).search}`; const headers: Record = { "content-type": "application/json", authorization: `Bearer ${process.env.CAIRN_INVOKE_KEY}`, // Run the request at the node that leads this chat's range. "x-cairn-forward": "leader", }; // The transport sends Idempotency-Key with each message, Last-Event-ID when it reconnects. for (const h of ["idempotency-key", "accept", "last-event-id"]) { const v = req.headers.get(h); if (v !== null) headers[h] = v; } return fetch(`${process.env.CAIRN_URL}${target}`, { method: req.method, headers, body: req.method === "GET" ? undefined : await req.text(), }); // the SSE body streams straight through } export { handler as GET, handler as POST }; ``` An **Invoke only** key is enough. `allowed` should let through exactly these routes, and check that the user may use that chat: | Route | Chat ID is in | | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `POST /invoke/Chat/send/send`, `POST /invoke/Chat/active`, `POST /invoke/Chat/messages` | `?key=` | | `POST /promises/Chat/{chatId}/{approvalId}/resolve` | the path | | `GET /invocations/{id}/streams/ui`, `POST /invocations/{id}/cancel` | the invocation ID: the proxy sees it in the answers of `send/send` (`{ id }`) and `active`, so it can keep an `id → chatId` map | Do not buffer or compress `text/event-stream` responses in the proxy (with nginx: `X-Accel-Buffering: no`). On a server that talks to cairnflow directly, give the key to the transport instead: `cairnChatTransport({ baseUrl, service, headers: { authorization: "Bearer …" } })`. ## Retries and errors [Section titled “Retries and errors”](#retries-and-errors) | What fails | What happens | | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | | A transient error in a model or tool call (provider 429 or 5xx, timeout, a tool throwing a normal `Error`) | The turn fails and cairnflow retries it under the handler’s retry policy. Completed steps replay from the journal; only the failed step runs again | | A provider error marked not retryable (`isRetryable: false`, such as 400 prompt too long or 401 bad key) | Journaled as the step’s failed result. The UI receives an `error`, the turn ends, no retry | | A tool throws `TerminalError` | Journaled, so a replay does not run the tool again. The model sees the tool error (`tool-output-error` in the UI, `errorText` in history) and carries on | Because retries happen at the turn level, the AI SDK’s own `maxRetries` has no effect on calls that go through `cairnMiddleware`. So that a provider that keeps refusing does not retry forever, `chatObject` stops after 5 attempts unless you set your own policy: ```ts const chat = chatObject("Chat", run, { options: { retryPolicy: { maxAttempts: 3, onMaxAttempts: "PAUSE" } }, }); ``` After the last attempt the invocation is paused; fix the cause, then resume it from the [console](/docs/cloud/console). See [Errors and retries](/docs/develop/errors-retries). ### `turn.onError` and `Suspend` [Section titled “turn.onError and Suspend”](#turnonerror-and-suspend) `streamText` reports every error to `onError`, and its default is `console.error`. `turn.onError` writes errors to the invocation’s log instead, where the console’s **Log** tab shows them. When a turn waits (for an acknowledgement, a promise or an approval), nothing is thrown through your code: the waiting promise stays pending until the turn ends. The SDK throws `Suspend` only for a `ctx` command made after the turn has already suspended. That is not an error of your code, so `turn.onError` ignores it. If you write your own `onError`, ignore it too: ```ts import { Suspend } from "@cairnflow/sdk"; const onError = ({ error }: { error: unknown }) => { if (error instanceof Suspend) return; report(error); }; ``` `cairnOnError(ctx)` is the same function `turn.onError` uses, for agents built without `chatObject`. ## Streaming versus request-response [Section titled “Streaming versus request-response”](#streaming-versus-request-response) How your environment calls the service decides what the chat can do. See [Deployments](/docs/cloud/deployments) for how the mode is chosen. | | `BIDI_STREAM` | `REQUEST_RESPONSE` | | ------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ | | Tokens in the browser | As they are generated | All the text of a step at once, when the step completes | | `stop()` during a model or tool call | The call receives an `AbortSignal` and stops; the partial answer is kept | The running step finishes; cancellation takes effect from the next step | | Reload during the first model call | Reconnects at once | `active` is visible only after the first durable step, so there is nothing to reconnect to yet | | A long model call | The SDK keeps the connection alive while it runs | It must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit), or it is cut and made again | | Needs | HTTP/2 all the way to your service | Any HTTPS host, serverless functions included | On Cairnflow Cloud an `https://` endpoint is registered in request-response mode unless you ask for the declared mode (`"transport": "declared"`); streaming has not been verified on Fly.io yet. More in [Streaming to the browser](/docs/agents/streaming). ## Size and cost [Section titled “Size and cost”](#size-and-cost) * **Each model step’s journal entry** keeps every part of the model stream (text, tool calls, usage). The middleware drops the request body sent to the provider and the raw response body. * **History lives in state.** Each turn reads it once and writes it back. Above 256 KiB the history is stored as immutable segments: the journal keeps references plus the open tail, so journal bytes per turn stay about the same as the conversation grows. In our tests a turn journals about 218 KB whether the history is 1, 3 or 6 MiB. * **No need to trim for the payload limit.** A history larger than the [payload limit](/docs/cloud/limits#payload) (1 MiB during the Beta) is stored as segments instead of failing the turn. `transport.messages` returns the whole history in one response, capped at 64 MiB. Trim or summarise when the model’s context window needs it, not the runtime. * **The SDK caches segments.** A long-running `serve()` keeps the segments it has read in memory (`valueCacheBytes`, 64 MiB by default), so a turn downloads only segments it has not seen. * **Each approval** adds a journal entry and a durable wait. ## Observe a chat [Section titled “Observe a chat”](#observe-a-chat) | To see | Ask | | --------------------------------------- | ------------------------------------------------------------- | | The running turn of a chat | `POST /invoke/Chat/active?key=` | | Spans and tokens of a turn | `GET /invocations/{id}/spans`, or the console’s **Trace** tab | | `streamText` errors and `ctx.log` lines | `GET /invocations/{id}/logs`, or the **Log** tab | | Each model step, tool call and approval | `GET /invocations/{id}/journal`, or the **Journal** tab | | Whether an approval was answered | `GET /promises/Chat/{chatId}/{approvalId}` | ## Known limitations [Section titled “Known limitations”](#known-limitations) * **AI SDK v7 only.** Earlier major versions declare middleware and usage differently. * **Providers.** The adapter is provider-agnostic and its tests use the AI SDK mock model. It has been run against a real model through `@ai-sdk/openai-compatible`; not every provider package has been tried yet. * **A provider that refuses permanently with a transient status code** (for example a quota exhausted reported as `429`) is retried with backoff; the UI just waits. The error shows in the invocation’s status and log. Set `retryPolicy.maxAttempts`. ## Next [Section titled “Next”](#next) * [Human approval](/docs/agents/approvals) * [Streaming to the browser](/docs/agents/streaming) * [Agents without chatObject](/docs/agents/custom-agents) # Cairnflow Cloud > The hosted service — organizations, environments, region, and what the Beta includes. Early-access waitlist Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting). Cairnflow Cloud runs cairnflow for you. You write and host your service; Cloud keeps the journals, state and timers, calls your service when a handler has work to do, and gives you a console for each environment. Cloud is planned to start as a **private Beta**: invite-only, free during the Beta, and with no SLA. Only invited email addresses will be able to create organizations and environments, and invitations have not started. How many organizations, environments and keys an account can create is in [Account limits](/docs/cloud/limits#account-limits). ## Organizations [Section titled “Organizations”](#organizations) Everything in Cloud belongs to an **organization**: usually your company or team. You create one the first time you sign in, and invite teammates by email (an invitation link is shown once and expires after 7 days). Each member has a role in the organization: | Role | Can | | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Owner | Everything an admin can, plus inviting, promoting, demoting and removing owners. An organization always keeps at least one owner. Deleting an organization is not in the web app yet: ask support | | Admin | Manage environments, API keys and members | | Member | Create and revoke API keys; cannot manage members | | Viewer | Read-only access | | Billing | Billing only; no access to environments | The same roles decide what you can do in an environment’s console: owners, admins and members open it with full rights, viewers read only, and billing members cannot open it. ## Environments [Section titled “Environments”](#environments) An **environment** is where your invocations run: for example `prod` and `staging`. Each one has its own: * **endpoint**: the URL your service and scripts talk to, such as `https://e0123456789a.iad.cairnflow.cloud`; * **API keys**: see [API keys](/docs/cloud/api-keys); * **identity key**: the public key your service uses to check that requests really come from this environment; * **data**: journals, state, schedules, streams, archives and audit log; * **console**. An environment is an **isolated tenant on a shared cell**. A cell is a group of cairnflow nodes and its storage bucket, shared by many environments. Isolation between environments is enforced by the runtime: every request, query and stored object is scoped to its environment, and one environment cannot read, call or list another’s data. An environment is not a dedicated cell, and you cannot bring your own bucket. A new environment usually becomes **Active** within a few seconds; the endpoint, identity key and API keys appear then. If it is still pending after a couple of minutes, write to . ## Region [Section titled “Region”](#region) Cloud runs in one region: **iad (US East, Virginia)**. Every resume of a handler is a round trip between the cell and your service, so host your service close to it. ## How Cloud calls your service [Section titled “How Cloud calls your service”](#how-cloud-calls-your-service) * Only **`https://`** endpoints on the public internet. Private and internal addresses are refused. * Your service must check the **identity key**: `identityKeys` in `serve()` or `fetchHandler()`. Registering an endpoint that does not is refused. * `https://` endpoints are called in **request-response** mode unless you register them with `"transport": "declared"`. Each turn is then one HTTP request and must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit); tokens reach the browser when a step finishes, not as they are generated. Streaming mode needs HTTP/2 all the way to your app. Details in [Deployments](/docs/cloud/deployments). ## What the Beta includes [Section titled “What the Beta includes”](#what-the-beta-includes) * Every environment has the same plan. See [Limits](/docs/cloud/limits) for the numbers. * No billing page: the Beta is free. * One region, no SLA, no uptime credit. * Backups of each cell to a second storage provider, kept for about 45 days. See [Data and deletion](/docs/cloud/data-and-deletion). What is not there yet is listed in [Known limitations](/docs/cloud/known-limitations). ## Self-hosting [Section titled “Self-hosting”](#self-hosting) Cloud runs the same runtime you can run yourself. Most of this section (deployments, the console, the query API) applies to a self-hosted cluster too; the plan limits, organizations and the shared-cell rules are specific to Cloud. See [Self-hosting](/docs/self-hosting). ## Support [Section titled “Support”](#support) Write to . Include your organization name and, for a problem with an invocation, its ID (shown in the console). To report a security issue, write to . ## Next [Section titled “Next”](#next) * [Quickstart](/docs/quickstart) * [API keys](/docs/cloud/api-keys) * [Deployments](/docs/cloud/deployments) # API keys and identity > The environment endpoint, API keys and their roles, console sign-in, and the identity key your service checks. Early-access waitlist Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting). Three values connect your code to an environment. All three are on the environment page once the environment is **Active**. | Value | Looks like | Used by | | ------------ | ------------------------------------------ | ------------------------------------------------------------------------------------- | | Endpoint | `https://e0123456789a.iad.cairnflow.cloud` | Everything that calls cairnflow: scripts, your backend, the chat proxy | | API key | `cf_…` | Sent as `Authorization: Bearer ` on every request to the endpoint | | Identity key | `publickeyv1_…` | Your service, in `identityKeys`, to check requests that come **from** the environment | API keys authenticate you to the environment. The identity key works the other way round: it lets your service check that a request comes from your environment and not from someone who found its URL. ## API keys [Section titled “API keys”](#api-keys) Create a key on the environment page. Name it after where it will be used (`ci`, `laptop`, `billing-worker`) so you know what breaks when you revoke it. The secret is shown **once**, when the key is created. Cloud keeps only a hash and the key’s metadata; if you lose a secret, revoke the key and create a new one. ```sh curl -X POST "$CAIRN_URL/invoke/Greeter/greet" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '"world"' ``` A missing or wrong key gets `401`; a key whose role does not allow the route gets `403`. ### Roles [Section titled “Roles”](#roles) | Role | For | Can | | ----------------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Admin** (deploy and invoke) | CI, operators, your own scripts | Everything an Invoke key can, plus: register and remove deployments, move service revisions, read journals, logs, spans, usage, audit and archives, run SQL queries, hard-cancel, purge, resume, restart and migrate invocations. Signs in to the console | | **Invoke only** | Clients that call your services: your backend, a chat proxy | Invoke handlers (`/invoke`, `/send`, workflows), read an invocation’s status and wait for it, resolve and reject durable promises and awakeables, send signals, cancel cooperatively, manage schedules, read the invocation’s own streams and artifacts | An Invoke only key cannot read journals or state, and cannot register deployments. Give each client the smallest role that works: a browser-facing proxy needs Invoke only. ### Revoking [Section titled “Revoking”](#revoking) Revoking a key refuses requests that use it within seconds, on every node. An event stream already open with the key is closed within about 30 seconds. It cannot be undone. Keys do not belong to the person who created them: when a member leaves the organization, the keys they created keep working until someone revokes them. ## Console sign-in [Section titled “Console sign-in”](#console-sign-in) **Open console** on the environment page signs you in with your Cairnflow Cloud account; no key to paste. Your organization role decides what you can do there (see [Cairnflow Cloud](/docs/cloud#organizations)). The console’s own sign-in page also accepts an Admin API key. The key is exchanged for a session cookie and is not stored in the browser. Signing out revokes the session on the server, so a copy of the cookie stops working too. ## Identity key [Section titled “Identity key”](#identity-key) Every request Cloud sends to your service carries a signed token. Pass the environment’s identity key to the SDK and it rejects anything not signed by your environment: wrong signature, wrong path, expired, or replayed for another request. The handler does not run. service.ts ```ts await serve({ services: [greeter], port: Number(process.env.PORT ?? 9080), hostname: "0.0.0.0", identityKeys: ["publickeyv1_…"], }); ``` route.ts ```ts const handler = fetchHandler({ services: [greeter], identityKeys: ["publickeyv1_…"], }); ``` Cloud refuses to register an endpoint that does not check identity keys, because a function URL is public: without the check, anyone who knows the URL could call your handlers. `identityKeys` is a list so that a key can be rotated without downtime: the new key is added to the list before it starts signing, and the old one is removed after. You can also read the current keys with an Admin key: ```sh curl "$CAIRN_URL/identity" -H "authorization: Bearer $CAIRN_KEY" ``` The answer is `{tenant, signing, keys: [{generation, kid, active}]}`; each `kid` is a `publickeyv1_…` value for `identityKeys`. Caution The identity key is public: it only verifies signatures. API keys are secrets. Never put an API key in a browser, a mobile app or a public repository. ## Next [Section titled “Next”](#next) * [Deployments](/docs/cloud/deployments) * [Vercel AI SDK: keep the API key on the server](/docs/agents/vercel-ai-sdk#keep-the-api-key-on-the-server) # The console > Follow invocations step by step, see why one is waiting, act on it, query with SQL, and read usage and the audit log. Early-access waitlist Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting). Each environment has a web console. **Open console** on the environment page signs you in with your Cairnflow Cloud account. Owners, admins and members get full rights; viewers can read but not act. You can also sign in on the console’s own page with an Admin API key. The console uses the same HTTP API you can call yourself: anything it shows, you can read with the [query API](/docs/query) or the [HTTP API](/docs/reference/http-api). ## Overview [Section titled “Overview”](#overview) Invocations by service and state, the ones that need attention (failed, paused), the busiest handlers, and completed and failed invocations over the last 24 hours. Hourly summaries are written about once a minute, so a new environment shows history after a short while. ## Invocations [Section titled “Invocations”](#invocations) The list shows invocations newest first, across the whole environment. Filter by service, handler, key, tag (`k=v`), idempotency key, parent invocation, creation time, roots only, or an ID prefix. Select several invocations, or every invocation matching the filter, to run a **bulk action**: cancel, purge, resume or restart. Each invocation gets exactly the single-invocation action, in pages of up to 1,000; one failure does not stop the rest, and the errors can be downloaded as CSV. ## One invocation [Section titled “One invocation”](#one-invocation) The header shows the status, service, handler, key, deployment, creation and end time, tags, and the schedule that started it, if any. ### Why it is in this state [Section titled “Why it is in this state”](#why-it-is-in-this-state) A plain-language answer to “why is this not done?”, for example: * sleeping until a given time; * waiting for a call to another handler, a promise, a step, or another invocation; * waiting in the queue of a virtual object, with its position and the invocation holding the lock; * paused after running out of attempts, with the last failure; * failed, with the code, message and stack trace; * the last failed attempt and when the next attempt is due. ### Tabs [Section titled “Tabs”](#tabs) | Tab | Shows | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Journal** | Every entry in order: commands and their results, paired. Open an entry to see its decoded body (cut at 64 KiB). Entries still waiting for a result are highlighted | | **Log** | `ctx.log` lines and errors reported through `turn.onError`. Live while the invocation runs (including lines not yet durable), filterable by level | | **Trace** | A timeline per attempt (failed attempts in red, the retry wait between them) and the spans of `ctx.trace.span` as a waterfall, with token totals. Handlers declared with `trace: "runtime"` get a span per turn and per `ctx.run` | | **Streams** | Durable streams (`ctx.stream(name, { durable: true })`), live while the invocation runs. Temporary streams, such as the `ui` stream of a chat, are not shown | | **Tree** | Calls from and to other invocations, up to the root | | **State** | The state of the virtual object or workflow, and its promises | | **Artifacts** | Files stored with `ctx.artifact`, with preview and download | ### Actions [Section titled “Actions”](#actions) | Action | What it does | Needs | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | | **Resume** | Runs a paused invocation again | Admin | | **Cancel (cooperative)** | Sends a cancel signal: the handler’s own cleanup runs and the invocation ends with its own failure. Needs your service to be running | Invoke | | **Cancel now** | Ends the invocation as failed (code 572) without waiting for your service. Side effects of a turn already in flight still happen | Admin | | **Restart from step…** | Starts a new invocation that reuses the journal before the chosen step (results of steps there are kept) and runs again from that step. Also available on each journal entry as **Restart from here** | Admin | | **Replay check** | Runs the existing journal against a deployment without committing anything, to see whether new code would take the same path | Admin | | **Migrate…** | Moves an unfinished invocation to another deployment; a replay check must match first unless you force it | Admin | | **Send signal…** | Delivers a named signal (what `ctx.signal(name)` waits for). Sending the same name again does nothing | Invoke | | **Purge** | Deletes the journal, status and idempotency key of an ended invocation (for a workflow run, also the workflow’s state and promises). It is archived first. Cannot be undone | Admin | Destructive actions ask you to type a confirmation. The console reports success only after the server has answered. ## Services, workflows, objects [Section titled “Services, workflows, objects”](#services-workflows-objects) * **Services**: every service and handler of the current deployments, with statistics. * **Workflows**: one run per workflow ID; pick a run or type an ID to open it. * **Objects & state**: the keys of each virtual object, with their state and the invocations each one holds. ## Deployments [Section titled “Deployments”](#deployments) Every deployment, its transport, the services it is current for, and how many unfinished invocations are pinned to it. **Deploy safely** registers a new version without moving traffic, compares handlers, replay-checks unfinished invocations, moves services, drains and removes the old version. See [Deployments](/docs/cloud/deployments#ship-a-new-version). ## Schedules [Section titled “Schedules”](#schedules) Create, edit, pause, resume, run now and delete server-side schedules: cron (five fields, with an IANA time zone) or every N seconds. See [Schedules](/docs/develop/schedules). ## Query [Section titled “Query”](#query) A SQL editor over the environment’s `sys_*` tables, with sample queries and the table list on the side. Run with Ctrl/Cmd + Enter, switch between a table and a chart (a time column and numbers, or a text column and a number), and **Download CSV**. See [Query with SQL](/docs/query). ## Usage [Section titled “Usage”](#usage) Per hour, for a chosen time range: invocations, durable steps, SDK turns, completed and failed, compute units, billing units, run time, and input and output tokens per model (from spans that carry token counts, which `cairnMiddleware` records). Costs are shown only when token prices are set for the cell. ## Slow runs and archive [Section titled “Slow runs and archive”](#slow-runs-and-archive) * **Slow runs**: runs that took longer than the slow threshold, newest first, with where the time went (your code, the SDK, durable waits, engine wait, quota wait). Kept in each node’s memory only. * **Archive**: purged invocations read back from the archive (final status, output and journal), by day. ## Audit log [Section titled “Audit log”](#audit-log) Who did what to the environment through its API and console: deployments, invocations, keys, sign-ins, refused requests. Filter by time range (up to 31 days), actor and action. The organization’s own audit log (members, invitations, environments, keys) is in the Cloud web app. ## Not available on Cloud [Section titled “Not available on Cloud”](#not-available-on-cloud) Cell-wide pages (**Cluster**, **Flow control**, **Settings**) need operator access to the cell and are not available to environments. # Data and deletion > What Cairnflow Cloud stores for an environment, how long it keeps it, and what deleting an environment does. Early-access waitlist Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting). This is the Beta data policy. ## What is stored [Section titled “What is stored”](#what-is-stored) For each environment: * the journal of every invocation: inputs, step results, outputs, errors; * the state of virtual objects and workflows, and their durable promises; * schedules; * durable streams, logs and trace spans of invocations; * artifacts stored with `ctx.artifact`; * archives of finished invocations; * an audit log of who did what. API keys are stored as hashes: a secret cannot be shown again. Everything an environment stores sits on the cell’s object storage, scoped to that environment. You cannot bring your own bucket during the Beta. Caution Step results and state are kept in the journal, and the journal is visible in the console to anyone with access to the environment. Do not return secrets (tokens, API keys) from `ctx.run` or store them in state: keep them in your service’s environment variables or secret manager. ## How long it stays [Section titled “How long it stays”](#how-long-it-stays) * **Finished invocations** are removed 7 days after they end. Before removal, each one is written to the archive; the console’s **Archive** page reads it back. Archives do not expire yet. * **Purging an invocation** yourself (console or `POST /invocations/{id}/purge`) removes its journal, status and idempotency key at once, after archiving it; purging a workflow run also removes that workflow’s state and promises. Only ended invocations can be purged. * **Deleted items** sit in the cell’s trash for 7 days before they are removed for good, so a mistake can be undone. * **Backups** copy each cell to a second storage provider on a schedule. Each copy expires about 45 days after it is made. Retention is also the window of idempotency keys: once an invocation is removed, the same key starts a new invocation. ## Deleting an environment [Section titled “Deleting an environment”](#deleting-an-environment) When you delete an environment: 1. It is suspended at once: new invocations are refused and scheduled work stops. 2. Every API key is revoked and console sessions end. 3. The environment disappears from the web app. Its data is then removed **permanently within 60 days**. The delay covers the trash (7 days) and the last backup that still holds it (about 45 days). Caution Deleting an environment cannot be undone from the web app. Export what you need from the console first: SQL query results download as CSV. ## Deleting an organization [Section titled “Deleting an organization”](#deleting-an-organization) There is no self-service way to delete an organization yet. Write to . ## Questions [Section titled “Questions”](#questions) For anything about your data, write to with your organization name. # Deployments > Register your service's URL, choose the transport, and ship new versions without breaking runs in flight. Early-access waitlist Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting). A **deployment** is one registered endpoint of your service: a URL where cairnflow can reach the handlers of one version of your code. Registering reads the endpoint’s list of services and handlers and makes it the current version of each service it contains. The same API applies to a self-hosted cluster; the rules about `https://`, identity keys and the default transport are those of Cairnflow Cloud. ## Register [Section titled “Register”](#register) ```sh curl -X POST "$CAIRN_URL/deployments" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"uri":"https://your-service.example.com"}' ``` You need an **Admin** key. The answer describes the new deployment: its ID (`dp_…`) and `protocolMode`, which says how the environment will call your service. Each registration creates a new, immutable deployment, even for the same URL. Handler options such as the retry policy and timeouts are read at registration, so changing them in code means registering again. ### What Cloud checks [Section titled “What Cloud checks”](#what-cloud-checks) | Requirement | If not met | | ---------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | | The URI is `https://` on the public internet | Refused: private and internal addresses are not allowed | | The service checks identity keys (`identityKeys` in `serve()` or `fetchHandler()`) | `400` with code `identity_required` | | The SDK compresses request-response bodies (the TypeScript SDK does by default; do not set `compression: false`) | `400` with code `compression_required` | | The SDK and the runtime share a protocol version | Refused at registration | | At most 10 registrations per minute | `429` with code `deploy_rate_limited` and a `Retry-After` header | ## Transport [Section titled “Transport”](#transport) Cairnflow calls your service in one of two modes: * **`REQUEST_RESPONSE`.** Each turn of a handler is one HTTP request. When the handler waits (a sleep, a call, a promise) the request ends, and the next turn sends the journal recorded so far. A turn must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit), and tokens and stream records of a step reach readers when the step finishes. Works behind every host and on serverless functions. * **`BIDI_STREAM`.** One HTTP/2 stream stays open for the whole invocation, and the SDK keeps it alive while a step runs. Needed for live token streaming and for cancelling a running step through its `AbortSignal`. `serve()` declares this mode. On Cloud, an `https://` endpoint is registered as **`REQUEST_RESPONSE`** by default, even if your service declares `BIDI_STREAM`. Most hosts end TLS at their edge and talk HTTP/1.1 to your app, or buffer the request body, and a streaming invocation would hang there. If your host forwards HTTP/2 all the way to your app (Fly.io with `h2_backend` and Cloud Run with `--use-http2` are meant to; streaming has not been verified on Fly.io yet), keep the mode your service declares: ```sh curl -X POST "$CAIRN_URL/deployments" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"uri":"https://your-service.example.com","transport":"declared"}' ``` Check `protocolMode` in the answer. If streaming does not reach your app, invocations fail with a message starting with `bidi_no_response_headers` (in the invocation’s last failure) and are retried. Register the endpoint again without `transport`. `fetchHandler` always declares `REQUEST_RESPONSE`: a Fetch API handler cannot hold a bidirectional stream. ### Keeping request-response cheap [Section titled “Keeping request-response cheap”](#keeping-request-response-cheap) In `REQUEST_RESPONSE` the journal travels to your service on every turn, so bytes grow with the number of steps. Two SDK features reduce that: * **Compression.** Request and response bodies are gzipped (on by default). Each journal entry is compressed on its own, so bytes of one entry are never compressed together with another. * **Replay cache.** `serve()` keeps the journal it has already received for each running invocation in memory (64 MiB, 15 minutes by default), and the runtime then sends only the new entries plus a digest of the rest. If the cache misses, your service answers `409` and the turn is sent again in full at once, so it is always safe. `serve({ replayCache: false })` turns it off; `fetchHandler` has it off by default, because Lambda, Workers and edge functions do not keep a process between turns. With several replicas behind a load balancer, the cache only hits when turns of one invocation reach the same replica. Cairnflow sends back cookies that your previous response set for the same invocation, so sticky-session cookies work; on Fly.io the SDK asks for the same machine by itself. Keep step results small either way: large values belong in [artifacts](/docs/develop/artifacts), not in the journal, and the [payload limit](/docs/cloud/limits) applies. ## Platforms [Section titled “Platforms”](#platforms) | Platform | Serve with | Notes | | ------------------------------------------------------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | | Container, VM (Node.js 22.6 or newer) | `serve()` | Long-running process; replay cache on. Listen on `hostname: "0.0.0.0"` and the port your host gives you | | Vercel (Next.js App Router) | `fetchHandler` in `app/api/cairn/[...path]/route.ts`, exported as `GET` and `POST` | Node.js runtime. Register a production or named domain: preview Deployment Protection answers with a login page | | Cloudflare Workers | `export default { fetch: handler }` | Set `compatibility_flags = ["nodejs_compat"]` | | AWS Lambda (Function URL or API Gateway HTTP API, payload v2) | `export const handler = lambdaHandler(fetchHandler({ … }))` | `identityKeys` is what keeps strangers out, so a Function URL with auth type `NONE` is fine | | Deno, Bun | `Deno.serve(handler)`, `Bun.serve({ fetch: handler })` | | The Fetch adapter is tested on Node.js, not yet on these platforms themselves. Register the **base URL** where the handler is mounted, for example `https://your-app.vercel.app/api/cairn`. With a function, one turn must finish within the platform’s time limit: split long work into several short `ctx.run` steps. See [Serverless](/docs/workflows/serverless). ## Ship a new version [Section titled “Ship a new version”](#ship-a-new-version) Every invocation stays on the deployment it started on, for its whole life, even after you register a new version. New invocations go to the current version. So: 1. **Keep the old endpoint running** until nothing is left on it. 2. Register the new version. It becomes current for the services it contains. 3. Watch the old deployment drain: `GET /deployments/{id}` reports `pinnedInvocations`, the number of unfinished invocations still on it. 4. Remove it when it is empty: `DELETE /deployments/{id}`. It answers `409` while the deployment is still a current version or still has invocations on it. While it is being removed, moving a service to it, migrating to it or restarting on it answers `409` too. For a careful rollout, register without moving anything with `POST /deployments?activate=false`, then move each service yourself: ```sh curl -X PUT "$CAIRN_URL/services/Chat/revision" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"deployment":"dp_new…","expect":"dp_old…"}' ``` `expect` makes the move happen only if the service still points at that deployment: when two people roll back at once, exactly one wins. The same call with an older deployment is a rollback. The console’s **Deployments → Deploy safely** page walks through these steps: register without moving, compare handlers, replay-check up to 20 unfinished invocations per service on the new version (read-only, nothing is committed), move, drain, migrate the invocations that replay cleanly, roll back, and remove the old version. See [Versioning](/docs/develop/versioning) for what makes a code change safe for invocations in flight. ## List and inspect [Section titled “List and inspect”](#list-and-inspect) | Request | Returns | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `GET /deployments` | Every deployment: `id`, `endpoint`, `createdAtMs`, `protocolMode`, `currentFor` (services it is the current version of) | | `GET /deployments/{id}` | The same, plus `pinnedInvocations` and the manifest: services, handlers and their options as registered | | `GET /services` | Services and handlers you can call, with the deployment that serves each | `protocolMode` is the first thing to check when every invocation of a deployment fails in transport. ## Next [Section titled “Next”](#next) * [Limits](/docs/cloud/limits) * [The console](/docs/cloud/console) * [HTTP API reference](/docs/reference/http-api) # Known limitations > What Cairnflow Cloud and the SDK do not do yet during the Beta. Early-access waitlist Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting). What the Beta does not do yet. None of these items changes the code you write today. ## Availability [Section titled “Availability”](#availability) * **Not open yet.** The Beta will be invite-only: only invited email addresses can create organizations and environments, and invitations have not started. * **The SDKs are not on the public npm and PyPI registries yet**, and the Go module has no tagged release. Self-hosting binaries are not released either: the runtime is built [from source](/docs/self-hosting#build-from-source). * **No SLA** and no uptime credit. Plan for interruptions. * **No public status page yet.** Write to if something looks wrong. ## SDKs [Section titled “SDKs”](#sdks) Three SDKs exist: **TypeScript** (`@cairnflow/sdk`), **Python** (`cairnflow`, Python 3.11 or newer) and **Go** (package `cairn`, Go 1.25 or newer). The TypeScript `serve()` runs on Node.js 22.6 or newer. The Fetch adapter (`@cairnflow/sdk/fetch`, `fetchHandler`) targets Vercel (Node.js runtime), Cloudflare Workers (with `nodejs_compat`), AWS Lambda, Deno (`Deno.serve(handler)`) and Bun (`Bun.serve({ fetch: handler })`). It is tested on Node.js, against the standard Fetch API and Lambda payload v2 events, but not yet on those platforms themselves; report anything that behaves differently on one of them. The Python SDK serves with its built-in server, as an ASGI app, or on AWS Lambda. The [Go SDK](/docs/develop/go) serves with its built-in server, as an `http.Handler`, or on AWS Lambda. Neither has a Vercel AI SDK integration. ## Account [Section titled “Account”](#account) * Invite-only, with caps on organizations, environments and API keys: see [Account limits](/docs/cloud/limits#account-limits). * No organization settings page yet: you cannot rename or delete an organization from the web app. Ask support. * No billing page: the Beta is free. ## Transport [Section titled “Transport”](#transport) Endpoints on `https://` are called in request-response mode unless you register them with `"transport": "declared"` ([Deployments](/docs/cloud/deployments#transport)). In request-response mode: * every resume of a handler sends the invocation’s journal again (compression and the replay cache reduce the bytes, not the round trips); * each turn is one HTTP request and must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit); a longer step is cut and retried; * tokens of an AI step reach the browser all at once when the step completes, not as they are generated; * `stop()` and cooperative cancel cannot interrupt the step that is running; they take effect from the next step. Streaming mode needs HTTP/2 all the way to your app; it has not been verified on Fly.io yet. Detecting hosts that carry HTTP/2 to your app, so streaming is chosen for you, is planned. ## AI SDK adapter [Section titled “AI SDK adapter”](#ai-sdk-adapter) * **Vercel AI SDK v7 only.** * Not every provider package has been tried. The adapter does not depend on the provider, and it has been run with a real model through `@ai-sdk/openai-compatible`. * A provider that refuses permanently but answers with a transient status code (such as a used-up quota reported as `429`) is retried with backoff until the retry policy gives up. Set `retryPolicy.maxAttempts`. ## Streams [Section titled “Streams”](#streams) Temporary streams (the `ui` stream of a chat) live in the memory of the node leading the invocation’s range. A node failure or a change of leader loses them, and the console does not show them. The chat recovers from `messages`; see [Streaming to the browser](/docs/agents/streaming#temporary-streams-what-to-expect). ## Observability [Section titled “Observability”](#observability) * Spans and logs stay in the console and the API; exporting them to your own OpenTelemetry collector is turned off on shared cells. * Slow runs are kept in each node’s memory only. ## Region [Section titled “Region”](#region) One region: **iad (US East, Virginia)**. Pick hosting close to it: every resume of a handler is a round trip between the cell and your service. ## Backups and recovery [Section titled “Backups and recovery”](#backups-and-recovery) Cells are backed up on a schedule to a second storage provider, and each copy expires after about 45 days. A restore brings an environment back to the last backup: work done after it can be lost, and an invocation that was waiting on another one at that moment may have to be restarted. # Beta limits > What every Cairnflow Cloud environment is allowed during the Beta, and what happens at each limit. Early-access waitlist Cairnflow Cloud is not open yet — [join the waitlist](/#pricing) to hear when early access opens. This page describes the hosted service as it is built for its Beta, and details may change before it opens. To run cairnflow today, [host it yourself](/docs/self-hosting). Every environment has the same Beta plan. Your environment page shows it under **Plan & limits**, and `GET /tenant` with an Admin key returns your environment’s limits and current usage. ## Plan limits [Section titled “Plan limits”](#plan-limits) | Limit | Beta | At the limit | | --------------------------------------------------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Finished invocations kept | 7 days | Removed after that (archived first; see [Data and deletion](/docs/cloud/data-and-deletion)) | | Largest payload | 1 MiB | A request body over it gets `413` with code `payload_too_large`. Larger state values, step results, inputs and outputs inside an invocation are stored as segments instead (see [Payload](#payload)) | | Journal entries per invocation | 10,000 | The invocation fails with code `578` (`journal_too_long`) | | Live invocations, whole environment | 1,000 | A new invocation gets `429` with code `live_invocations_limit`, and nothing is created. Schedules skip the runs that come due meanwhile. Invocations already running carry on, and so do the calls and sends they make | | Deployments | 20 | Registering one more gets `409` with code `deployments_limit`. Remove a deployment that is no longer current to free a slot (see [Deployments](/docs/cloud/deployments#ship-a-new-version)) | | Deployment registrations | 10 per minute | `429` with code `deploy_rate_limited` and a `Retry-After` header | | Schedules | 50 | Creating one more gets `409` with code `schedules_limit`. Changing an existing schedule still works | | Pending timers per invocation | 1,000 | The invocation fails with code `579`; the message starts with `timers_limit` | | State keys per virtual object or workflow | 10,000 | Writing a new key fails the invocation with code `579`; the message starts with `state_keys_limit` | | Artifact storage, whole environment | 1 GiB | Storing another artifact fails the invocation with code `579`; the message starts with `artifacts_limit` | | Sustained throughput | 200 compute units per second | New work waits and runs as capacity frees up | | Burst | 400 compute units | | | Open streams and attached waits, per environment and node | 256 | `429` with code `too_many_open_streams` | ### Live invocations and artifact storage [Section titled “Live invocations and artifact storage”](#live-invocations-and-artifact-storage) Both are counted every few seconds, so an environment can go a little over either one before new work is refused. An invocation is live while it runs, waits or is paused; it stops counting when it ends. Artifacts stop counting when the invocation that stored them is purged, by you or at the end of retention. ### Compute units [Section titled “Compute units”](#compute-units) A compute unit (CU) is one per durable step, one per invocation created, and one per started 100 ms that each turn is open. A turn is open while your service works on it, and that includes time your handler waits inside `ctx.run`, for example for a model to answer. Time an invocation spends suspended is not counted: after a `ctx.sleep`, or while it waits on a promise, an awakeable, a signal or another invocation, the SDK ends the turn and nothing is counted until the next one starts. A handler that sleeps for a week costs nothing while it sleeps. At 200 CU per second, about 20 turns can be open at once in an environment; further turns wait for capacity. The console’s **Usage** page shows compute units per hour and per handler. ### Payload [Section titled “Payload”](#payload) The payload limit applies to each request body sent to your environment. Inside an invocation, values larger than 256 KiB (state values, `ctx.run` results, invocation inputs and outputs, promise values) are stored as immutable segments in your environment’s storage. The journal keeps references, and a turn sends only the open tail of a value and what changed. Your code sees the whole value as before; nothing in the SDK API changes. A conversation history in `chatObject` therefore grows past the payload limit without trimming. We test histories up to 8 MiB. One value read back in a single response, such as the history from `transport.messages` or an output from the HTTP API, is capped at 64 MiB. See [Vercel AI SDK](/docs/agents/vercel-ai-sdk#size-and-cost). Files and images still belong in [artifacts](/docs/develop/artifacts): they are bytes your code stores and passes by reference, not values it reads back on every turn. ### Journal length [Section titled “Journal length”](#journal-length) Each step, sleep, call, state read or write and promise is a journal entry. An invocation that loops for a very long time should hand over to a fresh invocation (`ctx.continueAsNew`) rather than grow one journal without end. ### Open streams [Section titled “Open streams”](#open-streams) Each SSE stream reader (a chat page following a turn, for example) and each request waiting for an invocation’s result holds a connection. The cap is per environment on each node of the cell. The chat transport retries a refused connection with backoff. ## Turn time limit [Section titled “Turn time limit”](#turn-time-limit) In request-response mode, each turn of a handler is one HTTP request, and it must finish within the handler’s `inactivityTimeout`: **60 seconds** unless the service or the handler declares a longer one, up to one hour (see [Handler options](/docs/develop/services#handler-options)). Like every handler option, it is read when you register the deployment. A turn that takes longer is cut and retried. The step it was running starts again from the beginning on the next attempt (a model call is made, and paid for, again), and without a retry policy the retries do not stop. Keep each `ctx.run` well under the limit, declare a longer `inactivityTimeout` for the handlers that need one, and set a [retry policy](/docs/develop/errors-retries#retry-policy) with `maxAttempts`. Request-response is how Cloud calls an `https://` endpoint unless you register it with `"transport": "declared"`, and the only mode of `fetchHandler`. Only the streaming transport (`BIDI_STREAM`) keeps the connection alive while a closure runs, so a long step is not cut there. On a serverless platform a turn must also finish within the platform’s own time limit, and a proxy or tunnel in front of your service may have its own. ## Runtime limits [Section titled “Runtime limits”](#runtime-limits) These come from the runtime and apply to every environment: | Limit | Value | | ----------------------------------------------- | ----------------------------------------------------------------------------------------- | | Streams per invocation | 16 | | Temporary stream buffer, per stream | 1 MiB (older records are overwritten) | | Temporary stream kept after the invocation ends | about 60 seconds | | `ctx.log` per invocation | 1 MiB | | Trace spans per invocation | 1 MiB | | Durable streams per invocation, together | 8 MiB | | One SSE connection | at most 10 minutes; clients reconnect | | SQL query | 200,000 read units, 128 MiB, 10 seconds (up to 30 seconds with `timeout_ms`), 10,000 rows | | SQL queries at once | 4 per node, 2 of them per environment | Records over a stream or log cap are dropped and replaced by a `gap` marker; an invocation never fails because of a stream. ## Account limits [Section titled “Account limits”](#account-limits) Cloud is invite-only during the Beta: only an invited email address can create an organization, and environments can be created only in an organization whose owner was invited. People you invite into your organization do not need an invitation of their own. Invitations have not started. | Limit | Beta | At the limit | | ------------------------------------------------- | ---- | --------------------------- | | Organizations one person can create | 2 | `409` with code `org_limit` | | Environments per organization | 3 | `409` with code `env_limit` | | API keys per environment, active or being revoked | 20 | `409` with code `key_limit` | A deleted environment or a revoked API key frees its place once the deletion or revocation has finished. Changes made through the Cloud web app and its API are rate limited per person: over the limit they get `429` with code `rate_limited` and a `Retry-After` header. ## How Cloud calls your service [Section titled “How Cloud calls your service”](#how-cloud-calls-your-service) * **HTTPS only.** Deployments must be `https://` URLs on the public internet. Private and internal addresses are refused. * **Identity keys are required.** Your service must check the environment’s identity key (`identityKeys` in `serve()` or `fetchHandler()`). * **Request-response by default.** Each time a handler resumes is a new request. On serverless platforms the runtime sends the journal recorded so far with every resume; a long-running `serve()` keeps recent journals in memory, so a resume usually carries only what is new. Long journals and large step results still cost bytes: keep step results small. Each turn must finish within the [turn time limit](#turn-time-limit). Streaming needs `"transport": "declared"` and HTTP/2 all the way to your app; see [Deployments](/docs/cloud/deployments#transport). * **No telemetry export from your handlers.** Spans and logs stay in the console; exporting them to your own OpenTelemetry collector is turned off on shared cells. ## No SLA [Section titled “No SLA”](#no-sla) The Beta has no service level agreement and no uptime credit. Plan for interruptions. # Query with SQL > Ask questions about invocations, journals, state and usage with read-only SQL over POST /query. Everything cairnflow knows about your environment can be read with SQL: invocations and their state, journals, timers, promises, streams, deployments, schedules and usage. Queries are read-only, run across every node of the cell, and see only your environment’s data. Use it from the console’s **Query** page, or over HTTP: ```sh curl -X POST "$CAIRN_URL/query" \ -H "authorization: Bearer $CAIRN_KEY" \ -H "content-type: application/json" \ -d '{"sql": "SELECT service, class, sum(count) AS n FROM sys_invocation_counts GROUP BY service, class"}' ``` You need a key or console role that can read the environment: an **Admin** key, or a console session of an owner, admin, member or viewer. An Invoke only key cannot query. ## Request and response [Section titled “Request and response”](#request-and-response) | Field | Meaning | | --------------- | ----------------------------------------------------------- | | `sql` | One read-only statement | | `params` | Values for `$1 … $n`: strings, integers, booleans or `null` | | `allow_partial` | Default `true`. `false` turns a partial answer into a `503` | | `timeout_ms` | Default 10,000; at most 30,000 | ```json { "columns": [{ "name": "service", "type": "…" }, { "name": "n", "type": "…" }], "rows": [["Chat", 42], ["Greeter", 7]], "partial": false, "warnings": [], "read": 12, "ms": 3 } ``` Times come back as ISO-8601 strings; numbers and booleans keep their type. `read` is the number of read units the query used. ### Parameters [Section titled “Parameters”](#parameters) Pass values separately instead of writing them into the SQL text. They are bound before the query is planned and never become SQL: ```json { "sql": "SELECT id, class, created_at FROM sys_invocation WHERE service = $1 AND key = $2", "params": ["Chat", "chat-42"] } ``` Parameters are positional and consecutive (`$1`, `$2`, …), with exactly one value each. Named parameters, floats, arrays and objects are refused. ## The tables [Section titled “The tables”](#the-tables) | Group | Tables | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | Invocations | `sys_invocation` (one row per invocation), `sys_invocation_counts` (counts per service, handler and state) | | Inside one invocation | `sys_journal`, `sys_timer`, `sys_attachment`, `sys_log`, `sys_span`, `sys_stream`, `sys_stream_record`, `sys_artifact`, `sys_outbox` | | Objects and workflows | `sys_state`, `sys_value`, `sys_promise`, `sys_promise_waiter`, `sys_object`, `sys_vqueue_entry` | | Scheduled work | `sys_schedule`, `sys_delayed` | | Code | `sys_deployment`, `sys_service`, `sys_handler` | | Usage and performance | `sys_metering`, `sys_artifact_bytes`, `sys_handler_stats`, `sys_handler_history`, `sys_slow_run` | | History | `sys_archive`, `sys_audit` | Columns and meanings are in the [table reference](/docs/query/tables). **Some tables need a key.** Tables that read inside one invocation or one object require an equality filter on their key, so a query never scans everything: `id = …` for `sys_journal`, `sys_log`, `sys_artifact` and the other per-invocation tables; `service = … AND key = …` for `sys_state`, `sys_value`, `sys_promise` and `sys_promise_waiter`. Without it the query is refused with `400`. ## Questions operators ask [Section titled “Questions operators ask”](#questions-operators-ask) ### What is stuck? [Section titled “What is stuck?”](#what-is-stuck) Invocations still running or waiting after an hour: ```sql SELECT id, service, handler, status, created_at FROM sys_invocation WHERE class = 'active' AND created_at < now() - INTERVAL '1 hour' ORDER BY created_at LIMIT 50 ``` Paused invocations (out of attempts, or stopped by an error that needs a person), with the last error: ```sql SELECT id, service, handler, last_failure_message, transitioned_at FROM sys_invocation WHERE class = 'paused' ORDER BY transitioned_at DESC, id LIMIT 50 ``` Invocations waiting for a retry, and why the last attempt failed: ```sql SELECT id, service, handler, attempt, retry_at, last_failure_code, last_failure_message FROM sys_invocation WHERE retry_at IS NOT NULL ORDER BY retry_at LIMIT 50 ``` ### What is one invocation waiting for? [Section titled “What is one invocation waiting for?”](#what-is-one-invocation-waiting-for) ```sql SELECT index, name, entry_lite FROM sys_journal WHERE id = $1 ORDER BY index ``` In `entry_lite`, a command with `"completed": false` is still waiting for its result: a call, a promise, a sleep. Pending sleeps are also in `sys_timer`: ```sql SELECT completion_id, due_at_ms FROM sys_timer WHERE id = $1 ``` The console’s **Why it is in this state** panel answers the same question in words. ### What is failing? [Section titled “What is failing?”](#what-is-failing) ```sql SELECT id, service, handler, failure_code, failure_message, transitioned_at FROM sys_invocation WHERE class = 'failed' ORDER BY transitioned_at DESC, id LIMIT 50 ``` Failed invocations per handler, from in-memory counters (reads nothing from storage): ```sql SELECT service, handler, sum(count) AS n FROM sys_invocation_counts WHERE class = 'failed' GROUP BY service, handler ORDER BY n DESC LIMIT 10 ``` Common failure codes: `572` cancelled, `575` out of attempts, `578` journal too long. See [Errors](/docs/reference/errors). ### What is slow? [Section titled “What is slow?”](#what-is-slow) Handlers by turn latency over the recent window: ```sql SELECT service, handler, sum(turns) AS turns, sum(failed) AS failed, max(p99_ms) AS p99_ms FROM sys_handler_stats GROUP BY service, handler ORDER BY p99_ms DESC LIMIT 10 ``` Invocations that took longer than ten seconds end to end: ```sql SELECT id, service, handler, duration_ms FROM sys_invocation WHERE duration_ms >= 10000 ORDER BY created_at DESC, id LIMIT 50 ``` Long journals, which cost more on every resume in request-response mode: ```sql SELECT id, service, handler, journal_len FROM sys_invocation WHERE journal_len >= 100 ORDER BY created_at DESC, id LIMIT 50 ``` ### How much is used? [Section titled “How much is used?”](#how-much-is-used) The current hour: ```sql SELECT hour, invocations, steps, run_ms, input_tokens, output_tokens, units FROM sys_metering ``` Completed, failed and compute units per hour, from a start time in milliseconds: ```sql SELECT hour_ms, sum(completed) AS completed, sum(failed) AS failed, sum(cu) AS cu FROM sys_handler_history WHERE hour_ms >= $1 GROUP BY hour_ms ORDER BY hour_ms ``` Tokens of one agent turn, per model call: ```sql SELECT name, input_tokens, output_tokens FROM sys_span WHERE id = $1 AND input_tokens IS NOT NULL ``` ### Find an invocation [Section titled “Find an invocation”](#find-an-invocation) By object key, idempotency key, tag, parent or whole call tree: ```sql SELECT id, handler, class, created_at FROM sys_invocation WHERE service = 'Chat' AND key = 'chat-42' ORDER BY created_at DESC, id LIMIT 50; SELECT id, service, handler, class FROM sys_invocation WHERE idempotency_key = 'order-42' LIMIT 10; SELECT id, parent_id, service, handler, class FROM sys_invocation WHERE root_id = $1 ORDER BY id; ``` Send one statement per request; the block above shows three. ## Consistency [Section titled “Consistency”](#consistency) * **Only durable data.** A query sees rows that are committed to storage. It never waits for, or slows down, the invocations it reads. When the node ships the query worker, each statement runs in a separate worker process, apart from the engine. * **Counts are exact** as of the last commit of each key range: `sys_invocation_counts` is kept in memory and updated with each commit. * **Partial answers are flagged.** If part of the data cannot be read (a node does not answer, or an index is still being built after a change), the answer has `partial: true` and a `warnings` entry per affected range (`reason` such as `indexing`). It never silently drops rows. Send `allow_partial: false` to get a `503` instead. * **Live tables come from the API.** Deployments, services, schedules, statistics, usage, archive and audit tables are read through the same API the console uses, with your key’s permissions. ## Limits and errors [Section titled “Limits and errors”](#limits-and-errors) | Answer | Cause | | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | SQL syntax error, unknown table or column, a statement that is not read-only (DDL, DML, `COPY`, `SET`), table functions, recursive CTEs, file reads, a keyed table without its key, or a statement too large to plan: over 64 KiB of text, more than 500 operators, more than 64 joined tables or more than 64 query blocks (`SELECT`, `UNION`, …) | | `422`, `error` starting with `query_budget:` | The query would read more than 200,000 read units, use more than 128 MiB, run longer than its timeout, or return more than 10,000 rows. Add a `LIMIT` or filter on an indexed column (`service`, `class`, `created_at`, `id`) | | `429` | More than 4 queries at once on a node or 2 of your environment’s, or your environment used up its read units for now (`error` starting with `query_budget:`). Retry shortly | A query either completes or fails: an error never comes back as a truncated `200`. `sys_invocation` is stored in `created_at DESC, id` order, so “newest first” lists with a `LIMIT` are cheap. Filters on `id`, `service`, `handler`, `key`, `kind`, `class`, `root`, `parent_id`, `root_id`, `schedule`, `deployment`, `restarted_from`, `created_at`, `transitioned_at` and `duration_ms` are applied during the scan; filters on other columns are applied after reading, so combine them with one of these. ## Next [Section titled “Next”](#next) * [Table reference](/docs/query/tables) * [The console](/docs/cloud/console) # CLI > Reference for the cairn command-line client, plus a summary of the cairn-ctl recovery tool. `cairn` is a thin client of the [HTTP API](/docs/reference/http-api): each command is one request (or two, when it follows a `503` to the leader). It prints a readable table by default and the raw JSON with `--json`. ## Global options [Section titled “Global options”](#global-options) ```sh cairn [--server URL] [--token KEY] [--json] ... ``` | Option | Environment | Default | Meaning | | -------------- | ------------------ | ----------------------- | ----------------------------------------- | | `--server URL` | `CAIRNFLOW_SERVER` | `http://127.0.0.1:8080` | Node or endpoint to talk to. | | `--token KEY` | `CAIRNFLOW_TOKEN` | none | API key, sent as `Authorization: Bearer`. | | `--json` | | off | Print the API’s JSON instead of a table. | | `--version` | | | Print the version line. | ```sh export CAIRNFLOW_SERVER=https://cairn.example.com export CAIRNFLOW_TOKEN= ``` When a node answers `503` with a `leader`, `cairn` resends the request there once. Exit codes: `0` success; `1` the request failed (the CLI prints the HTTP status and the error message); `2` wrong usage (the CLI prints the usage text); `3` `replay --bundle` found a mismatch. ## Deployments and services [Section titled “Deployments and services”](#deployments-and-services) | Command | Does | | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `cairn register ` | Register the service at `` (`POST /deployments`). Prints the deployment id and its services. | | `cairn deployments` | List deployments and which services they are the current revision for. | | `cairn deployments rm ` | Remove a deployment that is no longer a revision and has no bound invocations. | | `cairn revision [--expect ID]` | Point a service at another deployment (rollback, pinning). With `--expect`, only if the current revision is `ID`. | | `cairn services` | Services and handlers you can call. | The URL you register must be reachable from the cairnflow nodes. ## Invoking [Section titled “Invoking”](#invoking) ```sh cairn invoke [--key K] [--input DATA] [--scope S] [--limit-key L] ``` | Option | Meaning | | --------------- | ---------------------------------------------------- | | `--key K` | Object key (virtual object) or workflow id. | | `--input DATA` | Request body. `-` reads it from stdin. | | `--scope S` | Run in a flow-control scope (`/scope/S/invoke/...`). | | `--limit-key L` | Limit key inside the scope. Requires `--scope`. | ```sh cairn invoke Greeter greet --input '"world"' cairn invoke Cart add --key user-1 --input '{"sku":"tea"}' echo '{"amount": 100}' | cairn invoke Orders submit --key order-42 --input - ``` The command waits like `POST /invoke`: it prints the result, or the invocation id when the result is not ready within the node’s wait time. ## Workflows [Section titled “Workflows”](#workflows) ```sh cairn workflow [--attach] [--scope S] ``` Prints the result of a workflow’s run, found by its workflow id. Without `--attach` it does not wait (`GET /workflow/.../output`); with it, it waits (`POST /workflow/.../attach`). ## Inspecting invocations [Section titled “Inspecting invocations”](#inspecting-invocations) | Command | Does | | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------ | | `cairn status ` | State of one invocation, with its output or error. | | `cairn journal ` | The journal, entry by entry. | | `cairn invocations [--status S] [--limit N] [--all-nodes]` | Invocations of the ranges led by the node you ask; `--all-nodes` asks the whole cluster. | | `cairn invocations --cursor '' [--tag k=v] [--class C] [--service S] [--root] [--limit N]` | Paged listing across the cluster, newest first. Any of these options selects it; pass the printed cursor to get the next page. | | `cairn sql ""` | Run a read-only SQL query (`POST /query`). | | `cairn stats [--window 5m\|15m\|1h] [--tenant T] [--all-nodes]` | Per-handler summary: turns, outcomes, failed attempts, p50, p99, max. | ```sh cairn invocations --status suspended cairn sql "SELECT class, sum(count) FROM sys_invocation_counts GROUP BY class" ``` ## Acting on invocations [Section titled “Acting on invocations”](#acting-on-invocations) | Command | Does | | ------------------------------------------------- | ---------------------------------------------- | | `cairn cancel ` | Hard cancel (`failed`, code 572). | | `cairn purge ` | Delete a finished invocation now. | | `cairn resume ` | Take an invocation out of `paused` and run it. | | `cairn signal [--value JSON]` | Send a signal to a waiting invocation. | ## Promises [Section titled “Promises”](#promises) | Command | Does | | ----------------------------------------------------- | ---------------------------------------- | | `cairn resolve [--value JSON]` | Resolve a durable promise. | | `cairn reject ` | Reject it; waiters get a terminal error. | | `cairn promise ` | Show whether the promise has a result. | ```sh cairn signal approve --value '{"by":"alice"}' cairn resolve Orders order-42 approved --value '"ok"' ``` ## API keys [Section titled “API keys”](#api-keys) | Command | Does | | ----------------------------------- | -------------------------------------------------------- | | `cairn keys` | List stored keys (never secrets). | | `cairn keys create ` | Create a key. The secret is printed **once**. | | `cairn keys rm ` | Revoke a key. Reports nodes that have not confirmed yet. | | `cairn keys check ` | Whether the key is still accepted by any live node. | Roles accepted by the API are `invoke`, `view`, `admin`, `provision` and `cluster-admin`. See [Security](/docs/self-hosting/security#roles). ```sh cairn keys create default invoke ``` ## Flow control [Section titled “Flow control”](#flow-control) | Command | Does | | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | | `cairn rules` | The rule book. | | `cairn rules set [--concurrency N\|unlimited] [--description TXT] [--disabled\|--enabled]` | Add or update a concurrency rule (merge). | | `cairn rules rm ` | Remove a rule. | | `cairn limits` | Usage, limit and availability of each active counter. | | `cairn vqueues` | Queues that have work, and what blocks them. | | `cairn scheduler` | Queue depth, slots in use, locks held, rule book version in effect. | Rate limits (`rate`, `burst`) and per-tenant rows are set through `POST /rules`; see [Flow control](/docs/reference/flow-control). ## Cluster [Section titled “Cluster”](#cluster) | Command | Does | | -------------------------------------- | ------------------------------------------------------------------------- | | `cairn cluster` | Who leads each range. | | `cairn ranges` | The range table: version, key bounds, generation, pending split or merge. | | `cairn ranges split [--at HEX16]` | Split a range (default: the middle of its keys). | | `cairn ranges merge ` | Merge two adjacent ranges. | ## Capturing runs for debugging [Section titled “Capturing runs for debugging”](#capturing-runs-for-debugging) | Command | Does | | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `cairn capture [--tenant T] [--deployment D] [--count N] [--ttl SECONDS]` | Capture the next matching invocations (journal and final state) when they finish or pause. | | `cairn capture ls [--tenant T]` | Pending capture requests and captured bundles. | | `cairn capture get [--out FILE]` | Download a bundle (default `.bundle`). | | `cairn replay --bundle FILE [--endpoint URL]` | Replay a bundle against a service, read-only, without a cluster. `--endpoint` points at a local build you are fixing. Exits `3` on a mismatch. | Capture commands need a `cluster-admin` key. ## cairn-ctl [Section titled “cairn-ctl”](#cairn-ctl) `cairn-ctl` is a separate tool that works on the bucket directly, without a running node. It takes the store like a node does (`--main-store URI` or `--data-dir DIR`, optional `--wal-store` and `--prefix`) and the bucket credentials from the environment. | Command | Does | | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `verify [--deep] [--wal-logs] [--no-restore-checks]` | Check the bucket’s invariants; exit code `1` on findings. `--deep` also checks that every data file a range’s manifest names is present (one listing per range). By default it also looks for cross-range calls that lost a message; `--no-restore-checks` turns that off. | | `table show`, `owners`, `ranges retired`, `wal floors`, `range dump ` | Read-only views of the range table, ownership records and data. | | `cluster status` | Cluster version, gates and live sessions. | | `cluster enable- --apply` | Turn on a one-way feature gate after every node is upgraded. | | `table restore [--force] --apply` | Rebuild a lost range table from its newest saved version, only when the rest of the bucket proves it is the last one. Every node must be stopped. | | `keys create --apply` | Create an API key directly in the bucket. | | `identity publish\|activate\|retire --apply` | Rotate a tenant’s request-signing key. | | `pricing`, `pricing set --apply` | The token price table, in micro-USD per million input and output tokens (`0 0` removes a model). | | `backup --to URI`, `backup list`, `backup prune`, `restore --from URI`, `backup check-restore` | Backups at another store. | | `trash list`, `trash restore` | Inspect and restore cairnflow’s own deletions. | | `fork --to [--artifacts live\|all\|none]` | Copy the cluster under another prefix for investigation, with live artifacts by default. | | `intent clear `, `range force-retire ` | Repair a stuck split or merge. | | Option | Meaning | | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--backup-env-prefix P` | The backup store (`--to` of `backup`, `backup list` and `backup prune`, `--from` of `restore`) takes its credentials, endpoint and region only from `P`-prefixed `AWS_*` variables, for example `CAIRN_BACKUP_AWS_ACCESS_KEY_ID`. Without it, the backup store uses the same `AWS_*` variables as `--main-store`. | | `--report-to-bucket ID` | Also write the result (the JSON of `--json`, the exit code, the error; no secrets) to the cluster’s bucket, readable with a `provision` key at `GET /admin/ops-reports/{ID}`. Only for `backup`, `backup list`, `backup prune`, `restore`, `cluster status`, `cluster enable-*` and `table restore`. `ID` is 1 to 128 characters of `A-Za-z0-9-_.` and must be new for each run. | | `--who NAME` | Who is running the command, recorded in the bucket’s audit log (default `$USER@$HOST`). | | `--json` | Print JSON. | Commands that write run dry unless you add `--apply`. Exit codes: `0` done, `1` `verify` found problems, `2` bad arguments, `3` refused, `4` store error. See [Backup and restore](/docs/self-hosting/backup-restore). # Errors > The cairnflow error body, HTTP status codes, machine-readable error codes, invocation failure codes, and what clients should retry. Two kinds of failure come back from the API, and they are easy to tell apart: * **The request failed.** The body is the common error body below. * **The invocation reached an outcome.** `/invoke`, `/send`, workflow and attach routes answer with a body that has a `status` field (`failed`, `paused`, `throttled`, …). See [Invoking handlers](/docs/reference/http-api#invoking-handlers). ## The error body [Section titled “The error body”](#the-error-body) ```json { "error": "a sentence for humans", "code": "range_overloaded", "retry_after_ms": 1000 } ``` | Field | Present | Meaning | | ---------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------- | | `error` | always | A message for people. Do not parse it. | | `code` | some errors | A stable machine-readable code (see below). | | `leader` | some `503` | The client address of the node that leads the range. Retry once there. | | `id` | when known | The invocation the error is about. Its existence is not guaranteed: look it up, or resend with the same `Idempotency-Key`. | | `retry_after_ms` | some `429` | When to try again. A `Retry-After` header (seconds) accompanies it. | | `table` | `409 wrong_range` | The current range table, for internal callers. | Unexpected internal errors answer `500` with a generic message that includes a reference code; the details are only in the node’s log. ## HTTP status codes [Section titled “HTTP status codes”](#http-status-codes) | Status | Meaning | What to do | | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `400` | Bad request: malformed parameter, invalid header, limit key without scope, forbidden SQL. | Fix the request. | | `401` | Missing or invalid key. | Check the key. | | `403` | The key’s role does not allow this route, or the tenant is suspended or being deleted. | Use a key with the right role. | | `404` | Not found, including an invocation of another tenant. | Do not retry. | | `409` | Conflict: invocation `paused` or `already_invoked` (as a `status`), purge of a running invocation, resume of an invocation that is not paused, deployment still in use or being removed, revision moved under you, disabled feature gate. | Read the state, then decide. | | `410` | Stream expired. | Do not retry. | | `413` | Request body over 2 MiB, payload larger than the tenant’s limit (`payload_too_large`), or an output too large to return in one response (`value_too_large`). | Send less; use artifacts for large data. | | `422` | SQL query over budget (the `error` starts with `query_budget:`). | Narrow the query, add `LIMIT`. | | `429` | Too many requests or over a limit. See the codes below: some mean the work was accepted, some mean nothing was created. | Wait for `Retry-After`. | | `500` | Internal error, or `status: failed` on invoke routes. | For a generic `500`, retry with the same `Idempotency-Key`. | | `502` | The node lost the operation before it could answer (for example while accepting an invocation, or stepping down as leader). | If an `id` is present, look it up; otherwise resend with the same `Idempotency-Key`. | | `503` | Not the leader (with `leader`), the cluster is electing a leader or changing its range table (without `leader`), or storage is briefly unavailable (`store_unavailable`). | With `leader`: retry once there. Without: back off and retry. | | `504` | A forwarded request (`x-cairn-forward: leader`) was sent but no response came back. The operation may have run. | Check state, or resend with the same `Idempotency-Key`. | ## Error codes [Section titled “Error codes”](#error-codes) | `code` | Status | Meaning | | ------------------------ | ------ | --------------------------------------------------------------------------------------------------------------------------------------------- | | `range_overloaded` | `429` | The range is overloaded (compaction is behind). **Nothing was created**, no `id`. Resending after `Retry-After` is safe. | | `tenant_limited` | `429` | The tenant is in the `limited` state. Nothing was created. | | `live_invocations_limit` | `429` | The tenant has reached its limit of live invocations. Nothing was created. | | `deploy_rate_limited` | `429` | Too many deployment registrations for the tenant. Retry after `Retry-After`. | | `sse_limit` | `429` | The node has reached its limit of open event streams. Reconnect after `Retry-After`. | | `too_many_open_streams` | `429` | The tenant has reached its limit of long-lived connections on this node. | | `value_assembly_busy` | `429` | The tenant already has 4 large outputs being assembled on this node. Retry after `Retry-After`. | | `tenant_suspended` | `403` | The tenant is suspended. | | `tenant_deleting` | `403` | The tenant is being deleted or has been deleted. | | `egress_denied` | `400` | The node’s outbound policy refused the deployment’s endpoint. The message says which address and why. | | `identity_required` | `400` | The node requires services that verify signed requests. Set `identityKeys` in `serve()` and register again. | | `compression_required` | `400` | The node requires request compression for request-response deployments. Enable `compression` (the TypeScript SDK default) and register again. | | `payload_too_large` | `413` | The request body exceeds the tenant’s payload limit. | | `value_too_large` | `413` | An output larger than 64 MiB cannot be returned in one response. | | `deployments_limit` | `409` | The tenant has reached its limit of deployments. Remove an old one. | | `schedules_limit` | `409` | The tenant has reached its limit of schedules. | | `schedules_disabled` | `409` | Server-side schedules are not enabled on this cluster yet. | | `key_roles_disabled` | `409` | `view` and `provision` keys are not enabled on this cluster yet. | | `wrong_range` | `409` | Internal: a node addressed a range with a stale table. | | `stream_expired` | `410` | The stream is no longer kept. | | `store_unavailable` | `503` | The cell’s storage failed for a moment. Nothing about the storage is in the body. Retry later. | | `keys_busy` | `503` | Too many key changes at once. Nothing was written; retry after `Retry-After`. | SQL query limits have no `code` field: the `error` of a `422` (over the read, memory, time or row budget) or of a `429` (the tenant used up its read units) starts with `query_budget:`. Codes for operators of multi-tenant nodes also exist (`tenant_state_disabled`, `tenant_purge_disabled`, `tenant_purging`, `tenant_purged`), returned by the tenant administration routes. ### `429 throttled` versus `429 range_overloaded` [Section titled “429 throttled versus 429 range_overloaded”](#429-throttled-versus-429-range_overloaded) They look alike and mean opposite things: * **`status: "throttled"`** in an invoke body: the invocation **was accepted**, is durable, and will run when the limit allows. The body has an `id`. Do not resend; wait or attach. * **`code: "range_overloaded"`**: **nothing was created**. Resend after `Retry-After`. With the same `Idempotency-Key` (or the same workflow id) the resend maps to a single invocation. An invocation that already exists never gets this answer. ## Invocation failure codes [Section titled “Invocation failure codes”](#invocation-failure-codes) A `failed` or `paused` invocation carries a numeric `code` and a `message`. Other codes come from your handler (the code of a `TerminalError`, HTTP-like). The runtime uses: | Code | Meaning | | ----- | --------------------------------------------------------------------------------------------------------------------- | | `570` | Journal mismatch: the handler took a different path on replay than the journal records (for example, a renamed step). | | `571` | Protocol violation by the service, including a state write (`set`, `clear`, `clearAll`) from a `SHARED` handler. | | `572` | Cancelled. | | `573` | Workflow already invoked. | | `574` | Missing object key for a virtual object handler. | | `575` | Retry attempts exhausted (`retryPolicyMaxAttempts`). The message includes the last error. | | `576` | Quarantined: new invocations of a handler that keeps failing are held. | | `577` | Stuck on infrastructure: the runtime cannot move the invocation forward. | | `578` | Journal longer than the tenant’s limit. | | `579` | Over a tenant resource limit. The message starts with `timers_limit`, `state_keys_limit` or `artifacts_limit`. | | `413` | An output or state value larger than the tenant’s payload limit. | A `paused` invocation keeps its place; fix the cause (deploy a fix, or migrate it), then `POST /invocations/{id}/resume`. Resuming a `570` without changing the deployment reproduces the same mismatch. ## What to retry [Section titled “What to retry”](#what-to-retry) * **Always resend with an `Idempotency-Key`.** Without one, a retry after a timeout or a `502` can run the side effect twice. With one, the retry points to the same invocation and returns its result or its current state. Keys are remembered for the retention period (24 hours by default). * **`503` with `leader`**: once, to that address. The CLI and the TypeScript SDK client do this for you. * **`503` without `leader`**, **`429` with `Retry-After`**, generic **`500`**: back off and retry. * **`202 waiting`**: not an error. Attach (`POST /invocations/{id}/attach?wait_ms=25000`) or poll `GET /invocations/{id}`. * **`4xx` other than `429`**: do not retry unchanged. * **Workflows**: a workflow’s `run` must not carry an `Idempotency-Key`; the workflow id already deduplicates. A second call gets `409 already_invoked` with the id; attach with `/workflow/{service}/{key}/attach`. # Flow control > Scopes, limit keys, concurrency and rate rules, how 429 differs from 202, and the diagnostics endpoints. Concurrency limits are the one valve that closes before money leaves the account. When every running invocation calls a paid model or API, a traffic spike does not make the system slower; it makes the bill bigger. Flow control lets you cap how much runs at once, per customer or per plan. ## Two entry points [Section titled “Two entry points”](#two-entry-points) | Path | Behaviour | | -------------------------------- | --------------------------------------------------------------------------------------- | | `POST /invoke/...` | Subject to no limit other than the node’s turn capacity (`--max-concurrent-turns`). | | `POST /scope/{scope}/invoke/...` | Everything this invocation touches lives **in the scope**, and the scope’s rules apply. | A scope is not a label for counting: it is **part of identity**. | Thing | Without scope | In scope `bob` | | ------------------------------ | --------------------- | ------------------------------------------------------ | | Virtual object `Cart/a` | one instance | a **different** instance, with its own state and queue | | `Idempotency-Key: k` | deduplicated globally | deduplicated **within `bob`** | | Promise `(service, key, name)` | one promise | a separate promise | So `/invoke/Cart/add?key=u1` and `/scope/bob/invoke/Cart/add?key=u1` address two different objects. They do not see each other’s state and do not lock each other. Scope names use `[a-zA-Z0-9_.-]`, are not empty and are at most 36 bytes; anything else is `400`. Calls made from inside a scoped invocation stay in its scope, which also decides which range runs them. ## Limit keys [Section titled “Limit keys”](#limit-keys) `?limit-key=l1` or `?limit-key=l1/l2` (or the `x-cairn-limit-key` header) splits a scope’s budget further, for example per user inside a customer’s scope. * **A limit key requires a scope.** On the unscoped path it is `400`: with no scope there is no counter to attach it to, and silently ignoring it would let you believe a limit is in place. * **A limit key is not part of identity.** Two calls with the same target, scope and object key but different limit keys reach the **same** virtual object. The limit key only affects queueing. ```sh curl -X POST "$CAIRNFLOW_SERVER/scope/acme/invoke/Agent/run?limit-key=user-42" \ -H "Authorization: Bearer $CAIRNFLOW_TOKEN" -d '{"prompt":"..."}' ``` ## The rule book [Section titled “The rule book”](#the-rule-book) Rules are cluster-wide and managed with a `cluster-admin` key (a `provision` key can manage the per-tenant rate rows only). Counters are per tenant: a rule `acme` with concurrency 10 gives **each** tenant’s scope `acme` its own 10 slots. | Method and path | Purpose | | ------------------------------------ | ------------------------------------------------------------------------------- | | `GET /rules` | The whole rule book with its `version`: pattern rules and per-tenant rate rows. | | `POST /rules` | Add or update a pattern rule. Idempotent and merging. | | `POST /rules` with `{"tenant": ...}` | Rate limit for a whole tenant. | | `DELETE /rules/{pattern}` | Remove a pattern rule. `404` if absent. | | `DELETE /rules?tenant=` | Remove a tenant’s rate row. `404` if absent. | ```json { "pattern": "acme/growth", "concurrency": 5, "rate": 50, "burst": 100, "description": "growth plan", "disabled": false } ``` * A field you leave out is **not touched**. `null` on `concurrency`, `rate` or `burst` removes that limit, so the next less specific rule applies; `"unlimited"` sets no limit explicitly. * `pattern` is `comp`, `comp/comp` or `comp/comp/comp`, where each part is a value or `*`. The first part matches the scope, the next ones the limit key levels. * **The most specific rule wins**, from the scope down: `checkout/premium` beats `checkout/*`, which beats `*/premium`, which beats `*/*`. A rule applies only to counters at its own depth: `scope/l1` limits the first limit-key level, not the scope. * Each property has its own winner: the concurrency of a counter comes from the most specific rule that **sets** `concurrency`, and its rate from the most specific rule that sets `rate`. * `disabled: true` keeps the rule but removes it from matching. Disabling a specific rule can let a broader `*` rule win, which **loosens** the limit rather than removing it. Caution **`*` is not a shared pool.** `{"pattern": "*", "concurrency": 1000}` gives **each** scope its own budget of 1000; two scopes can run 2000 invocations at once under that rule. Every API response involving `*` repeats this in a `warning` field. The node that writes a rule change notifies the other nodes, which re-read the rule book right away; each node also re-reads it every 30 seconds in case a notice was missed. Compare `version` in `/rules` with `rulesVersion` in `/scheduler` to see whether a node has picked a change up. ### Rate limits [Section titled “Rate limits”](#rate-limits) `rate` is in **compute units per second**, the same unit as `cu` in `GET /metering`. A turn costs its durable steps plus one unit per started 100 ms of run time. One unit is taken before a turn and the rest after it; the bucket may go negative, and the next turn waits until it is positive again. `burst` (default: equal to `rate`) is the most units that can accumulate. * **Per tenant** (`{"tenant": "acme", "rate": 50, "burst": 100}`): the rate is split evenly across the nodes that currently lead at least one range, so the total never exceeds `rate`. If load concentrates on one node, the tenant gets less than `rate`. * **Per pattern**: like concurrency, every matching `(tenant, counter)` has its own bucket. * Only turns are rate-limited; creating an invocation is not. ## `429` versus `202` [Section titled “429 versus 202”](#429-versus-202) | Situation | Answer | Why | | -------------------------------------------------------------- | ------------------------------------------------------------------------- | -------------------------------------- | | Waiting for the exclusive lock of a virtual object | `202 waiting` | Normal serialisation, not a limit. | | Scope or limit key out of concurrency budget | `429` with `status: "throttled"` and `Retry-After` | The tenant hit its cap. | | Tenant or counter out of rate tokens | `429` with `status: "throttled"`, `Retry-After` = when the bucket refills | Same, for rate limits. | | Waited longer than `--queue-wait-ms` (default 10 s) for a slot | `429` with `status: "throttled"` | The invocation stays queued. | | Range overloaded: compaction behind | `429` with `code: "range_overloaded"`, **no `id`** | Nothing was created. | | Node is not the leader | `503` with `leader` | Go to another node, do not wait. | | Range being split or merged, or without a leader yet | `503` without `leader` | Wait a moment and retry the same node. | A `throttled` answer is **not a refusal**: the invocation was accepted, is durable, is queued, and will run. The body carries its `id`, so you can look it up or attach. `Retry-After` (seconds) says when to check back. `range_overloaded` is different: nothing exists yet, and resending after `Retry-After` is safe and expected. Only new work is refused, only on the invoke routes, with a probability that grows with the range’s backlog and never reaches 100 percent. Everything already running (completions, timers, retries, signals, attach, calls between invocations) continues, since draining it is what lets the range recover. `503` is never used for limits, because it already means “not the leader” and clients handle the two differently. ## Diagnostics [Section titled “Diagnostics”](#diagnostics) | Method and path | Answers | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /limits` | Which counters are in use, their limit, what is left, and which rule won. | | `GET /vqueues` | Which queues have work, how much is waiting, and what blocks it. | | `GET /scheduler` | Queue depth, slots in use, locks held, the `rulesVersion` in effect, and per-tenant rate buckets (`rate`, `burst`, `balance`; negative means debt). | All three are `cluster-admin` and describe only the **ranges led by the node you ask**. Ask each node, or use `cairn limits`, `cairn vqueues` and `cairn scheduler` against each one. Two things to keep in mind when reading them: * `GET /limits` lists only counters that are **not zero**. To see the limit of a scope that is idle, read `/rules`. * Per-queue statistics are kept in memory and reset when a range changes leader. Metrics: `cairnflow_flow_granted_total`, `cairnflow_flow_wait_ms_total` (divide by `granted` for the average wait), `cairnflow_flow_blocked_total{resource="lock|concurrency|turns"}`, `cairnflow_flow_throttled_total` and `cairnflow_invoke_throttled_total`. Labels carry the kind of resource, never scope names. ## Limits to know [Section titled “Limits to know”](#limits-to-know) A scope belongs to **one range**, and a range is a single writer committing through object storage. The effective concurrency of one scope is therefore bounded by what one range on one node can sustain, whatever its rule says: `concurrency: 10000` on one scope does not give you 10 000. Think about scope cardinality up front. One scope per large customer works well; one scope per request does not. # HTTP API > Reference for the cairnflow ingress and admin HTTP API, grouped by area, with parameters and main responses. Every capability of cairnflow is an HTTP endpoint with JSON bodies. The `cairn` CLI and the console are thin clients of this API; anything they do, `curl` can do. ## Conventions [Section titled “Conventions”](#conventions) **Base URL.** The client port of any node, `http://:8080` by default, or your environment’s endpoint on Cairnflow Cloud. **Authentication.** Every route except `GET /health` and `GET /values/v1/{token}` needs `Authorization: Bearer `. Missing or wrong key: `401`. Role not allowed: `403`. The role each route needs is noted below; see [Security](/docs/self-hosting/security#roles) for what each role includes. The role columns give the smallest tenant role that can call a route: `admin` can do what `view` and `invoke` can, `cluster-admin` can call everything, and `GET` routes open to `invoke` are open to `view` too. **Tenant.** Every request acts in the tenant of its key. Invocations of another tenant answer `404`. A `cluster-admin` key can pass `?tenant=` on tenant routes that document it. **Errors.** Errors have a JSON body with at least `error` (a sentence for humans, do not parse it). See [Errors](/docs/reference/errors) for `code`, `leader`, `id` and retry rules. **Request bodies** are capped at 2 MiB; a larger body gets `413`. **Leaders.** In a cluster, a request handled by the wrong node gets `503` with `leader`. Retry once there, or send `x-cairn-forward: leader` and let the node forward the request. **Invocation ids** are 48 hex characters. Treat them as opaque strings: store them and look them up on any node later. Calls made with an `Idempotency-Key` get an id that is deterministic for that key. ## Invoking handlers [Section titled “Invoking handlers”](#invoking-handlers) | Method and path | Purpose | | ----------------------------------------------------- | --------------------------------------------------------------------- | | `POST /invoke/{service}/{handler}` | Call and wait for the result, up to `--invoke-wait-ms` (default 5 s). | | `POST /invoke/{service}/{handler}/send` | Fire and forget: answers `202` as soon as the invocation is durable. | | `POST /scope/{scope}/invoke/{service}/{handler}` | Same, inside a flow-control scope. | | `POST /scope/{scope}/invoke/{service}/{handler}/send` | Same, inside a scope. | Role: `invoke`. The request body is the handler’s input, passed through as raw bytes. | Parameter | Where | Meaning | | --------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `key` | query | Object key of a virtual object, or workflow id for a workflow’s `run` handler. | | `limit-key` | query, or header `x-cairn-limit-key` | Concurrency sub-key inside a scope (`l1` or `l1/l2`). Only valid with a scope. | | `Idempotency-Key` | header | Same key (within tenant, scope, service, handler and object key) means the same invocation. The deduplication window is the retention period. Not allowed on a workflow’s `run`. | | `cairnflow-tag` | header | A user tag `k=v`; repeat the header for several (up to 8). Immutable after creation. | | `cairnflow-log-level` | header | Minimum level for `ctx.log` in this invocation. | Responses carry the invocation id in the `x-cairn-invocation-id` header, and a body whose `status` field tells the outcome: | HTTP | `status` | Other fields | Meaning | | ----- | ----------------- | ----------------------- | ----------------------------------------------------------------------- | | `200` | `completed` | `id`, `output` | Finished successfully. | | `202` | `waiting` | `id` | Not finished yet (or `/send`). Ask again later. | | `409` | `paused` | `id`, `code`, `message` | Paused, for example after the last retry attempt (`575`). | | `409` | `already_invoked` | `id` | A workflow `run` already holds this workflow id. | | `429` | `throttled` | `id`, `retry_after_ms` | Accepted and durable, but over a flow-control limit; it will run later. | | `500` | `failed` | `id`, `code`, `message` | Finished with a terminal error. | `output` is a **string**: the handler’s result bytes decoded as UTF-8. The TypeScript SDK writes results with `JSON.stringify`, so parse `output` once more to get the value. `waiting` is only an answer of these routes, never a stored state. `202` is normal for handlers that sleep or wait: keep the id, then attach or poll. If the call to your service fails after the invocation was accepted (connection refused, reset, `5xx`), `/invoke` keeps waiting through the retries like it does for a retryable handler error. ## Workflows [Section titled “Workflows”](#workflows) | Method and path | Role | Purpose | | --------------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /workflow/{service}/{key}/attach` | `invoke` | Wait for the workflow’s `run` to finish, without knowing its id. Same responses as `/invoke`; `404` if `run` was never called. Accepts `?wait_ms=`. | | `GET /workflow/{service}/{key}/output` | `invoke` | The same without waiting: `200`, `500`, `409` or `202`, or `404` if it never ran. | | `GET /workflow/{service}/{key}/id` | `invoke` | Compute the id of the workflow’s run: `{id, tenant, service, key}`. Reads nothing. | Each has a `/scope/{scope}/workflow/...` variant. Start a workflow that waits for people with `/send`, then collect the result with `attach`. ## Invocations [Section titled “Invocations”](#invocations) ### Reading [Section titled “Reading”](#reading) | Method and path | Role | Purpose | | --------------------------------------- | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /invocations` | `view` | Invocations of the ranges this node leads (an array). See below. | | `GET /invocations/{id}` | `invoke` | `{id, status, output?, code?, message?, lastFailure?, createdAt, modifiedAt, endedAt?, tags?}`. | | `POST /invocations/{id}/attach` | `invoke` | Wait until the invocation finishes. Same responses as `/invoke`. | | `GET /invocations/{id}/journal` | `view` | Journal entries: `index`, `ty`, `name`, `payload` (hex). `?decode=1` adds a decoded `entry` and `body`. Paged with `?from=` and `?limit=` (default and max 10 000; a page also ends at 4 MiB of payload); the header `x-cairnflow-journal-next` gives the next `from`, absent on the last page. | | `GET /invocations/{id}/logs` | `view` | Records of `ctx.log`. `?level=`, `?attempt=`, `?from=`, `?limit=` (default 1 000, max 10 000); `?follow=1` streams them as server-sent events. | | `GET /invocations/{id}/spans` | `view` | Span tree from `ctx.trace.span`, plus `tokens: {input, output}`. | | `GET /invocations/{id}/streams/{name}` | `invoke` (user streams), `view` (`$log`, `$trace`) | A stream as server-sent events. `?from=` or `Last-Event-ID` resumes. | | `GET /invocations/{id}/artifacts` | `invoke` | `{artifacts: [{sha256, size, contentType}]}`. | | `GET /invocations/{id}/artifacts/{sha}` | `invoke` | Artifact bytes, served inert (`nosniff`, sandboxing CSP, download unless image, text or JSON). | Stored states are `running`, `suspended`, `completed`, `failed` and `paused`. `lastFailure` holds the error of the latest failed attempt while an invocation is retrying or paused. `GET /invocations/{id}` and journal pages carry `x-cairn-read: leader` or `follower`: a follower’s copy is durable but may be older than what the leader just returned. **Attach.** `?wait_ms=N` long-polls up to `min(N, --attach-max-wait-ms)` (default cap 60 s); without it the wait is `--invoke-wait-ms`. Around 25 000 ms fits under common load balancer timeouts. `GET /invocations/{id}` never waits. **Listing.** `GET /invocations` accepts `?status=`, `?service=`, `?handler=`, `?limit=` (per range, default 100, max 1 000, applied after filtering), `?created_after=`, `?created_before=`, `?ended_after=`, `?ended_before=` (Unix milliseconds, half-open) and `?order=created_desc`. Scans are bounded: at most 10 000 rows and 2 seconds per range, and a range that does not answer within 4 seconds is left out. A truncated answer carries `x-cairn-partial: true`. Two variants: * `?scope=cluster` asks every node and returns `{scope, nodes, invocations, partial, missing, missingRanges}`. `partial: true` names what could not be reached; nothing is guessed. * `?cursor=` (empty for the first page) pages across the whole cluster, newest first: `{invocations, nextCursor?, partial, warnings}`. Filters: `?class=active,paused,completed,failed`, `?service=`, `?handler=`, `?key=`, `?root=true|false`, `?tag=k=v`, `?limit=` (default 50, max 1 000). No `nextCursor` means the last page. **Streams.** Events are `record` (`{offset, durable, step, attempt, k, data}`), `gap` (records dropped), `superseded` (a retried attempt replaced earlier records), `end` (stream sealed and fully read), `moved` (the range’s leader changed: reconnect to `leader`) and `reset` (after `moved`, for in-memory streams: discard what you showed). Only the leader serves streams. In-memory streams stay readable 60 seconds after they are sealed, then answer `410 stream_expired`. A connection lasts at most 10 minutes; reconnect with `Last-Event-ID`. Access is checked again every 30 seconds: a revoked key, an ended console session or a tenant being deleted closes the stream. ### Acting [Section titled “Acting”](#acting) | Method and path | Role | Purpose | | ------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /invocations/{id}/signal` | `invoke` | Body `{"signal": "name" or number, "value": }`. Wakes `ctx.signal` waiters. Returns `{id, status}`. Sending the same signal again is a no-op. | | `POST /invocations/{id}/cancel` | `admin` | Hard cancel: the invocation ends `failed` with code `572`. Returns `{id, cancelled, status}`. | | `POST /invocations/{id}/cancel?mode=signal` | `invoke` | Cooperative cancel: your code gets a terminal error at its next wait and can clean up. Needs your service to be up. | | `POST /invocations/{id}/resume` | `admin` | Take a `paused` invocation out of pause and run it now. `409` if not paused. Returns `{id, resumed, status}`. | | `POST /invocations/{id}/purge` | `admin` | Delete journal, state and idempotency key of a **finished** invocation. `409` while it runs (including `paused`). | | `POST /invocations/{id}/restart` | `admin` | Restart as a new invocation from the first `from` entries (default 1, the input), on `deployment` (default: its own). Returns `{id, new}`. `409` for a workflow’s `run`. | | `POST /invocations/{id}/replay` | `admin` | Read-only replay of the journal on `?deployment=` (default: its own). Commits nothing. Returns `{matches, upto, mismatchAt?, expected?, got?, message?}`. | | `POST /invocations/{id}/migrate` | `admin` | Move an unfinished invocation to `?deployment=`. Requires a matching replay unless `&force=true`. | | `POST /invocations/batch/{op}` | `admin` | `op` is `cancel`, `purge`, `resume` or `restart`. Body `{"ids": [...]}` with 1 to 1 000 ids. Returns `{op, results: [{id, ok, status, result or error}]}`; one failing id does not fail the batch. | **Cancellation reaches children.** Cancelling an invocation also cancels the calls it made with `ctx.call` that have not returned, recursively. One-way sends (`ctx.send`) are left alone. A hard cancel does not interrupt a turn already running in your service: that turn finishes, its side effects have happened, but its outcome is discarded. ## Value segments [Section titled “Value segments”](#value-segments) | Method and path | Role | Purpose | | ------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `GET /values/v1/{token}` | none (the token) | The bytes of one segment of a large value. The runtime hands these URLs to your service with a turn, when the node is set up to serve them; the SDK fetches them itself. | The token is the permission: it opens exactly one segment of one tenant and expires after a short time (60 seconds by default). An invalid or expired token, or a tenant being deleted, gets `403`; a missing segment `404`; more than 8 reads at once for one tenant on a node `429` with `Retry-After`. Treat these URLs as secrets and do not log them. ## Promises and awakeables [Section titled “Promises and awakeables”](#promises-and-awakeables) | Method and path | Role | Purpose | | ----------------------------------------------- | -------- | -------------------------------------------------------------------------------- | | `POST /promises/{service}/{key}/{name}/resolve` | `invoke` | Body is the value, raw bytes. Returns `{service, key, name, completed, woken?}`. | | `POST /promises/{service}/{key}/{name}/reject` | `invoke` | Body `{"code"?: number, "message": "..."}`. Waiters get a terminal error. | | `GET /promises/{service}/{key}/{name}` | `invoke` | `{completed, value?, failure?}`: whether the promise has a result. | | `POST /awakeables/{id}/resolve` | `invoke` | Complete a `ctx.awakeable()` with a JSON value. Returns `{id, status}`. | | `POST /awakeables/{id}/reject` | `invoke` | Body `{"code"?: number, "message": "..."}`. | Promise routes have `/scope/{scope}/promises/...` variants. Resolving a promise twice is a no-op (`completed: false`), so webhook retries are safe. Resolving before anyone waits is fine: the promise is durable and a later waiter reads it directly. ## Schedules [Section titled “Schedules”](#schedules) | Method and path | Role | Purpose | | -------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `PUT /schedules/{name}` | `invoke` | Create or update a schedule. The same definition is a no-op that does not move `nextAt`. | | `GET /schedules/{name}` | `invoke` | The schedule, `nextAt`, the next 10 fire times, recent fires, and `fired`, `missed`, `skipped` counters. | | `DELETE /schedules/{name}` | `invoke` | Delete it. Runs already started are not touched. | | `POST /schedules/{name}/pause` | `invoke` | No fires until resumed. | | `POST /schedules/{name}/resume` | `invoke` | Next fire computed from now; missed fires are not replayed. | | `POST /schedules/{name}/trigger` | `invoke` | Fire once now, ignoring `paused` and `overlap`, without moving `nextAt`. Accepts `Idempotency-Key`. | | `GET /schedules` | `invoke` | All schedules of the tenant across the cluster: `{schedules, partial, missing, missingRanges, truncatedRanges}`. Each range is read in a bounded number of chunks; a range cut short is listed in `truncatedRanges` and sets `partial: true`. | Each route has a `/scope/{scope}/schedules/...` variant. Names are 1 to 128 characters of `[A-Za-z0-9._-]`, unique within tenant and scope. ```json { "cron": "0 9 * * 1-5", "timeZone": "Europe/Paris", "target": { "service": "Reports", "handler": "daily" }, "input": { "kind": "summary" }, "overlap": "skip", "jitterMs": 30000 } ``` | Field | Meaning | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cron` or `everyMs` | Exactly one. `cron` has 5 fields (minute, hour, day, month, weekday), no seconds. `everyMs` is anchored on the Unix epoch and must be at least `--schedule-min-period-ms` (default 10 000). | | `timeZone` | IANA name, default UTC. Nonexistent local times do not fire; repeated ones fire twice. | | `target` | `{service, handler, key?}`. `key` is at most 4 096 bytes. | | `input` | JSON input of every run, up to 64 KiB. | | `limitKey` | Flow-control limit key of the runs. | | `overlap` | `skip` (default for targets without a key): skip a fire while the previous run is unfinished. `allow`: always fire (the only mode for keyed targets). | | `paused` | Create paused. | | `jitterMs` | Spread fires by a deterministic offset below this value. At most 86 400 000 (24 hours). | ## Deployments and services [Section titled “Deployments and services”](#deployments-and-services) | Method and path | Role | Purpose | | ------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `POST /deployments` | `admin` | Body `{"uri": "https://..."}`. Discovers the service at that URL and registers a new, immutable deployment (`dp_...`), then points every service it declares at it. `?activate=false` registers without moving any service. Optional `"transport": "auto"` or `"declared"`. | | `GET /deployments` | `view` | Deployments with `id`, `endpoint`, `createdAtMs`, `protocolMode`, `currentFor`. `?pinned=true` adds `pinnedInvocations`. | | `GET /deployments/{id}` | `view` | One deployment, with `pinnedInvocations` (unfinished invocations still bound to it) and its `manifest`. | | `DELETE /deployments/{id}` | `admin` | `409` while it is the current revision of a service or invocations are bound to it; `503` when not every range could be counted. | | `PUT /services/{service}/revision` | `admin` | Body `{"deployment": "dp_...", "expect"?: "dp_..."}`. Move a service to an existing deployment (rollback, pinning). With `expect`, moves only if the current revision matches, else `409`. | | `GET /services` | `view` | Services and handlers of the current revisions, with service type (`service`, `virtualObject`, `workflow`) and effective handler type. | | `POST /deployments/{id}/replay-check` | `admin` | `?service=&sample=20`: replay a sample of unfinished invocations of `service` on deployment `id`. Returns `{checked, matched, failures, ranges}`. `&scope=cluster` asks every node. | Registering the same URL again creates a new id. If the service and the runtime share no protocol version, registration is refused right away. Removal marks the deployment first: while it is being removed, moving a service revision to it, migrating to it or restarting on it answers `409`. Each invocation stays bound to the deployment it started on; new invocations follow the current revision. ## SQL queries [Section titled “SQL queries”](#sql-queries) | Method and path | Role | Purpose | | --------------- | ------ | -------------------------------------- | | `POST /query` | `view` | Read-only SQL over the `sys_*` tables. | ```json { "sql": "SELECT id, status FROM sys_invocation WHERE service = $1", "params": ["Orders"], "allow_partial": true, "timeout_ms": 10000 } ``` Returns `{columns: [{name, type}], rows, partial, warnings, read, ms}`. A key sees its own tenant only; `cluster-admin` sees all. Errors: `400` for invalid or forbidden SQL, `422` when a limit is exceeded and `429` when the tenant ran out of read units (both with an `error` starting with `query_budget:`), `429` when too many queries run at once, `503` when ranges are missing and `allow_partial` is `false`. See [Query](/docs/query) and [Tables](/docs/query/tables). ## Archive and usage [Section titled “Archive and usage”](#archive-and-usage) | Method and path | Role | Purpose | | ---------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `GET /archive?date=yyyy-mm-dd` | `view` | Archived invocations of one UTC day: `{date, entries: [{id, run, bytes, writtenAtMs}]}`. `?limit=` up to 10 000. | | `GET /archive/{id}` | `view` | A purged invocation: `{id, status, output?, failure?, journal, purgedAtMs, chain}`. `?date=`, or searches back `?days=` days (default and max 31). Each day searched counts against the tenant’s read units; when they run out, `429`. | | `GET /metering?hour=yyyy-mm-ddThh` | `view` | Usage of the tenant for one UTC hour, summed over nodes. | | `GET /metering/hours?from=&to=` | `view` | Usage per hour over a range of up to 744 hours. | | `GET /stats/handlers` | `view` | Per-handler summary over `?window=5m` to `60m`: turns, outcomes, failed attempts, p50, p99, max. `?scope=cluster` for every node. | | `GET /stats/slow-runs` | `view` | Recent slow runs of the node, newest first. `?scope=cluster` for every node. | | `GET /audit` | `view` | Audit log of human actions on the tenant. `?from&to&actor&action`; default 24 hours, max 31 days. | ## Flow control [Section titled “Flow control”](#flow-control) `GET /rules`, `POST /rules`, `DELETE /rules/{pattern}`, `GET /limits`, `GET /vqueues` and `GET /scheduler` (`cluster-admin`; a `provision` key can manage per-tenant rate rows through `/rules`) are described in [Flow control](/docs/reference/flow-control). ## Keys, identity and tenant [Section titled “Keys, identity and tenant”](#keys-identity-and-tenant) | Method and path | Role | Purpose | | --------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `POST /admin/keys` | `provision` | Body `{"tenant": "...", "role": "invoke"}`. Returns `{id, tenant, role, createdAtMs, secret}`; `secret` appears only here. Roles: `invoke`, `view`, `admin`, `provision`, `cluster-admin`. | | `GET /admin/keys` | `provision` | Stored keys, without secrets. Environment keys are not listed. | | `DELETE /admin/keys/{id}` | `provision` | Revoke. `204` when every live node confirmed; `202 {pending}` otherwise. | | `GET /admin/keys/{id}/revocation` | `provision` | `{revoked, confirmed, pending, listed}`. Use after a `202`. | | `GET /auth/whoami` | any | Tenant, role, key id and node of the calling key. No secrets. | | `GET /identity` | `view` | `{tenant, signing, keys: [{generation, kid, active}]}`: public keys for verifying signed requests in your service. | | `GET /tenant` | `view` | State, limits and usage of the key’s tenant. | ## Cluster and health [Section titled “Cluster and health”](#cluster-and-health) | Method and path | Role | Purpose | | ----------------------------------------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `GET /health` | none | `ok` when the HTTP server is up. | | `GET /metrics` | `cluster-admin` or metrics token | Prometheus text. | | `GET /cluster` | `cluster-admin` | Range table: `version`, `ranges` with `range`, `start`, `end`, `gen`, `intent?`, `leader`, `address`, `term`. Same answer on every node. | | `GET /cluster/nodes` | `cluster-admin` | Nodes, the ranges they lead, write health, disk cache. | | `POST /ranges/{id}/split` | `cluster-admin` | Split at `?at=<16 hex digits>` (default: middle). Must reach the range’s leader. Returns the new table, a timing `report` and `opId`. | | `POST /ranges/merge?left=&right=` | `cluster-admin` | Merge two adjacent ranges. | | `GET /ranges/ops`, `GET /ranges/ops/{id}` | `cluster-admin` | Split and merge operations started on this node (in memory). | | `GET /ranges/stats` | `cluster-admin` | Load per range led by this node. `?scope=cluster`, `?detail=1`. | | `GET /ranges/suggestions` | `cluster-admin` | Automatic split proposals with the reason and what blocks them, and merge proposals (`reason: merge`, `mergeWith`, `coldSecs`) for two adjacent ranges that have been cold and small for a long time. Merges are only proposed, never done automatically. `?scope=cluster` for every node. | | `GET /admin/cluster-version` | `provision` | Cluster version, migration lock, `knows` of every node. | Split and merge answer `400` for a bad split key, `409` when the table changed or an operation is already pending, and `503` for temporary conditions (retry later). A client that disconnects does not cancel a split or merge: it runs to commit or rollback; check `GET /ranges/ops`. # Serverless (fetchHandler) > Run services and workflows on Vercel, Cloudflare Workers, AWS Lambda, Deno and Bun. `serve()` needs a long-running process that holds a port. On platforms that only take a function `(Request) => Promise`, use the Fetch adapter from `@cairnflow/sdk/fetch`. It shares its core with `serve()`. app/api/cairn/\[...path]/route.ts ```ts import { fetchHandler, service, type ServiceContext } from "@cairnflow/sdk/fetch"; const orders = service("OrderService", { async submit(ctx: ServiceContext, input: { amount: number }) { const receipt = await ctx.run("charge", () => charge(input.amount)); return { receipt }; }, }); const handler = fetchHandler({ services: [orders], identityKeys: ["publickeyv1_…"], }); export const GET = handler; export const POST = handler; ``` Register the **base URL** where the handler is mounted, for example `https://my-app.vercel.app/api/cairn`. ## Platforms [Section titled “Platforms”](#platforms) | Platform | Mount | Notes | | ------------------------------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | Vercel (Next.js App Router) | `app/api/cairn/[...path]/route.ts`: `export const GET = handler; export const POST = handler;` | Node.js runtime. Register the production domain: preview deployments behind Deployment Protection answer with a login page | | Cloudflare Workers | `export default { fetch: handler };` | Enable `compatibility_flags = ["nodejs_compat"]`. If turns fail once bodies reach 8 KiB, set `compression: false` | | AWS Lambda (Function URL or HTTP API, payload v2) | `export const handler = lambdaHandler(fetchHandler({ … }));` | `lambdaHandler` comes from `@cairnflow/sdk/fetch`. Bodies travel base64-encoded both ways | | Deno, Bun | `Deno.serve(handler)`, `Bun.serve({ fetch: handler })` | — | The adapter is tested on Node.js (the standard Fetch API, and Lambda payload v2 events built by hand), not yet on these platforms themselves. Report anything that behaves differently on one of them. ## What is different from `serve()` [Section titled “What is different from serve()”](#what-is-different-from-serve) * **Request-response only.** Each wait whose result is not ready (`ctx.sleep`, a call, a promise) ends the request; cairnflow sends the journal again with the next one. It works everywhere, and costs more bytes and latency than streaming for handlers with many steps — which is why long agents belong on `serve()`. * **A turn must finish within the platform’s time limit** and within the handler’s `inactivityTimeout` (see [Turn time limit](/docs/cloud/limits#turn-time-limit)). A step that runs longer is cut and runs again on the next attempt. Split long work into several short `ctx.run` steps. * **Set `identityKeys`.** A function URL is public; without signature checks, anyone who knows the URL can call your handlers. The signature covers the request body and the host it was sent to. Set `identityHosts` to the public hosts you registered to bind it to this endpoint; it is required when a proxy in front of the function rewrites the `Host` header. * **Keep files out of the journal.** In request-response mode the journal travels with every request. Pass files and images through `ctx.artifact` so the journal keeps only a reference; large JSON values are stored as segments (see [Payload](/docs/cloud/limits#payload)). * **The replay cache is off by default.** A function process does not live across turns, so `fetchHandler` sets `replayCache: false`; turn it on only on a long-lived server such as `Deno.serve` or `Bun.serve`. `fetchHandler` takes the same `identityKeys`, `identityHosts`, `segmentOrigins`, `compression`, `replayCache`, `valueCacheBytes`, `maxValueBytes` and `maxTurnValueBytes` options as `serve()` ([serve() options](/docs/develop/services#serve-options)), plus `basePath`: when set, only requests under exactly that path prefix are accepted; when unset, routing uses the end of the path, so the handler can be mounted under any prefix. # Workflows > Multi-step processes that run once per workflow ID. A workflow is a multi-step process with **one run per workflow ID**. Its `run` handler holds the process; other handlers on the same workflow can read it or signal it while `run` is suspended. signup.ts ```ts import { type Context, serve, workflow } from "@cairnflow/sdk"; const signup = workflow("UserSignup", { async run(ctx: Context, user: { email: string }) { ctx.set("email", user.email); // only `run` writes state const secret = await ctx.run("secret", () => crypto.randomUUID()); await ctx.run("mail", () => sendVerification(user, secret)); const clicked = await ctx.promise("email-link-clicked").get(); return clicked === secret; }, // Shared handler: runs alongside `run`, even while `run` is waiting. async click(ctx: Context, req: { secret: string }) { await ctx.promise("email-link-clicked").resolve(req.secret); }, }); await serve({ services: [signup], port: Number(process.env.PORT ?? 9080), hostname: "0.0.0.0", identityKeys: [process.env.CAIRN_IDENTITY_KEY!], }); ``` Start it, signal it, and read the result: ```sh curl -X POST "$CAIRN_URL/invoke/UserSignup/run/send?key=u-1" \ -H "authorization: Bearer $CAIRN_KEY" -d '{"email":"a@example.com"}' curl -X POST "$CAIRN_URL/invoke/UserSignup/click?key=u-1" \ -H "authorization: Bearer $CAIRN_KEY" -d '{"secret":"…"}' curl -X POST "$CAIRN_URL/workflow/UserSignup/u-1/attach" \ -H "authorization: Bearer $CAIRN_KEY" ``` `ctx.key` inside `run` is the workflow ID. ## Rules [Section titled “Rules”](#rules) * `run` is required and unique. A workflow that does not declare exactly one `run` handler is refused at registration. * Calling `run` a second time for the same ID returns `409`, not the first run’s result. * Shared handlers cannot write state: they run in parallel with `run`, so a read-modify-write on both sides would lose updates. The `SharedContext` type stops it at compile time. ## Timers and waiting [Section titled “Timers and waiting”](#timers-and-waiting) `ctx.sleep(ms)` and `ctx.promise(name).get()` suspend the workflow in storage. Nothing holds a process or a connection while it waits, so a workflow can wait for an email click for a week. # Self-hosting overview > What you run when you host cairnflow yourself, the deployment shapes, and the ports involved. Note Prebuilt binaries for Linux (`x86_64`, `arm64`) and macOS (`arm64`) are published on [GitHub Releases](https://github.com/cairnflowdev/cairnflow/releases) (`v0.1.0-beta.0`), and a container image is available at `ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0` (see [Docker](/docs/self-hosting/docker)). You can also [build from source](#build-from-source) from the [repository](https://github.com/cairnflowdev/cairnflow). The runtime is source-available under the Business Source License 1.1. Cairnflow can run on your own machines against your own bucket. There is no database, no coordinator service and no etcd to operate: every piece of state lives in object storage, and the runtime nodes only read and write it. ## What you run [Section titled “What you run”](#what-you-run) | Binary | Role | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `cairnflow` | The runtime. Serves the HTTP API, calls your services, keeps journals, state and timers in the bucket. | | `cairn` | A thin CLI. Every command is one HTTP request to a node, so anything it does can also be done with `curl`. See [CLI reference](/docs/reference/cli). | | `cairn-ctl` | A recovery tool that reads and writes the bucket directly, with no node running: `verify`, backup, restore, trash. See [Backup and restore](/docs/self-hosting/backup-restore). | | `cairn-query-worker` | Not run by hand. `cairnflow` starts it as a child process for each SQL query sent to `POST /query`, so a hostile query cannot take the node down. Ship it in the same directory as `cairnflow`. See [Security](/docs/self-hosting/security#sql-queries-run-in-a-child-process). | `cairnflow`, `cairn` and `cairn-ctl` print the same version line with `--version`: ```text cairnflow (data=, knows=) ``` Use a `cairn-ctl` with the same `knows=` value as the nodes of your cluster; taking every binary from the same build is the simplest way to guarantee it. ## Shapes [Section titled “Shapes”](#shapes) | Shape | Minimal command | Use when | | -------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------- | | One node, local disk | `cairnflow --data-dir /var/lib/cairnflow` | Development, a single machine, no failover | | One node, in memory | `cairnflow --main-store memory://` | Tests. Everything is lost when the process exits. | | One node, S3 | `cairnflow --main-store s3://bucket/prefix` | One machine, with state outside the machine | | Cluster, S3 | `cairnflow --main-store s3://bucket/prefix --partitions N --host
` on every node | Failover, several nodes sharing one bucket | Without `--data-dir` or `--main-store`, data goes to `./cairnflow-data`, relative to the working directory at startup. If both are given, `--main-store` wins. A single node is a cluster of one: every node runs the same lease protocol, so moving from one node to several is a matter of starting more nodes on the same bucket. The local-disk shape is the exception: `file://` storage supports one node only (see [Object stores](/docs/self-hosting/storage)). ## What the bucket holds [Section titled “What the bucket holds”](#what-the-bucket-holds) Everything: journals, state, timers, queues, the API key book, deployments, and the ownership records of each key range. A node owns a range of keys through a lease written to the bucket with compare-and-swap. When a node stops renewing, another node takes its ranges over from the bucket. This is why the store must support conditional writes. Each node checks its store at startup and refuses to run on one that does not. ## Ports [Section titled “Ports”](#ports) | Flag | Default | Serves | | ----------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------- | | `--port` | `8080` | Clients: invoke, admin and introspection API, `/metrics`, `/health`, and the web console under `/ui` | | `--internal-port` | `--port` + 1 | Other nodes only: cross-range messages, range hand-offs, forwarded requests. Every request is signed with the cluster secret. | The ingress port returns `404` for internal routes. Keep the internal port reachable only from the other nodes. A single node still opens it, because messages between ranges always travel over HTTP, even to the same process. By default a node listens on `127.0.0.1`. Use `--host 0.0.0.0` to accept connections from other machines on a single node; in a cluster `--host` must be an address that peers can reach (see [Running a cluster](/docs/self-hosting/cluster)). ## Build from source [Section titled “Build from source”](#build-from-source) You need Rust (the toolchain named in `rust-toolchain.toml` installs itself through `rustup`), `protoc`, CMake and a C++ compiler. To include the web console you also need Node.js 22.18 or newer. ```sh git clone https://github.com/cairnflowdev/cairnflow.git cd cairnflow git submodule update --init # the SlateDB fork in vendor/slatedb; the build needs it (cd ui && npm ci && npm run build) # optional: the web console, embedded at build time cargo build --release ``` The binaries are in `target/release/`. Without the console step, `/ui/` shows a placeholder page. ## A first node [Section titled “A first node”](#a-first-node) ```sh export CAIRNFLOW_ADMIN_KEY="cf_$(openssl rand -hex 24)" cairnflow --data-dir /var/lib/cairnflow --port 8080 ``` Authentication is on by default. `CAIRNFLOW_ADMIN_KEY` is a bootstrap key with the `cluster-admin` role, at least 32 bytes long (the command above makes a 51-character key); a node with no key at all refuses to start unless you pass `--no-auth`, which is for a development machine only. See [Security](/docs/self-hosting/security). Register a service that is already listening (for example one started with `serve()` on port 9080) and call it: ```sh export CAIRNFLOW_TOKEN="$CAIRNFLOW_ADMIN_KEY" cairn register http://127.0.0.1:9080 cairn services cairn invoke Greeter greet --input '"world"' ``` The runtime calls your service at the URL you register, so that URL must be reachable from the node, not just from your laptop. ## Next [Section titled “Next”](#next) * [Object stores](/docs/self-hosting/storage): URIs, credentials, and which stores are supported. * [Running a cluster](/docs/self-hosting/cluster): several nodes, failover, splitting ranges. * [Docker](/docs/self-hosting/docker): the image and a two-node compose example. * [Configuration](/docs/self-hosting/configuration): flags, environment variables and defaults. * [Security](/docs/self-hosting/security): keys, roles, console sign-in, SSO, TLS. * [Operations](/docs/self-hosting/operations): health, metrics, logs, upgrades. * [Backup and restore](/docs/self-hosting/backup-restore): `cairn-ctl`, backups, the trash. # Backup and restore > What can be recovered in a self-hosted cairnflow, and how to use cairn-ctl to verify, back up, restore and recover from the trash. ## What can be recovered [Section titled “What can be recovered”](#what-can-be-recovered) | You lost | Where it is | How to get it back | | --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | | A finished invocation that was purged | The archive, under `archive///` | Read it with `GET /archive/{id}` (journal and final state). It is not restored as a live invocation. | | Data that cairnflow deleted itself: retired range data, ownership records, write-ahead logs of dead nodes | The trash, for `--trash-keep-s` (default 7 days) | `cairn-ctl trash restore` | | The range table, deleted from outside cairnflow | History copies of the table kept in the bucket | `cairn-ctl table restore`, see [Rebuilding the range table](#rebuilding-the-range-table) | | A tenant marked for deletion | Held in place for `--tenant-purge-keep-s` (default 7 days) | Set the tenant’s state back to `active` before the hold ends | | The whole bucket | A backup at another provider | `cairn-ctl restore` | | Low-level storage deletions that do not use the trash | Only in bucket versioning, if enabled | Your store’s version history | Purging an invocation by hand (`POST /invocations/{id}/purge`) or by retention removes it from the live data; it is not undoable beyond reading the archive. Archiving is on unless you run with `--no-archive`. ## cairn-ctl [Section titled “cairn-ctl”](#cairn-ctl) `cairn-ctl` reads and writes the bucket directly. No node needs to be running, but it needs the bucket credentials (the same `AWS_*` environment as the nodes), so it is a separate binary: do not hand it to people who only need an API key. Point it at the bucket exactly like a node: ```sh cairn-ctl --main-store s3://bucket/prod verify cairn-ctl --data-dir ./data table show ``` Commands that change something run **dry** by default: they print the before and after and write nothing. Add `--apply` to write. Each applied change leaves an audit record in the bucket with who ran it (`--who`, default `$USER@$HOST`), the command, and the before and after. Exit codes: `0` done (or `verify` clean), `1` `verify` found problems, `2` bad arguments, `3` refused, `4` store error. `--json` prints machine-readable output. Use a `cairn-ctl` with the same `knows=` as your nodes (`cairn-ctl --version`). ## Verify [Section titled “Verify”](#verify) ```sh cairn-ctl --main-store s3://bucket/prod verify ``` `verify` only reads. It checks that the range table covers the whole key space, that every range in the table has data that opens, that references between ranges point to data that exists, that no range directory is orphaned, and that no split or merge has been stuck for more than 100 seconds. By default it also looks for cross-range calls that lost a message. It exits with `1` when it finds a problem. `verify --deep` also checks that every sorted file named by the current manifest and live checkpoints of each live range is still in the bucket (finding `sst_missing`). It costs one listing per range and is not part of the background check, so run it on a schedule: it finds a file deleted from outside cairnflow before a read does. Other read-only commands: `table show` (range table), `owners` (ownership record of every range and whether its session is alive), `ranges retired`, `range dump ` (raw rows of a range), `wal floors`, `trash list`, `cluster status`. ## Backups [Section titled “Backups”](#backups) A backup copies the cluster to another store, ideally at **another provider**, so that losing the source account does not take the backups with it. ```sh cairn-ctl --main-store s3://source-bucket/prod backup --to s3://backup-bucket/prod cairn-ctl --main-store s3://source-bucket/prod backup list --to s3://backup-bucket/prod ``` A backup: 1. places a guard against garbage collection on the source and checkpoints every range in the range table. The guard lasts 10 minutes and the command renews it every 2 minutes, so a backup that is killed stops holding back garbage collection within 10 minutes. If renewals keep failing until the guard may have expired, the command fails instead of finishing an incomplete copy; 2. copies every object those checkpoints reference, plus the cluster’s own objects, 16 at a time. Temporary checkpoints of the source (the compactor’s, readers’, other backups’) are not copied and are removed from the copy; 3. writes a manifest with the size and SHA-256 of every object **last**; 4. removes its checkpoints and the guard. A backup without its manifest is incomplete: `restore` ignores it and `backup list` marks it. The source is not modified, apart from an audit record. The whole run uses one snapshot of the range table. If a split or merge commits while the backup runs, the run is abandoned and started again with a new id, at most three times; after that the command fails, and you run it again when splitting is quiet. Not included: the cluster secret, the bootstrap key and the identity master secret (keep them in your secret store), and per-node runtime state such as sessions and node write-ahead logs. Remove old backups on a schedule. The command runs dry first: ```sh cairn-ctl --main-store s3://source-bucket/prod backup prune --to s3://backup-bucket/prod \ --keep-daily 7 --keep-weekly 4 cairn-ctl --main-store s3://source-bucket/prod backup prune --to s3://backup-bucket/prod \ --keep-daily 7 --keep-weekly 4 --apply ``` Incomplete backups older than 24 hours are removed too. ### Credentials for a backup store at another provider [Section titled “Credentials for a backup store at another provider”](#credentials-for-a-backup-store-at-another-provider) `--backup-env-prefix P` builds the backup store’s client **only** from variables named `P` + `AWS_*`, while `--main-store` keeps using `AWS_*`: ```sh # source, as for the nodes export AWS_ENDPOINT_URL_S3=https://source.example.com AWS_REGION=auto \ AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... # backup store, its own set export CAIRN_BACKUP_AWS_ENDPOINT=https://backup.example.com \ CAIRN_BACKUP_AWS_REGION=auto \ CAIRN_BACKUP_AWS_ACCESS_KEY_ID=... CAIRN_BACKUP_AWS_SECRET_ACCESS_KEY=... cairn-ctl --main-store s3://source-bucket/prod --backup-env-prefix CAIRN_BACKUP_ \ backup --to s3://backup-bucket/prod ``` The access key and secret are required; an unknown `P...AWS_` variable is an error. With wrong backup credentials the command fails at its first listing, before touching the source. Pass secrets only through the environment: the command line is recorded in the audit record. A backup destination with the same bucket and prefix as the source is refused. ### Limits [Section titled “Limits”](#limits) * **Each range contributes what had reached its sorted files.** Commits still only in the write-ahead log at backup time are not included. Idle ranges flush after `--wal-age-flush-ms` (default 60 s), so each range lags the backup time by at most about that. * **Recovery point** = time between backups + up to about 60 seconds per range. * **Ranges are not cut at one instant.** Under load, a call between two ranges that was in flight during that window can lose its request or its reply; the caller then waits forever. `backup check-restore` finds these cases (see below). * Clusters with a separate `--wal-store` are not supported by backup yet. ## Restoring a cluster [Section titled “Restoring a cluster”](#restoring-a-cluster) 1. **Create a new, empty bucket.** The new `--main-store` must use the **same prefix** as the source (`prod` in the examples). `restore` refuses a different prefix and says why. 2. **Copy the backup back:** ```sh cairn-ctl --main-store s3://new-bucket/prod restore --from s3://backup-bucket/prod ``` Without `--id`, the newest complete backup is used; pick another with `--id ` from `backup list`. Objects are copied 16 at a time, every object’s size and SHA-256 are checked, and the marker that makes the bucket openable is written last, so nodes refuse a half-restored bucket. If the restore fails midway, empty the destination and run it again. With a backup store at another provider, add the same `--backup-env-prefix` as for `backup`. `restore` refuses, before writing anything, a backup whose range table lists a range with an ownership record but no data in the backup (possible with backups taken during a split by older binaries): restoring it would open that range empty. Choose another backup. 3. **Check, before starting any node:** ```sh cairn-ctl --main-store s3://new-bucket/prod backup check-restore ``` Continue only on exit code `0`, or when the only findings are lost cross-range messages (`restore.lost_call`, `restore.lost_reply`), which name the caller and the callee. For any other finding, choose another backup. 4. **Start the nodes** on the new bucket, with the cluster secret and bootstrap key from your secret store. 5. **Handle the reported calls.** For each caller, either restart it from just before the call, `POST /invocations/{id}/restart?from=`, which replays earlier `ctx.run` results and sends the call again (the callee may then run a second time, so use this only when that is safe), or cancel it with `POST /invocations/{id}/cancel` and settle the business side by hand. 6. **Delete again** any tenant you deleted after the backup was taken: restoring an older backup brings it back. 7. Point clients at the new cluster. Stop the old cluster completely: two clusters taking the same work run it twice. Rehearse this on a scratch bucket before you need it. ## Recovering from the trash [Section titled “Recovering from the trash”](#recovering-from-the-trash) Cairnflow does not delete its own data directly. Retired range data, the leftovers of a rolled-back split or merge, and the logs of dead nodes are **moved** to a trash area in the bucket. One node deletes a trash entry for good only once it is older than `--trash-keep-s` **and** a fresh check shows nothing needs it; when in doubt it keeps the entry. ```sh cairn-ctl --main-store s3://bucket/prod trash list ``` Before restoring, stop anything that could clean up again: stop the cluster if you can, or restart the nodes with `--retire-orphans-every-s 0 --reconcile-intents-every-s 0 --trash-keep-s 0` and without `--gc-retired-dbs`. Then: ```sh cairn-ctl --main-store s3://bucket/prod trash restore --range 7 # dry run cairn-ctl --main-store s3://bucket/prod trash restore --range 7 --apply # data and owner record of range 7 cairn-ctl --main-store s3://bucket/prod trash restore --apply # one entry by id cairn-ctl --main-store s3://bucket/prod verify ``` Restoring copies objects back with “create only if absent”, so it **never overwrites** anything; a conflicting object is reported and the entry is kept. It refuses (exit code `3`) when the range already has data in place. Restoring brings objects back but does not change the range table. An entry you had to restore means a deletion was wrong. Keep the `trash list --json` output and the node logs, and report it. ## Rebuilding the range table [Section titled “Rebuilding the range table”](#rebuilding-the-range-table) After every change to the range table, nodes write a history copy of the new table to the bucket and keep the 16 newest. If the range table object is deleted from outside cairnflow (an operator, a lifecycle rule), `table restore` rebuilds it from the newest copy, **only** when the rest of the bucket proves that copy is the last table: no ownership record, range directory or operation record carries a newer range id, every live range of that table has an ownership record without a tombstone, and the operation records agree. Otherwise it refuses and prints the mismatches. ```sh cairn-ctl --main-store s3://bucket/prod table restore # dry run cairn-ctl --main-store s3://bucket/prod table restore --apply ``` The table is written only if absent. `--apply` refuses while any node session is still live: stop every node first, and add `--force` only once you are sure they are all stopped. ## Reports for automation [Section titled “Reports for automation”](#reports-for-automation) `--report-to-bucket ` on `backup`, `backup list`, `backup prune`, `restore`, `cluster status`, `cluster enable-*` and `table restore` also writes the command’s JSON result to the cluster’s bucket, with the command name, exit code, `cairn-ctl` version and timings, even when the command fails. It carries no secrets. A service holding a `provision` key reads it with `GET /admin/ops-reports/` (or lists them with `GET /admin/ops-reports`), so it can run `cairn-ctl` as a one-off job without ever holding bucket credentials itself. The id is yours to choose and must be new each time: 1 to 128 characters from `A-Z a-z 0-9 - _ .`, starting with a letter or digit. An id that already has a report makes the command refuse (exit code `3`) without running. The 256 newest reports are kept, and reports more than 30 days older than the newest are removed. ## Investigating on a copy [Section titled “Investigating on a copy”](#investigating-on-a-copy) `cairn-ctl fork --to ` makes a copy of the cluster under another prefix **in the same bucket**, from a checkpoint, without stopping the cluster. Start a node with `--main-store s3://bucket/` to investigate on real data without touching it. The copy shares sorted files with the source; the fork places a 24-hour guard against garbage collection on the source for the data it relies on. Ranges contribute only what had reached their sorted files. # Running a cluster > Several cairnflow nodes on one bucket, addressing rules, failover, and splitting and merging key ranges. A cluster is several `cairnflow` processes pointed at the same bucket and prefix. There is nothing else to set up: nodes find each other through the bucket, each key range has one leader at a time, and ranges move to another node when their leader stops. Clusters need a store with compare-and-swap: an `s3://` store that passes the startup checks (see [Object stores](/docs/self-hosting/storage)). `file://` runs one node only. ## Starting nodes [Section titled “Starting nodes”](#starting-nodes) ```sh # on every node: same bucket and prefix, same --partitions, same keys cairnflow --main-store s3://cairnflow/prod --partitions 8 \ --node-id node-a --host 10.0.0.11 --port 8080 # internal port 8081 cairnflow --main-store s3://cairnflow/prod --partitions 8 \ --node-id node-b --host 10.0.0.12 --port 8080 ``` Every node needs: * the same `--main-store` (and `--wal-store`, if you use one); * the same `--partitions` value (see [Ranges](#ranges)); * the same authentication setup: the same `CAIRNFLOW_ADMIN_KEY` (or hashed variant), and keys created with `cairn keys create` are shared automatically through the bucket; * the same cluster secret. Set `CAIRNFLOW_CLUSTER_SECRET` (32 bytes or more, identical on every node), or leave it unset and the first node creates one in the bucket. Setting it is safer: a secret stored in the bucket can be read, and used to sign internal requests, by anyone who can read the bucket. Give each machine a stable `--node-id`. Without it, a node generates an id per process. ## Addresses [Section titled “Addresses”](#addresses) Each node has two ports: `--port` for clients and `--internal-port` (default `--port` + 1) for peers. A node advertises both in its lease: peers send to the internal port, and clients are pointed to the ingress port. Caution **`--host` must be an address that peers can reach, not `0.0.0.0`.** Unless you set `--advertise-host`, a node advertises exactly the address it is bound to. Bound to `0.0.0.0`, it advertises `http://0.0.0.0:8080`, cross-range messages reach no one, and the failure is silent: each node still looks healthy on its own. You can pass a hostname to `--host`; it is resolved to an IP when the node binds. When a platform requires a node to listen on all interfaces while peers must reach it at a private address, bind on all interfaces and advertise the private address: ```sh cairnflow --main-store s3://bucket/prod --partitions 8 --node-id "$NODE_ID" \ --host :: --advertise-host "$PRIVATE_IP" --port 8080 ``` `--advertise-host` takes a hostname or an IP (IPv6 with or without brackets). It is not resolved at startup, so names that only peers can resolve work. `0.0.0.0`, `::`, a scheme, a port or a path are rejected. The advertised port is always the port actually bound. **Firewall the internal port** so that only the other nodes reach it. Requests there must carry an HMAC signature made with the cluster secret, but if you bind on all interfaces the signature is the only thing standing between the internal API and the network. ## Requests that reach the wrong node [Section titled “Requests that reach the wrong node”](#requests-that-reach-the-wrong-node) A request about a key whose range is led by another node gets `503` with a `leader` field: the ingress address of the current leader. The `cairn` CLI and the TypeScript SDK client follow it once, keeping the same `Idempotency-Key`. A client of your own should read `leader` from the body and resend there. Following `leader` requires clients to reach every node’s advertised address. Behind a load balancer that hides the nodes, send the header `x-cairn-forward: leader` instead. The node that receives the request forwards it to the leader over the internal port (one hop, no retry) and returns the leader’s response with an `x-cairn-forwarded-by` header. If the request was sent but no response came back, the node returns `504`: the operation **may** have run, so check its state (or resend with the same `Idempotency-Key`) before repeating it. The web console always sends this header. A `503` without `leader` means the cluster is electing a leader or a range is being split or merged: back off and retry. ## Failover [Section titled “Failover”](#failover) Leases expire after `--lease-ttl-ms` (default 10 000 ms). When a node dies, its ranges get a new leader after about one lease TTL, plus up to a third of a TTL for peers to notice. By default, a new cluster delegates lease renewal to one coordinating node to save requests; there, a dead node’s ranges move in under two TTLs, and in under three if the coordinator dies at the same time as another node. A graceful stop is much faster. On `SIGTERM` or `SIGINT` a node seals each range, closes its session and tells its peers, which take the ranges over almost immediately. The whole shutdown is capped by `--shutdown-timeout-ms` (default 20 000 ms); past that, or on a second signal, the node exits at once and peers take over after a TTL. Give your process manager a grace period longer than the shutdown timeout. Ranges balance themselves across live nodes. There is no rebalance command to run; `cairn cluster` shows who leads what. ## Ranges [Section titled “Ranges”](#ranges) The key space is cut into **ranges**, each with its own leader. `--partitions N` sets the number of ranges when the bucket is first initialised. The value is recorded in the bucket; while the range table has never been split or merged, a node started with a different value refuses to start. After the first split or merge, the table in the bucket is authoritative. Start with more ranges than nodes; 8 to 64 is reasonable for a small cluster. You can change the layout at runtime: ```sh cairn ranges # range table: version, key bounds, generation, intent cairn ranges split 3 # split range 3 at the middle of its key range cairn ranges split 3 --at 8000000000000000 # split at a given key (16 hex digits) cairn ranges merge 4 5 # merge two adjacent ranges into a new one ``` A split or merge must be sent to a node that leads the range (others answer `503` with `leader`), pauses writes to the ranges involved for a short window, and returns the new table with a per-phase timing report. If the node dies midway, the next leader of the source range rolls the change back. While a split or merge is in progress, requests for those ranges may get `503` without `leader`; the ingress itself waits up to two seconds for the table to settle before answering that way. ### Automatic splitting [Section titled “Automatic splitting”](#automatic-splitting) Each leader measures load per range: the share of the node’s turn capacity the range uses, and its size. `--auto-split` chooses what happens: | Mode | Behaviour | | ------------------- | --------------------------------------------------------------- | | `suggest` (default) | Proposals only, at `GET /ranges/suggestions`. Nothing is split. | | `on` | Hot or oversized ranges are split automatically. | | `off` | Automatic splitting is disabled. | A range is proposed for a split when it is busy (by default, at least half of the node’s turn capacity for 60 consecutive seconds) or larger than `--max-range-bytes` (default 8 GiB). The split point balances measured work, not key count. When one key owner accounts for most of the load, no split is proposed (`hot_owner`): a single owner cannot span two ranges, so use flow control instead (see [Flow control](/docs/reference/flow-control)). In `on` mode, only one split or merge runs in the whole cluster at a time, a range that was just split cools down for 10 minutes, each node splits at most once a minute, and nothing is split while the cluster is upgrading. Splits for load stop once the table holds `--auto-split-max-ranges` ranges (default 128, `0` for no cap); the proposal then shows `blocked_by: max_ranges`. Ranges are never merged automatically. In `suggest` and `on` modes, two adjacent ranges that have both been cold for `--auto-split-merge-cold-ms` (default 6 hours, `0` turns this off), are together under a quarter of `--max-range-bytes` and are not cooling down from a split are proposed for a merge at `GET /ranges/suggestions`, with reason `merge`. Run the merge yourself with `cairn ranges merge`. Look at the proposals on real traffic before switching to `on`. `GET /ranges/stats` shows the load per range. ### Storage after splits [Section titled “Storage after splits”](#storage-after-splits) A split or merge retires the parent range’s data instead of deleting it. Retired data stays in the bucket until you enable `--gc-retired-dbs`, which removes it (through the trash, see [Backup and restore](/docs/self-hosting/backup-restore)) once no live range references it. It is off by default because it deletes data; `--gc-retired-dbs=plan` only logs what it would remove. A range keeps reading the sorted files of its ancestors after a split. When a range a node leads still depends on files of two or more ancestor ranges (`--lineage-compact-depth`, default 2, `0` turns this off), or on an ancestor retired for more than a day (`--lineage-compact-age-ms`), the node runs one full compaction of that range so it stops depending on them and the retired data can be collected. It compacts one range at a time and skips ranges that are being throttled. Automatic splitting refuses a range that is already `--lineage-auto-split-max-depth` levels deep (default 3). ## Write-ahead log [Section titled “Write-ahead log”](#write-ahead-log) Every node writes one shared write-ahead log for all the ranges it leads. The number of log writes to the store therefore grows with the number of nodes, not with the number of ranges. Tuning flags are listed in [Configuration](/docs/self-hosting/configuration). ## Readiness [Section titled “Readiness”](#readiness) `GET /health` answers `ok` as soon as the HTTP server is up; it says nothing about leadership. A cluster is ready when every range in `GET /cluster` (or `cairn cluster`) has a `leader`. Wait for that before stopping the next node during a rolling restart. # Configuration > The important cairnflow runtime flags, their environment variables and defaults, grouped by purpose. `cairnflow --help` lists every flag. This page covers the ones you are likely to set. ## How settings are read [Section titled “How settings are read”](#how-settings-are-read) 1. Built-in defaults. 2. Environment variables, where a flag has one. 3. Command-line flags, which win over environment variables. A malformed number in an environment variable is ignored and the default is kept; a malformed flag value stops the node at startup. Values that select a mode (such as `CAIRNFLOW_QUIET_LEASE` or `CAIRNFLOW_ADVERTISE_HOST`) are checked strictly in both forms. ## Storage [Section titled “Storage”](#storage) | Flag | Environment | Default | Meaning | | ------------------------------ | ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `--main-store URI` | `CAIRNFLOW_MAIN_STORE` | none | Main store: `file://`, `memory://` or `s3://`. See [Object stores](/docs/self-hosting/storage). | | `--data-dir DIR` | `CAIRNFLOW_DATA_DIR` | `./cairnflow-data` | Shortcut for `--main-store file://DIR`. `--main-store` wins if both are set. | | `--wal-store URI` | `CAIRNFLOW_WAL_STORE` | main store | Separate store for the write-ahead log. | | `--wal-atomic-put true\|false` | none | by store | Declares whether PUTs on the log store are atomic under crashes. Required for `s3://` stores other than AWS S3, Tigris and SeaweedFS; use `false` for MinIO. | S3 credentials and endpoint come from environment variables such as `AWS_ACCESS_KEY_ID`; there are no flags for them (see [Object stores](/docs/self-hosting/storage#s3-credentials-and-endpoint)). ## Network [Section titled “Network”](#network) | Flag | Environment | Default | Meaning | | ---------------------------- | ---------------------------------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--host ADDR` | `CAIRNFLOW_HOST` | `127.0.0.1` | Bind address. Also the advertised address unless `--advertise-host` is set. | | `--advertise-host ADDR` | `CAIRNFLOW_ADVERTISE_HOST` | `--host` | Host advertised to peers and clients. | | `--port N` | `CAIRNFLOW_PORT` | `8080` | Client port: API, console, metrics. `0` lets the OS choose; the real port is in the first log line. | | `--internal-port N` | `CAIRNFLOW_INTERNAL_PORT` | `--port` + 1 | Node-to-node port. `0` when `--port` is `0`. | | `--http-header-timeout-ms N` | `CAIRNFLOW_HTTP_HEADER_TIMEOUT_MS` | `75000` | Time allowed to read request headers on both ports. Also the idle limit of keep-alive connections: set it above the idle timeout of the proxy in front, so the proxy closes idle connections first. | | `--trust-proxy CIDR[,CIDR]` | `CAIRNFLOW_TRUST_PROXY` | none | Peers in these ranges are trusted TLS proxies: their `X-Forwarded-*` headers are used. Repeatable. | Both ports speak HTTP/1 only. ## Cluster [Section titled “Cluster”](#cluster) | Flag | Environment | Default | Meaning | | ------------------------------------- | ------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--node-id ID` | `CAIRNFLOW_NODE_ID` | generated per process | Node identity. Keep it stable per machine. | | `--partitions N` | `CAIRNFLOW_PARTITIONS` | `1` | Number of ranges when the bucket is first initialised. Must match on every node. | | `--lease-ttl-ms N` | `CAIRNFLOW_LEASE_TTL_MS` | `10000` | Lease lifetime; failover takes about one TTL. | | `--shutdown-timeout-ms N` | `CAIRNFLOW_SHUTDOWN_TIMEOUT_MS` | `20000` | Cap on a graceful shutdown after `SIGTERM`/`SIGINT`. | | `--quiet-lease off\|solo\|delegation` | `CAIRNFLOW_QUIET_LEASE` | `delegation` | Lease renewal mode written when this node **creates** a new bucket. `delegation`: a single node renews with conditional reads, and a multi-node cluster delegates renewal to a coordinating node. `solo`: only the single-node mode. `off`: every node renews with writes. Ignored for a bucket that already holds a cluster. | | `--auto-split off\|suggest\|on` | `CAIRNFLOW_AUTO_SPLIT` | `suggest` | Automatic range splitting. See [Running a cluster](/docs/self-hosting/cluster). | | `--max-range-bytes N` | none | 8 GiB | Size above which a range is proposed for a split. | | `--auto-split-max-ranges N` | none | `128` | Splits for load stop once the range table has this many ranges. `0` removes the cap. | | `--auto-split-merge-cold-ms N` | none | `21600000` (6 h) | Two adjacent ranges cold for this long are proposed for a merge (never merged automatically). `0` turns merge proposals off. | | `--lineage-compact-depth N` | none | `2` | A range that still reads the files of this many ancestor ranges gets one full compaction. `0` turns it off. | | `--slow-shed on\|off` | `CAIRNFLOW_SLOW_SHED` | `on` | A node that is much slower than its peers at writing to the store gives up leadership, one node at a time. | | `--deploy-refresh-ms N` | `CAIRNFLOW_DEPLOY_REFRESH_MS` | `30000` | Safety-net interval for re-reading cluster-wide records (deployments, keys, tenants). Changes are pushed to peers immediately; this bounds the delay when a push is missed. | `--cluster` (`CAIRNFLOW_CLUSTER`) is still accepted but has no effect: every node runs the lease protocol. ## Authentication and secrets [Section titled “Authentication and secrets”](#authentication-and-secrets) These are environment variables only. See [Security](/docs/self-hosting/security). | Variable | Meaning | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | | `CAIRNFLOW_ADMIN_KEY` | Bootstrap key: `cluster-admin` role, tenant `default`, never written anywhere. At least 32 bytes, or the node does not start. | | `CAIRNFLOW_ADMIN_KEY_SHA256` | 64 hex digits, the SHA-256 of a bootstrap key. The node knows only the hash. Do not set it together with `CAIRNFLOW_ADMIN_KEY`. | | `CAIRNFLOW_PROVISION_KEY_SHA256` | 64 hex digits, the SHA-256 of a `provision` key for tenant `default`. | | `CAIRNFLOW_METRICS_KEY` | Token that can only call `GET /metrics`. At least 32 bytes, different from the bootstrap key. | | `CAIRNFLOW_CLUSTER_SECRET` | HMAC secret between nodes. At least 32 bytes and identical on every node. If unset, the first node creates one in the bucket. | | `CAIRNFLOW_IDENTITY_MASTER` | Master secret for signing requests to your services. At least 32 bytes, identical on every node. Unset: requests are not signed. | | Flag | Environment | Default | Meaning | | ---------------- | ------------------------ | ------- | -------------------------------------------------------------------------------------------------- | | `--no-auth` | `CAIRNFLOW_NO_AUTH` | off | Disables API keys. Development only; the internal port still requires signatures. | | `--profile saas` | `CAIRNFLOW_PROFILE=saas` | off | Hardened defaults for a shared, multi-tenant node; refuses to start when a requirement is missing. | ## Invocations [Section titled “Invocations”](#invocations) | Flag | Environment | Default | Meaning | | --------------------------------- | --------------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--invoke-wait-ms N` | `CAIRNFLOW_INVOKE_WAIT_MS` | `5000` | How long `POST /invoke` waits for a result before answering `202` with the id. `0` answers right after the first turn. | | `--attach-max-wait-ms N` | `CAIRNFLOW_ATTACH_MAX_WAIT_MS` | `60000` | Cap on `?wait_ms=` for attach calls. | | `--inactivity-timeout-ms N` | `CAIRNFLOW_INACTIVITY_TIMEOUT_MS` | `60000` | A turn is abandoned (and retried with backoff, journal intact) when your service makes no progress for this long. In practice, the longest `ctx.run` closure you allow. `0` disables it. | | `--inactivity-timeout-max-ms N` | `CAIRNFLOW_INACTIVITY_TIMEOUT_MAX_MS` | `3600000` (1 h) | Upper bound for the `inactivityTimeout` a handler declares; longer values are clamped. | | `--max-concurrent-turns N` | `CAIRNFLOW_MAX_CONCURRENT_TURNS` | `32` | Client-initiated turns running at once on the node, shared by its ranges. Each turn is one connection to your service. | | `--max-turns-per-tenant N` | `CAIRNFLOW_MAX_TURNS_PER_TENANT` | `0` (no cap) | Turns of one tenant running at once on the node, so one tenant whose service hangs cannot hold every slot. | | `--key-rate N/S` | `CAIRNFLOW_KEY_RATE` | no cap | Request rate of one API key (or one SSO user) on the node: a burst of `N`, then one request every `S/N` seconds. Over it: `429 key_rate_limited` with `Retry-After`. | | `--replay-ram-budget-bytes N` | `CAIRNFLOW_REPLAY_RAM_BUDGET_BYTES` | `536870912` (512 MiB) | Journal bytes the node’s running turns may hold in memory at once; one tenant holds at most a quarter. A turn that does not fit is rescheduled after 1 s without calling your service. `0` removes the budget. | | `--retention-ms N` | `CAIRNFLOW_RETENTION_MS` | `86400000` (24 h) | How long finished invocations are kept before they are purged. Also the deduplication window of idempotency keys. `0` keeps them forever. A handler’s `journalRetention` overrides it. | | `--no-archive` | `CAIRNFLOW_NO_ARCHIVE` | archive on | Purge without writing an archive copy first. | | `--archive-artifacts` | none | off | Copy artifact bytes into the archive too. By default the archive keeps only references. | | `--schedule-min-period-ms N` | `CAIRNFLOW_SCHEDULE_MIN_PERIOD_MS` | `10000` | Smallest `everyMs` accepted for a server-side schedule. | | `--max-open-streams-per-tenant N` | `CAIRNFLOW_MAX_OPEN_STREAMS_PER_TENANT` | `256` | Long-lived connections (stream reads, pending attaches) per tenant per node. Over the limit: `429 too_many_open_streams`. `0` removes the limit. | | `--tick-interval-ms N` | `CAIRNFLOW_TICK_MS` | `200` | Background safety-net tick for timers and retries. | ## Backpressure [Section titled “Backpressure”](#backpressure) | Flag | Environment | Default | Meaning | | ------------------- | ------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `--queue-wait-ms N` | `CAIRNFLOW_QUEUE_WAIT_MS` | `10000` | How long a request waits for a concurrency slot before the client gets `429`. `0` waits forever. | | `--l0-soft N` | `CAIRNFLOW_L0_SOFT` | `5` | From this many level-0 views in a range (the limit is 8), new work is refused with some probability (`429 range_overloaded`). `0` disables it. | | `--l0-max-reject P` | `CAIRNFLOW_L0_MAX_REJECT` | `0.9` | Highest refusal probability, in `[0, 1)`. | See [Flow control](/docs/reference/flow-control). ## SQL queries [Section titled “SQL queries”](#sql-queries) | Flag | Environment | Default | Meaning | | ----------------------------------------- | ------------------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--query-isolation auto\|process\|inline` | none | `auto` | Where SQL sent to `POST /query` runs. `process`: a `cairn-query-worker` child process per query, killed at the query deadline or its memory limit. `inline`: inside the node. `auto`: `process` when `cairn-query-worker` sits next to `cairnflow`, otherwise `inline` with a warning at startup. | | `--query-worker PATH` | `CAIRNFLOW_QUERY_WORKER` | next to `cairnflow` | Path of the `cairn-query-worker` binary. | | `--query-worker-memory-mb N` | none | `512` | Memory limit of each query process. A query over it gets `422 query_budget`; the node is unaffected. | See [Security](/docs/self-hosting/security#sql-queries-run-in-a-child-process). ## Web console [Section titled “Web console”](#web-console) | Flag | Environment | Default | Meaning | | ---------------------------- | ---------------------------- | ------------------------------ | ---------------------------------------------------------------------------- | | `--no-ui` | `CAIRNFLOW_NO_UI` | console on | Do not serve the web console. | | `--ui-base-path P` | `CAIRNFLOW_UI_BASE_PATH` | `/ui` | Path of the console. Must not collide with an API route. | | `--ui-cookie-secure on\|off` | `CAIRNFLOW_UI_COOKIE_SECURE` | on unless `--host` is loopback | Whether the session cookie carries `Secure`. | | `--ui-env-label L` | `CAIRNFLOW_UI_ENV_LABEL` | none | Environment badge in the console header, 1 to 24 printable ASCII characters. | ## Outbound requests (egress) [Section titled “Outbound requests (egress)”](#outbound-requests-egress) | Flag | Default | Meaning | | -------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------- | | `--egress-deny-private` | off | Requests to your services may not reach loopback, private, link-local and metadata, CGNAT or other special addresses. | | `--egress-allow-cidr CIDR` | none | Repeatable. A private network you do want to reach; wins over `--egress-deny-private`. | | `--egress-deny-cidr CIDR` | none | Repeatable. Always blocked, even when `--egress-deny-private` is off. | | `--egress-require-https` | off | Accept only `https://` service endpoints. | ## Shared write-ahead log (advanced) [Section titled “Shared write-ahead log (advanced)”](#shared-write-ahead-log-advanced) | Flag | Environment | Default | Meaning | | -------------------------- | ----------------------------- | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `--flush-interval-ms N` | `CAIRNFLOW_FLUSH_INTERVAL_MS` | `10` | Minimum gap between two log objects of one stream. On S3 a PUT takes longer than this, so it rarely binds. Smaller means more PUTs under heavy load. | | `--wal-window-ms N` | none | `--flush-interval-ms` | Node-wide log window; a range can have its own (`PUT /ranges/{id}/window`). | | `--wal-linger-us N` | none | `1000` | After an idle period, wait this long so commits that arrive together share one object. Maximum `100000`. | | `--wal-stripes N` | none | `2` | Log streams per node. | | `--wal-inflight N` | none | `1` | PUTs in flight per stream. | | `--wal-object-cap-bytes N` | none | `1048576` | Maximum size of one log object. | | `--wal-age-flush-ms N` | none | `60000` | Age after which a range’s in-memory data is flushed to sorted files. | | `--wal-put-timeout-ms N` | none | `2000` | Timeout of one log PUT; after three consecutive failures the node stops itself. | | `--engine-threads N` | `CAIRNFLOW_ENGINE_THREADS` | `0` (one per core) | Threads that run range engines. | `--wal-kind shared` is accepted and changes nothing; any other value is refused at startup. ## SST disk cache [Section titled “SST disk cache”](#sst-disk-cache) | Flag | Default | Meaning | | ---------------------- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `--disk-cache-dir DIR` | off | Cache copies of sorted files (SSTs) of every range on local disk. Holds customer data. See [Operations](/docs/self-hosting/operations). | | `--disk-cache-bytes N` | `17179869184` (16 GiB) | Cache size limit, kept by LRU eviction. | ## Background maintenance [Section titled “Background maintenance”](#background-maintenance) | Flag | Environment | Default | Meaning | | ------------------------------- | ------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--gc-retired-dbs` | `CAIRNFLOW_GC_RETIRED_DBS=1` | off | Remove the data of ranges retired by split or merge once nothing references it. Deletes data. `--gc-retired-dbs=plan` (or `=plan` in the variable) only logs the plan. | | `--gc-every-s N` | `CAIRNFLOW_GC_EVERY_S` | `600` | Interval of that collection. | | `--gc-min-age-s N` | `CAIRNFLOW_GC_MIN_AGE_S` | `1800` | Minimum age of retired data before it can be collected. | | `--trash-keep-s N` | `CAIRNFLOW_TRASH_KEEP_S` | `604800` (7 days) | How long deleted objects stay in the trash. `0` never empties it. | | `--tenant-purge-keep-s N` | `CAIRNFLOW_TENANT_PURGE_KEEP_S` | `604800` (7 days) | How long a tenant marked for deletion stays reversible before its data is deleted. `0` never deletes. | | `--scrub-every-s N` | `CAIRNFLOW_SCRUB_EVERY_S` | `600` | Shortest interval of the background consistency check (read-only). `0` disables it. | | `--scrub-requests-per-hour N` | `CAIRNFLOW_SCRUB_REQUESTS_PER_HOUR` | `6000` at the default interval | Caps the store requests of that check: after a round that cost C requests it pauses at least C/N hours, so the interval stretches as the number of ranges grows. `0` removes the cap. | | `--retire-orphans-every-s N` | `CAIRNFLOW_RETIRE_ORPHANS_EVERY_S` | `3600` | Safety-net interval for cleaning up after interrupted splits and merges. `0` disables it. | | `--reconcile-intents-every-s N` | `CAIRNFLOW_RECONCILE_INTENTS_EVERY_S` | `15` | Interval for rolling back splits and merges that no node is coordinating. `0` disables it. | ## Handler health [Section titled “Handler health”](#handler-health) | Flag | Environment | Default | Meaning | | ------------------------------------------- | ----------------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `--slow-log-ms N` | `CAIRNFLOW_SLOW_LOG_MS` | `5000` | Runs longer than this leave one `warn` line (target `cairnflow::slow_log`), at most 10 lines per second per node. | | `--quarantine off\|observe\|cooldown\|hold` | `CAIRNFLOW_QUARANTINE` | `observe` | What to do with a handler that keeps failing. `observe` only logs and counts; `cooldown` limits it to one concurrent run per range; `hold` puts new invocations of it in `paused` (code 576). | | `--quarantine-rule A/I/S` | none | `20/5/300` | A handler is flagged after at least A failed attempts across at least I invocations, with no success, within S seconds. | | `--quarantine-ttl-s N` | none | `3600` | How long a quarantine entry lives. | ## Logging and tracing [Section titled “Logging and tracing”](#logging-and-tracing) | Variable | Meaning | | ------------------------------------------------------------ | ---------------------------------------------------------------------------------- | | `RUST_LOG` | Log filter, default `info`. Logs go to stderr. | | `CAIRNFLOW_LOG=json` | One JSON object per line instead of text. | | `CAIRNFLOW_OTEL_ENDPOINT` (or `OTEL_EXPORTER_OTLP_ENDPOINT`) | Export traces over OTLP/HTTP, when the binary is built with OpenTelemetry support. | `--no-user-otlp` (`CAIRNFLOW_NO_USER_OTLP`) exports only system spans and keeps the spans and logs your handlers write inside cairnflow. # Docker > Running cairnflow from the container image, and a two-node cluster on SeaweedFS with Docker Compose. Note The official image is published on GitHub Container Registry: `ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0`. To build an image yourself from the `Dockerfile` at the root of the [source repository](https://github.com/cairnflowdev/cairnflow) instead: ```sh git submodule update --init # the Dockerfile copies vendor/; the build fails without it docker build -t cairnflow:local . ``` ## The image [Section titled “The image”](#the-image) * Contains `cairnflow`, `cairn`, `cairn-ctl` and `cairn-query-worker`, built together, so their versions match. `cairn-query-worker` sits next to `cairnflow`, so SQL queries run in a child process by default. * Runs as a non-root user (uid and gid `10001`). * `ENTRYPOINT ["cairnflow"]`: every argument after the image name is passed to `cairnflow`. * Defaults to a single node on `file:///var/lib/cairnflow`, listening on `0.0.0.0:8080` (`CAIRNFLOW_HOST=0.0.0.0`, `CAIRNFLOW_PORT=8080`, `CAIRNFLOW_DATA_DIR=/var/lib/cairnflow`). * Exposes `8080` (clients) and `8081` (internal, node to node). Publish only `8080`. * Includes `curl`, so a health check can call `GET /health`. * Carries its license and notice files under `/usr/share/doc/cairnflow/`. Authentication is on: pass a bootstrap key, or `--no-auth` for a quick local try. ```sh # one node, data in a named volume docker run --rm -p 8080:8080 \ -e CAIRNFLOW_ADMIN_KEY="$CAIRNFLOW_ADMIN_KEY" \ -v cairnflow-data:/var/lib/cairnflow \ ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 # one node on S3; s3.env holds the AWS_* variables docker run --rm -p 8080:8080 \ -e CAIRNFLOW_ADMIN_KEY="$CAIRNFLOW_ADMIN_KEY" \ --env-file s3.env \ ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 --main-store s3://bucket/prefix ``` Keep `s3.env` limited to the variables you need; the S3 client reads every variable of the process (see [Object stores](/docs/self-hosting/storage)). ### Reaching your service from the container [Section titled “Reaching your service from the container”](#reaching-your-service-from-the-container) The runtime calls your service, so register it at an address the container can reach. With Docker Desktop and a service running on the host: ```sh cairn register http://host.docker.internal:9080 ``` On Linux, use the host’s IP on the Docker bridge, or run your service in the same Compose project. ### Running `cairn-ctl` [Section titled “Running cairn-ctl”](#running-cairn-ctl) `cairn-ctl` reads the bucket directly, with the same S3 environment as the node. Override the entrypoint: ```sh docker run --rm --env-file s3.env --entrypoint cairn-ctl \ ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 --main-store s3://bucket/prefix verify ``` Anyone who can run it with those credentials can change the bucket: hand it only to people who are allowed to. ## Clusters in containers [Section titled “Clusters in containers”](#clusters-in-containers) The image sets `CAIRNFLOW_HOST=0.0.0.0`, which is right for one node and **wrong for a cluster**: a node advertises the address it binds to, and peers cannot reach `0.0.0.0`. In a cluster, pass `--host` with the container’s own hostname or IP, or bind on all interfaces and set `--advertise-host` (see [Running a cluster](/docs/self-hosting/cluster)). ## Compose example: two nodes on SeaweedFS [Section titled “Compose example: two nodes on SeaweedFS”](#compose-example-two-nodes-on-seaweedfs) This example runs SeaweedFS as the S3 store, creates a bucket, and starts two nodes sharing `s3://cairnflow/demo` with four ranges. The S3 keys are samples for a local trial, not secrets. There are no default API keys or cluster secret: Compose stops at once unless you set them. `seaweed-s3.json`, the SeaweedFS S3 identities: seaweed-s3.json ```json { "identities": [ { "name": "cairnflow", "credentials": [{ "accessKey": "dev-only-access-key", "secretKey": "dev-only-not-a-secret" }], "actions": ["Admin", "Read", "Write", "List", "Tagging"] } ] } ``` Set the bootstrap key (at least 32 bytes) and the cluster secret in the shell that runs `docker compose` (or put their values in a `.env` file next to the Compose file): ```sh export CAIRNFLOW_ADMIN_KEY="cf_$(openssl rand -hex 24)" export CAIRNFLOW_CLUSTER_SECRET="$(openssl rand -hex 32)" ``` docker-compose.yml ```yaml name: cairnflow x-s3-env: &s3-env AWS_ENDPOINT: http://seaweedfs:8333 AWS_ACCESS_KEY_ID: dev-only-access-key AWS_SECRET_ACCESS_KEY: dev-only-not-a-secret AWS_REGION: us-east-1 AWS_ALLOW_HTTP: "true" AWS_VIRTUAL_HOSTED_STYLE_REQUEST: "false" x-auth-env: &auth-env CAIRNFLOW_ADMIN_KEY: ${CAIRNFLOW_ADMIN_KEY:?set CAIRNFLOW_ADMIN_KEY} CAIRNFLOW_TOKEN: ${CAIRNFLOW_ADMIN_KEY:?set CAIRNFLOW_ADMIN_KEY} # lets `cairn` inside the container authenticate CAIRNFLOW_CLUSTER_SECRET: ${CAIRNFLOW_CLUSTER_SECRET:?set CAIRNFLOW_CLUSTER_SECRET} x-cairn: &cairn image: ghcr.io/cairnflowdev/cairnflow:v0.1.0-beta.0 restart: unless-stopped stop_grace_period: 30s # longer than the 20 s graceful shutdown depends_on: create-bucket: condition: service_completed_successfully healthcheck: test: ["CMD-SHELL", "curl -fsS http://$$(hostname):8080/health || exit 1"] interval: 5s timeout: 3s retries: 20 services: seaweedfs: image: chrislusf/seaweedfs:latest # pin a version in production command: > server -dir=/data -s3 -s3.config=/etc/seaweed/s3.json -volume.max=0 -master.volumeSizeLimitMB=1024 volumes: - ./seaweed-s3.json:/etc/seaweed/s3.json:ro - seaweed-data:/data healthcheck: test: ["CMD", "curl", "-s", "-o", "/dev/null", "http://localhost:8333"] interval: 3s timeout: 2s retries: 30 create-bucket: image: amazon/aws-cli:latest environment: AWS_ACCESS_KEY_ID: dev-only-access-key AWS_SECRET_ACCESS_KEY: dev-only-not-a-secret AWS_DEFAULT_REGION: us-east-1 entrypoint: ["/bin/sh", "-c"] command: - > aws --endpoint-url http://seaweedfs:8333 s3api head-bucket --bucket cairnflow 2>/dev/null || aws --endpoint-url http://seaweedfs:8333 s3api create-bucket --bucket cairnflow depends_on: seaweedfs: condition: service_healthy cairn-1: <<: *cairn hostname: cairn-1 environment: <<: [*s3-env, *auth-env] command: [--main-store, s3://cairnflow/demo, --node-id, cairn-1, --partitions, "4", --host, cairn-1, --port, "8080", --disk-cache-dir, /var/lib/cairnflow/disk-cache, --disk-cache-bytes, "2147483648"] volumes: - cairn-1-cache:/var/lib/cairnflow ports: - "127.0.0.1:8080:8080" cairn-2: <<: *cairn hostname: cairn-2 environment: <<: [*s3-env, *auth-env] command: [--main-store, s3://cairnflow/demo, --node-id, cairn-2, --partitions, "4", --host, cairn-2, --port, "8080", --disk-cache-dir, /var/lib/cairnflow/disk-cache, --disk-cache-bytes, "2147483648"] volumes: - cairn-2-cache:/var/lib/cairnflow ports: - "127.0.0.1:8081:8080" volumes: seaweed-data: cairn-1-cache: cairn-2-cache: ``` ```sh docker compose up -d docker compose exec cairn-1 cairn --server http://cairn-1:8080 cluster ``` Node 1 answers on `127.0.0.1:8080` and node 2 on `127.0.0.1:8081` (each container’s ingress port; the internal port stays inside the Compose network). Points to know: * Published ports listen on the host’s loopback only: a port Docker publishes on `0.0.0.0` goes around the host’s firewall. To open the cluster to the network, put a TLS proxy in front. * The cluster secret comes from the environment, so it is never stored in the bucket, and a leaked S3 key cannot be used to forge internal requests or console cookies. * `--host` is the container’s hostname, which resolves to its IP on the Compose network. That is the address the node advertises to its peer. * Advertised addresses are Compose-network IPs. From the host machine, a `503` pointing at the other node cannot be followed. Call from inside the network, run your service as a Compose service, or send `x-cairn-forward: leader` so the receiving node forwards the request. * Each node has its own volume for the SST disk cache. The cache holds copies of customer data; delete the volume when a node leaves (see [Operations](/docs/self-hosting/operations)). * This setup has no TLS, and SeaweedFS runs as one process on one disk. It is a starting point, not a production layout. ## Kubernetes notes [Section titled “Kubernetes notes”](#kubernetes-notes) No persistent volume is needed: nodes keep no state. A workable layout: * a StatefulSet, only so that pods have stable names to use as `--node-id`; * `--host` set to the pod IP (from the downward API, `status.podIP`). Do not use the pod’s DNS name through a headless service: the record may not exist yet when the container starts, and a node that cannot resolve its own address exits; * a headless service for the internal port between pods, and a regular service for the ingress port; * `terminationGracePeriodSeconds` longer than `--shutdown-timeout-ms`, so `SIGTERM` has time to hand ranges over; * the optional SST disk cache on a size-limited `emptyDir`, which is discarded with the pod; * S3 credentials and the bootstrap key in Secrets, exposed as environment variables. # Operations > Health checks, metrics, logs, graceful shutdown, upgrades and the SST disk cache for a self-hosted cairnflow. ## Health and readiness [Section titled “Health and readiness”](#health-and-readiness) | Check | Meaning | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `GET /health` | Returns `ok` once the HTTP server is up. No key needed. Use it as a liveness probe. | | `GET /cluster` (`cairn cluster`) | The range table and who leads each range. Every range with a `leader` means the cluster is ready. The answer is the same on every node. | | `GET /cluster/nodes` | Nodes, the ranges they lead, the health of their writes to the store, disk cache usage. | `/health` does not tell you whether a node leads anything. During rolling restarts, wait until every range in `/cluster` has a leader before stopping the next node. ## Metrics [Section titled “Metrics”](#metrics) `GET /metrics` serves Prometheus text on the client port of every node. It accepts the metrics token (`CAIRNFLOW_METRICS_KEY`) or a `cluster-admin` key. Give Prometheus the metrics token: if the scrape configuration leaks, only metrics leak. prometheus.yml ```yaml scrape_configs: - job_name: cairnflow metrics_path: /metrics authorization: type: Bearer credentials_file: /etc/prometheus/cairnflow-metrics-key static_configs: - targets: ["node-a:8080", "node-b:8080", "node-c:8080"] ``` Each node is a target; the `instance` label tells nodes apart. Metrics describe what that node sees, so aggregate across instances. Useful series to start with: | Metric | Watch for | | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | `cairnflow_commit_wait_seconds` | Time to make a commit durable in the store (histogram). | | `cairnflow_drive_seconds` | Duration of one run of an invocation (histogram). | | `cairnflow_timer_lateness_seconds` | How late timers fire (histogram). | | `cairnflow_partitions`, `cairnflow_partitions_with_leader` | A difference that lasts means ranges without a leader. | | `cairnflow_range_l0_views{range}`, `cairnflow_range_l0_reject_ratio{range}` | Compaction falling behind; new work is being refused with `429 range_overloaded`. | | `cairnflow_invoke_throttled_total`, `cairnflow_flow_blocked_total{resource}` | Flow-control limits being hit. | | `cairnflow_failstop_total{cause}` | A node stopping itself to stay safe; repeated stops need attention. | | `cairnflow_slow_score` | A node much slower than its peers at writing to the store. | | `cairnflow_registry_stale` | A node that cannot confirm its key book is fresh and refuses stored keys. | | `cairnflow_scrub_findings` | The background consistency check found something. | | `cairnflow_nodewal_floor_age_seconds` | The shared write-ahead log cannot be trimmed. | | `cairnflow_disk_cache_hits_total`, `cairnflow_disk_cache_misses_total` | Disk cache effectiveness. | Labels never carry user-chosen values such as scope names, so cardinality stays bounded. Per-scope and per-handler detail lives in the API (`/limits`, `/vqueues`, `/stats/handlers`) and in SQL (see [Query](/docs/query)). The source repository includes a Grafana dashboard (`deploy/grafana/cairnflow.json`) and a set of Prometheus alerting rules (`deploy/prometheus/alerts.yml`) built on these metrics. ## Logs [Section titled “Logs”](#logs) Logs go to stderr. `RUST_LOG` filters them (default `info`); `CAIRNFLOW_LOG=json` switches to one JSON object per line for log collectors. Runs longer than `--slow-log-ms` (default 5000 ms) leave one `warn` line with target `cairnflow::slow_log`. It breaks the time down: waiting for your service, waiting for durable writes, waiting for a concurrency slot, and so on. At most 10 lines per second per node are printed. A tenant can have its own threshold (`PUT /admin/tenants/{tenant}` with `{"slowMs": n}`). The last 1 000 slow runs of each node are also available at `GET /stats/slow-runs` until the node restarts. ## Traces [Section titled “Traces”](#traces) A binary built with OpenTelemetry support exports traces over OTLP/HTTP when `CAIRNFLOW_OTEL_ENDPOINT` (or `OTEL_EXPORTER_OTLP_ENDPOINT`) is set: one trace per invocation, spans for each run and each turn, plus the spans and logs your handlers record. `--no-user-otlp` exports only the system spans. Handler logs and spans are always readable through the API (`/invocations/{id}/logs`, `/invocations/{id}/spans`) and the console. ## Stopping a node [Section titled “Stopping a node”](#stopping-a-node) Send `SIGTERM` or `SIGINT`. The node stops accepting connections, seals each range, closes its session and tells its peers, which take the ranges over almost immediately. The shutdown is capped by `--shutdown-timeout-ms` (default 20 s). Past the cap, or on a second signal, the node exits at once and peers wait one lease TTL before taking over. Set your orchestrator’s grace period above the cap. ## Upgrades [Section titled “Upgrades”](#upgrades) ### Data format and migrations [Section titled “Data format and migrations”](#data-format-and-migrations) The bucket carries a data format number, which is frozen, and a **cluster version** that advances through ordered migration steps. Each binary knows how many steps it can apply; `--version` prints both (`data=`, `knows=`). Releases are designed to open existing buckets and migrate them automatically: * cluster-wide objects are migrated by the **first** upgraded node to start, under a lock in the bucket; * each range’s own data is migrated lazily by its leader, the first time the range opens on an upgraded node. While the migration lock is held, split and merge answer `503` and the collection of retired range data skips its turn. ### Rolling upgrade [Section titled “Rolling upgrade”](#rolling-upgrade) 1. **Back up the bucket** (see [Backup and restore](/docs/self-hosting/backup-restore)). There are no reverse migrations. 2. Record the state: `GET /admin/cluster-version` (`cluster-admin`) shows `version`, `requiresKnows`, the migration lock (`upgrading`) and the `knows` of every node. 3. Upgrade **one node at a time**: `SIGTERM`, replace the binary, start it. 4. Wait until every range has a leader in `/cluster` before stopping the next node. 5. After the last node, `GET /admin/cluster-version` must show `upgrading: null`, `version` equal to `binary.knows`, and the same `knows` for every node. Only two consecutive releases can run side by side. After the cluster version moves past what an old binary knows, that binary keeps serving the ranges it already leads but cannot open new ones, and stops rather than overwrite an object it does not understand. Finish an upgrade instead of leaving the cluster mixed. **Rolling back** is possible only before the cluster version moves past what the old binary knows (`requiresKnows` still at or below the old binary’s `knows`). After that, the old binary refuses to start and the way back is the backup taken in step 1; invocations written after it are lost. ### One-way feature gates [Section titled “One-way feature gates”](#one-way-feature-gates) Features that older binaries would mishandle are switched on by one-way gates once every node runs a binary that knows them, with commands such as `cairn-ctl cluster enable-key-roles --apply`. `cairn-ctl cluster status` shows the gates and the `knows` of every session. A cluster created by a binary that already knows a gate starts with it enabled. ### Upgrading your services [Section titled “Upgrading your services”](#upgrading-your-services) An invocation stays bound to the deployment it started on, so registering a new version of your service does not move in-flight invocations to new code. New invocations use the new revision. To move existing ones on purpose, test with `POST /deployments/{id}/replay-check`, then use `POST /invocations/{id}/migrate` (which requires a matching replay) or `restart`. See the [HTTP API](/docs/reference/http-api#deployments-and-services). ## SST disk cache [Section titled “SST disk cache”](#sst-disk-cache) By default a node uses no disk: after a restart or a leadership change, the first reads of a range go to the store. `--disk-cache-dir DIR` keeps copies of sorted files (SSTs) of every range on local disk, up to `--disk-cache-bytes` (default 16 GiB) for the whole node, with LRU eviction. Newly written SSTs enter the cache immediately, and when a node takes over a range it warms the cache with that range’s recent files in the background. The cache survives restarts. The cache can only make reads faster, never wrong: only immutable SSTs go in it, never the write-ahead log, manifests or leases. A damaged entry is read again from the store, and a full or broken disk falls back to the store. Deleting the directory while the node is stopped is always safe. Size it to the hot SSTs of the ranges a node leads; 10 to 20 percent of the data per node is a reasonable start. Watch `cairnflow_disk_cache_evictions_total` and the hit ratio, also visible with `SELECT node, disk_cache_bytes, disk_cache_hit_ratio FROM sys_node` through `POST /query`. Caution The cache holds customer data: journals, state and outputs. * Put `DIR` on an encrypted volume. * Purging an invocation does not remove copies already in the cache. They disappear when evicted or when the directory is deleted, with no time bound. * When a node leaves the cluster, delete its cache directory. Ephemeral volumes do this for you. * Do not copy a cache directory between nodes. ## Bucket growth [Section titled “Bucket growth”](#bucket-growth) * **Retention.** Finished invocations are purged after `--retention-ms` (default 24 hours). With `0` they are kept forever and the bucket grows with history, not with load. * **Archive.** Before purging, cairnflow writes a compressed copy of the journal and final state under `archive///`. Archives never expire on their own: set a lifecycle rule on the `archive/` prefix, or run with `--no-archive`. * **Splits and merges** leave retired range data behind until `--gc-retired-dbs` is enabled (see [Running a cluster](/docs/self-hosting/cluster)). * **Trash.** Cairnflow’s own deletions are kept for `--trash-keep-s` (default 7 days) before they are removed for good. ## Background consistency check [Section titled “Background consistency check”](#background-consistency-check) Every `--scrub-every-s` seconds (default 600), one node runs a read-only check of the bucket’s invariants, the same family of checks as `cairn-ctl verify`. Its store requests are capped by `--scrub-requests-per-hour`: a round that costs more requests is followed by a longer pause, so on a cluster with many ranges the interval stretches while every round stays complete. It never changes anything; findings appear in `cairnflow_scrub_findings`, in the log and at `GET /admin/scrub`. A finding that persists over two rounds deserves a look with `cairn-ctl verify` (see [Backup and restore](/docs/self-hosting/backup-restore)). The background check does not look for missing individual sorted files. Run `cairn-ctl verify --deep` periodically for that, so a file deleted from outside cairnflow is found before a read needs it. # Security > API keys and roles, tenants, console sessions, single sign-on, request identity, TLS and outbound request policy for self-hosted cairnflow. ## Authentication is on by default [Section titled “Authentication is on by default”](#authentication-is-on-by-default) Every route except `GET /health` requires `Authorization: Bearer `. A missing or wrong key gets `401`; a key whose role does not allow the route gets `403`. A node with no key configured refuses to start. `--no-auth` turns keys off and treats every request as `cluster-admin` of tenant `default`: use it on a development machine only. Wrong keys are rate-limited per client IP (taken from `X-Forwarded-For` only behind `--trust-proxy`): a burst of 100 failed attempts, then one per second. Past that, a wrong key gets `429 auth_failures_limited` with `Retry-After`. A correct key is never limited, so clients behind the same NAT as a prober are not locked out. ## Keys that live in the environment [Section titled “Keys that live in the environment”](#keys-that-live-in-the-environment) | Variable | Gives | | -------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `CAIRNFLOW_ADMIN_KEY` | The bootstrap key: role `cluster-admin`, tenant `default`. Never written anywhere. | | `CAIRNFLOW_ADMIN_KEY_SHA256` | The same, but the node only holds the SHA-256 of the key; the key itself stays in your break-glass store. | | `CAIRNFLOW_PROVISION_KEY_SHA256` | A `provision` key for tenant `default`, by hash. Enough for a node to start without any `cluster-admin` key. | | `CAIRNFLOW_METRICS_KEY` | A token that can call `GET /metrics` and nothing else, for Prometheus. | Generate keys with enough randomness, and hash them without a trailing newline: ```sh KEY="cf_$(openssl rand -hex 24)" printf %s "$KEY" | sha256sum ``` The node refuses to start if `CAIRNFLOW_ADMIN_KEY` is shorter than 32 bytes, if a hash is not 64 hex digits, if both `CAIRNFLOW_ADMIN_KEY` and its `_SHA256` variant are set, if the metrics token is shorter than 32 bytes, or if two roles share the same secret. These keys cannot be revoked through the API: to rotate one, set the new value on every node and restart the nodes one by one. ## Roles [Section titled “Roles”](#roles) Each key belongs to one **tenant** and has one **role**. | Role | Can | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `invoke` | Call handlers and workflows, resolve promises and awakeables, send signals, cooperative cancel (`?mode=signal`), read an invocation by id, attach to it, read its user streams and artifacts, manage schedules of its tenant. | | `view` | Read everything in its tenant: invocations, journals, logs and spans, deployments, services, archive, stats, metering, SQL queries. Cannot call or change anything. | | `admin` | Everything `view` and `invoke` can do, plus: register and remove deployments, move service revisions, hard cancel, purge, resume, restart, migrate, batch operations. | | `provision` | Control-plane work without access to run data: create and revoke `invoke`, `view` and `admin` keys, tenant settings and state, SSO configuration, cluster version. Cannot read invocations, journals, state, queries, archive, artifacts or streams, and cannot sign in to the console. | | `cluster-admin` | Everything, across all tenants: flow-control rules, range split and merge, `/cluster`, `/metrics`, all `/admin` routes, and `?tenant=` on tenant routes. | | `metrics` | `GET /metrics` only. Exists only through `CAIRNFLOW_METRICS_KEY`. | A `provision` key can grant and revoke only `invoke`, `view` and `admin` keys, so a leaked `provision` key cannot mint a peer or a `cluster-admin` key. Note On a cluster first created by an older binary, `view` and `provision` keys stored in the bucket are behind a one-way gate. Once every node runs the new binary, enable it with `cairn-ctl cluster enable-key-roles --apply`. Until then, creating such a key returns `409 key_roles_disabled`. Clusters created by a current binary have it enabled. ## Managing keys [Section titled “Managing keys”](#managing-keys) ```sh cairn keys create default invoke # prints the secret once cairn keys # lists stored keys, never secrets cairn keys rm # revokes cairn keys check # is the key still accepted anywhere? ``` The secret (`cf_...`) appears only in the response that creates the key; the bucket keeps its SHA-256. The same operations are available at `/admin/keys` (see [HTTP API](/docs/reference/http-api#keys-identity-and-tenant)). Revocation is synchronous. `cairn keys rm` returns `204` only when every live node has confirmed it stopped accepting the key. Nodes that did not confirm in time are listed in a `202` response with `pending`; they pick up the change within one `--deploy-refresh-ms` interval. After a `202`, or a revocation whose outcome you did not see, ask any node with `cairn keys check ` (`GET /admin/keys/{id}/revocation`): `confirmed: true` means no live node accepts the key. An id that is not in the key book, including a typo, also reports `revoked: true`, so check the id with `cairn keys` first. A node that cannot confirm its key book is fresh for more than two refresh intervals answers `503` to requests authenticated with stored keys until it can. The bootstrap key keeps working. `cairn-ctl keys create --apply` writes a key directly to the bucket, without a running node, for example to bootstrap the first `provision` key. ## Tenants [Section titled “Tenants”](#tenants) The tenant of a request is the tenant of its key, never a path segment or a header. Service names, state, promises, idempotency keys, workflow ids and virtual-object keys are all scoped by tenant: `Cart/x` in two tenants is two objects. Another tenant’s invocation answers `404`, as if it did not exist. A self-hosted node with one team typically uses only tenant `default`. ## Console sessions [Section titled “Console sessions”](#console-sessions) The web console is served at `/ui`. Its static files need no key; all data goes through the API. The browser never stores your API key: the console exchanges it once at `POST /ui/session` for an `HttpOnly`, `SameSite=Strict` cookie that lasts 12 hours, without sliding renewal. The cookie carries the key id, not the key, and every request looks the key id up again, so revoking a key ends its console sessions too. Changing `CAIRNFLOW_ADMIN_KEY` ends every bootstrap session. Unsafe requests made with the cookie (`POST`, `PUT`, `DELETE`) must come from the same origin (`Sec-Fetch-Site: same-origin`, or a matching `Origin`), otherwise `403`. Requests with an `Authorization` header ignore the cookie. The cookie gets the `Secure` attribute by default unless `--host` is a loopback address; control it with `--ui-cookie-secure on|off`. Signing out revokes the session on the server, for key sessions and SSO sessions alike: only that session ends, and other sessions of the same person or key keep working. Other nodes see the revocation within a few seconds. Each tenant can hold at most 200 signed-out sessions that have not expired yet; past that, signing out answers `429` (the browser still drops the cookie, but the session lives until it expires; revoke the key to end it at once). Sign-outs are also rate-limited per client IP and per tenant. Cookies issued by binaries from before this behaviour are refused after an upgrade, so console users sign in again once. ## Single sign-on (OIDC) [Section titled “Single sign-on (OIDC)”](#single-sign-on-oidc) A node can be an OpenID Connect relying party for one issuer (Keycloak, Authentik, Okta and similar). There are no flags: the configuration is stored in the bucket and set through the API with a `provision` or `cluster-admin` key. Without it, the console offers key sign-in only, which always remains available. ```sh curl -X PUT -H "Authorization: Bearer $KEY" https://cairn.example.com/admin/oidc \ -d '{"issuer":"https://idp.example.com/realms/ops","sessionTtlMs":3600000,"displayName":"Keycloak"}' # one client per hostname: requests to that hostname sign in to that tenant curl -X PUT -H "Authorization: Bearer $KEY" https://cairn.example.com/admin/oidc/clients/cairn-prod \ -d '{"hostname":"cairn.example.com","tenant":"default","maxRole":"admin"}' ``` At the identity provider: * a **public** client (no secret) with PKCE `S256`; * redirect URI `https:///ui/login/oidc/callback` (adjust for `--ui-base-path`); * scopes `openid email profile`; * an ID token signed with `RS256`, `PS256`, `ES256` or `EdDSA`, carrying `sub` and a `cairn_role` claim of `admin`, `view` or `invoke`. A missing or unknown role is refused. The tenant comes from the client configuration, not from a claim, and the role is capped at the client’s `maxRole`. `cluster-admin` is never available through SSO. Session TTL defaults to one hour (60 seconds to 24 hours). The SSO cookie uses the `__Host-` prefix, which browsers accept only over HTTPS or on `localhost`. Behind a TLS proxy, set `--ui-cookie-secure on` or `--trust-proxy` so the node knows requests arrive over HTTPS. Removing a client, changing the issuer or lowering `maxRole` takes effect on the next request. To end one person’s sessions, `POST /admin/oidc/revoked` with `{"client", "sub", "beforeMs"}`. ## Request identity: signed calls to your services [Section titled “Request identity: signed calls to your services”](#request-identity-signed-calls-to-your-services) Set `CAIRNFLOW_IDENTITY_MASTER` (32 bytes or more, the same on every node, kept outside the bucket) and every request the runtime sends to your services carries a short-lived signed token, derived per tenant. Get the public key with `GET /identity` and verify in the SDK: ```ts await serve({ services: [greeter], identityKeys: ["publickeyv1_..."] }); ``` Requests without a valid signature, for another path, expired, or for another invocation get `401` and the handler does not run. Your service’s clock must be within 60 seconds of the nodes. `--deploy-require-identity` makes `POST /deployments` refuse services that do not verify signatures (`400 identity_required`). Rotate a tenant’s key in four steps, each recorded in the bucket’s audit trail: 1. `cairn-ctl identity publish --apply`: publishes a new key; signing still uses the old one. 2. Add the new key id to `identityKeys` and deploy your service. 3. `cairn-ctl identity activate --apply`: signing switches to the new key. 4. `cairn-ctl identity retire --apply`, then remove the old key id from your service. Changing the master secret changes every tenant’s key at once. ## TLS [Section titled “TLS”](#tls) Cairnflow has no built-in TLS. Put a TLS-terminating proxy or load balancer in front of the client port; without it, API keys travel in clear text. Tell the node which proxies to trust with `--trust-proxy`, so it can use `X-Forwarded-*` for origin checks, the `Secure` cookie flag and per-IP sign-in limits. The internal port is signed but not encrypted. Keep traffic between nodes on a private network. A captured internal request could be replayed within 60 seconds; internal requests are idempotent. ## Outbound requests [Section titled “Outbound requests”](#outbound-requests) Registering a deployment makes the node send requests to a URL chosen by the caller. If people you do not fully trust can hold `admin` keys, restrict where those requests can go: ```sh cairnflow ... --egress-deny-private --egress-deny-cidr 203.0.113.10/32 ``` `--egress-deny-private` blocks loopback, private networks, link-local and cloud metadata addresses, CGNAT, other special ranges and IPv6 addresses that embed IPv4. Checks apply to the URL, to every address DNS returns and to the actual peer of the socket. Use `--egress-deny-cidr` for the public address of your own load balancer, and `--egress-allow-cidr` for a private network you do want to reach. A refused endpoint gets `400 egress_denied`. These requests never follow redirects and ignore `HTTP_PROXY` and `HTTPS_PROXY`. ## SQL queries run in a child process [Section titled “SQL queries run in a child process”](#sql-queries-run-in-a-child-process) SQL sent to `POST /query` (and the console’s SQL screen) is planned without memory or time limits, so a crafted query could exhaust a node. By default (`--query-isolation auto`) each query runs in a separate `cairn-query-worker` process when that binary sits next to `cairnflow`; without it, queries run inside the node and startup logs a warning. Ship both binaries together, or point at the worker with `--query-worker PATH`. The child gets no cluster secret, environment variables, store credentials or direct access to ranges: the node serves its reads and enforces the tenant, the ranges and the read budget itself. The child has its own memory limit (`--query-worker-memory-mb`, default 512), no file writes and a small file-descriptor limit; on Linux it is also non-dumpable and runs under a seccomp filter that blocks the network, starting programs, signalling other processes, tracing and opening files. On macOS only the resource limits apply. A query over its memory limit or deadline kills the child and gets `422 query_budget`; the node is unaffected. The child still runs as the same user as the node. `--query-isolation process` requires the worker and refuses to start without it; `--query-isolation inline` runs every query inside the node, for very small machines where only trusted people hold keys. ## Hardened profile [Section titled “Hardened profile”](#hardened-profile) `--profile saas` is meant for a cluster shared by tenants who do not trust each other. It mostly turns on protections that also exist as separate flags, and refuses to start, listing everything that is missing, when a requirement is not met: * **Turns on:** `--egress-deny-private`, `--egress-require-https`, `--ui-cookie-secure on`, `--no-user-otlp`, `--deploy-require-identity`, `--deploy-https-request-response`, `--deploy-require-compression`, and `--query-isolation process`. On Linux it also makes the node process non-dumpable, so other processes of the same user, query workers included, cannot read its environment (cluster secret, store credentials) or trace it. * **Sets defaults** where you gave none: `--query-worker-memory-mb 256`, `--key-rate 1000/1`, `--max-turns-per-tenant` at a quarter of `--max-concurrent-turns`, `--inactivity-timeout-max-ms` at most 15 minutes, and a default for every per-tenant resource limit a tenant’s settings leave empty. * **Requires** `CAIRNFLOW_CLUSTER_SECRET` (which is then never stored in the bucket), `CAIRNFLOW_IDENTITY_MASTER`, and at least one `--egress-deny-cidr` for the cluster’s own public addresses. * **Refuses** `--no-auth`, `--ui-cookie-secure off`, `--inactivity-timeout-ms 0` and `--query-isolation inline`. Without the profile, the same protections can be turned on one flag at a time. If people outside your organisation can register deployments or hold keys on your cluster, set at least `CAIRNFLOW_CLUSTER_SECRET`, `CAIRNFLOW_IDENTITY_MASTER` with `--deploy-require-identity`, the egress flags above, `--trust-proxy`, `--key-rate` and `--max-turns-per-tenant`. ## What to protect most [Section titled “What to protect most”](#what-to-protect-most) The S3 credentials are the most sensitive secret of a deployment. Anyone holding them can read the cluster secret stored in the bucket and change journals. Give bucket credentials, and the `cairn-ctl` tool, only to people who need them. ## Reporting a security issue [Section titled “Reporting a security issue”](#reporting-a-security-issue) If you find a vulnerability in cairnflow, the SDK or Cairnflow Cloud, write to . # Object stores > Store URIs, S3 credentials, the startup capability checks, and which object stores cairnflow supports. Cairnflow keeps all of its state in one object store, the **main store**. Choosing the store is the most important decision of a self-hosted deployment: the safety of leases and of the write-ahead log depends on how the store behaves under concurrent and interrupted writes. ## Store URIs [Section titled “Store URIs”](#store-uris) | URI | Meaning | | --------------------- | --------------------------------------------------------------------------- | | `file:///path/to/dir` | A local directory, created if missing. One node only. | | `memory://` | The process’s memory. For tests: everything is lost when the process exits. | | `s3://bucket/prefix` | An S3 or S3-compatible bucket. `prefix` is optional. | Pass the URI with `--main-store` (or `CAIRNFLOW_MAIN_STORE`). `--data-dir DIR` is a shortcut for `--main-store file://DIR`. Several clusters can share one bucket as long as each uses a different prefix. `--wal-store URI` moves the write-ahead log tier to a different store; the prefix is taken from `--main-store`. Most deployments keep one store. Among cloud stores, only `s3://` is available. Native Google Cloud Storage and Azure Blob Storage URIs are not supported. ## S3 credentials and endpoint [Section titled “S3 credentials and endpoint”](#s3-credentials-and-endpoint) There are no command-line flags for credentials. The S3 client is configured from the environment of the `cairnflow` process: ```sh export AWS_ENDPOINT=http://seaweedfs:8333 # omit for AWS S3 export AWS_ACCESS_KEY_ID=... export AWS_SECRET_ACCESS_KEY=... export AWS_REGION=us-east-1 export AWS_ALLOW_HTTP=true # only when the endpoint is http:// export AWS_VIRTUAL_HOSTED_STYLE_REQUEST=false # path-style requests, needed by SeaweedFS and MinIO ``` Caution The client reads **every** environment variable of the process, lower-cased, as possible S3 configuration. Plain variable names that match the client’s aliases are picked up too: `ENDPOINT`, `REGION`, `BUCKET`, `TOKEN`, `SESSION_TOKEN`, `ACCESS_KEY_ID`, `SECRET_ACCESS_KEY` and so on. A stray `TOKEN=` in a container environment would be sent as a session token. Keep the environment of the `cairnflow` process clean. Static access keys are the configuration that has been exercised. Other credential sources that the S3 client understands (session tokens, web identity, container credentials) are read the same way but have not been tested with cairnflow. The backup tool can use a separate set of credentials for a backup bucket at another provider; see [Backup and restore](/docs/self-hosting/backup-restore). ## Startup capability checks [Section titled “Startup capability checks”](#startup-capability-checks) Before writing anything, each node checks its store. If a check fails the node does not start, and there is no flag to skip checks 1 and 2. 1. **Conditional create.** The node writes the same key twice with “create only if absent”. The second write must be rejected, and the first object must be left intact. This is the fence that stops a stale leader from writing. Checked on every shape, and on both tiers when the write-ahead log is on a separate store. 2. **Compare-and-swap on ETag.** An update with the current ETag must succeed and an update with a stale ETag must be rejected. Leases are renewed with exactly this operation. Checked on the main store. 3. **Atomic PUT for the write-ahead log.** When a write to the log has an ambiguous outcome (a timeout, a retried request), the node resolves it by reading the object back. That is only safe if a PUT is whole-or-nothing even when the writer crashes mid-request. A store that can leave a torn object could lead the node to acknowledge a write that was lost. Checks 1 and 2 test real behaviour, so any store either passes or not. Check 3 cannot be observed at startup (a torn object only appears when a client dies mid-PUT), so for `s3://` it works as an allowlist. The node identifies the store and runs only on stores known to be safe: * **AWS S3**: no custom endpoint, or an endpoint under `amazonaws.com`; * **Tigris**: endpoint `t3.storage.dev` or `fly.storage.tigris.dev`; * **SeaweedFS**: identified by the `Server` header returned by the endpoint. Any other `s3://` store, a proxy that rewrites the `Server` header, or an endpoint that does not answer stops the node at startup until you declare the capability yourself: * `--wal-atomic-put false` is safe on **every** store. An ambiguous log write is treated as fenced: the node stops itself and its ranges recover on another node (or on its restart). You trade some availability for safety. * `--wal-atomic-put true` declares that PUTs are atomic under crashes. Use it only if you have verified that on your store. The startup log prints which capability was used and why (declared, identified by endpoint, or identified by header). ## Supported stores [Section titled “Supported stores”](#supported-stores) | Store | Status | Notes | | ------------------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | SeaweedFS | Verified, recommended for self-hosting | Passes all three checks. Crash and range split/merge testing was done on a single-process SeaweedFS; the distributed mode (several filers and volume servers) has not been measured. | | Tigris | Verified | Use a **single-region** bucket (for example `iad`) or a multi-region one. A bucket created without a location is Global: strongly consistent only within a region, so a lease update could be judged against a stale copy. The region cannot be changed after creation. | | AWS S3 | Accepted by the startup check, not yet measured | AWS S3 supports conditional writes, and the node checks them at startup. The project has not yet published latency or cost measurements on AWS, nor run its crash test for atomic PUTs there. | | MinIO | Only with `--wal-atomic-put false`; not recommended for clusters | Passes checks 1 and 2. A local erasure-coded MinIO has been observed to tear a lease object when a client is killed mid-update, leaving that range without a leader for good. | | Garage (v1.0.1) | Unsupported | Fails check 1: it accepts the second conditional write and overwrites the object. | | Other S3-compatible stores (Ceph, gateways) | Not identified | The node refuses to start until you pass `--wal-atomic-put`. Checks 1 and 2 still run. | | `file://` | One node only | See below. | | `memory://` | Tests only | One process. | To create and check a Tigris bucket in a single region: ```sh aws s3api create-bucket --bucket my-bucket \ --create-bucket-configuration '{"LocationConstraint":"iad"}' aws s3api get-bucket-location --bucket my-bucket # "global" means a Global bucket ``` ## Limits of `file://` [Section titled “Limits of file://”](#limits-of-file) A local directory passes the conditional-create check but has no compare-and-swap. As a result: * only **one** node can run on it; the node holds an exclusive lock on the directory; * range split and merge are not available, since they need compare-and-swap; * objects that are normally updated with compare-and-swap (such as the flow-control rule book) fall back to plain overwrites, which is safe with a single writer; * on a **case-insensitive** file system (the default on macOS, and NTFS), tenants `Acme` and `acme` share one directory: tenant isolation breaks, and purging one tenant deletes the other’s objects. Use a case-sensitive file system, or only lower-case tenant names. S3 is not affected. For more than one node, use an `s3://` store. ## Bucket settings worth turning on [Section titled “Bucket settings worth turning on”](#bucket-settings-worth-turning-on) * **Versioning.** Cairnflow moves its own deletions to a trash area for a week (see [Backup and restore](/docs/self-hosting/backup-restore)), but some low-level deletions do not go through it, and nothing in cairnflow can stop a deletion made from outside: an operator, a lifecycle rule, a store bug. Only the range table keeps its own history (see [Rebuilding the range table](/docs/self-hosting/backup-restore#rebuilding-the-range-table)); any other lost object comes back only from bucket versioning or from a backup. Keep old versions at least as long as it may take you to notice an incident; a periodic `cairn-ctl verify --deep` finds missing files before a read does. Cairnflow does not check at startup whether versioning is on. * **A lifecycle rule on `archive/`.** Archived invocations never expire on their own (see [Operations](/docs/self-hosting/operations)). Keep every other lifecycle rule away from the cluster’s prefix. * **Object Lock on `audit/`**, if you need the audit log to be tamper-resistant. Cairnflow only creates audit objects; it never overwrites or deletes them. # Table reference > Columns, types and meanings of the sys_* tables you can query in an environment. The tables below are available to every environment through `POST /query` and the console’s **Query** page. Each query only sees the data of the environment it runs in. Columns may be added over time; existing columns are not renamed or removed. Types: `text`, `int` (signed integer), `uint` (unsigned integer), `float`, `bool`, `timestamp` (returned as an ISO-8601 string). Columns ending in `_ms` hold milliseconds, as Unix time when they are points in time. **Required key** means the table can only be read with an equality filter on those columns, for example `WHERE id = '…'`. Other `sys_*` tables describe the cell itself (nodes, ranges, rules, keys, trash) and need operator access; they are not listed here. ## Invocations [Section titled “Invocations”](#invocations) ### `sys_invocation` [Section titled “sys_invocation”](#sys_invocation) One row per invocation, newest first (`created_at DESC, id ASC`). | Column | Type | Meaning | | ---------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `id` | text | Invocation ID (48 hex characters) | | `tenant` | text | Environment the invocation belongs to | | `service` | text | Service | | `handler` | text | Handler | | `key` | text | Object or workflow key (empty for a plain service) | | `kind` | text | How it was started: `call`, `send`, `workflow`, … | | `class` | text | `active`, `paused`, `completed` or `failed` | | `status` | text | Detailed status: `running`, `suspended`, … | | `root` | bool | `true` if it was not started by another invocation | | `created_at` | timestamp | When it was created | | `transitioned_at` | timestamp | When it entered its current class (`active`: creation time) | | `ended_at` | timestamp | When it ended | | `duration_ms` | int | `ended_at − created_at` | | `scope` | text | Scope it runs in | | `parent_id` | text | The invocation that called or sent it | | `root_id` | text | Root of its call tree (`NULL` on a root). `WHERE root_id = …` returns a whole tree | | `schedule` | text | The schedule that started it | | `idempotency_key` | text | Idempotency key it was started with | | `limit_key` | text | Limit key it was started with | | `tags` | text | Tags set when it was started, as JSON | | `deployment` | text | Deployment it was created on | | `pinned_deployment` | text | Deployment it is attached to now (differs after a migrate); unfinished invocations only | | `restarted_from` | text | The invocation it was restarted from | | `range` | uint | Key range holding it | | `failure_code` | int | Failure code of a `failed` or `paused` invocation (572 cancelled, 575 out of attempts, 576 quarantined, 577 stuck in infrastructure) | | `failure_message` | text | Message that goes with `failure_code` | | `attempt` | int | Attempts counted for the pending retry | | `retry_at` | timestamp | When the pending retry is due | | `last_failure_code` | int | Code of the most recent failed attempt | | `last_failure_message` | text | Message of the most recent failed attempt (cut at 1 KiB) | | `last_failure_at` | timestamp | When the most recent failed attempt ended | | `purge_at` | timestamp | When an ended invocation will be removed (retention) | | `journal_len` | int | Number of journal entries | | `hash_chain_len` | int | Entries covered by the tamper-evident hash chain, when enabled | Columns such as `status`, `failure_code`, `attempt`, `purge_at` and `journal_len` cost an extra read per row when you select them; filter first, then select. ### `sys_invocation_counts` [Section titled “sys_invocation_counts”](#sys_invocation_counts) Invocation counts per group, kept in memory and exact as of the last commit. Reads nothing from storage, so it is the cheap way to count. | Column | Type | Meaning | | --------- | ---- | ------------------------------------------- | | `tenant` | text | Environment | | `service` | text | Service | | `handler` | text | Handler | | `class` | text | `active`, `paused`, `completed` or `failed` | | `root` | bool | Root invocations only | | `count` | uint | Number of invocations | ## Inside one invocation [Section titled “Inside one invocation”](#inside-one-invocation) ### `sys_journal` [Section titled “sys_journal”](#sys_journal) The journal of one invocation, in order. **Required key:** `id`. | Column | Type | Meaning | | ------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `id` | text | Invocation ID | | `index` | int | Entry index | | `ty` | text | Message type code, such as `0x0402` | | `name` | text | Message type name (`Sleep`, `Call`, …) | | `payload` | text | Raw payload in hex, cut at 64 KiB | | `payload_len` | int | Payload size in bytes | | `entry_lite` | text | Decoded header, as JSON: `kind`, `name`, target (`service`, `handler`, `key`), `invocationId`, `wakeUpAtMs`, `promise`, `stateKey`, `signal`, `failure`, `awaits`/`completes`, `completed` (`false` means still waiting for its result), `hasBody` | | `body` | text | Decoded user body, as JSON `{encoding, size, truncated, text or base64}`, cut at 64 KiB; `NULL` when the entry has no body | ### `sys_timer` [Section titled “sys_timer”](#sys_timer) Pending sleeps of one invocation. **Required key:** `id`. | Column | Type | Meaning | | --------------- | ---- | ------------------------------------ | | `id` | text | Invocation ID | | `completion_id` | int | The completion the timer will fulfil | | `due_at_ms` | int | When it fires | ### `sys_attachment` [Section titled “sys_attachment”](#sys_attachment) Who else is waiting for this invocation’s result (attach by ID or by workflow, duplicate calls). **Required key:** `id`. | Column | Type | Meaning | | --------------- | ---- | ---------------------------------------------------- | | `id` | text | The invocation being waited for | | `caller_id` | text | The invocation waiting | | `completion_id` | int | The waiter’s completion that will receive the result | ### `sys_log` [Section titled “sys_log”](#sys_log) `ctx.log` lines of one invocation, by offset. Durable records only. **Required key:** `id`. | Column | Type | Meaning | | --------- | ---- | ------------------------------------------------------------ | | `id` | text | Invocation ID | | `offset` | int | Record offset | | `step` | int | Step | | `attempt` | int | Attempt | | `kind` | text | `data`, `gap` (records dropped over the cap) or `superseded` | | `body` | text | The record (UTF-8, otherwise hex) | ### `sys_span` [Section titled “sys_span”](#sys_span) Trace spans of one invocation, one row per span. Build the tree with `parent_id`. Durable records only. **Required key:** `id`. | Column | Type | Meaning | | --------------- | ---- | -------------------------------------------------- | | `id` | text | Invocation ID | | `span_id` | text | Span ID | | `parent_id` | text | Parent span | | `name` | text | Span name (`llm `, `tool `, your own) | | `start_ts` | text | Start time (JSON) | | `end_ts` | text | End time (JSON) | | `status` | text | Status at the end | | `unfinished` | bool | Started but never ended | | `start_lost` | bool | Ended, but its start record was lost | | `attrs` | text | Attributes, as JSON | | `input_tokens` | int | Input tokens reported at the end | | `output_tokens` | int | Output tokens reported at the end | | `step` | int | Step | | `attempt` | int | Attempt | ### `sys_stream` [Section titled “sys_stream”](#sys_stream) Durable streams of one invocation (`ctx.stream(name, { durable: true })`, the log and the trace), one row per stream. Temporary streams are not stored and do not appear. **Required key:** `id`. | Column | Type | Meaning | | ------------- | ---- | ---------------------------- | | `id` | text | Invocation ID | | `name` | text | Stream name | | `chunks` | int | Stored chunks | | `records` | int | Records | | `total_bytes` | int | Payload bytes received | | `dropped` | int | Records dropped over the cap | | `last_offset` | int | Offset of the last record | ### `sys_stream_record` [Section titled “sys_stream_record”](#sys_stream_record) Records of one durable stream. **Required key:** `id` and `name`. | Column | Type | Meaning | | --------- | ---- | ------------------------------------------------ | | `id` | text | Invocation ID | | `name` | text | Stream name | | `offset` | int | Offset | | `step` | int | Step | | `attempt` | int | Attempt | | `kind` | text | `data`, `gap` or `superseded` | | `body` | text | The record (UTF-8, otherwise hex), cut at 64 KiB | ### `sys_artifact` [Section titled “sys_artifact”](#sys_artifact) Artifacts of one invocation. The bytes are at `GET /invocations/{id}/artifacts/{sha}`. **Required key:** `id`. | Column | Type | Meaning | | -------------- | ---- | ----------------- | | `id` | text | Invocation ID | | `sha256` | text | Content hash, hex | | `size` | int | Size in bytes | | `content_type` | text | Content type | | `epoch` | int | Write epoch | ### `sys_outbox` [Section titled “sys_outbox”](#sys_outbox) Calls, replies and cancels that an invocation produced and that are not delivered yet. **Required key:** `id` (the sender). | Column | Type | Meaning | | --------------- | ---- | -------------------------------------------------------------------- | | `range` | int | Key range holding the row | | `seq` | int | Order produced | | `id` | text | The sending invocation | | `completion_id` | int | Completion of the sending command | | `kind` | text | `call`, `reply`, `attach`, `peek_output`, `cancel`, `fire`, `signal` | | `target` | text | Target invocation (`attach`, `peek_output`, `cancel`) | | `service` | text | Target service (`call`, `fire`) | | `handler` | text | Target handler (`call`, `fire`) | | `key` | text | Target key (`call`, `fire`) | ## Objects and workflows [Section titled “Objects and workflows”](#objects-and-workflows) ### `sys_state` [Section titled “sys_state”](#sys_state) State of one virtual object or workflow. **Required key:** `service` and `key`. | Column | Type | Meaning | | ----------- | ---- | ---------------------------------------------------------------------------------- | | `tenant` | text | Environment | | `scope` | text | Scope (empty when none) | | `service` | text | Service | | `key` | text | Object key | | `state_key` | text | State key (UTF-8, otherwise hex) | | `value` | text | Value (UTF-8, otherwise hex), cut at 64 KiB; `NULL` for a value stored as segments | | `value_len` | int | Value size in bytes (the whole value, also when stored as segments) | ### `sys_value` [Section titled “sys_value”](#sys_value) Segments of the large values of one virtual object or workflow: one row per holder and segment, so a segment shared by several holders has several rows. **Required key:** `service` and `key`. | Column | Type | Meaning | | ------------- | ---- | --------------------------------------------------------------------------------- | | `tenant` | text | Environment | | `scope` | text | Scope (empty when none) | | `service` | text | Service | | `key` | text | Object key | | `holder_kind` | text | `state` (the current value of a state key), `invocation` (a journal) or `promise` | | `holder` | text | State key (UTF-8, otherwise hex), invocation ID or promise name | | `sha` | text | SHA-256 of the segment, hex | | `gen` | text | Sealing generation, 16 hex characters | | `len` | int | Segment size in bytes | Bytes held by the object’s state: `sum(len)` over the rows with `holder_kind = 'state'`. ### `sys_promise` [Section titled “sys_promise”](#sys_promise) **Completed** durable promises of one object or workflow. Promises still waiting are in `sys_promise_waiter`. **Required key:** `service` and `key`. | Column | Type | Meaning | | ----------------- | ---- | ------------------------------------------- | | `tenant` | text | Environment | | `scope` | text | Scope | | `service` | text | Service | | `key` | text | Object key | | `name` | text | Promise name | | `ok` | bool | Completed with a value (not an error) | | `value` | text | Value (UTF-8, otherwise hex), cut at 64 KiB | | `failure_code` | int | Error code | | `failure_message` | text | Error message | | `completed_by` | text | The invocation that completed it | ### `sys_promise_waiter` [Section titled “sys_promise_waiter”](#sys_promise_waiter) Who is waiting on a promise of an object or workflow that is **not** completed yet. **Required key:** `service` and `key`. | Column | Type | Meaning | | --------------- | ---- | ----------------------- | | `tenant` | text | Environment | | `scope` | text | Scope | | `service` | text | Service | | `key` | text | Object key | | `name` | text | Promise name | | `waiter_id` | text | The waiting invocation | | `completion_id` | int | The waiter’s completion | ### `sys_object` [Section titled “sys_object”](#sys_object) Objects (virtual objects, workflows) of a service: one row per key that has state or holds an invocation. **Required key:** `service`. | Column | Type | Meaning | | ------------- | ---- | ------------------------------------------------------------- | | `tenant` | text | Environment | | `scope` | text | Scope | | `service` | text | Service | | `key` | text | Object key | | `has_state` | bool | The object has state | | `invocations` | int | Invocations it holds (counted up to 16; 16 means at least 16) | | `range` | int | Key range holding it | ### `sys_vqueue_entry` [Section titled “sys_vqueue_entry”](#sys_vqueue_entry) The queue of an object or service: who holds the lock or a slot (`running`) and who waits (`inbox`, by `seq`). **Required key:** `service` (add `key` for one object). | Column | Type | Meaning | | ----------- | ---- | ------------------------------------------- | | `tenant` | text | Environment | | `scope` | text | Scope | | `limit_key` | text | Limit key | | `service` | text | Service | | `key` | text | Object key | | `stage` | text | `inbox`, `running`, `suspended` or `paused` | | `seq` | int | Position in the queue | | `id` | text | Invocation ID | | `range` | int | Key range holding the entry | ## Scheduled work [Section titled “Scheduled work”](#scheduled-work) ### `sys_schedule` [Section titled “sys_schedule”](#sys_schedule) Server-side schedules. | Column | Type | Meaning | | ------------ | ---- | ------------------------------------------------------ | | `name` | text | Schedule name | | `id` | text | Schedule ID | | `service` | text | Target service | | `handler` | text | Target handler | | `overlap` | text | `skip` or `allow` | | `paused` | bool | Paused | | `next_at` | int | Next run, ms | | `fired` | int | Runs started | | `missed` | int | Runs missed | | `skipped` | int | Runs skipped because the previous one was still active | | `created_at` | int | Created, ms | | `updated_at` | int | Last changed, ms | ### `sys_delayed` [Section titled “sys_delayed”](#sys_delayed) One-way calls sent with a delay that are not due yet, by due time. | Column | Type | Meaning | | --------------- | ---- | ------------------------------ | | `caller_id` | text | The invocation that sent it | | `completion_id` | int | Completion of the send command | | `due_at_ms` | int | When it will be delivered | | `tenant` | text | Environment of the sender | | `service` | text | Target service | | `handler` | text | Target handler | | `key` | text | Target key | | `range` | int | Key range holding it | ## Code [Section titled “Code”](#code) ### `sys_deployment` [Section titled “sys_deployment”](#sys_deployment) Registered deployments. | Column | Type | Meaning | | --------------- | ---- | ---------------------------------------------------------------------------------------------------- | | `id` | text | Deployment ID | | `tenant` | text | Environment | | `created_at_ms` | int | Registered, ms | | `endpoint` | text | URI of your service | | `wire_version` | int | Protocol version | | `protocol_mode` | text | `BIDI_STREAM` or `REQUEST_RESPONSE` | | `services` | text | Its services, as JSON | | `current_for` | text | Services it is the current version of, as JSON | | `pinned` | int | Unfinished invocations still on it (`NULL` when a range did not answer); `0` means it can be removed | ### `sys_service` [Section titled “sys_service”](#sys_service) Current services. | Column | Type | Meaning | | --------------- | ---- | ----------------------------------------- | | `name` | text | Service name | | `ty` | text | `service`, `virtual_object` or `workflow` | | `deployment` | text | URI of the current deployment | | `deployment_id` | text | ID of the current deployment | ### `sys_handler` [Section titled “sys_handler”](#sys_handler) Handlers of every current service. | Column | Type | Meaning | | --------------- | ---- | ----------------------------------- | | `service` | text | Service | | `name` | text | Handler name | | `ty` | text | `exclusive`, `shared` or `workflow` | | `deployment_id` | text | ID of the current deployment | ## Usage and performance [Section titled “Usage and performance”](#usage-and-performance) ### `sys_metering` [Section titled “sys_metering”](#sys_metering) Usage of the current hour. | Column | Type | Meaning | | --------------- | ---- | ---------------------------------------------------------------------------------------------------------------- | | `tenant` | text | Environment | | `hour` | text | Hour, `yyyy-mm-ddThh` UTC | | `invocations` | int | Invocations | | `steps` | int | Durable steps | | `run_ms` | int | Run time, ms | | `input_tokens` | int | Input tokens | | `output_tokens` | int | Output tokens | | `cost_micros` | int | Token cost in millionths of a US dollar, when prices are set | | `sdk_bytes_out` | int | Bytes sent to your service, after compression | | `sdk_bytes_in` | int | Bytes received from your service | | `units` | int | Billing units: each durable command counts one per started 64 KiB of payload (at least 1), plus 2 per invocation | ### `sys_artifact_bytes` [Section titled “sys_artifact_bytes”](#sys_artifact_bytes) Bytes of live artifacts, counted in memory with each commit. This is what the artifact storage limit is checked against. While a range rebuilds its counters, the answer carries an `indexing` warning. | Column | Type | Meaning | | -------- | ---- | ----------------------- | | `tenant` | text | Environment | | `bytes` | uint | Bytes of live artifacts | ### `sys_handler_stats` [Section titled “sys_handler_stats”](#sys_handler_stats) Per-handler summary over the recent default window, for the whole cell. | Column | Type | Meaning | | ----------------- | ----- | ---------------------------------------- | | `node` | text | Node (absent in combined rows) | | `tenant` | text | Environment | | `service` | text | Service | | `handler` | text | Handler | | `deployment` | text | Deployment | | `turns` | int | Turns of your service | | `completed` | int | Completed | | `failed` | int | Failed | | `paused` | int | Paused | | `failed_attempts` | int | Failed attempts | | `suspensions` | int | Suspensions | | `steps` | int | Durable steps | | `run_ms` | int | Run time, ms | | `cu` | int | Compute units | | `p50_ms` | float | Median turn time, ms | | `p99_ms` | float | 99th percentile turn time, ms | | `max_ms` | float | Longest turn, ms | | `quarantine` | text | Why the handler is quarantined, if it is | ### `sys_handler_history` [Section titled “sys_handler_history”](#sys_handler_history) The same summary **per hour**, for the last 30 days. | Column | Type | Meaning | | ----------------- | ----- | --------------------------------------------------------- | | `hour_ms` | int | Start of the hour, ms | | `tenant` | text | Environment | | `service` | text | Service | | `handler` | text | Handler | | `deployment` | text | Deployment | | `turns` | int | Turns of your service | | `completed` | int | Invocations completed | | `failed` | int | Invocations failed | | `paused` | int | Invocations paused | | `failed_attempts` | int | Failed attempts | | `suspensions` | int | Suspensions | | `steps` | int | Durable steps | | `run_ms` | int | Run time, ms | | `cu` | int | Compute units | | `p50_ms` | float | Median turn time, ms (upper bound of the bucket) | | `p99_ms` | float | 99th percentile turn time, ms (upper bound of the bucket) | | `max_ms` | float | Longest turn, ms | ### `sys_slow_run` [Section titled “sys_slow_run”](#sys_slow_run) Recent runs that took longer than the slow threshold. Kept in each node’s memory (up to 1,000 rows per node). | Column | Type | Meaning | | ----------------- | ---- | ---------------------------------------------------------------- | | `at_ms` | int | When it was recorded, ms | | `node` | text | Node | | `tenant` | text | Environment | | `service` | text | Service | | `handler` | text | Handler | | `deployment` | text | Deployment | | `invocation` | text | Invocation ID | | `outcome` | text | `completed`, `failed`, `paused`, `retry`, `suspended` or `error` | | `total_ms` | int | Total time of the run, ms | | `threshold_ms` | int | The slow threshold, ms | | `turns` | int | Turns of your service | | `steps` | int | Durable steps | | `run_ms` | int | Time in your code, ms | | `sdk_ms` | int | Time waiting for your service, ms | | `durable_waits` | int | Durable waits | | `durable_wait_ms` | int | Time in durable waits, ms | | `engine_wait_ms` | int | Time waiting for the engine, ms | | `permit_wait_ms` | int | Time waiting for a flow-control slot, ms | ## History [Section titled “History”](#history) ### `sys_archive` [Section titled “sys_archive”](#sys_archive) Invocations removed (by retention or purge) on one UTC day. The archived journal and final status are at `GET /archive/{id}`. **Required filter:** `date = 'yyyy-mm-dd'`. | Column | Type | Meaning | | --------------- | ---- | ------------------------------------------- | | `date` | text | UTC day | | `id` | text | Invocation ID | | `run` | int | Run of that ID on that day (0 is the first) | | `bytes` | int | Size of the archive object | | `written_at_ms` | int | When it was archived, ms | ### `sys_audit` [Section titled “sys_audit”](#sys_audit) Actions on the environment in the last 24 hours. For longer ranges use the console’s **Audit log**. | Column | Type | Meaning | | ------------ | ---- | ------------------------------------------------------------------------------------------------------------- | | `ts` | int | When, ms | | `tenant` | text | Environment | | `kind` | text | `row`, `intent`, `done`, or `denied` and `noop` (refused requests and actions that changed nothing, grouped) | | `action` | text | Action, such as `invocation.cancel` or `deployment.register` | | `outcome` | text | `ok`, `noop`, `not_found`, `pending`, `error`, `denied` or `unknown` (the outcome of an intent never arrived) | | `actor_type` | text | Kind of actor | | `actor_id` | text | Actor ID (the key ID) | | `actor_role` | text | Role of the key | | `target` | text | Target, as JSON | | `status` | int | HTTP status | | `count` | int | Number of grouped `denied` or `noop` records | | `ip` | text | Client IP | | `user_agent` | text | User agent | | `request_id` | text | Request ID | | `name` | text | Object name |