Metadata-Version: 2.5
Name: agentflight-sdk
Version: 0.5.1
Summary: Black box recorder for AI agents: record, replay and debug agent runs
Project-URL: Homepage, https://github.com/shupandee/agentflight
Project-URL: Repository, https://github.com/shupandee/agentflight
Project-URL: Issues, https://github.com/shupandee/agentflight/issues
Project-URL: Changelog, https://github.com/shupandee/agentflight/blob/main/CHANGELOG.md
Author: Deepanshu Gautam
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agents,llm,observability,opentelemetry,replay,tracing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Debuggers
Classifier: Topic :: System :: Logging
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: opentelemetry-api>=1.24
Requires-Dist: opentelemetry-sdk>=1.24
Provides-Extra: dev
Requires-Dist: alembic>=1.13; extra == 'dev'
Requires-Dist: fastapi>=0.110; extra == 'dev'
Requires-Dist: jinja2>=3.1; extra == 'dev'
Requires-Dist: langgraph>=1.0; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: openai>=1.0; extra == 'dev'
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.24; extra == 'dev'
Requires-Dist: opentelemetry-proto>=1.24; extra == 'dev'
Requires-Dist: psycopg[binary]>=3.1; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.5; extra == 'dev'
Requires-Dist: sqlalchemy>=2.0; extra == 'dev'
Requires-Dist: uvicorn>=0.29; extra == 'dev'
Provides-Extra: langgraph
Requires-Dist: langgraph>=1.0; extra == 'langgraph'
Provides-Extra: openai
Requires-Dist: openai>=1.0; extra == 'openai'
Provides-Extra: server
Requires-Dist: alembic>=1.13; extra == 'server'
Requires-Dist: fastapi>=0.110; extra == 'server'
Requires-Dist: jinja2>=3.1; extra == 'server'
Requires-Dist: opentelemetry-proto>=1.24; extra == 'server'
Requires-Dist: psycopg[binary]>=3.1; extra == 'server'
Requires-Dist: sqlalchemy>=2.0; extra == 'server'
Requires-Dist: uvicorn>=0.29; extra == 'server'
Description-Content-Type: text/markdown

# AgentFlight

A black box recorder for AI agents. AgentFlight records what an agent does during a run:
model calls, tool executions, decisions, state changes, token spend and failures. Every run
is stored as an ordered timeline you can query, replay and fork.

> Status: early development (week 5, viewer). APIs may change; see [CHANGELOG.md](https://github.com/shupandee/agentflight/blob/main/CHANGELOG.md).

## AgentFlight, Langfuse, LangSmith or Phoenix?

[Langfuse](https://langfuse.com/docs), [LangSmith](https://docs.langchain.com/langsmith/home)
and [Arize Phoenix](https://arize.com/docs/phoenix) are full LLM engineering platforms.
Besides tracing they offer evaluations, datasets and experiments, prompt management and
dashboards, with many framework and provider integrations. Langfuse and Phoenix can be
self-hosted and accept OpenTelemetry traces. LangSmith runs as a LangChain cloud service,
with self-hosted and bring-your-own-cloud options on its Enterprise plan.

AgentFlight is much smaller: a Python recorder, one server on Postgres (or SQLite) and a
read-only viewer, with no evaluations, prompt management or dashboards. Its focus is
re-running your own agent code from a recording. [Replay](#replay-and-fork) serves the
recorded model and tool outputs back to the same code in your process, offline, and fork
swaps one step and runs live from there. That's different from re-running a single LLM
call in a playground (Phoenix's span replay, for example, replays LLM calls with different
inputs). Choose one of the platforms if you need evaluations, prompt management or team
features; AgentFlight if you want a small self-hosted recorder with step-by-step replay
of agent runs.

## Architecture

```mermaid
flowchart LR
    subgraph Agent process
        A[Your agent code] -->|run / llm_call / @tool / decision / state_change| SDK[agentflight SDK]
        SDK --> OTel[OpenTelemetry spans<br/>private TracerProvider]
        OTel --> EXP[AgentFlightExporter<br/>batched HTTP JSON]
    end
    EXP -->|POST /v1/spans| API[FastAPI ingest server]
    O[Any OpenTelemetry agent<br/>or Collector] -->|POST /v1/traces<br/>OTLP/HTTP| API
    API --> DB[(PostgreSQL<br/>runs + events)]
    C[curl / scripts] -->|GET /v1/runs, /v1/runs/:id| API
    V[Browser] -->|/ui viewer| API
```

- **One run = one OpenTelemetry trace.** `agentflight.run(...)` opens the root span; its
  trace id is the run id. Everything recorded inside it is a child span.
- **Each span carries `agentflight.*` attributes** (`kind`, model, messages, tokens, tool
  args/result, error type...). Structured values are stored as JSON.
- The SDK uses its **own TracerProvider**, so it doesn't change any global OTel setup your
  app already has.
- The server **upserts by span id** (re-sent batches are idempotent) and accepts child spans
  before their root span arrives (the run shows as `running` until then; see
  [Run status](#run-status)).
- **Run totals are stored on the run row** (calls, errors, tokens, cost) and recomputed in
  SQL for every run an ingest batch touches, so listing runs never reads their events and
  re-sent spans can't make the totals drift.

## Install

The package on PyPI is **`agentflight-sdk`**; the import name is still **`agentflight`**.

```bash
pip install agentflight-sdk                # the SDK: import agentflight
pip install "agentflight-sdk[server]"      # plus the server and viewer (agentflight-server)
pip install "agentflight-sdk[openai]"      # plus the OpenAI-style client integration
pip install "agentflight-sdk[langgraph]"   # plus the LangGraph integration
```

From a checkout, `pip install -e ".[server]"` (or `.[dev]`) installs the same package.

## Quickstart

```bash
# 0. A key for the server and the SDK (never commit it): the server reads
#    AGENTFLIGHT_ADMIN_API_KEY, the SDK, the CLI and curl send AGENTFLIGHT_API_KEY
export AGENTFLIGHT_ADMIN_API_KEY=$(openssl rand -hex 32)
export AGENTFLIGHT_API_KEY=$AGENTFLIGHT_ADMIN_API_KEY   # or a scoped key, see Authentication

# 1. Server + Postgres + retention job (applies Alembic migrations on start)
docker compose up --build       # passes both variables above to the server (see the note below)

# or without Docker, using SQLite (from a checkout; elsewhere,
# `pip install "agentflight-sdk[server]"`):
pip install -e ".[server]"
agentflight-server migrate      # uses AGENTFLIGHT_DATABASE_URL, default sqlite:///./agentflight.db
agentflight-server serve        # http://127.0.0.1:8000 (to keep it running after the
                                # shell closes, see "Running at login" below)

# 2. Record the toy agent (the SDK reads AGENTFLIGHT_API_KEY)
pip install -e .                # elsewhere: pip install agentflight-sdk
                                # (the package is agentflight-sdk; you import agentflight)
python examples/toy_agent.py

# 3. Inspect: open http://localhost:8000/ui and sign in with the key, or use the API
curl -H "Authorization: Bearer $AGENTFLIGHT_API_KEY" localhost:8000/v1/runs
curl -H "Authorization: Bearer $AGENTFLIGHT_API_KEY" localhost:8000/v1/runs/<run_id>
```

**Docker Compose and `AGENTFLIGHT_API_KEY`:** Compose passes the host's
`AGENTFLIGHT_ADMIN_API_KEY` and `AGENTFLIGHT_API_KEY` to the server. If only
`AGENTFLIGHT_API_KEY` is set, the server uses it as its all-permission key and logs a
deprecation warning. **If your host's `AGENTFLIGHT_API_KEY` holds a scoped or ingest-only
client key, set `AGENTFLIGHT_ADMIN_API_KEY` explicitly**, or that client key becomes the
all-permission key inside the container. With `AGENTFLIGHT_ADMIN_API_KEY` set, the server
ignores `AGENTFLIGHT_API_KEY` (see [Authentication](#authentication)).

**SQLite files use WAL mode** (`AGENTFLIGHT_SQLITE_JOURNAL_MODE`, default `wal`), so the
server keeps recording while a large run is read (an export, a big run page).

- **Existing databases are converted on first start:** the mode is set on every
  connection, so the first server (or `agentflight-server` command) that opens an
  existing file switches it to WAL, and the file stays in WAL mode.
- **Backups:** WAL adds `-wal` and `-shm` files next to the database, and recent writes
  may be only in the `-wal` file. A file-copy backup must include the `-wal` file (copy
  all three, with the server stopped), or checkpoint first (`sqlite3 agentflight.db
  "PRAGMA wal_checkpoint(TRUNCATE);"` with the server stopped, then copy the database
  file). `sqlite3 agentflight.db ".backup copy.db"` is safe while it runs.
- **Network filesystems are unsupported in WAL mode** (NFS, SMB/CIFS shares and the
  like): WAL needs shared memory between processes on one host. Keep the file on a local
  disk, or use Postgres.

`delete`, `truncate` or `persist` select a rollback journal
instead, where every write waits for readers, up to SQLite's 5 s busy timeout, then fails
(measured: [docs/benchmarks/export-ingest-2026-11-29.md](docs/benchmarks/export-ingest-2026-11-29.md)).

## Viewer

The server includes a read-only viewer at `/ui`:

- **Runs:** every run with its status, start time, duration, call counts, failures, tokens
  and cost, filtered by status, name, model, tool, errors, metadata (`key:value`), start
  time, parent run, and a toggle that hides sub-agent runs (`has_parent=false`). Filters update the table in place. A run whose recorder dropped spans is marked
  "incomplete recording: N spans dropped" (see "Dropped spans are counted" below).
- **Run page:** the run's spans as an indented tree (each span under its parent,
  siblings in start order) with a bar per span on the run's time axis, failures
  highlighted with their messages, and replay/fork runs linked to the run they came
  from. A span whose parent never arrived starts its own subtree at the left. Events load
  in pages of 100 without payloads, and the next page continues the tree where the last
  one stopped; selecting an event loads its messages, outputs, arguments and stack traces
  on demand. An incomplete recording gets a warning above the timeline. (To page in tree order the server reads every span's id and parent for each
  page, which is cheap next to loading the events themselves.) A sub-agent run links to
  the run that started it; a parent lists its sub-agent runs and marks the span each one
  started from (see [Sub-agent runs](#sub-agent-runs)).
- **Agents tab** (`/ui/runs/{id}/agents`, 0.5.0; on every run page, also for runs
  without agents): one box per agent (lead agent, workers, sub-agents) in a tree, each
  with its task, model, status, tokens (with new input vs. cached input), LLM and tool
  calls and failures rolled up over everything below it, plus its **own** tokens (without
  its sub-agents) and its own share of the run's tokens; a summary line (who failed, who
  used the most own tokens), sort by start, own tokens or errors, and "show all nodes".
  Clicking a box opens the run timeline for just that agent's subtree
  (`/ui/runs/{id}?span=<span_id>`) with its prompt and final output at the top, in a card
  coloured like its box (red for a failed agent). A run with no agents (any run recorded
  before 0.5.0) says "No agents recorded in this run", keeps the `main` box with the
  run's totals, and links "show all nodes" when it has node spans. See [Agents](#agents).
- **Compare:** `/ui/diff?base=…&head=…` shows two runs side by side: matched spans as a
  tree with what changed in each, spans added or removed, run-level changes, and a panel
  with a span pair's values and text diffs. Values that couldn't be compared (redacted or
  truncated) are marked "not comparable". A replay or fork has a "Compare with source run"
  link. On the run list, "Use as base" picks one run (it stays picked in the URL while you
  page or filter) and "Compare as head" on another opens the diff. The `/ui/diff` form is
  a GET form: it only builds a shareable link and changes nothing (see
  [Comparing runs](#comparing-runs)).

![Run list with filters](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/run-list.png)

![Run page: span tree, timeline bars, a failed tool call, and an event's payloads](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/run-page.png)

![A LangGraph run: model and tool calls nested under graph nodes](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/span-tree.png)

![A parent run listing its sub-agent runs, each marked on the span that started it](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/sub-agent-parent.png)

![A sub-agent run whose parent was never recorded](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/sub-agent-missing-parent.png)

![Agents tab: ten agents with nested sub-agents, a failed agent, a running group and a linked child run](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/agents-view.png)

![One agent's subtree: its prompt, error and timeline](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/agents-view-subtree.png)

![A fork run, linked to its source run, with cached, overridden and live steps](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/fork-run.png)

![Comparing a fork with its source run: the overridden tool result and what changed after it](https://raw.githubusercontent.com/shupandee/agentflight/main/docs/screenshots/diff-fork.png)

The screenshots come from the browser smoke test against the example agents; regenerate
them with `AGENTFLIGHT_SCREENSHOT_DIR=docs/screenshots pytest tests/test_viewer_browser.py`.

It is server-rendered (Jinja2 and [htmx](https://htmx.org), vendored, no build step) and
reads through the same service functions and JSON shapes as the `/v1` API, so another
frontend can be built on the API alone. Everything a run recorded is treated as untrusted:
templates autoescape everything and nothing is marked safe, and pages are served with a
Content-Security-Policy that allows no inline script or style (`script-src 'self'`). See
[Viewer sign-in](#viewer-sign-in) for how sessions work.

## Recording API

```python
import agentflight

agentflight.configure("http://localhost:8000")


@agentflight.tool  # records name, bound args, result or exception
def search(query: str) -> list[str]: ...


with agentflight.run("support-agent", metadata={"ticket": 42}) as run:
    with agentflight.llm_call("gpt-4o-mini", messages) as call:
        resp = client.chat(...)  # your model client
        call.record(resp.text, tokens_in=..., tokens_out=..., cost_usd=...)  # cost optional
    agentflight.decision("next_step", "search", reason="needs docs")
    agentflight.state_change("plan", new_plan, old=old_plan)
    try:
        search("refund policy")
    except Exception as exc:
        agentflight.error(exc)  # handled error: recorded, run continues

agentflight.flush()  # before exit, so batched spans are sent
```

- Latency is the span duration (`duration_ms` in the API).
- An exception escaping `run`, `llm_call` or a `@tool` marks that span (and the run) as
  `error` and is re-raised unchanged.
- `@agentflight.tool` works on sync and async functions; `@agentflight.tool(name="...")`
  overrides the name.
- If the server is unreachable, export fails with a logged warning; your agent keeps running.

### Cached input tokens

**`tokens_in` is always the total input, cached tokens included.**
`cache_read_tokens` (input read from the provider's prompt cache) and
`cache_write_tokens` (input written to it) are sub-counts of it, so new (uncached) input is
`tokens_in - cache_read_tokens - cache_write_tokens`, which the viewer shows as "new
input". Providers count differently, and the SDK normalizes both conventions:

| Provider usage | `tokens_in` recorded | `cache_read_tokens` | `cache_write_tokens` |
| --- | --- | --- | --- |
| Anthropic (`input_tokens` excludes cache) | `input_tokens + cache_read_input_tokens + cache_creation_input_tokens` | `cache_read_input_tokens` | `cache_creation_input_tokens` |
| OpenAI Chat Completions (`prompt_tokens` includes cache) | `prompt_tokens` | `prompt_tokens_details.cached_tokens` | not reported |
| OpenAI Responses (`input_tokens` includes cache) | `input_tokens` | `input_tokens_details.cached_tokens` | not reported |
| LangChain `usage_metadata` (`input_tokens` includes cache) | `input_tokens` | `input_token_details.cache_read` | `input_token_details.cache_creation` |

```python
call.record(resp, usage=resp.usage)  # any of the shapes above, read for you
# or by hand: tokens_in is the total; say so if yours isn't
call.record(text, tokens_in=1200, cache_read_tokens=1000, cache_write_tokens=100)
call.record(
    text, tokens_in=100, cache_read_tokens=1000, cache_write_tokens=100, input_includes_cache=False
)  # Anthropic-style: recorded as tokens_in=1200
```

- `agentflight.normalize_usage(usage)` returns the same `Usage` (`tokens_in`,
  `tokens_out`, `cache_read_tokens`, `cache_write_tokens`) for your own code. It never
  raises; an unknown shape gives all `None`.
- Only non-negative integers are recorded. Anything else (negative, a float, a string,
  `True`) is ignored with a warning, never turned into 0. Not reported means not recorded
  (`null` in the API), not 0.
- Clients posting to `/v1/spans` set `agentflight.llm.cache_read_tokens` /
  `agentflight.llm.cache_write_tokens` with the same meaning. The server applies the same
  rule and stores them in `tokens_cache_read` / `tokens_cache_write` on the event and the
  run (summed; `null` when no call reported them).
- If the sub-counts add up to more than `tokens_in` (a client that sent new input as
  `tokens_in`), new input shows as 0 and is flagged "cache counts exceed input" instead of
  going negative.
- Cost is still only what you pass (`cost_usd`); cached tokens don't change it.
- **OTLP:** `gen_ai.usage.*` cache counts (such as `gen_ai.usage.cache_read_input_tokens`)
  are **not mapped in 0.5.0**: they are kept as attributes, and the cached fields stay
  `null` for OTLP sources. `tokens_in` is `gen_ai.usage.input_tokens` (or
  `prompt_tokens`) **stored as reported**, not normalized: if the instrumentation's input
  count excludes cached tokens (as Anthropic's API does), so does `tokens_in`. Spans
  that carry `agentflight.llm.*` attributes are read as on `/v1/spans`.
- **Migration `0006`** adds the columns and backfills them from stored attributes in
  batches of 5,000 events (one transaction each): on one machine, 1,000,000 events took
  11 s on SQLite and 30 s on Postgres 17, with concurrent reads and writes interleaving
  ([measurements](docs/benchmarks/migration-0006-backfill-2026-11-30.md)). Downgrading it
  (`AGENTFLIGHT_DATABASE_URL=... alembic downgrade 0005` from a checkout) drops the
  columns; **on SQLite that rebuilds both tables** (`events` and `runs`), about 29 s per
  1,000,000 events on the same machine.
  On Postgres it is instant.

### Agents

A run often has several agents: a lead agent that launches workers or sub-agents through
a tool call, and they launch more. Mark each agent's span and the viewer's
[Agents tab](#viewer) and `GET /v1/runs/{id}/agents` give each one a box with its own
roll-up:

```python
with agentflight.run("refactor-auth"):
    with agentflight.agent("lead", task="Refactor auth", model="claude-sonnet-4") as lead:
        lead.input = prompt
        with agentflight.llm_call(...):
            ...
        with tool_span("Task"):  # the launching tool call (your @agentflight.tool)
            with agentflight.agent("test-runner", task="Run the auth tests") as worker:
                worker.input = worker_prompt
                ...
                worker.output = report
```

`agentflight.agent(name, *, task=None, model=None, launch_span_id=None, input=None)` is a
`node` span named `agent:<name>`. Everything recorded inside belongs to it; an exception
marks it `error` and propagates. The prompt and final report are `input` / `output`
(through your `redact` hook and `max_attr_chars`). A client that posts spans itself sets
the same attributes on a `node` span:

| Attribute | Required | Type | Meaning |
| --- | --- | --- | --- |
| `agentflight.kind` | yes | `"node"` | An agent is a node span |
| `agentflight.agent.name` | **yes** (the marker) | string | Agent name (`Explore`, `test-runner`). A node with it is an agent |
| `agentflight.agent.task` | no | string | Short human title of what it was asked to do |
| `agentflight.agent.model` | no | string | Model it ran on. If unset, the model of its own first LLM call is shown, marked "(inferred)" |
| `agentflight.agent.launch_span_id` | no | 16 hex characters | Span id of the tool call or step that launched it, when the agent span isn't under that span |
| `agentflight.node.input` | no | JSON string | Prompt / assignment |
| `agentflight.node.output` | no | JSON string | Final output / report |
| `agentflight.node.name` | no | string | As for any node (the SDK sets it to the agent name) |

**Which agent is whose parent.** An agent's parent agent is the nearest agent above it in
the span tree; if there is none, the nearest agent at or above the span named by its
`launch_span_id`; otherwise the run itself (`main`). So both shapes work: agent spans
nested under the launching tool call, or agent spans posted under the run's root span with
`launch_span_id` pointing at the launcher. A `launch_span_id` that names no stored span,
the agent itself, or a loop is ignored (the agent goes under `main`).

**Roll-ups** are computed when the view is read: each span belongs to its nearest agent
ancestor (else `main`). A box's totals (`tokens_in`, `llm_calls`, ... at the top level
of each box in the API) include everything below it, sub-agents included, and `main`
equals the run's totals. Its **own** totals (`own` in the API) are its spans without its
sub-agents' subtrees (a lead agent's own LLM calls, not its workers'), so the own totals
of all boxes add up to the run's. `share` and `own_share` are the box's inclusive and own
tokens (in + out) as a fraction of the run's. The "most own tokens" headline and
`sort=tokens` use own tokens, so a parent doesn't outrank its workers just by including
them. Spans whose parent span hasn't been received
(yet) aren't dropped: they are grouped by the missing parent id as a "running" box
("node not received yet") under `main` and counted in its totals; when the parent arrives
they move to its agent. Linked [sub-agent runs](#sub-agent-runs) appear as separate boxes
under the agent whose span started them, with their own totals, not added to the parent
run's.

- Plain nodes (LangGraph steps) aren't boxes unless "show all nodes" (`all_nodes=true`)
  is on; their spans count toward their agent either way.
- A node whose `agentflight.agent.name` was removed by [server-side
  redaction](#server-side-redaction-opt-in) (listed in `agentflight.redacted`) is still an
  agent, shown as "[redacted]". `agentflight.agent.*` keys are not protected, so a policy
  can mask or drop them; span names (`agent:<name>`) are structural and never redacted.
- Nothing depends on the launching tool's name (`Agent`, `Task` or anything else): the
  hierarchy comes from the span tree and `launch_span_id`; the name is only shown as
  "launched from tool:<name>".
- The view reads every span's columns (no payloads) for a run of up to
  `AGENTFLIGHT_MAX_AGENT_VIEW_SPANS` spans (default `50000`); above that the API answers
  `413` and the page says why and links to the timeline. One machine: 10,000 spans took
  65 ms (SQLite) / 45 ms (Postgres 17) median, 50,000 spans 340 / 283 ms
  ([measurements](docs/benchmarks/agents-view-2026-11-30.md), `scripts/bench_agents.py`).

### Sub-agent runs

A run started inside another run is a **sub-agent run** of it: it is still its own run
(its own trace), and it records the run that started it (`parent_run_id`) and the span
that was open when it did (`parent_span_id`). The viewer links the two, and
`GET /v1/runs?parent_run_id=...` lists a run's sub-agent runs. A run is never its own
parent. Where the parent comes from, first match wins:

1. **`agentflight.run(..., parent_run_id=..., parent_span_id=...)`**: a run id (or the
   parent's `RunHandle`), for a run started where the context doesn't reach (another
   thread, another process that was handed the id). An id that isn't 32 lowercase hex
   characters is ignored with a warning, and the run is recorded with no parent.
2. **The run being recorded in this context**, if any (a run started inside another in
   the same process).
3. **`AGENTFLIGHT_PARENT_RUN`**, for agent frameworks and hooks that spawn a process
   without passing an id through: the launcher sets it to its own run id in the child's
   environment, and a top-level run started in that process links to it.

```bash
# in the launcher, while its run is open: export AGENTFLIGHT_PARENT_RUN=<its run_id>
AGENTFLIGHT_PARENT_RUN=$RUN_ID python sub_agent.py
```

- The value must be exactly 32 lowercase hex characters (`\A[0-9a-f]{32}\Z`, so no
  surrounding whitespace or trailing newline). Anything else is ignored with one warning
  per run (the value isn't logged) and the run is recorded with no parent; it never
  raises. An empty value means unset, silently.
- It is read when each run starts, and only for a run with no `parent_run_id` argument
  and no enclosing run in the process (a nested run still links to the run around it).
  If it names the new run itself, the link is dropped with a warning.
- The link is stored as **`parent_source: "explicit"`**, the same as `parent_run_id=`
  (`inferred` is only for parents the server reads from OTLP span links). There is no
  `parent_span_id`: the launcher's span isn't known.
- **Every descendant process inherits the variable**, not just the direct child. A
  grandchild started by the child links to the same parent (the launcher's run), not to
  the child, unless whoever starts it overrides the variable (the child sets it to its
  own run id for its children) or clears it (`AGENTFLIGHT_PARENT_RUN=` or removing it from
  the environment it passes on).
- The SDK only reads it; raw HTTP clients that post to `/v1/spans` themselves set
  `agentflight.run.parent_run_id` on their run span instead.

## Integrations

Optional extras; the core SDK depends on neither package.

### OpenAI-style chat clients

```bash
pip install "agentflight-sdk[openai]"   # import name: agentflight
```

```python
from openai import OpenAI
from agentflight.integrations.openai import instrument_openai

client = instrument_openai(OpenAI())  # same client, now recorded
with agentflight.run("support-agent"):
    resp = client.chat.completions.create(model="gpt-4o-mini", messages=msgs, tools=tools)
```

- Each `chat.completions.create` call is an `llm` span with the model, messages, request
  params (`tools`, `temperature`, ...), the full response (tool calls included) and
  `tokens_in`/`tokens_out` from `response.usage`, and `cache_read_tokens` from
  `usage.prompt_tokens_details.cached_tokens` (`tokens_in` stays `prompt_tokens`, which
  already includes them; see [Cached input tokens](#cached-input-tokens)).
- Works with `OpenAI` and `AsyncOpenAI`, and with any client that has the same
  `client.chat.completions.create(model=..., messages=...)` shape. `openai` itself is never
  imported by AgentFlight.
- Cost isn't guessed. There's no built-in price table, so pass
  `instrument_openai(client, cost=lambda model, tokens_in, tokens_out: ...)` if you want it.
- `extra_headers`, `extra_query`, `extra_body` and `timeout` are passed to the client but
  never recorded (headers can carry credentials). Everything recorded goes through your
  `redact` hook.
- Fail-open: the call happens exactly once with your arguments and its response or
  exception comes back unchanged. If response parsing or your `cost` function fails, that's
  logged and ignored. A client without the expected shape is returned untouched.
- **Not recorded yet:** `stream=True` calls (passed straight through) and the Responses API.

### LangGraph

```bash
pip install "agentflight-sdk[langgraph]"   # import name: agentflight
```

```python
from agentflight.integrations.langgraph import AgentFlightCallbackHandler

handler = AgentFlightCallbackHandler(run_name="react-agent")
graph.invoke(inputs, config={"callbacks": [handler]})
print(handler.run_id)
```

- The graph becomes a `run`. Inside an `agentflight.run(...)` it's a `node` span in that run
  instead. Each executed node is a `node` span with `agentflight.node.name`, `.step`,
  `.input` (state in) and `.output` (state update).
- Chat model and LLM calls inside nodes are `llm` spans (messages, params, response, token
  usage from `usage_metadata` or `token_usage`). LangChain tools are `tool` spans. So
  `create_react_agent`-style graphs record without any SDK calls in your code.
- Model usage records cached input from `usage_metadata.input_token_details`
  (`cache_read`, `cache_creation`) as `cache_read_tokens` / `cache_write_tokens`.
- **Agents:** `AgentFlightCallbackHandler(agent_nodes={"researcher", "writer"})` (or a
  function `(node_name, metadata) -> bool`) marks those nodes as [agents](#agents), with
  `agentflight.agent.task` / `agentflight.agent.model` from the node's metadata keys of
  the same names, else the model of the node's first model call. Other nodes aren't
  agents (the default marks none), so graphs with many steps don't flood the Agents tab.
- LangChain's own runnables inside a node (prompts, sequences, routers) aren't recorded.
  Their children attach to the nearest recorded span.
- Errors are recorded where they happen and share one failure id up the graph. LangGraph
  interrupts aren't errors: the node's output records `{"interrupted": ...}`.
- Params whose names contain `api_key`, `secret`, `password` or `authorization` are dropped.
- Fail-open: every callback is guarded, so a broken recorder never changes the graph's
  result or exception.
- **Limitation:** spans you record yourself inside a node (`@agentflight.tool`,
  `llm_call`) attach to the surrounding `agentflight.run`, not to the node span, and are
  only part of a run if one is open.

Both examples run offline (scripted model, no API key needed):

```bash
python examples/openai_agent.py      # uses the real API if OPENAI_API_KEY is set
python examples/langgraph_agent.py
```

## OTLP ingest (any OpenTelemetry agent)

Agents that are already instrumented with OpenTelemetry (OpenLLMetry, OpenInference,
framework auto-instrumentation or your own spans) can send traces to AgentFlight over
standard **OTLP/HTTP**, without the AgentFlight SDK: `POST /v1/traces` accepts
`application/x-protobuf` and `application/json`, optionally with
`Content-Encoding: gzip`. OTLP over gRPC is not supported.

Use an `ingest` key, sent as `Authorization: Bearer <key>` (or `X-AgentFlight-Key`).
With the stock environment variables (the exporter appends `/v1/traces` to
`OTEL_EXPORTER_OTLP_ENDPOINT`; the space in the header value is written `%20`):

```bash
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:8000
export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20${AGENTFLIGHT_INGEST_KEY}"
export OTEL_EXPORTER_OTLP_COMPRESSION=gzip
```

Or in Python (`pip install opentelemetry-exporter-otlp-proto-http`):

```python
from opentelemetry.exporter.otlp.proto.http import Compression
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

exporter = OTLPSpanExporter(
    endpoint="http://localhost:8000/v1/traces",
    headers={"Authorization": f"Bearer {ingest_key}"},
    compression=Compression.Gzip,
)
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(exporter))
```

Or from an OpenTelemetry Collector, next to whatever else it exports to:

```yaml
exporters:
  otlphttp/agentflight:
    endpoint: http://agentflight:8000        # the exporter appends /v1/traces
    headers:
      authorization: "Bearer ${env:AGENTFLIGHT_INGEST_KEY}"
    compression: gzip
service:
  pipelines:
    traces:
      receivers: [otlp]
      exporters: [otlphttp/agentflight]
```

**How spans become runs.** One trace is one run (the run id is the trace id), as with
the SDK:

| OTLP | AgentFlight |
| --- | --- |
| Span without a parent | Closes the run: its name is the run name, its status the run status (`unset` counts as `ok`, OpenTelemetry's convention). Until it arrives the run is `running`. |
| Span without a parent that has an `agentflight.run.parent_run_id` attribute (explicit), or else span links into exactly one other trace (inferred; `AGENTFLIGHT_OTLP_INFER_PARENT_FROM_LINKS=false` turns this off) | The run is a [sub-agent run](#sub-agent-runs) of that run |
| `gen_ai.operation.name` `chat`, `text_completion`, `generate_content` or `embeddings` (or a `gen_ai.request.model` / `gen_ai.system` / `gen_ai.provider.name` without an operation) | An `llm` event: model from `gen_ai.response.model`, else `gen_ai.request.model`; tokens from `gen_ai.usage.input_tokens` / `output_tokens` (or the older `prompt_tokens` / `completion_tokens`), stored as reported. `gen_ai.usage` cache counts are not mapped in 0.5.0 (kept as attributes; the cached-token fields stay `null`). These count in the run's call and token totals and the `model` filter. |
| `gen_ai.operation.name` `execute_tool` (or a `gen_ai.tool.name` without an operation) | A `tool` event named by `gen_ai.tool.name` (the `tool` filter) |
| Any other span | A `span` event |
| Resource `service.name`, `service.namespace`, `service.version`, `deployment.environment(.name)` | Run metadata of the root span (the `meta=` filter) |
| Every other attribute | Kept on the event as is. Resource attributes are copied to every span as `otel.resource.*`, plus `otel.scope.name` / `otel.scope.version`, `otel.span_kind` and `otel.links`. Span events are kept. |

Spans that carry `agentflight.*` attributes (the SDK's own spans, sent through an OTLP
exporter or a Collector) are read exactly as on `POST /v1/spans`; `gen_ai.*` attributes are
not applied to them. Re-sending a batch is idempotent (spans are upserted by span id and
totals recomputed in SQL), so exporter and Collector retries can't double-count.
Exporters in several processes sending the same trace at once are fine too: batches for
the same run are safe: on Postgres they take turns (a row lock on the run); on SQLite a
batch that loses the race to store a new run or span is rolled back and redone. Every span
is stored and the totals count each one once.

**Responses** follow the OTLP/HTTP spec, encoded like the request (protobuf or JSON):

| Status | When | Retried by OTLP exporters |
| --- | --- | --- |
| `200` | Stored. Spans that can't be stored (an invalid trace or span id, a name over 255 characters, an attribute over a [limit](#ingest-limits)) are left out and counted in `partial_success` (`rejected_spans`, `error_message` naming the first few); the rest of the batch is stored. | no |
| `400` | The body isn't valid OTLP protobuf/JSON, or isn't valid gzip | no |
| `401` / `403` | Missing or wrong key / a key without `ingest` | no |
| `413` | Body over `AGENTFLIGHT_MAX_BODY_BYTES`, compressed **or decompressed** (decompression stops at the cap, so a gzip bomb can't use more memory than that), or more than `AGENTFLIGHT_MAX_SPANS_PER_BATCH` spans | no |
| `415` | Another `Content-Type`, or a `Content-Encoding` other than `gzip` / `identity` | no |
| `503` | The database is unavailable, SQLite is locked by another write, or a batch kept colliding with concurrent writes of the same run and was rolled back (with `Retry-After`) | yes |

Errors carry a `google.rpc.Status` body. The server never answers `429` (it has no rate
limit). Unlike the SDK's exporter, stock OTLP exporters don't split a batch on `413`; the
default batch processor sends at most 512 spans per request, so keep payloads well under
16 MiB per batch or raise the cap.

**Limitations**

- **No replay for OTLP-only runs.** Replay and fork need the recorded outputs the SDK
  stores (`agentflight.llm.response`, `agentflight.tool.result`...). `gen_ai` prompts,
  completions and tool arguments stay under their own attribute names, and the viewer shows
  them, but `Recording` doesn't read them. SDK spans sent over OTLP stay replayable.
- **No cost.** The `gen_ai` conventions have no cost attribute, so `cost_usd` is only set
  from `agentflight.llm.cost_usd`.
- **Distributed traces:** a trace whose root span lives in a service that doesn't export
  to AgentFlight never closes, and shows as `abandoned` after the stale threshold. A trace
  with several parentless spans takes its name and status from the last one received.
- A span whose name, or one of whose span event names, is over 255 characters is
  rejected (counted in `partial_success`); `POST /v1/spans` rejects the whole request with
  `422`, as for any request that doesn't match its schema.
- The pre-1.0 `instrumentationLibrarySpans` field is ignored; send `scopeSpans`.

## Replay and fork

Re-run an agent against a recorded run. Recorded model and tool outputs are served instead of
calling anything, so a replay costs nothing and gives the same result. A fork replays up to
a step, then runs live from there.

**Know the limits first:**

- **Only intercepted calls are replayed.** Replay suits agents that only call models and
  tools. File writes, database queries, raw HTTP, the clock and randomness inside your
  agent still run live during a replay. Replay only notices them indirectly, when they
  change the input of a later step and that step diverges.
- **An incomplete recording can't replay faithfully.** If the recorder dropped spans of
  the run (full export queue), `replay()` and `fork()` log a warning as they start, before
  any step runs, and `Recording.incomplete` / `Recording.dropped_spans` say so. Missing
  steps then show up as divergences, or as live calls with `on_divergence="live"`.
- **Not covered yet:** LangGraph runs (their model and tool calls go through LangChain,
  which can't be intercepted yet; LangGraph's own checkpointer time travel covers some of
  this) and streamed OpenAI calls (`stream=True`).
- **Sequential agents only.** Steps are matched in recorded order, so calls made in
  parallel threads or tasks can come in a different order and diverge.

```python
recording = agentflight.Recording.fetch(run_id)  # or Recording.load("run.json")
for step in recording.steps:
    print(step.index, step.kind, step.name)  # 0 llm gpt-4o-mini, 1 tool search, ...

with agentflight.replay(recording) as session:
    answer = my_agent(question)  # same code as the recorded run
assert session.remaining == 0  # the replay covered every recorded step

with agentflight.fork(recording, at=1, output="no results"):
    answer = my_agent(question)  # step 0 cached, step 1 returns "no results", rest live

with agentflight.fork(recording, at=2):
    answer = my_agent(question)  # steps 0-1 cached, live from step 2 (e.g. a changed prompt)
```

**Steps.** A step is one `@agentflight.tool` call or one model call (`instrument_openai`, or
an `llm_call` block), in the order recorded. A call made inside another step (say, a model
call inside a tool) is part of that step. Serving the outer call means the inner one
never runs.

**What gets intercepted.** Only these calls are intercepted:

- `@agentflight.tool` functions: the recorded result is returned and the function doesn't
  run.
- Clients wrapped with `instrument_openai`: the client isn't called. The recorded response
  comes back as an `openai` `ChatCompletion` (or as a dict with attribute access if
  `openai` isn't installed).
- Manual `llm_call` blocks, only if your code checks `call.replayed`:

  ```python
  with agentflight.llm_call(model, messages) as call:
      if call.replayed:
          reply = call.response
      else:
          reply = client.chat(...)
          call.record(reply, tokens_in=..., tokens_out=...)
  ```

**What replay guarantees:**

- Each intercepted call is checked against its recorded step: the same kind, the same
  model or tool name, and the same inputs (messages and params, or bound tool arguments).
  Inputs are compared after the same redaction and truncation that was used for recording.
  Any mismatch, or a call beyond the end of the recording, raises `ReplayDivergence`
  naming the step and the field. Values are never included in the error.
- By default, replay never falls back to a live call. If a step can't be served, it
  raises (unlike recording, which is fail-open). A recorded failure is re-raised. Built-in exception types
  (`LookupError`, `ValueError`...) come back as that type with the recorded message. Other
  types raise `ReplayedError`, which carries `error_type` and `message`.
- A replay or fork is recorded as a new run. Its run carries
  `agentflight.replay.source_run`, `.mode` (`replay`/`fork`) and `.fork_step`. Each step span
  carries `agentflight.replay.step` and `agentflight.replay.source` (`cached`, `override`
  or `live`). Cached calls record no tokens or cost, because nothing was spent.

**Going live on divergence (opt-in).** `replay(recording, on_divergence="live")` and
`fork(..., on_divergence="live")` don't raise on the first mismatch. Instead they stop
serving recorded outputs: that step and every later call run live, and the steps are marked
`live`. The step and the reason are recorded on the session (`session.diverged_at`,
`session.divergence`), on the innermost open run as `agentflight.replay.diverged_at` and
`agentflight.replay.divergence`, and in a warning on the `agentflight` logger.

```python
with agentflight.replay(recording, on_divergence="live") as session:
    answer = my_agent(new_question)
print(session.diverged_at)  # e.g. 0: the first model call already differed
```

- This makes real model and tool calls from the divergence point on, so use it only
  where that's acceptable.
- Only mismatches switch to live. That covers a different kind, name or input, or a call
  beyond the recording. A step whose recorded output was truncated still raises
  `ReplayError`, and a recorded failure is still re-raised.

**What it doesn't guarantee:**

- **Only intercepted calls are replayed** (see the limits above).
- **Outputs come back as recorded JSON.** Tuples come back as lists, and custom objects
  come back as whatever was recorded (often a `repr` string). Redacted values come back
  redacted. A step whose recorded output was truncated raises `ReplayError` instead of
  returning a partial value. If an input was truncated, only the stored prefix is
  compared.
- **Inputs redacted by the server can't be compared.** A step whose recorded input was
  changed by [server-side redaction](#server-side-redaction-opt-in) (listed in the event's
  `redacted` field) raises `RedactedInputError`, a `ReplayDivergence`, even with
  `on_divergence="live"`. To run live from that step instead, opt in separately with
  `replay(recording, on_redacted_input="live")` (or `fork(...)`); the replayed run then
  carries `agentflight.replay.on_redacted_input = "live"`. A step whose recorded output was
  redacted by the server raises `ReplayError`; `fork(recording, at=N, output=...)` supplies
  that output.
- **Use the same `redact` hook** (and `max_attr_chars`) as when recording, or the inputs
  won't match.
- **Sequential agents only** (see above). The replay is bound to the current context (a
  `ContextVar`): asyncio tasks started inside it see it, but new threads don't.

`python examples/replay_agent.py` records the toy agent, replays it and forks it at the
tool step (needs the server running).

### Comparing runs

`agentflight.diff_runs` compares two recorded runs, for example a fork and the run it
forked from:

```python
import agentflight

base = agentflight.Recording.fetch(source_run_id)
head = agentflight.Recording.fetch(fork_run_id)
result = base.diff(head)  # or agentflight.diff_runs(base.run, head.run)
print(result.status)  # "same", "different" or "not_comparable"
for pair in result.pairs:
    if pair.status != "same":
        print(pair.kind, pair.name, pair.status, [c.field for c in pair.changes])
```

- **Matching:** a replay or fork is matched to its source run step by step. Any other two
  runs are matched through the span tree: the same name and identical input first, then
  the same name in order, then the same kind. Model calls are matched regardless of the
  model, which is compared instead.
- **Redacted and truncated values are never reported as equal.** The server doesn't keep
  the originals, so two identical `[REDACTED:rule]` markers may hide different values.
  Such values come out `unknown`, and a run with nothing else different is
  `not_comparable`, not `same`. Only the redaction rule names and counts are compared,
  and a value redacted on one side only is shown on neither.
- **Timing and usage (tokens, cost) are reported but never count as a difference** by
  themselves: a re-run with the same inputs and outputs and different token counts is
  `same`. They are in each pair's `usage` and timing fields and in `RunDiff.info`.
- **Limits:** by default a run may have at most 10,000 spans and 64 Mi characters of
  stored payload (`DiffTooLarge` otherwise). Strings over 200,000 characters, or past
  2,000,000 characters of text diffs in one diff, are reported as changed without a text
  diff. Change these with `agentflight.DiffOptions`. The defaults come from
  [a benchmark on one machine](docs/benchmarks/diff-caps-2026-11-29.md).

The server compares stored runs too: `GET /v1/runs/{base}/diff/{head}` (read permission)
returns the same document as `RunDiff.to_dict()`, and the viewer shows it at `/ui/diff`.
From a shell:

```bash
agentflight diff BASE HEAD             # run ids on the server (AGENTFLIGHT_ENDPOINT, AGENTFLIGHT_API_KEY)
agentflight diff base.json head.json   # runs saved with Recording.save, no server needed
agentflight diff --json --strict BASE HEAD
```

It prints a summary (or the whole diff with `--json`) and exits 0 when the runs are the
same, 1 when they differ, 3 when nothing differs but some values couldn't be compared, and
2 on errors (a run that can't be loaded, a run over a diff limit (`413`), a server still
busy after retries (`429`), a bad file). `--strict` turns 3 into 1, for CI checks that
must not pass on redacted values. `--no-payloads` skips text diffs. A `429` is retried
`--retries` times (default 3), waiting as long as `Retry-After` says (at most 10 s each).
`--local` fetches both runs and diffs them on this machine with the library's limits, the
same as diffing files saved with `Recording.save`; the `413` message points there. A `404`
for the endpoint itself (a server older than this command) says so, rather than "run not
found".

A diff of an unfinished run says so: the JSON has `unfinished` (`{"head": "running"}` or
`"abandoned"`), the summary and the viewer show a banner, since spans may still arrive. A
run compared with itself is answered from its span tree alone (ids, parents, names),
without loading or counting payloads: on one machine 120 to 180 ms for a 10,000-span run,
against 3 to 7 s for a full diff.

The server has its own limits, checked before a run's payloads are loaded (`413` over
them), and caps how many diffs run at once (`429` with `Retry-After: 2` over that;
nothing queues). A viewer page counts as one diff. A span pair's panel doesn't: it loads
only the two spans (each must belong to its run, `404` otherwise) and compares just that
pair.

The `413` message gives the run's measured size and the limit, e.g. `head run holds
40,123,456 characters of stored JSON (attribute, span event and status message text as
stored, keys and quotes included); the server's diff limit is 33,554,432 characters per
run`. The count is of characters (not bytes) of the JSON as the database stores it, so
SQLite and Postgres accept and refuse the same runs. (Rows written to SQLite by
AgentFlight 0.3.0 or earlier store non-ASCII text as `\uXXXX` escapes, and count six
characters for each such character.)

Diffs run in worker processes (one per diff slot, started on first use), so a large diff
doesn't hold up span ingest in the server process. On one machine, with two worst-case
diffs running (two 10,000-span, 32 Mi runs), `POST /v1/spans` p50/p99 stayed at 11/20 ms
on Postgres (baseline 9/19 ms) and 8/61 ms on SQLite (baseline 8/18 ms; SQLite's file
lock still makes writers wait on the diff's reads). On a server thread they were 10/640
ms and 820/3,282 ms ([measurements](docs/benchmarks/diff-ingest-2026-11-29.md),
`scripts/bench_diff_ingest.py`). A worker that dies (for example killed out of memory)
is a `503` for that diff, and the next diff starts a new one. `AGENTFLIGHT_DIFF_PROCESSES=false` runs diffs on a server thread instead (in-memory
SQLite always does).

**The limits are per server process.** With `N` uvicorn or gunicorn workers, up to `N × 2`
diffs can run at once, and diff memory is up to `N ×` the figures below. Set
`AGENTFLIGHT_MAX_CONCURRENT_DIFFS` with that in mind.

| Setting | Default | Limit |
| --- | --- | --- |
| `AGENTFLIGHT_MAX_DIFF_SPANS` | `10000` | Spans per run |
| `AGENTFLIGHT_MAX_DIFF_CHARS` | `33554432` (32 Mi) | Characters of stored payload per run, counted over the stored JSON (keys and quotes included, so a little stricter than the library's `max_chars`) |
| `AGENTFLIGHT_MAX_CONCURRENT_DIFFS` | `2` | Diffs running at once in one server process |
| `AGENTFLIGHT_DIFF_PROCESSES` | `true` | Run diffs in worker processes (`false`: on a server thread) |

The character default is half the library's: on one machine, two runs at 32 Mi added up to
about 182 MiB per diff, and two at 64 Mi up to about 278 MiB
([measurements](docs/benchmarks/diff-memory-2026-11-29.md),
`scripts/bench_diff_memory.py`). That memory is now in the diff worker processes, and a
worker keeps its peak until it exits.

## Failure isolation

AgentFlight follows one rule: **observability must never become a dependency for
successful agent execution.** `tests/test_failure_isolation.py` checks each guarantee.

Guarantees:

- **Return values and exceptions pass through unchanged.** `run`, `llm_call` and `@tool`
  return what your code returns and re-raise your exact exception object, even if
  recording that exception fails.
- **Recorder failures never raise into agent code.** Each of these is caught and logged as a
  warning on the `agentflight` logger: the server being down, HTTP 4xx/5xx, redirects,
  malformed or truncated responses, transport exceptions, timeouts, exceptions from the
  exporter's `export` / `force_flush` / `shutdown`, exceptions from span processor hooks,
  and a broken tracer or serializer. If a span can't be opened, your code still runs under
  a non-recording span.
- **Weird payloads are safe.** Payloads that JSON can't serialize fall back to `repr`.
  If `repr` itself raises, the value is stored as `<unrepresentable Type>`. This covers
  circular structures, `NaN`, bytes, locks, generators and objects whose `__repr__` or
  `__str__` raise. Values are cut off at 32,000 characters.
- **No blocking in the default mode.** With `batch=True` (the default), spans are exported
  on a background thread, so a hanging server doesn't slow the agent down.
- **Run spans skip the queue.** A run's root span (the one that closes the run and
  carries its status and drop count) doesn't go through the bounded batch queue. It goes
  to a lane of its own, which a dedicated thread sends as soon as the run ends, several at
  a time if runs end together. So a run whose other spans were dropped still closes on
  the server instead of staying `running` and later showing as `abandoned`. Ending a run
  only appends the span to that lane under a lock; the agent thread never waits on the
  network. Each send has a deadline: no request starts after it, and each request's
  timeouts are capped to what is left of it (the exporter's `timeout`, 5 s by default).
  It's still best effort and fail-open: if the send fails or runs out of time, the run
  span is lost like any failed export (and the run can end up `abandoned`), and if more
  than 1,024 run spans are waiting, new ones are dropped and counted. Each run span is
  handed to the exporter once, never to both the lane and the queue. The exporter is
  only ever called by one thread at a time, so a run span can wait for a batch that is
  being sent. `flush()` and `shutdown()` wait for the lane too, within their timeouts.
- **Bounded waits.** `flush(timeout_millis=30_000)` and `shutdown(timeout_millis=30_000)`
  never raise and return within their timeout. AgentFlight enforces this itself, because
  OpenTelemetry's isn't reliable: in opentelemetry-sdk 1.45, `force_flush(300)` against a
  hanging server with four batches queued took 4.0 s (one 1 s HTTP timeout per batch).
  When the wait runs out, `flush()` returns `False` and export carries on in the
  background; whatever `shutdown()` hasn't sent by then is lost. Interpreter exit is also
  clean: AgentFlight replaces OpenTelemetry's atexit hook with a fail-safe one, bounded
  the same way.
- **A bad configuration disables recording instead of raising.**

### On-disk spool (opt-in)

```python
agentflight.configure("http://localhost:8000", spool_dir="/var/tmp/agentflight-spool")
# or AGENTFLIGHT_SPOOL_DIR=/var/tmp/agentflight-spool
```

| Setting | `configure(...)` | Environment | Default |
| --- | --- | --- | --- |
| Directory (setting it turns the spool on) | `spool_dir` | `AGENTFLIGHT_SPOOL_DIR` | unset: off |
| Kill switch | `spool_enabled=False` | `AGENTFLIGHT_SPOOL_ENABLED=false` | on (when a directory is set) |
| Size cap | `spool_max_bytes` | `AGENTFLIGHT_SPOOL_MAX_BYTES` | 64 MiB |
| Age cap | `spool_max_age_s` | `AGENTFLIGHT_SPOOL_MAX_AGE_SECONDS` | 24 h |

An explicit argument wins over the environment; the kill switch wins over a directory (so a
deployment can switch the spool off without editing code) and logs one warning at startup
saying it did. A size or age of zero or less, in code or in the environment, disables the
spool with one warning (it means "nothing on disk", not "the default") and recording
carries on. An environment value that isn't a number is ignored with a warning (the
default is used).

With a spool directory, spans that weren't stored because of a failure that may clear up
(server down, transport error, timeout, 5xx, 408/425/429, rejected credentials, the
attempt cap or the run span deadline) are written to disk, one file per failed batch,
instead of being dropped. Every later export first sends what is spooled, oldest first,
then its own batch; when a process restarts (or crashed), its first export sends what the
last one left behind. Run spans are sent before the spool is replayed.

- **Same rules as any export.** Replay shares the export's attempt cap
  (`max_export_attempts`), is split on 413 like any batch, and stops at the first other
  failure; what isn't sent stays on disk for the next export. A file that was partly sent
  keeps only the spans still unsent, in its place in line. Spans the server rejects for
  good (a single span over its body cap, `422` and other 4xx) are dropped, not retried
  and not spooled; so is a span that can't be encoded as JSON (a lone UTF-16 surrogate,
  or NaN/Infinity), dropped alone before the batch is sent. The server upserts by
  span id, so a span that is sent twice (the server stored it, but the response was lost)
  is harmless.
- **Bounded.** At most `spool_max_bytes` (`AGENTFLIGHT_SPOOL_MAX_BYTES`, default 64 MiB)
  and 10,000 files; when a new batch doesn't fit, the oldest files are deleted. Files older
  than `spool_max_age_s` (`AGENTFLIGHT_SPOOL_MAX_AGE_SECONDS`, default 24 h) are deleted
  unsent. A batch bigger than the whole spool isn't kept.
- **Private, but it is sensitive data on disk.** The spool holds recorded payloads
  (messages, tool arguments and results, stack traces; after `redact`, if you set one) in
  plain, unencrypted JSON until they are sent or expire. The directory is created `0700`
  (an existing one you own is tightened to `0700`) and files, including the temporary and
  marker files, are created `0600`, whatever the umask, on systems that support Unix
  permissions (on Windows these modes do nothing; use a directory only your account can
  read). A directory that is a symlink or belongs to another user is not used. Put the
  spool on storage you would trust with the payloads themselves, and prefer a short
  `spool_max_age_s` for sensitive data.
- **Fail-open.** A full disk, a directory that can't be created or written, or a corrupt
  file (deleted when found) loses those spans, logs one warning per kind of problem and
  never raises. Files are written to a temporary name and renamed, so a crash mid-write
  leaves no half file in line (stale temporary files are cleaned up after an hour).
  `get_recorder().spool.dropped` counts the spans the spool gave up on.
- **Never on the agent's thread.** Spool writes and replay run on the export threads
  (the batch worker and the run-span lane). That's why it needs `batch=True`: with
  `batch=False` the export runs on the agent's thread, so `spool_dir` is ignored with a
  warning. It also only works with the built-in exporter.
- **Sharing a directory works but may resend duplicates; one folder per process avoids
  that.** There is no locking. File names are unique per process, a file another process
  already sent (and deleted) is skipped silently, and the size cap never deletes a file
  another process is sending: a sender marks the file it is sending, and eviction skips
  marked files (a crashed sender's marker expires after 10 minutes). If every file left is
  being sent, a new batch that doesn't fit is dropped (and counted) rather than going past
  the cap. Two processes can still send the same file; ingest is idempotent, so the cost
  is a duplicate send.

Limitations (known, not yet handled):

- **Lost spans, unless you turn on the spool.** By default, spans whose export fails are
  dropped, and if the server is unreachable the run is missing from the recording. With
  the on-disk spool (below), failures that may clear up are retried on later exports;
  without it there's no retry.
- **Raw HTTP clients have no spool.** The spool and retries are part of the Python SDK. A
  client that posts JSON to `POST /v1/spans` (or OTLP to `/v1/traces`) itself, such as a
  shell or editor hook, loses whatever it sends while the server is down unless it keeps
  and resends it. If you need that, record through the Python SDK with `spool_dir` set
  (even a hook can call a short Python script), or an OpenTelemetry Collector with a
  persistent queue in front of `/v1/traces`.
- **The batch queue is bounded.** It holds 2048 finished spans by default; set it with
  `configure(max_queue_size=...)` or `AGENTFLIGHT_MAX_QUEUE_SIZE` (OpenTelemetry's
  `OTEL_BSP_MAX_QUEUE_SIZE` also works). When the queue is full, spans are dropped rather
  than blocking the agent. A bigger queue absorbs longer bursts at the cost of memory
  (each queued span holds its payloads, up to `max_attr_chars` each).
- **Dropped spans are counted, on a best-effort basis.** AgentFlight checks the queue
  itself before handing a span to OpenTelemetry, so it knows every span it drops (on its
  own, OpenTelemetry 1.45 drops the *oldest* queued span, which can belong to another
  run). When a run ends, the spans of that run dropped so far go on the run span as
  `agentflight.run.dropped_spans`, and the viewer and replay warn about it. Run spans
  skip the queue (see "Run spans skip the queue"), so the span carrying the count isn't
  competing with the spans it counts. What this can't cover: spans of the run that end
  *after* the run span (background threads or tasks still running), a run span dropped
  because more than 1,024 were waiting to be sent, and spans lost later in export
  (server down, see "Lost spans"). Those are only in the recorder's
  total, `agentflight.get_recorder().dropped_spans`, and a warning is logged on the first
  drop. `batch=False` has no queue and never drops this way.
- **`batch=False` blocks.** It exports inside the agent's thread, so each span can block
  for up to the HTTP timeout. Use it only for tests or debugging.
- **A partly broken span processor can mis-parent later spans.** If a processor fails while
  a span is closing, the current-span context may not be restored. The agent still runs,
  but later spans in that run may be attached to the wrong parent.
- **Custom exporters must honor timeouts.** If you write a custom exporter
  that blocks forever (ignoring timeouts), only `flush`/`shutdown` timeouts protect you.
- **`BaseException`s are recorded and re-raised.** `KeyboardInterrupt` and `SystemExit` are
  never swallowed. Only ordinary `Exception`s raised by the instrumentation are suppressed.

## Overhead

Measured with [`scripts/bench_overhead.py`](https://github.com/shupandee/agentflight/blob/main/scripts/bench_overhead.py) on 2026-11-27, with run
spans on their own lane (0.1.0): **5 repeats**, each against a fresh server. Raw output:
[`docs/benchmarks/overhead-2026-11-27-run-lane.md`](https://github.com/shupandee/agentflight/blob/main/docs/benchmarks/overhead-2026-11-27-run-lane.md)
(and [`.json`](https://github.com/shupandee/agentflight/blob/main/docs/benchmarks/overhead-2026-11-27-run-lane.json)). Earlier numbers (a single run
for week 6, 5 repeats before run spans had their own lane) are in the git history.

**Method.** The "agent" makes 5 model calls and 5 tool calls that do no work, so a run is
11 spans and nearly all of its time is recording overhead. In each repeat, each scenario
runs it 2,000 times (200 for `batch=False`) after 200 warm-up runs, timing each run on
the agent thread with `time.perf_counter_ns`. The table gives the median of the five
per-repeat medians, the spread of those medians (min to max), the median p95, and the
added time per span versus the same code without AgentFlight. The HTTP scenarios export
to a real server (uvicorn + SQLite, separate process); the benchmark is pinned to one CPU
and the server to the other seven, and afterwards the spans the server stored, the spans
the SDK counted as dropped and the runs the server has with a final status are added up
over all repeats. Messages are about 100 characters ("small") or 8,000 ("large").

**Machine.** Linux 6.12 x86_64 VM (KVM), Intel Xeon, 8 vCPUs; CPython 3.13.5,
opentelemetry-sdk 1.45.2, httpx 0.29.0, uvicorn 0.54.0. The box is shared: the 1-minute
load average at the start of the repeats ranged from 0.81 to 1.24.

| Payload | Scenario | Median per run | Spread (5 medians) | p95 | Added per span | Spans stored | Dropped (SDK count / on runs) | Runs closed |
| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| small | no AgentFlight | 0.7 µs | 0.7 to 0.8 µs | 0.8 µs | — | — | — | — |
| small | SDK, no exporter | 383.3 µs | 381.3 to 389.8 µs | 458.5 µs | 34.8 µs | — | — | — |
| small | SDK + JSON serialization, no network | 532.0 µs | 528.4 to 535.9 µs | 623.2 µs | 48.3 µs | — | — | — |
| small | HTTP, `batch=True` (default), queue drained every 100 runs | 421.4 µs | 413.0 to 457.3 µs | 784.3 µs | 38.2 µs | 121,000 of 121,000 | 0 / 0 | 11,000 of 11,000 |
| small | HTTP, `batch=True`, tight loop | 420.0 µs | 416.4 to 447.4 µs | 533.9 µs | 38.1 µs | 55,718 of 121,000 | 65,282 / 65,282 | 11,000 of 11,000 |
| small | HTTP, `batch=False` | 64,347.6 µs | 59,479.7 to 65,389.2 µs | 71,882.5 µs | 5,849.7 µs | 12,100 of 12,100 | 0 / 0 | 1,100 of 1,100 |
| large | no AgentFlight | 1.5 µs | 1.4 to 1.6 µs | 1.5 µs | — | — | — | — |
| large | SDK, no exporter | 833.4 µs | 826.0 to 836.4 µs | 946.6 µs | 75.6 µs | — | — | — |
| large | SDK + JSON serialization, no network | 1,235.4 µs | 1,228.5 to 1,252.0 µs | 1,397.1 µs | 112.2 µs | — | — | — |
| large | HTTP, `batch=True` (default), queue drained every 100 runs | 875.7 µs | 865.9 to 878.7 µs | 1,640.2 µs | 79.5 µs | 121,000 of 121,000 | 0 / 0 | 11,000 of 11,000 |
| large | HTTP, `batch=True`, tight loop | 864.9 µs | 861.3 to 928.2 µs | 1,127.0 µs | 78.5 µs | 60,018 of 121,000 | 60,982 / 60,982 | 11,000 of 11,000 |
| large | HTTP, `batch=False` | 70,389.9 µs | 66,609.9 to 72,645.4 µs | 80,479.0 µs | 6,398.9 µs | 12,100 of 12,100 | 0 / 0 | 1,100 of 1,100 |

**Server ingest rate**, measured by sending already-recorded spans in 512-span batches
back to back from one thread (20 batches per payload and repeat), next to how fast the
tight loop makes spans:

| Payload | Server ingest, spans/s (median of 5) | Spread | Tight loop makes, spans/s | Tight loop: stored, spans/s |
| --- | ---: | ---: | ---: | ---: |
| small | 9,604 | 9,211 to 9,773 | 26,189 | 7,162 |
| large | 4,248 | 3,735 to 4,362 | 12,718 | 3,371 |

What this says:

- With the default `batch=True`, recording costs the agent about **38 µs per span with
  small payloads and 79 µs with 8,000-character ones**, about 0.42 ms and 0.87 ms for
  this 11-span run. In the `batch=True` rows the slowest repeat was up to 8.5% above
  the median and the fastest within 2% of it (the box is shared).
- **The dropped spans are a rate mismatch.** The tight loop makes spans 2.7 to 3.0 times
  faster than one exporter thread and this server store them (26,189 vs 9,604 spans/s
  small, 12,718 vs 4,248 large), and while the loop runs the exporter also shares the
  agent's CPU, so the server stored only 7,162 and 3,371 spans/s. The 2,048-span queue
  fills in well under a second, and about half the spans were dropped (54% and 50% over
  the five repeats). The SDK counted every one (stored + dropped = sent), **every drop
  is recorded on its run** (65,282 of 65,282 small, 60,982 of 60,982 large), and **every
  run closed** (11,000 of 11,000): run spans skip the queue.
- Real agents spend hundreds of milliseconds on each model call, far below these rates.
  A burst of thousands of spans can still lose some; `max_queue_size` buys headroom.
- `batch=False` waits for an HTTP round trip and a database commit per span, about 6 ms
  each here. Use it for short scripts and debugging, not in a loop.

These are one machine's numbers for a synthetic agent, not a guarantee; run the script on
yours (`python scripts/bench_overhead.py`, about 5 minutes; `--quick` for a short run).

## Run status

| Status | Meaning |
| --- | --- |
| `running` | The run span hasn't arrived with an end time yet. |
| `ok` / `error` | The run span ended with that status. |
| `unknown` | The run span ended without setting a status (possible with raw `/v1/spans` senders and non-SDK OTel spans; the SDK always sets one). |
| `abandoned` | Still `running`, but no span of the run has been received for `AGENTFLIGHT_STALE_AFTER_MINUTES` (default `60`, `0` turns it off), e.g. because the agent process crashed. |

`abandoned` is never stored. It's decided when runs are read, from the run's
`last_seen_ns` (server time of its last received span), so changing the threshold needs no
data fix, and a late span turns the run back into `running` or its final status. Filter
with `GET /v1/runs?status=abandoned`.

## Errors and failures

Each run summary has two error numbers:

- `errors` is the number of **distinct logical failures**.
- `error_events` is the number of events with error status.

Every error event carries `agentflight.failure.id`. The id follows the exception object, so
a tool raising `LookupError`, the agent calling `agentflight.error(exc)` on it, and the run
failing with it all share one id and count as **one** failure. An exception raised while
handling a recorded one (`raise X from exc`, or inside its `except`) inherits that id.
Independent exceptions get new ids and count separately. Every event is still stored.
Error events from SDKs that don't send ids count one each.

## Payload size and redaction

```python
agentflight.configure(
    max_attr_chars=32_000,  # per payload; None disables the cap
    redact=agentflight.redact_fields("api_key", "password", "authorization"),
)
```

- **Truncation is explicit.** A payload (messages, response, tool args/result, metadata,
  decision choice, state) longer than `max_attr_chars` is cut to that length. Its key is then
  listed in the span's `agentflight.truncated` attribute, and in the API's per-event
  `truncated` field, as
  `{"original_length": ..., "stored_length": ..., "reason": "exceeds max_attr_chars=..."}`.
  So you can always tell a truncated recording from the original message. The limit is a
  storage limit, not a model context limit.
- **Redaction.** `redact(key, value)` runs on every payload before it is serialized, and
  `key` is the attribute name (for example `agentflight.tool.args`). `redact_fields(...)`
  masks dict entries with those names (case-insensitive) at any depth. If your hook
  raises, the value is replaced with `"<redaction failed>"`; it fails closed and nothing is
  recorded.
- **Errors are redacted too.** Exception messages go through the hook with the key
  `agentflight.error.message`, and stack traces with `exception.stacktrace`, before they
  are stored (in the error attributes, the span status and the OpenTelemetry `exception`
  event). Both are plain strings, so a hook that should scrub them has to handle `str`
  values; `redact_fields(...)` only masks dict entries. Both are capped at
  `max_attr_chars`, and a cut message is listed in `agentflight.truncated`.
- **Names are not redacted.** Run, tool, model and span names (including
  `agent:<name>`) are stored as given, because replay matches steps by them. Don't put personal data or secrets in run names (or tool
  names); put them in metadata or arguments, where the hook applies. This holds for
  server-side redaction too.

### Server-side redaction (opt-in)

The `redact` hook only covers what your own process records with the SDK. To enforce a
policy on everything the server stores, including spans from other services and plain
OpenTelemetry agents over [OTLP](#otlp-ingest-any-opentelemetry-agent), give the server a
TOML policy file:

```toml
# redaction.toml
version = 1
# marker = "[REDACTED:{rule}]"   # the default

[[rules]]
name = "credentials"
keys = ["api_key", "password", "authorization"]   # dict keys at any depth, any case

[[rules]]
name = "tokens"
preset = ["bearer", "aws-access-key-id", "openai-key"]

[[rules]]
name = "internal-ids"
patterns = ['\bACCT-[0-9]{8}\b']                  # Python regular expressions

[[rules]]
name = "resource-secrets"
attributes = ["otel.resource.deploy.token"]        # exact names or globs (fnmatch)
action = "drop"                                    # remove instead of masking
# scope = ["attributes", "events", "status"]       # the default: everywhere
```

```bash
AGENTFLIGHT_REDACTION_FILE=/etc/agentflight/redaction.toml agentflight-server serve
```

| Setting | Default | |
| --- | --- | --- |
| `AGENTFLIGHT_REDACTION_FILE` | unset (off) | The policy. The server refuses to start if it is missing or invalid |
| `AGENTFLIGHT_REDACTION_ON_ERROR` | `redact` | A value whose redaction fails: `redact` stores `[REDACTION_FAILED]` in its place; `reject` doesn't store that span |

- **Applied before anything is stored.** Both `POST /v1/spans` and `POST /v1/traces` run
  the policy on every span after the size checks and before the run name, metadata,
  tokens or failure ids are derived. It covers span attributes, span event attributes
  (such as OpenTelemetry `exception` events) and status messages; `scope` limits a rule to
  some of them.
- **What a rule matches.** `keys` match dict keys inside JSON values: SDK payloads, run
  metadata, OTLP map and array values, span link attributes, and plain string attributes
  that hold JSON (such as `gen_ai.input.messages`), which are parsed when they start with
  `{` or `[`. `patterns` are replaced wherever they match a string. `attributes` redact a
  whole attribute. Presets cover key-shaped secrets only: `bearer` tokens, AWS access key
  ids, and `sk-...` API keys. Emails, card numbers and the like need your own `patterns`.
- **Truncated or broken JSON is matched as text.** A payload the SDK cut at
  `max_attr_chars` (listed in `agentflight.truncated`) isn't valid JSON, so the server
  applies `patterns` and looks for `"key": value` pairs in the text instead. A secret that
  the truncation itself cut in half may not match any more; set `max_attr_chars` high
  enough, or redact on the client too.
- **Never redacted:** span and event names, and the structural attributes AgentFlight
  reads: `agentflight.kind`, run, tool, model, node, decision and state names
  (`agentflight.tool.name`, `agentflight.llm.model`...), token counts, cost, error type,
  failure ids, parent run ids, `agentflight.truncated`, `agentflight.replay.*`. Globs skip
  them, and naming one exactly in `attributes` is a startup error. Token counts include
  `agentflight.llm.cache_read_tokens` / `cache_write_tokens` (0.5.0). Agent attributes
  (`agentflight.agent.*`) are **not** protected: a policy can mask or drop an agent's
  task, model or name, and a node whose name was redacted stays an agent.
- **What was redacted is recorded.** The server writes `agentflight.redacted` on the span:
  `{key: {"rules": [...], "count": n}}` (with `"dropped": true` for dropped attributes,
  keys such as `status_message` and `events[0].exception.message` for those parts). The API
  returns it as each event's `redacted` field, also with `payloads=false`. It is always the
  server's own: a value sent by a client is replaced, and a re-sent span gets a new one.
- **Markers can be longer than the text they replace.** If a redacted value would exceed
  `AGENTFLIGHT_MAX_ATTRIBUTE_CHARS`, the whole value is stored as one marker (and
  `"over_cap": true`); it is never cut.
- **Fails closed.** If redacting a value raises, `[REDACTION_FAILED]` is stored instead of
  it. If a whole span can't be processed, every string or structured value that isn't
  structural, every span event attribute and the status message become
  `[REDACTION_FAILED]`. With `AGENTFLIGHT_REDACTION_ON_ERROR=reject` such a span isn't
  stored; the rest of the batch is. `POST /v1/spans` then answers `202` with
  `"rejected": n` and an `error_message` naming the spans (never values), and OTLP reports
  them in `partial_success`. The SDK exporter logs one warning per export for rejected
  spans and neither retries nor spools them (they would be rejected again).
- **Not retroactive.** The policy applies to spans received after a (re)start; spans
  already stored are not rewritten (and backups or database replicas keep what they have).
  A policy change needs a restart and applies to spans received from then on. There is no
  command yet to redact stored runs.
- **Cost.** Redaction runs on every span, in the request. On one machine, a
  `POST /v1/spans` of 512 spans took, without a policy file and with a two-rule policy (one
  key rule with three keys, one rule with three presets): about 40 ms and 55 ms (in-memory
  SQLite) or 56 ms and 74 ms (local Postgres) for a realistic batch (multi-line prompts,
  replies and tool output, 1.47 MB of payload), and about 44 ms and 50 ms, or 58 ms and
  66 ms, for single-line payloads with nothing to redact (2.36 MB). Payloads that contain
  a pattern's literals (for example the word "bearer", or "sk-" in "task-") cost more:
  the pattern then scans them.
  Measure with your own policy and payloads; the cost grows with payload size and rule
  count. Custom patterns get no literal pre-check. The method is in
  `docs/design/server-side-redaction.md`.
- **Client and server together** work: the client hook runs first, then the server policy.
  Markers never match a rule, so redacting twice changes nothing.
- `422` responses never echo the submitted values, and database errors are logged without
  their SQL parameters, whether or not a policy is set.

## Running at login

`agentflight-server serve` started from a terminal stops when that terminal (its process
group) closes. To keep a personal server running, start it from the OS service manager
at login. [docs/run-at-login.md](docs/run-at-login.md) has copy-paste recipes for
**Windows Task Scheduler**, a **Linux `systemd --user` unit** and a **macOS `launchd`
agent**. Each sets `AGENTFLIGHT_ADMIN_API_KEY` in the service's own environment (so a
client key in your user environment can't collide with it, see
[Client and server on one machine](#client-and-server-on-one-machine)), runs `migrate`
before `serve`, restarts it if it crashes and writes a log file.

**Every line of `agentflight-server serve`'s log starts with the local time** (ISO 8601
with milliseconds and the UTC offset, e.g. `2026-12-01T13:15:31.847+05:30 INFO:
127.0.0.1:44668 - "POST /v1/spans HTTP/1.1" 202 Accepted`), on access lines, uvicorn's
own lines and AgentFlight's warnings, so a client-side timeout can be matched to the
server's lines. An access line is written when the response starts, not when the request
arrives. `AGENTFLIGHT_LOG_TIMESTAMPS=false` restores the formats without a time (as
before 0.5.1). Running uvicorn yourself (`uvicorn agentflight.server.main:app`) keeps
uvicorn's formats; pass `--log-config` for timestamps there.

## Authentication

The server **requires an API key by default** and refuses to start without one.

| Setting | Meaning |
| --- | --- |
| `AGENTFLIGHT_ADMIN_API_KEY` | The server's key with every permission (0.4.1+). Clients send `Authorization: Bearer <key>` (or `X-AgentFlight-Key`). |
| `AGENTFLIGHT_API_KEY` | **Server:** the all-permission key if `AGENTFLIGHT_ADMIN_API_KEY` isn't set (deprecated there; a warning is logged at startup), ignored if it is. **Clients** (SDK, `agentflight diff`): the key they send. |
| `AGENTFLIGHT_API_KEYS` | Scoped keys: comma-separated `<key>:<permission>[+<permission>...]`, e.g. `k1:ingest,k2:read,k3:read+delete`. Permissions: `ingest`, `read`, `delete`, `import`. |
| `AGENTFLIGHT_AUTH_DISABLED=true` | Explicit opt-out for local development only. A warning is logged at startup. |

The server starts if an all-permission key or `AGENTFLIGHT_API_KEYS` is set. Give
recorders an `ingest`-only key, so a leaked agent key can't read or delete history, and
give people and dashboards a `read` key.

**Which variable the server uses for its all-permission key:**

| `AGENTFLIGHT_ADMIN_API_KEY` | `AGENTFLIGHT_API_KEY` | All-permission key | At startup |
| --- | --- | --- | --- |
| set | set or not | `AGENTFLIGHT_ADMIN_API_KEY` | If `AGENTFLIGHT_API_KEY` is set: one `INFO` line saying it is ignored. It gets **no** permissions (only what `AGENTFLIGHT_API_KEYS` gives it, if listed there), and it isn't validated or checked against `AGENTFLIGHT_API_KEYS`. |
| not set | set | `AGENTFLIGHT_API_KEY` | A deprecation warning pointing to `AGENTFLIGHT_ADMIN_API_KEY`. Otherwise exactly as in 0.4.0. |
| not set | not set | none (`AGENTFLIGHT_API_KEYS` only) | |

Both being set is never an error. Moving a key from `AGENTFLIGHT_API_KEY` to
`AGENTFLIGHT_ADMIN_API_KEY` with the same value keeps everyone signed in to the viewer
(sessions are signed from the key values, not the variable names). The all-permission key
listed again in `AGENTFLIGHT_API_KEYS` stops the server at startup; the error names the
variable it came from and, for `AGENTFLIGHT_API_KEY`, explains the overlap below.

#### Client and server on one machine

`AGENTFLIGHT_API_KEY` is also the variable the SDK and `agentflight diff` read, so on a
laptop running both, the server inherits the recorder's key. Before 0.4.1 the server took
it as its all-permission key: an ingest key listed in `AGENTFLIGHT_API_KEYS` stopped it
with "AGENTFLIGHT_API_KEYS repeats AGENTFLIGHT_API_KEY", and an ingest key *not* listed
there silently gained every permission. Give the server its own key:

```bash
# shell profile / user environment: what clients send (ingest-only)
export AGENTFLIGHT_API_KEY=<ingest key>

# the server's environment (a service file, see "Running at login")
AGENTFLIGHT_ADMIN_API_KEY=<admin key>                     # every permission
AGENTFLIGHT_API_KEYS=<ingest key>:ingest,<read key>:read  # the recorder's key, scoped
```

The server ignores the inherited `AGENTFLIGHT_API_KEY`, so the recorder's key has exactly
the permissions `AGENTFLIGHT_API_KEYS` gives it. Sign in to the viewer with the read key
(or the admin key). On Windows, `setx AGENTFLIGHT_API_KEY <ingest key>` sets the user
variable; a task started from Task Scheduler at login usually sees it too, which is fine
once `AGENTFLIGHT_ADMIN_API_KEY` is set.

- Every configured key must be at least 32 characters (`openssl rand -hex 32` gives 64);
  a shorter one stops the server at startup, and the error names the setting, not the
  key. That is what makes guessing impractical: **the sign-in page and the API have no
  rate limit on failed keys yet** (deferred; put a rate-limiting proxy in front if you
  need one now).
- `AGENTFLIGHT_ADMIN_API_KEY` is checked the same way as the old name (at least 32
  characters, never echoed).
- Keys are compared in constant time (`hmac.compare_digest`). Wrong or missing keys get
  `401`, and the response never echoes the key.
- Endpoints require an `ingest`, `read`, `delete` or `import` permission (`import` only
  for `POST /v1/import`; existing keys don't get it unless listed). A valid key without the
  needed permission gets `403`. A malformed `AGENTFLIGHT_API_KEYS` (unknown permission,
  duplicate key) stops the server at startup, and the error never includes the key.
- `Authorization` and `X-AgentFlight-Key` are never logged. `redact_headers()` is the
  helper for anything that logs headers, and a log filter on the server's loggers scrubs the
  configured keys from any message as a backstop.
- **SDK:** `configure(api_key=...)`, or the `AGENTFLIGHT_API_KEY` environment variable
  (unchanged; the SDK never reads `AGENTFLIGHT_ADMIN_API_KEY`).
  If the server rejects the key, the SDK logs one warning (without the key) and drops the
  spans. The agent keeps running.
- `/health` and `/ready` are unauthenticated so orchestrators can probe them.

### Viewer sign-in

The viewer at `/ui` asks once for a key with the `read` permission (an all-permission key
works too) and then keeps a **signed session** in a cookie:

- The cookie never contains the key. It holds an HMAC fingerprint of the key, the `read`
  permission and an expiry, signed with the session secret. Every request re-checks the
  fingerprint against the configured keys, so removing a key ends its sessions.
- The cookie is `HttpOnly`, `SameSite=Strict`, scoped to `/ui`, and `Secure` when the
  request is HTTPS (behind a TLS-terminating proxy, run uvicorn with `--proxy-headers`, or
  set `AGENTFLIGHT_COOKIE_SECURE=true`).
- Sessions are **read-only**. The `/v1` API never accepts the cookie, and the viewer has
  no delete or ingest actions.
- Sign-in and sign-out posts must carry an `Origin` header whose host matches `Host`;
  a cross-site, `null` or **missing** `Origin` gets `403` (current browsers always send
  it on form posts). A reverse proxy must pass the original `Host` through.
- With `AGENTFLIGHT_AUTH_DISABLED=true` there is no sign-in page.
- By default the signing secret is an HMAC of all configured API keys, so every worker
  and replica with the same keys accepts the same sessions and restarts don't sign anyone
  out. **Rotating, adding or removing any key ends every viewer session**; people sign in
  again. Set `AGENTFLIGHT_SESSION_SECRET` to decouple sessions from the keys.

| Setting | Default | Meaning |
| --- | --- | --- |
| `AGENTFLIGHT_SESSION_SECRET` | derived from the API keys | Override for the signing secret, at least 32 characters. |
| `AGENTFLIGHT_SESSION_HOURS` | `12` | Session lifetime. |
| `AGENTFLIGHT_COOKIE_SECURE` | `false` | Always mark the cookie `Secure`. |

## Ingest limits

Every ingest request is bounded. The defaults are deliberately generous, so they shouldn't
reject anything the SDK sends with its default settings; they will be tuned once real
batch sizes are measured. A request over a limit gets `413` and nothing from it is stored. On `POST /v1/traces` the body
cap also applies to the decompressed body, and a span over a per-span limit is rejected on
its own (see [OTLP ingest](#otlp-ingest-any-opentelemetry-agent)).

| Setting | Default | Limit |
| --- | --- | --- |
| `AGENTFLIGHT_MAX_BODY_BYTES` | `16777216` (16 MiB) | Request body size, checked from `Content-Length` and while reading chunked bodies |
| `AGENTFLIGHT_MAX_SPANS_PER_BATCH` | `2048` | Spans in one `POST /v1/spans` or `POST /v1/traces` (the SDK's batch processor sends at most 512 by default) |
| `AGENTFLIGHT_MAX_ATTRIBUTE_CHARS` | `262144` | Characters in one attribute value, span event attribute value or status message (the SDK caps payloads at 32,000 by default) |
| `AGENTFLIGHT_MAX_ATTRIBUTES_PER_SPAN` | `1024` | Attributes on one span or span event (OpenTelemetry's SDK keeps 128 by default) |
| `AGENTFLIGHT_MAX_EVENTS_PER_SPAN` | `1024` | Events on one span (OpenTelemetry's SDK keeps 128 by default) |

A full SDK batch of payload-heavy spans can be bigger than 16 MiB. When the server answers
`413`, the SDK's exporter splits the batch in half and retries each half, so only spans
over the cap on their own are dropped, with one warning per export.

Splitting is capped at `max_export_attempts` HTTP requests per export (default `32`, set
it with `configure(max_export_attempts=...)`), and the first failure that isn't a `413`
(a timeout, a transport error, a 5xx, rejected credentials) stops the export: the halves
not yet sent are dropped (or spooled, with the [on-disk spool](#on-disk-spool-opt-in))
instead of being tried against a server that is already failing. Isolating one oversized span in a full 512-span batch takes 19 requests.

Worst case for one export: a server that is down or hanging costs one `timeout` (5 s by
default), since the first failure ends the export. Only a server that keeps answering
`413` slowly can make an export take up to `max_export_attempts` × `timeout`. Replaying
the spool is part of the same export and shares its attempt cap, so it doesn't change
these bounds. With
`batch=True` (the default) exports run on a background thread; `flush()` and
`shutdown()` stop waiting at their own timeouts (see [Failure isolation](#failure-isolation)).
With `batch=False` every span is exported on its own as it ends, so there is nothing to
split and a span end blocks for at most one `timeout`.

Spans with attribute values that can't be stored or read back are refused one span at a
time. `POST /v1/spans` stores the rest of the batch and answers `202`, with the refused
spans counted in `rejected` and named in `error_message` (index, span id, attribute key;
never a value); the SDK logs them once and neither retries nor spools them. `POST
/v1/traces` counts them in `partial_success`, and an import refuses the run. The values: a lone
UTF-16 surrogate (`"\ud800"` with no pair, which isn't valid Unicode) in an attribute or
span event attribute key or value, or a structured value nested more than 100 levels deep
(`[]` is one level). OTLP bodies can't carry a lone surrogate at all (protobuf strings are
UTF-8; an OTLP JSON body holding one is a `400`). A payload *string* whose JSON text
would decode to a lone surrogate (`'{"q": "\\ud800"}'`) or nest more than 100 levels is
valid text and is stored; the API returns it as the stored string instead of decoding it.

Span, span event and attribute names are limited to 255 characters (`422` above that). If
you turn off the SDK's payload cap (`max_attr_chars=None`), raise
`AGENTFLIGHT_MAX_ATTRIBUTE_CHARS` too, or large payloads will be rejected.

## Retention and deletion

| Setting | Default |
| --- | --- |
| `AGENTFLIGHT_RETENTION_ENABLED` | `true` |
| `AGENTFLIGHT_RETENTION_DAYS` | `30` |
| `AGENTFLIGHT_CLEANUP_INTERVAL_HOURS` | `24` |

```bash
agentflight-server cleanup --dry-run    # count runs older than the retention period
agentflight-server cleanup              # delete them (and all their events)
agentflight-server cleanup --days 7     # one-off override
agentflight-server cleanup --loop       # repeat every CLEANUP_INTERVAL_HOURS (Compose runs this)
```

A run's age is measured from when it ended, or from when it started if it never finished.
Runs with no timestamps are kept. `DELETE /v1/runs/{id}` (which needs the `delete`
permission) removes a single run with all its events, including the messages and tool
payloads stored on them.

## Export

`agentflight-server export` writes stored runs to a bundle: a versioned JSONL file
(`*.afb.jsonl`, or gzipped `*.afb.jsonl.gz`), one JSON object per line.
[Import](#import) reads it into another server, including SQLite to Postgres and back.

> **The bundle format (`schema_version: 1`) is stable from 0.4.0.** Bundles written by
> 0.4.0 are read by every later 0.x release; any change to the format comes with a new
> `schema_version`, and version 1 keeps being read. Real v1 bundles are committed as test
> fixtures (`tests/fixtures/bundle-v1.jsonl` and `.jsonl.gz`), and a test checks that they
> import with the same `content_sha256` values on SQLite and Postgres.

```bash
agentflight-server export RUN_ID -o run.afb.jsonl              # one run (or several ids)
agentflight-server export --name checkout --since 2026-11-01 -o runs.afb.jsonl.gz
agentflight-server export RUN_ID --with-children --with-replay-source -o bundle.afb.jsonl
agentflight-server export RUN_ID --redaction-file policy.toml -o shareable.afb.jsonl
```

Like `cleanup`, it works directly on `AGENTFLIGHT_DATABASE_URL` (or `--url`), and refuses a
database that isn't migrated to the current revision. Output goes to stdout unless `-o` is
given; a file is written as `FILE.partial` and renamed when complete. Exit 0, or 2 on an
error.

- **Picking runs:** run ids, or the run list filters: `--status`, `--name`, `--model`,
  `--tool`, `--meta key:value`, `--has-parent`/`--no-parent`, and `--since`/`--until`.
  These two filter on the **run's start time** (the run span's start, or the earliest span
  if no run span arrived): `--since` is inclusive (started at or after), `--until`
  exclusive (started before). They take Unix nanoseconds or ISO 8601 (UTC unless it has
  an offset). Matching runs are exported newest first.
- **Linked runs** are included only when asked for. `--with-children` adds sub-agent runs,
  following `parent_run_id` down through every level. `--with-replay-source` adds the run
  a replay or fork came from (`agentflight.replay.source_run`), and that run's source,
  and so on. **Together**, both links are followed from every run added, until nothing new
  turns up: a replay's source brings its sub-agent runs, and a sub-agent run that is a
  replay brings its source. Cycles are safe. A linked run that isn't stored is skipped,
  and the link stays a dangling id; a bundle with such a link is valid.
- **Caps:** the CLI exports at most **1,000** runs by default (`--max-runs`); the HTTP API
  at most **500** (`AGENTFLIGHT_MAX_EXPORT_RUNS`, below), since a large export over HTTP
  ties up a server worker. If the filters match more than `--max-runs` runs, the export is
  refused with the number that matched and the flag to raise. Runs added by
  `--with-children`/`--with-replay-source` count toward the cap; run ids given
  explicitly don't, but the linked runs they bring in do.
- **What's in it:** a header (`schema_version: 1`, a `bundle_id`, the AgentFlight version,
  the source database's dialect and revision, and the export policy if any), then each
  run line followed by all its events in start order, then an end record with the run and
  event counts and a sha256 of everything before it.
- **Values exactly as stored:** payloads stay JSON strings, and `agentflight.redacted`
  and `agentflight.truncated` are kept. Derived data (event columns such as `model`, and
  run totals) is left out; the importer recomputes it.
- **Checksums:** each run line has `content_sha256`, over the run and its events as
  written to the file (after any export-time redaction), as canonical JSON: sorted keys,
  and every integral float written as an integer (`2.0` as `2`, `1e20` as
  `100000000000000000000`, `-0.0` as `0`; NaN and Infinity are refused). It leaves out
  `last_seen_ns` and the five import provenance attributes (`agentflight.import.bundle_id`,
  `imported_at_ns`, `original_run_id`, `original_parent_run_id`,
  `original_replay_source_run`; no other). So it is the same whether the
  run is stored in SQLite or Postgres. (Postgres keeps JSON numbers as exact decimals, so
  a very large float, say `1e20`, comes back as the integer `100000000000000000000`
  after a move between the two; the value is equal and the hash is the same.) The
  checksums catch corruption and truncation, not tampering: bundles are not signed.
- **Redaction:** what was redacted at ingest is exported as its marker; the server never
  had the original. A policy is **not** applied to older runs by default. With
  `--redaction-file` (or `apply_policy=true` on the API, using the server's policy) it is
  applied to the exported copy only, the database is not changed, its report is merged
  into each event's `agentflight.redacted`, and the header records the rule names and the
  policy file's sha256 (never the patterns). In `reject` mode a span that can't be
  redacted stops the export, and the error names the run, span and attribute, never the
  value.
- **Consistency while the server records:** each run is read twice, once to count and hash
  it (its run line comes first) and once to write it, both inside **one read transaction
  per run** (`REPEATABLE READ` on Postgres, `BEGIN` on SQLite), so the count and hashes
  always match the events written, and a run still being recorded is exported as it was
  when its read began. There is no transaction across the whole export. The run's lines
  are spooled and sent after its transaction ends, so a slow client or disk never holds
  one open. On SQLite in WAL mode (the default) recording goes on while a run is read; on
  one machine, ingest kept working (max 80 ms per batch) during the 7.8 s read of a
  100,000-span, 327 MiB run. With a rollback journal (`AGENTFLIGHT_SQLITE_JOURNAL_MODE=delete`)
  every write waits for that read, and writes failed after SQLite's 5 s busy timeout
  ([benchmark](docs/benchmarks/export-ingest-2026-11-29.md)).
- **The spool** holds a run's event lines as stored, so possibly unredacted: in memory up
  to 8 MiB, then in a temporary file in `TMPDIR`, created owner-only (`0600`) and, on
  Linux and macOS, without a name (unlinked as it is created), so no other process can
  open it, and it is gone when the run has been sent, when the export stops or the client
  disconnects, and when the process dies, crash included; nothing is left to clean up at
  startup. (On Windows it is a named file deleted when closed.) A run whose lines exceed
  `AGENTFLIGHT_MAX_EXPORT_SPOOL_BYTES` (default 1 GiB; CLI `--max-spool-bytes`) stops the
  export with an error naming the cap.
- **Streaming:** events are read in chunks of 500 (a server-side cursor on Postgres), so
  memory doesn't grow with a run or the bundle beyond the spool.

Over HTTP: `GET /v1/runs/{id}/export` and `GET /v1/export` (same filters as `GET /v1/runs`,
every matching run) stream the same bundle, `Content-Type: application/x-ndjson` (or
`application/gzip` with `gzip=true`) and `Content-Disposition: attachment;
filename="agentflight-<run id>.afb.jsonl"` (`agentflight-export.afb.jsonl` for
`/v1/export`; `.gz` added when gzipped), with `with_children`, `with_replay_source` and
`apply_policy`. When more than `AGENTFLIGHT_MAX_EXPORT_RUNS` (default 500) runs would be
exported (matching runs plus linked runs; for a single run, its linked runs), the answer
is `413` with the counts, before anything is streamed. If an export fails once streaming
has started, the connection is closed without the end of the chunked body, so a client
sees an incomplete transfer (and the bundle has no end record), never a clean ending.

| Setting | Default | Limit |
| --- | --- | --- |
| `AGENTFLIGHT_MAX_EXPORT_RUNS` | `500` | Runs one export over HTTP may write, linked runs included (the CLI's `--max-runs` defaults to `1000`) |
| `AGENTFLIGHT_MAX_EXPORT_SPOOL_BYTES` | `1073741824` (1 GiB) | Largest run (bytes of event lines) an export spools to a temporary file, HTTP and CLI (`--max-spool-bytes`) |

## Import

`agentflight-server import` reads a bundle into the database, and `POST /v1/import` does
the same over HTTP for smaller bundles:

```bash
agentflight-server import runs.afb.jsonl.gz                     # into AGENTFLIGHT_DATABASE_URL
agentflight-server import runs.afb.jsonl --url postgresql+psycopg://...   # SQLite -> Postgres
agentflight-server import runs.afb.jsonl --dry-run              # report only, write nothing
cat runs.afb.jsonl | agentflight-server import -                 # stdin
curl -H "Authorization: Bearer $KEY" --data-binary @runs.afb.jsonl.gz \
  "http://localhost:8000/v1/import?dry_run=true"
```

Like `export`, the CLI works directly on the database and refuses one that isn't migrated
to the current revision. It prints one line per run (`status run_id [-> stored id] (N
events): reason`) and a summary on stderr. Exit **0** when every run is stored (imported,
unchanged, remapped or replaced), **1** when some run isn't (a conflict, a refused or
failed run), **2** when the bundle is refused and nothing was written. Over HTTP the same
report comes back as JSON: `200` when every run is stored, `409` when some run isn't,
`400`/`413` when the bundle is refused.

- **Permission:** `POST /v1/import` needs the **`import`** permission. `ingest` isn't
  enough (an import keeps the bundle's redaction map and run fields, which ingest never
  trusts), so a leaked recorder key can't import. `on_conflict=replace` needs `delete`
  too (`403` without it). The all-permission `AGENTFLIGHT_API_KEY` has both.
- **Checked whole, then written run by run.** The bundle is read once, writing nothing:
  the caps, the format, an unknown (newer) `schema_version`, every run's
  `content_sha256` and the file's `sha256`, and every event against the server's
  [ingest limits](#ingest-limits). A truncated, corrupt, too large or newer bundle is
  refused and **nothing is written**. Then it is read again and each run is written in
  **its own transaction**, committed only after the stored copy has been read back and
  its hash matches. `--atomic` (`atomic=true`) puts the whole bundle in one transaction
  instead: all runs or none (for small bundles).
- **Nothing derived is trusted.** Event columns (model, tokens, cost, ...) and run totals
  are recomputed from the events, as ingest does. The run's name, status, root span,
  start and end time, metadata, dropped spans and parent run are derived from its events
  too, and **those values are stored**. Where the run line disagrees (a status that
  depended on time, such as `abandoned`, a run from a version that derived it
  differently, an edited bundle), the run is still imported, and the report lists each
  difference under the run's `adjustments` (`field`, `bundle`, `recomputed`; the CLI
  names the fields). The hashes catch corruption either way. `last_seen_ns` is kept
  (clamped to now), so an abandoned run stays abandoned.
- **The server's redaction policy applies**, as at ingest, with the reports merged into
  the bundle's `agentflight.redacted` map; under `reject`, a run with a rejected span is
  refused whole. The run's hash is taken **after** the policy, so importing the same
  bundle twice under a policy gives `unchanged`, not a conflict.
- **Same run id already stored** (`--on-conflict`, `on_conflict=`):
  - `skip-identical` (default): identical content is `unchanged`; different content is a
    `conflict`, not written, with both hashes and each side's status, `last_seen_ns` and
    event count in the reason (usually a run exported while still running). Over HTTP
    those details are only for a key that also has `read`; an import-only key gets the
    reason `stored with different content`, and a span-id refusal says "another run"
    instead of naming it (the CLI, which works on the database, always gets the details).
    Nothing picks a "newer" copy for you.
  - `replace`: the bundle's copy replaces the stored run, in one transaction.
  - `remap`: every run of the bundle gets a new id, and links between them (parent run,
    replay source) are rewritten. The new id is deterministic, keyed on the run's id and
    its `content_sha256` in the bundle, **not on the bundle**: `sha256("agentflight-import:"
    + id + ":" + content_sha256)[:32]`. So the same run with the same content gets the same
    id from any bundle: exported twice into two bundles and imported twice with `remap`,
    it is one copy (the second import is `unchanged`). A run whose content changed in
    between (it kept recording, or was exported with a different `--redaction-file`)
    gets a different id: **a second copy**, by design, since remap keeps both.
    A parent run or replay source that **isn't in the bundle** is not kept as a link:
    the old id could name an unrelated run in this database. It is removed from the
    copy (`agentflight.run.parent_run_id`, `agentflight.replay.source_run`; the run has no
    parent and no replay source here) and the bundle's value is kept in
    `agentflight.import.original_parent_run_id` or
    `agentflight.import.original_replay_source_run`, only if it is a well-formed run id
    (32 lowercase hex characters; these keys are never redacted, so any other value is
    dropped with the link). The rest of the record
    (`agentflight.run.parent_span_id`, `agentflight.replay.mode`, steps) is kept as it is.
  - `fail`: stop at the first run id that is already stored (even an identical one).
- **Span ids:** the database would store the same span id under two runs, but import
  refuses a run whose span id is already stored under another run, unless that run is a
  copy of the same run (a remapped copy and its original) **and** the stored span is the
  same span: same parent span, kind, name and start time. (Which run a bundle's run is
  a copy of comes from the bundle, which can name any run id; the span check stops it
  from reusing a stored run's span ids for other spans. A copy that kept recording keeps
  its earlier spans as they were, so it passes.) It never overwrites or merges events. The check runs in the run's write transaction, after its events are inserted
  and before the commit: on SQLite that transaction holds the write lock, and on
  Postgres imports take an advisory lock, so no other import can slip a span in between.
- **Links to runs that aren't in the bundle or the database are kept** as dangling ids, as
  at ingest, except with `remap` (above).
- **Provenance:** the run span (or the first event, for a run without one) gets
  `agentflight.import.bundle_id` and `agentflight.import.imported_at_ns`, and remapped
  runs `agentflight.import.original_run_id` (and, for a cleared external link,
  `original_parent_run_id` / `original_replay_source_run`). These five keys are
  protected from redaction and left out of `content_sha256` (only these five; any other
  attribute counts), so an imported run exports with the same hash. Any `agentflight.import.*` in
  the bundle is discarded and the import writes its own, and ingest (`/v1/spans`, OTLP)
  strips client-sent `agentflight.import.*` attributes, so only the importer writes them.
- **Postgres can't store NUL characters** (`\u0000`) in JSON: a run that has one is
  refused with the span and attribute named, before anything is written for it.
- **Caps, checked while reading, before any work:** decompressed bytes
  (`AGENTFLIGHT_MAX_IMPORT_BYTES` 128 MiB over HTTP, `--max-bytes` 4 GiB on the CLI), runs
  (`AGENTFLIGHT_MAX_IMPORT_RUNS` 500 over HTTP, `--max-runs` 1,000 on the CLI), and
  `AGENTFLIGHT_MAX_BODY_BYTES` for each line (and for the compressed HTTP body), so a gzip
  bomb stops at the cap. Input that can't be read twice (stdin, the HTTP body) is copied to
  an owner-only, unnamed temporary file first.
- **SQLite has one writer at a time** (WAL too), and each run is written in one
  transaction, so ingest waits while a run is written. **The risk is the size of the
  largest single run**, not of the bundle: the lock is taken and released per run (a
  bundle of many small runs lets ingest in between them). On one machine a run held it
  about 18 ms per MiB: 3.0 s for a 50,000-span run, 6.2 s for a 100,000-span run (327
  MiB), and with the 5 s busy timeout 2 of about 2,000 ingest requests sent during that
  import failed (`docs/benchmarks/import-sqlite-2026-11-29.md`; measured before ingest
  answered `503`). So the HTTP cap is 128 MiB (no run over HTTP can be larger), and
  **import very large runs into SQLite with the server stopped**, or use Postgres.
  `--atomic` holds the lock for the whole bundle.
- **A write that waits out SQLite's busy timeout gets `503` with `Retry-After`** (not
  `500`), on ingest and every other endpoint, so OTLP exporters retry and the SDK spools
  the spans when it has a spool (without one it drops them, see
  [What the SDK does with a `503`](#what-the-sdk-does-with-a-503)).
- **One import at a time** per server process: a second `POST /v1/import` while one runs
  gets `429` with `Retry-After`. The lock is taken only once the whole body has been
  received into the spill file (written from a worker thread, not the event loop), so a
  slow or stalled upload never blocks another import; the `429` comes after the upload.
  An aborted or over-cap upload closes (removes) its spill file and never takes the lock.
- **Malformed input is refused, never a crash:** a bundle line nested more than 128
  levels deep (checked before it is parsed) or holding a lone UTF-16 surrogate is a
  `400` ("import refused, nothing written"), like any other malformed bundle.

| Setting | Default | Limit |
| --- | --- | --- |
| `AGENTFLIGHT_MAX_IMPORT_BYTES` | `134217728` (128 MiB) | Decompressed bytes of one bundle over HTTP (CLI: `--max-bytes`, default 4 GiB) |
| `AGENTFLIGHT_MAX_IMPORT_RUNS` | `500` | Runs in one bundle over HTTP (CLI: `--max-runs`, default 1,000) |

## HTTP API

The API is versioned by its `/v1` prefix. From 0.1.0 on, `/v1` only changes in ways
that don't break clients (new endpoints, optional fields, new response fields; clients
should ignore fields they don't know); a breaking change would mean `/v2`, served next to
`/v1` for a while. The full policy is in the
[changelog](https://github.com/shupandee/agentflight/blob/main/CHANGELOG.md#http-api-versioning).

| Method | Path | Permission | Description |
| --- | --- | --- | --- |
| `POST` | `/v1/spans` | ingest | Ingest a batch of spans (`{"spans": [...]}`). `202` with `accepted` (spans stored), `runs`, `rejected`/`error_message` (spans not stored by [server-side redaction](#server-side-redaction-opt-in) in `reject` mode), and `stripped_attributes` (client-sent `agentflight.import.*` attributes removed; only the [importer](#import) writes them). `503` with `Retry-After` when SQLite is locked by another write, or when the batch kept colliding with concurrent batches for the same run (rolled back, nothing stored; rare, since such batches normally wait for each other) |
| `POST` | `/v1/traces` | ingest | [OTLP/HTTP](#otlp-ingest-any-opentelemetry-agent) trace export (protobuf or JSON, optionally gzip) |
| `GET` | `/v1/runs` | read | List runs, newest first, with token/cost/error totals. Paging: `limit` (1-500, default 50), `offset`. Filters (all must match): `status` (`running`, `ok`, `error`, `unknown`, `abandoned`), `name` (case-insensitive substring), `since_ns`/`until_ns` (run start, Unix ns), `has_errors`, `model`, `tool` (exact), `meta=key:value` (string metadata values, exact; up to 5), `parent_run_id` (the runs that run started), `has_parent` (`true`: only sub-agent runs, `false`: only top-level runs) |
| `GET` | `/v1/runs/{run_id}` | read | One run with its events ordered by start time. Every event with payloads by default (what replay uses). `events_limit` (1-1000) and `events_offset` page the events; `payloads=false` leaves recorded payloads (messages, outputs, args, stack traces) out and lists them in each event's `omitted` |
| `GET` | `/v1/runs/{run_id}/events/{span_id}` | read | One event with all of its payloads |
| `GET` | `/v1/runs/{run_id}/agents` | read | The run's [agents](#agents) as a tree with roll-ups (`agents`: boxes of type `root`, `agent`, `node`, `pending`, `run`, in tree order with `depth` and `parent`; inclusive totals at the top level of each box, own totals in `own`, `share` / `own_share` of the run's tokens). `all_nodes=true` adds plain nodes; `sort` (`start`, `tokens` = own tokens, `errors`) orders siblings. `404` for an unknown or malformed id, `413` above `AGENTFLIGHT_MAX_AGENT_VIEW_SPANS` |
| `GET` | `/v1/runs/{base_id}/diff/{head_id}` | read | [Compare two runs](#comparing-runs) (`RunDiff.to_dict()`). `payload_diffs=false` skips text diffs. `404` for an unknown or malformed id, `413` over `AGENTFLIGHT_MAX_DIFF_SPANS`/`AGENTFLIGHT_MAX_DIFF_CHARS`, `429` with `Retry-After` when `AGENTFLIGHT_MAX_CONCURRENT_DIFFS` diffs are running, `503` if the diff worker died |
| `GET` | `/v1/runs/{run_id}/export` | read | The run as an [AgentFlight bundle](#export) (`application/x-ndjson`, `Content-Disposition` filename `agentflight-<id>.afb.jsonl`). `with_children`, `with_replay_source` add linked runs; `apply_policy=true` applies the server's redaction policy to the exported copy (`400` without one); `gzip=true` gzips it. `404` for an unknown or malformed id; `413` if the linked runs are more than `AGENTFLIGHT_MAX_EXPORT_RUNS` |
| `GET` | `/v1/export` | read | Every run `GET /v1/runs` would list with the same filters, as one bundle; same options as above. `413` before streaming when more than `AGENTFLIGHT_MAX_EXPORT_RUNS` runs (linked runs included) would be exported |
| `POST` | `/v1/import` | import | [Import a bundle](#import) (body: NDJSON or gzip). `on_conflict` (`skip-identical`, `remap`, `replace` (needs delete too), `fail`), `dry_run`, `atomic`. `200` with the per-run report when every run is stored, `409` with it when some run isn't, `400` for a malformed, truncated, corrupt or newer bundle (including a line nested more than 128 levels or holding a lone surrogate) and `413` over a cap (nothing written), `429` with `Retry-After` while another import runs (checked after the body is received) |
| `DELETE` | `/v1/runs/{run_id}` | delete | Delete a run and all its events (`204`, or `404`) |
| `GET` | `/health` | none | Liveness (process is up) |
| `GET` | `/ready` | none | Readiness (database reachable and migrated); 503 otherwise |

Interactive docs at `/docs` when the server is running.

#### What the SDK does with a `503`

The Python SDK's exporter treats a `503` like every failure that may clear up (any `5xx`,
`408`, `425`, `429`, a timeout or connection error). It doesn't read `Retry-After` and
doesn't retry within the export:

- **With a spool** (`spool_dir` / `AGENTFLIGHT_SPOOL_DIR`, needs `batch=True`): the spans
  are written to the spool and sent again, oldest first, at the start of every later
  export, within the spool's size and age caps ([On-disk spool](#on-disk-spool-opt-in)).
- **Without a spool: the batch is dropped.** It is not kept in memory and not sent again
  by the next export; OpenTelemetry's batch processor has already taken it off its queue
  and doesn't retry a failed export. Each export that loses spans logs one warning on the
  `agentflight.exporter` logger, `agentflight: failed to export N of M spans: HTTP 503
  from <url>`. Those spans are not counted in `dropped_spans()` or the run span's
  `agentflight.run.dropped_spans`, which count only spans dropped from a full queue.

**Clients without the SDK:** a hook or script that posts JSON to `/v1/spans` directly is
fine, but it has **no local spool**: events it sends while the server is down (connection
refused, timeouts, `503`) are lost unless it keeps and resends them itself. Resending is
safe: spans are upserted by span id. Use the Python SDK with
`spool_dir` (`AGENTFLIGHT_SPOOL_DIR`) when you need events kept on disk until the server
is back. Don't resend a `422` (the request itself is malformed) or a `413` as is; a span
counted in `rejected` in a `202` was refused for good.

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
ruff check . && ruff format --check . && mypy && pytest
```

Tests use in-memory SQLite by default. Set `AGENTFLIGHT_TEST_DATABASE_URL` to a Postgres URL
to run the same suite against Postgres (CI does both).

CI also runs a Compose smoke test with a throwaway key. It brings up
`docker compose up --wait` (Postgres plus the server, both health-checked) and runs
`scripts/compose_smoke.py`, which checks that:

- missing and wrong keys are rejected;
- the toy agent still completes with a wrong key, and nothing is persisted;
- with the right key, both runs are persisted with the expected token, cost and
  (deduplicated) error totals;
- `DELETE` removes a run.

The stack is always torn down afterwards. You can run it locally:

```bash
export AGENTFLIGHT_API_KEY=$(openssl rand -hex 32)
docker compose up --build --wait
python scripts/compose_smoke.py
docker compose down --volumes
```

## Roadmap

- **Week 1: recorder core** (done): SDK, OTel exporter, ingest API, Postgres storage,
  migrations, failure isolation, tests, CI with a Compose smoke test.
- **Week 2: hardening** (done): logical failure counting, API-key auth, retention
  and deletion, explicit truncation and redaction.
- **Week 3: integrations** (done): OpenAI-style chat client instrumentation (usage from
  responses) and a LangGraph callback handler, with offline example agents.
  Deferred: streaming and the Responses API.
- **Week 4: deterministic replay and fork** (done): replay a recorded run from
  cached model and tool outputs with divergence checks, and fork from any step with a
  substituted output or changed code. Deferred: LangGraph replay, streamed calls,
  parallel tool calls, a server-side "fork" endpoint.
- **Week 5: viewer and scale fixes** (this branch): a server-rendered viewer (Jinja2 and
  htmx, no JavaScript build) with a run list, filters, a run timeline and highlighted
  failures; stored run totals and batched ingest; run filters and paged run detail;
  scoped API keys; `unknown` and `abandoned` run status; ingest limits; redacted
  exception messages and stack traces.
- **Week 6: tree, screenshots, overhead** (done): an indented span tree in the viewer,
  README screenshots, an overhead benchmark with its method and measured results, and a
  cap on the exporter's split-on-413 requests.
- **Week 7: dropped spans** (done): spans dropped from a full export queue are counted
  and shown as incomplete recordings in the viewer and replay; a configurable queue size;
  split retries stop at the first non-413 failure; bounded `flush()` and `shutdown()`;
  benchmark repeats and the server's ingest rate.
- **0.1.0** (released): run spans on their own lane, so runs with drops still close;
  release packaging (migrations in the package, `agentflight-server migrate`, a Trusted
  Publishing release workflow) and the `/v1` stability policy; an opt-in on-disk spool
  for failed exports.
- **0.2.0** (released): OTLP ingest: `POST /v1/traces` takes OTLP/HTTP (protobuf or JSON,
  gzip) from any OpenTelemetry-instrumented agent or Collector, with `gen_ai.*` mapped to
  models, tokens and tools. Deferred: OTLP over gRPC, replay from `gen_ai` content,
  cost from a price table.
- **0.3.0** (released): **sub-agent runs**: `parent_run_id` links runs started inside other runs
  across the SDK, `/v1/spans`, OTLP, the viewer and the run filters.
- **Server-side redaction** (0.3.0): a TOML policy the server applies to every span
  from `/v1/spans` and OTLP before storing it, with replay refusing redacted inputs.
  Deferred: a viewer badge and run-level count, a command to redact stored runs.
- **0.4.0** (released): run diff (the Python API, the HTTP endpoint, the viewer page and
  the `agentflight diff` command), export and import (`agentflight-server export|import`,
  the HTTP endpoints) with a stable bundle format (`schema_version: 1`); Apache-2.0.
- **0.4.1:** `AGENTFLIGHT_ADMIN_API_KEY` for the server (client and server on one
  machine), `AGENTFLIGHT_PARENT_RUN`, run-at-login recipes. Deferred to 0.5.0: separate
  cached-read and cache-write token counts, so `tokens_in` isn't read as new input or cost.
- **0.5.0:** the Agents tab and `GET /v1/runs/{id}/agents` (`agentflight.agent()`,
  LangGraph `agent_nodes`), cached-read / cache-write token counts
  (`tokens_in` stays the total input; migration `0006`). Deferred to 0.5.1: an agents
  summary in `/ui/diff`; `gen_ai.usage.cache_*` from OTLP.
- **Next:** shape-validate `agentflight.replay.*`
  attributes at ingest (ids and bounded values only), so they can't carry free text past
  redaction. Deferred: a client-side `agentflight export|import --endpoint`, a demo,
  overhead
  on real (non-synthetic) agent runs, and a rate limit on failed keys.

## License

Copyright 2026 Deepanshu Gautam

Licensed under the Apache License, Version 2.0 (the "License"); see [LICENSE](LICENSE)
for the full text, or <https://www.apache.org/licenses/LICENSE-2.0>.
