> ## Documentation Index
> Fetch the complete documentation index at: https://docs.magpiedb.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Magpie is a trace store for AI agents, used as a library (crate `magpiedb`, npm `magpiedb`, PyPI `magpiedb`) or as `magpie-server`, which takes OpenTelemetry (OTLP over HTTP on 127.0.0.1:4318 and gRPC on 127.0.0.1:4317 by default).
> Use only the commands, flags, routes and JSON shapes that these pages show. Do not guess a flag or a query field: if a page does not show it, say that the docs do not show it.
> Packages and server binaries are not published yet: build from source, as the quick start shows. Check the status note on the introduction page before you suggest `cargo add`, `npm install` or `pip install`.
> Only one process may write to a store folder at a time. For many apps, send traces to one `magpie-server`.

# HTTP API

> Every HTTP route of magpie-server: OTLP ingest, the query API, export, scores, deletes, storage, mask counts and health, with request and answer shapes and errors.

`magpie-server` has two doors. OTLP/HTTP and the query API are on `--http-addr` (default `127.0.0.1:4318`). OTLP/gRPC is on `--grpc-addr` (default `127.0.0.1:4317`). See [the server flags](https://docs.magpiedb.com/reference/server.md).

## OTLP ingest

`POST /v1/traces` takes OTLP/HTTP. The gRPC port takes OTLP/gRPC. A key needs the `write` right.

## OTLP behavior

* Bodies: protobuf (`application/x-protobuf`) and JSON (`application/json`), plain or gzip. gRPC accepts gzip.
* The response has the content type of the request. A span that cannot be stored is refused alone: the response is `200` with `partialSuccess` (`rejectedSpans`, `errorMessage`), and the other spans are stored. That is a span with bad ids (not 16 or 8 bytes, all zero; in JSON also an id that is not hex), no start time, an end before its start, and in OTLP/JSON any value that is wrong for its field (a time that is no whole number from 0 to 2^64-1, an `intValue` that is no 64-bit integer, a `bytesValue` that is not base64, an item of `attributes` that is not an object, ...; D-ur-2, D-ur-3). The message names the span by its number in the request and the field by its path (`span 7: attributes[1].value.intValue is not a whole number of 64 bits ...`). The message does not give the value. A wrong value of a resource or a scope refuses the spans of that resource or scope. The whole request is refused (`400`) only when it is not JSON, or when its frame is not OTLP (`resourceSpans`, `scopeSpans` or `spans` that is not a list of objects).
* OTLP/JSON reads values as the proto3 JSON mapping writes them: `"doubleValue": "NaN"`, `"Infinity"` and `"-Infinity"` are those doubles (the Go Collector writes them so; stored as the text `"NaN"`, as over protobuf), a number may come as a text, `kind` and `status.code` may be the names of their values (`"SPAN_KIND_CLIENT"`), and `null` is the default of any field.
* A text cut inside an emoji: JSON writers (`JSON.stringify`, Python's `json.dumps`) write the half of the UTF-16 surrogate pair that is left as an escape (`"...\ud83d"`). Each such half is stored as U+FFFD, what the protobuf exporters send for the same text, and the response is `200` with `partialSuccess`, `rejectedSpans` `0` and the count in `errorMessage` (the OTLP spec allows a warning so). The same holds for every JSON the server reads (the query API, `import`) and for the Node and Python packages.
* The depth rule. A span has at most 64 levels, a filter at most 32. In `attributes` and `events` of a span, a list or an object is one level, and what is in it is one level deeper. In a filter, of a query or of a delete, each `and`, `or`, `not` and each span condition of a trace filter (`root`, `anySpan`) is one level deeper than the filter it is in, and a list or an object in a value of `attributes` counts on from there. A deeper span or filter is refused. The server answers `400` with the reason, for a query (`/v1/search`, `/v1/count`, `/v1/traces/find`, `/v1/aggregate`, `/v1/scores/aggregate`, `/v1/export`) and for a delete (`/v1/traces/delete`). A text that is deeper than the reader of JSON reads (128 levels of JSON; a `not` is one of them, an `and` or an `or` is two) is a `400` too, with the reason of the reader. An OTLP body cannot bring a span that deep: its own readers stop a deeper value first (protobuf at 100 levels of its own, where a list in a list is two; JSON at 128, where it is three), also with `400`; over gRPC the answer is `INTERNAL`, from the gRPC library, before the server sees the body.
* A body that cannot be decoded: `400` with a `google.rpc.Status` body. Do not retry. Unknown content type or encoding: `415`.
* The store cannot write: `503`, gRPC `UNAVAILABLE`. OTLP clients retry these. On a disk that is nearly full the text starts with `io: DISK_FULL:`; the export passes when there is room again, with no restart (section [A full disk](https://docs.magpiedb.com/reference/server.md#a-full-disk)).
* With API keys: no key or an unknown one: `401` (gRPC `UNAUTHENTICATED`); a key without the `write` right, or an `x-magpie-tenant` that is not the key's tenant: `403` (gRPC `PERMISSION_DENIED`). OTLP clients do not retry these.
* Spans are written with `upsert`: a batch that arrives twice (a retry) is stored once.

## Query API

All bodies are JSON. They are the magpiedb types in their JSON shape, the same as in the Node package (`bindings/node/index.d.ts` has the types): field names are the Rust names in camelCase, and `null` is the same as a missing field. Unknown fields are refused, so a typo is a `400` with its place (line and column) and the names the field takes, not a filter that matches everything. `testdata/query-examples.json` has examples with their answers. Every error is `{"error": "message"}` with `400` (bad request), `401` or `403` (API keys, see there), `404` or `500`. An empty body is `{}`.

An error never quotes the request: not a value, a name, a key of an attribute, a text of a filter, a header. The text of a client can be private (a prompt, an email), and an answer also goes to logs and proxies. So a `400` gives a fixed reason, the line and column (or the number of the score or span) and what was expected, and for what it cut out the first 16 hex characters of its SHA-256 and its length: `bad request body: a value of the wrong type, expected u64 at line 1 column 30 (detail sha256=3a8eebab395d1728, 61 bytes)`. The hash can confirm a guess of the text; it cannot give the text back. A refused OTLP span is named by its number in the request (`span 0: traceId must be 16 bytes ...`), not by its name. The rule fails closed: a message of the engine is shown only in a shape the server knows (`src/redact.rs`), with the value cut out (`invalid query: text has no searchable words (detail sha256=…)`); a message it does not know is `refused (a reason that is not shown)` with its hash. A number of the request is a value too (`{"attributes": 987654321012345}` came back before). The gRPC port refuses an unknown `grpc-encoding` itself (`UNIMPLEMENTED`), without quoting it. The same rule holds for the problems of an `import` (its report and its stderr), also with `--mask`. The library (Node, Python, Rust) keeps the full messages: there the caller has the data.

The routes that write (`POST /v1/scores`, `POST /v1/traces/delete`, `POST /v1/purge`) need `Content-Type: application/json`, also with an empty body: else `415`. With curl: `-H 'content-type: application/json'` (`-d` alone sends a form type). A request from a page of another site is refused (`403`, `CROSS_SITE`; D260): every request but `GET`, `HEAD` and `OPTIONS` must have `Sec-Fetch-Site: same-origin` (or `none`) when it has that header, else an `Origin` with the request's own host (`Host`) when it has that header. Browsers send these headers and a page cannot change them; curl, the OpenTelemetry SDKs and other programs send neither, and pass. Why: with no keys, a page of any site that a person on this machine opens could send a POST to `127.0.0.1:4318/v1/traces/delete` (seen: `200`, before this rule). With keys, the key is not sent by a browser by itself, but the rule holds the same. The rule is the one of Go's `http.CrossOriginProtection`. The gRPC port has the same rule (the host is `:authority` there), and it reads a request only with the content type `application/grpc` (also `+proto`): else HTTP `415`. A page can send `text/plain` with any bytes and no preflight; before this rule such a request wrote a span through the gRPC port. A proxy that changes `Host` breaks it only for browsers that send no `Sec-Fetch-Site` (before 2023).

| request | body | response |
| - | - | - |
| `POST /v1/search` | `{filter, sort, limit, cursor, previewChars}` | `{"spans": [{traceId, spanId, startedAt}], "nextCursor": c}` |
| `POST /v1/count` | `{filter}` | `{"count": n}` |
| `POST /v1/traces/find` | `{filter: traceFilter, root: filter, anySpan: [filter], anyScore: [scoreFilter], sort, limit, cursor, previewChars}` | `{"count": n, "traces": [trace], "nextCursor": c}` (`count`: all matches, not only the returned ones) |
| `POST /v1/traces/stats` | `{"query": {filter, root, anySpan, anyScore}, "bars": 49}` | `{"count", "scanned", "complete", "failed", "ended", "durationP50Ms", "durationP95Ms", "inputTokens", "outputTokens", "costNanos", "bucketMs", "from", "to", "buckets": [{at, count, failed}]}`: the numbers of the viewer's summary strip for the traces of a trace query; see below |
| `POST /v1/aggregate` | `{filter, groupBy, thenBy, metrics, percentiles, sort, limit}` | `{"rows": [{key, key2, count, sums, percentiles}]}` |
| `GET /v1/traces/:id` | | `{"spans": [span]}`, or `404` when the trace has no spans |
| `GET /v1/traces/:id/scores` | | `{"scores": [score]}` |
| `GET /v1/traces/:id/spans?limit=n&cursor=c` | | `{"count": n, "spans": [lightSpan], "nextCursor": c}`: the spans of the trace without their text, oldest first (`count`: all spans of the trace) |
| `GET /v1/traces/:id/spans/:spanId` | | `span` (every field), or `404` when there is no such span |
| `POST /v1/export` | `{filter}` | JSON Lines (`application/x-ndjson`): one `span` per line, oldest first. Sent in chunks while it is made |
| `POST /v1/export/scores` | `{from, to}` | JSON Lines: one `score` per line, in no promised order |
| `POST /v1/scores` | `{"scores": [score]}` | `{"written": n}` |
| `POST /v1/scores/aggregate` | `{score: scoreFilter, traces: traceFilter, groupBy, thenBy, percentiles, sort, limit}` | `{"rows": [{key, key2, count, avg, percentiles, labels}]}`: sums of the scores with one name; see below |
| `GET /v1/sessions/:id/scores` | | `{"scores": [score]}`: the scores on the session itself |
| `POST /v1/sessions/find` | `{filter: {userId, from, to}, sort, limit, cursor}` | `{"count": n, "sessions": [session], "nextCursor": c}`, newest first (ties by session id) |
| `GET /v1/sessions/:id` | | `{"session": session, "traces": [trace]}` (every trace, oldest first; for a very large session, page `/v1/traces/find` with `filter.sessionId`), or `404` when no trace has this session id |
| `POST /v1/traces/delete` | one of `{"userId": id}`, `{"sessionId": id}`, `{"traceIds": [id]}`, `{"filter": traceFilter}` | `{"tracesDeleted", "spansDeleted", "scoresDeleted", "segmentsTouched", "segmentsWithDeleted"}`. Deletes whole traces for privacy; see below |
| `POST /v1/purge` | | `{"segmentsRewritten", "docsRewritten", "docsRemoved", "segmentsWithDeleted", "bytesBefore", "bytesAfter"}`. Takes the bytes of deleted data off the disk; see below |
| `GET /v1/storage` | | Where the store is and how big: `{"mode": "local", "spans": n, "traces": n, "diskBytes": n}`, or with `--s3` the uploader's or the reader's state too (section [S3](https://docs.magpiedb.com/reference/server-s3.md)). With tenants: the request's tenant's store |
| `GET /v1/mask` | | `{"enabled", "rules": [{"name", "masked"}], "droppedAttributes"}`: what the mask policy replaced since the store opened. Counts only (section [Masking](https://docs.magpiedb.com/reference/mapping-cost-masking.md#masking)) |
| `GET /healthz` | | `200` `ok` while the server takes writes. `503` with one line of text while it refuses them: `writes are refused: the disk is nearly full` or `writes are refused: the store cannot write` (section [A full disk](https://docs.magpiedb.com/reference/server.md#a-full-disk)). Queries can still answer then. A server that is read-only by its flags says `ok`. |

* `filter` (all set fields must hold, on one span): `text`, `traceId`, `kind`, `model`, `userId`, `sessionId`, `name`, `service`, `environment`, `tag`, `hasError`, `from`, `to` (ms, `from <= startedAt < to`), `rootOnly`, `attributes`, and the tree fields `and`, `or`, `not`.
  * `and: [filter]` (every one holds), `or: [filter]` (at least one holds; an empty list matches nothing), `not: filter` (it does not hold). They hold filters of the same shape and are conditions like the other fields: `{"kind": "tool_call", "or": [{"name": "a"}, {"name": "b"}], "not": {"hasError": true}}` is a tool call named a or b that did not fail. A span with no value for a field does not have that value: `{"not": {"model": "x"}}` also matches the spans with no model. There is no query language as text: a saved view or an alert keeps this JSON.
  * `text`: `{"words": "refund policy"}` (every word, in input or output) or `{"phrase": "refund policy"}` (next to each other). In `words`, a space makes two words free of each other; characters with no space between them are found together, in their order: `e-mail` is `e` next to `mail`, `user@example.com` is that address, and a run of Thai, Korean or Chinese characters is that run.
  * `text` inside a word: `{"contains": "fund pol"}` is the string as you type it for `LIKE '%...%'`. One piece is found anywhere in a word: `und` finds `refund`, `funding`, `REFUNDED`. With a space or a sign in it, the first piece is the end of a word, the last piece is the start of a word, the pieces between are whole words, and all are next to each other: `fund pol` finds `refund policy`. `{"prefix": "refund pol"}`: whole words, and the last one may go on (`refund` finds `refunded`). One character of Thai or Korean finds the runs that have it. It is not a byte-for-byte `LIKE`: signs and spaces are not in the index, so `a-b`, `a b` and `a,b` are the same; a word of 256 bytes or more and the `error` text are not searched. The cost follows the number of different words in the store, not the amount of text: a piece of one or two letters matches most words and is slow. A text of several pieces whose pieces match more than 16,384 different words in one segment answers 400 with a message that says so: make the first or the last piece longer. A phrase of 4,096 positions or more is refused (400): a position is a word, or a word too long to index (256 bytes or more) between two words. A phrase with 64 or more words too long to index in a row between two of its words is refused too (63 are searched). `phrase`, `contains` and `prefix` are one phrase each; in `words` each part between spaces is a phrase of its own, so `words` takes any number of words.
  * `attributes`: exact match, `{"path": value}` or `[["path", value]]`. A dot in a key is a path step, so the flat OpenTelemetry key and a nested object match the same path: `{"gen_ai.tool.name": "lookup_order"}`. Resource attributes are under `resource`: `"resource.host.name"`.
* `traceFilter` (all set fields must hold, on one trace): `traceId`, `userId`, `sessionId`, `name` (of the root span), `hasError`, `from`, `to`, `tag`, `service`, `environment`, the ranges of totals, `root`, `anySpan`, `anyScore`, and `and`, `or`, `not` (trace filters, as in `filter`).
  * Ranges of the totals of the trace: `spanCount`, `errorCount`, `inputTokens`, `outputTokens`, `totalTokens`, `costNanos`, `durationMs`, each `{"min": a, "max": b}` (`a <= value <= b`; each end may be left out). One dollar is `{"costNanos": {"min": 1000000000}}`. The duration is the end of the latest span minus the start of the earliest; a trace with no ended span has none and is in no duration range, so `{"durationMs": {}}` is the traces that have ended a span.
  * `root: filter`: the root span of the trace (`rootSpanId`: the earliest span with no parent, or the earliest span when every span has a parent) meets the filter. `anySpan: [filter]`: for each entry, some span of the trace meets it. `anyScore: [scoreFilter]`: for each entry, some score of the trace meets it. `rootOnly` in `anySpan` asks for some span with no parent; `root` asks for the one root.
  * `root`, `anySpan` and `anyScore` next to `filter` in the request mean the same; they are for the request with no `or` and no `not`. Traces that failed or cost a dollar and have no tool call: `{"filter": {"or": [{"hasError": true}, {"costNanos": {"min": 1000000000}}], "not": {"anySpan": [{"kind": "tool_call"}]}}}`.
  * Cost: `traceId`, `userId`, `sessionId`, `name`, `hasError`, `from`, `to`, `tag`, `service`, `environment`, `root` with only a `name`, and an `anySpan` entry with only `kind`, `model`, `name`, `tag`, `service` or `environment` (or `kind` with `model`, `name` or `hasError: true`, or an `or` of such entries) are one index lookup each. A range of a total and a `not` read one column of the trace summaries. Any other `anySpan` or `root` and every `anyScore` first finds the matching spans or scores, then their traces. `and`, `or` and `not` cost what their parts cost.
* `scoreFilter`: `name` (required), `min`, `max`, `label`, `source`.
* `sort`: `"newest"` (default) or `"oldest"`. Ties: `spanId`, then `traceId` (spans); `traceId` (traces). `limit`: default 50, at most 10000. `limit: 0` with `/v1/traces/find` returns only the count.
* `cursor`: the `nextCursor` of the page before; `nextCursor` is `null` on the last page. A cursor is a position in the sort order (the key of the last row), not a saved result: each page is read as of its own call, and costs about as much as page 1 (no offset). A row whose sort key does not change is returned exactly once, in order, also while writes go on; a new row that sorts before the position (with `"newest"`: newer than page 1) is not returned and does not shift later pages; a new row that sorts after it comes on a later page. A trace whose start moves during the walk (an earlier span arrives) can come twice or not at all. A cursor given with another `sort`, or to another list, is an error, and so is a string that is not a cursor.
* `previewChars`: every row gets `inputPreview` and `outputPreview`: the first `previewChars` characters of each span's `input` and `output` (search); of the root span's `input` and `output` (traces); a root with no input gives the input of the earliest span that has one (start, then span id), a root with no output gives the output of the span that ended last among those that have one (ties: earlier start, then smaller span id). A search row reads its stored span. A trace does not, up to 200 characters: the trace keeps the first 200 characters of both texts in its summary (so do session rows). With more than 200, the stored span of each text that is longer is read. Without it, rows have no such fields.
* `groupBy`: `"all"` (default), `{"field": "traceId" | "kind" | "model" | "userId" | "sessionId" | "name" | "tag"}`, `{"attribute": "user.plan"}`, or `{"time": {"bucketMs": 3600000}}`. `metrics` (exact sums): `"inputTokens"`, `"outputTokens"`, `"totalTokens"`, `"costNanos"`, `"durationMs"`, `"errorCount"` (failed spans). `sums` are in the order of `metrics`.
  * Time buckets start at the Unix epoch (a bucket of a day is a UTC day). Only buckets with a span are returned: a chart fills the others with zero.
  * `{"field": "tag"}`: one group per tag. A span with two tags is in both groups, so the counts and sums of the groups add up to more than the spans. A tag given twice on one span counts once. A span with no tag has the key `null`.
  * `{"attribute": path}`: one group per value at the attribute path, read as in the `attributes` filter (`user.plan` is `{"user": {"plan": ..}}` or the flat key `user.plan`). The key keeps its type: `"1"`, `1` and `true` are three groups (`1.0` is `1`). A span with a list at the path is in the group of each value. A span with no value there (no attributes, no such path, `null`, an object) has the key `null`.
  * `thenBy`: a second key, for a time series per value. `groupBy` must be a time bucket and `thenBy` a field or an attribute; anything else is an error. One row per bucket and value: `key` is the bucket, `key2` the value. Cost per model per hour: `{"groupBy": {"time": {"bucketMs": 3600000}}, "thenBy": {"field": "model"}, "metrics": ["costNanos"]}`. Rows come by bucket (oldest first), and inside a bucket in the order of the series.
  * `percentiles`: `[{"p": 95}, {"p": 99.9, "approx": true}, {"p": 95, "of": "costNanos"}]` (p from 0 to 100, at most 4 decimals). `of`: `"durationMs"` (default), `"costNanos"`, `"totalTokens"`, `"inputTokens"`, `"outputTokens"`. Exact: the nearest-rank rule. `approx`: a sketch, at most 1% off, small memory for any span count. Spans with no value do not count (for the duration: spans that have not ended; for the cost: spans with no cost); a group where none has a value gets `null`. The row has `percentiles` (in the order asked) only when the query asks for some.
  * `sort`: `{"by": "count" | {"sum": i} | {"percentile": i}, "order": "desc" | "asc"}` (default `"desc"`; `i` indexes the row's `sums` or `percentiles`). Ties by key; `null` values last. `limit`: keep that many rows after the sort (default: all). Top 10 users by cost: `{"groupBy": {"field": "userId"}, "metrics": ["costNanos"], "sort": {"by": {"sum": 0}}, "limit": 10}`.
  * `sort` and `limit` with `thenBy` are about the series, not single rows. A series is one value of `thenBy` over all buckets. The series are put in order by their count, sum or percentile over all matching spans (no `sort`: by key), the first `limit` series are kept, and every bucket of a kept series is returned. The 10 users with the highest cost in the whole time range, each with all its days: `{"groupBy": {"time": {"bucketMs": 86400000}}, "thenBy": {"field": "userId"}, "metrics": ["costNanos"], "sort": {"by": {"sum": 0}}, "limit": 10}`.
  * `key`: the value (`"gpt-4o"`; for an attribute also a number, `true` or `false`), the bucket start (`1764000000000`), or `null` (groupBy `"all"`, or spans with no value). Rows by key: `null`, then text, then `true` and `false`, then numbers. `key2` is in the row only with `thenBy`.
  * Cost: with no percentiles, a filter on `kind`, `model` and time only (also as a tree of `and`, `or`, `not`) reads the saved sums, one row per hour, kind and model, and the spans only for the parts of the time range that are not whole hours. The groups that the saved sums can give: `"all"`, kind, model, buckets of whole hours, and buckets of whole hours with `thenBy` kind or model. Every other query visits every matching span: another field, a tag, an attribute, a bucket that is not whole hours, any percentile. A group by attribute also reads, in each part of the store, the list of spans of every value of the path: a path with very many values is slow.
* `trace`: `traceId`, `rootSpanId`, `startedAt`, `endedAt`, `name`, `userId`, `sessionId`, `spanCount`, `errorCount`, `inputTokens`, `outputTokens`, `costNanos`.
* `session`: `sessionId`, `userId`, `startedAt`, `endedAt`, `traceCount`, `spanCount`, `errorCount`, `inputTokens`, `outputTokens`, `costNanos`, `firstTraceId`, `lastTraceId`, `firstInput`, `lastOutput`. A trace's session is the `sessionId` of its root span, or else of its earliest span that has one. Sums are over the session's traces; `startedAt` is its first trace's start; `userId` is of its earliest trace that has one. `firstInput`: the first 200 characters of the input of the first trace (earliest start, ties by `traceId`); `lastOutput`: the same of the output of the last trace (latest start, ties by `traceId` ascending); both by the rule of `previewChars` for traces. Session `filter`: `userId`, `from`, `to` (ms, `from <= session start < to`). `limit: 0` returns only the count.
* `POST /v1/traces/stats` (D-ui-4; the viewer's summary strip): `query` has the conditions of `/v1/traces/find` (its `limit`, `cursor`, `sort` and `previewChars` are not used). The numbers are of the newest `scanned` matching traces, at most 100,000; `complete` is `true` when every match was read, and only then `count` is the number of matching traces (else `null`: counting the rest would be the work the cap avoids, D-ui-9). The numbers: `failed` (traces with a failed span), `ended` (traces with an end), `durationP50Ms` and `durationP95Ms` (end minus start of the trace, nearest rank over the ended traces; `null` when none ended), and the sums `inputTokens`, `outputTokens`, `costNanos`. `buckets`: trace starts per bucket of `bucketMs` (the smallest of 1 s, 5 s, 15 s, 30 s, 1, 2, 5, 10, 15, 30 min, 1, 2, 3, 6, 12 h, 1, 2, 7, 14, 30, 90 days, or whole years, whose buckets, aligned to the Unix epoch, are at most `bars`, 2 to 200, default 48), every bucket from the one of `from` to the one of `to - 1` with the empty ones, oldest first. The window: the query's `filter.from` and `filter.to`; with a `from` and no `to`, `to` is now (the server's clock); with neither, the oldest to the newest read trace. It reads the traces newest first, in time windows that double from one minute back from the newest trace of the store (or from the query's `to` when that is earlier), and in each window it gives every span condition the window's start as its lowest start (no answer changes): the engine's joins and counts cover only the windows read. With more matches than the cap, that is the time from the newest trace back to at most twice the time that holds the newest 100,000 matches, whatever the server's clock; older matches cost nothing.
* Very large traces: `GET /v1/traces/:id` returns every span with its text, which is hundreds of MB for a trace of 100,000 spans. For such a trace, page `/v1/traces/:id/spans` to draw the tree, and get the text of one step with `/v1/traces/:id/spans/:spanId`.
  * `lightSpan`: `spanId`, `parentSpanId`, `name`, `kind`, `model`, `startedAt`, `endedAt`, `hasError` (`status` is `error` or `error` is set), `inputTokens`, `outputTokens`, `cost`: the same names and values as in `span`, and no `input`, `output`, `attributes` or `events`. The order is that of `GET /v1/traces/:id`: `startedAt`, then `spanId`.
  * `limit`: default 50, at most 10000; `limit=0` returns only the count. `cursor`: the `nextCursor` of the page before, as it is (it needs no escaping). A parameter that is not `limit` or `cursor` is a `400`. A trace that is not there is an empty list with `count` 0.
  * Each page reads the time of every span of the trace once, as every list by cursor does: for a whole trace use a large `limit`. All fields come from columns but `parentSpanId`, which is read from the stored span of each row of the page that has a parent.
  * A span that was written twice with the same ids by a client that does not use `upsert` (OTLP always does): `/spans/:spanId` returns the copy that started last.
* Export: `POST /v1/export` returns every span that matches `filter` (the span filter above; `{}` or no body: every span; a time range is `{"filter": {"from": a, "to": b}}`), one JSON object per line, in the shape of `span`. That is the shape the library's `write` takes, so the lines load back into a store.
  * One line per span: a line has no line break inside. JSON escapes the control characters, and U+0085, U+2028 and U+2029 are written as `\u` escapes too, so tools that end a line at them (Node's `readline`, Python's `str.splitlines`) still see one span per line. Spans with one `startedAt` come in no promised order.
  * The body is sent in chunks of whole lines, at most a few MB each (more if one span is bigger), and the next chunk is made only when the one before is on its way: the server holds about three chunks, for a store of any size. A client that goes away stops the export.
  * The export reads the commit that the store shows when the request comes, from start to end: later writes and deletes are not in it. It keeps that commit's files open until it ends, so a merge during a long export cannot free their disk space before.
  * A request that cannot run (unknown field, bad filter) is a `400` before any line. If the export fails after its first chunk, the status is already sent: the connection ends without the end of the body. A body read to its end with no error has every line.
  * `POST /v1/export/scores`: every score, or those with `from <= at < to` (the time of the score, not of its trace). Scores are a second file because a score can come long after its trace; a filter on spans does not pick scores. For the scores of one trace use `GET /v1/traces/:id/scores`.
  * With `curl`: `curl -sN localhost:4318/v1/export -d '{"filter": {"from": 1764000000000, "to": 1764086400000}}' > spans.ndjson`
* Deletes for privacy (`Store::delete_traces` and `Store::purge_deleted` in magpiedb). `POST /v1/traces/delete` removes whole traces: every span, the summary and the scores. `{"userId": id}` is every trace that has a span of that user (a trace with spans of two users goes whole); `{"sessionId": id}` is every trace that has a span of that session; `{"traceIds": [..]}` is those traces; `{"filter": traceFilter}` is every trace that `POST /v1/traces/find` gives for that filter (a filter with no condition is a `400`: it matches every trace). A filter whose text is over the word limit of `contains` and `prefix` is a `400` too (the limit is per segment, so it is asked at the call and again when the delete's turn comes): nothing is deleted, the store takes requests as before, and no later start of the server runs that delete. The answer comes after the commit: from then on no route gives the data, and a crash leaves the store before the delete or after it. A span that arrives after the delete stays, also of the same user. With tenants, a delete is in the store of the request's tenant only; a tenant with no store gets `404`. The bytes of deleted spans stay in the store's files until those files are written again; `segmentsWithDeleted` counts the files. `POST /v1/purge` writes them again now and answers when that is done (minutes on a large store: give the client a long timeout). With `"segmentsWithDeleted": 0` in its answer, no file of the store holds data that was deleted before the call. Both routes need the `write` right.
* Scores for evals. A `score` is on one target: a trace (`traceId`), a span (`traceId` and `spanId`) or a session (`sessionId`, and no `traceId`). `type` is `"number"` (also when it is left out), `"boolean"` (the value is 0 or 1) or `"category"` (it has a `label`; a score with a label and no value is a category). `source` is the kind of giver, `authorId` who gave it, `evalId` the eval that made it (an evaluator and its version, a config, or one run of an experiment), `comment` a comment or the reason of a judge. A score replaces the one with the same target, name, source, author and eval id. A score that breaks a rule is a `400`, and nothing of its request is written. `GET /v1/sessions/:id/scores` gives the scores on a session (an empty list when there is none; they are not in `GET /v1/traces/:id/scores` and not in `anyScore`). They go with a delete of the session, and when a delete or the retention removes the last trace of their session.
  * `POST /v1/scores/aggregate` sums the scores with the name `score.name`. `score` is a `scoreFilter`: `name`, `min`, `max`, `label`, `source`, `authorId`, `evalId`, and `from`, `to` on the score's own time `at`. A row: `count` (every score of the group), `avg` (the average of the numbers and booleans; of a boolean: the share of true; `null` for a group of categories), `percentiles` (exact, for `"percentiles": [50, 95]`) and `labels` (the count per label). `groupBy`: `"all"`, `{"time": {"bucketMs": ms}}` (buckets of the score's own time), `{"traceField": f}` with `f` one of `model`, `userId`, `sessionId`, `name`, `tag`, `environment`, `service`, or `{"rootAttribute": "prompt.version"}` (an attribute of the root span). `thenBy` with a time bucket in `groupBy` gives a series per value (`key` the bucket, `key2` the value); `sort: {"by": "count" | "avg", "order"}` and `limit` are then about the series, as in `/v1/aggregate`. `traces` is a `traceFilter`: only the scores of traces that meet it count.
  * Examples. The average per day: `{"score": {"name": "quality"}, "groupBy": {"time": {"bucketMs": 86400000}}}`. Per model: `"groupBy": {"traceField": "model"}`. Counts per label: `{"score": {"name": "tone"}}` gives `{"rows": [{"key": null, "count": 3, "avg": null, "labels": {"polite": 2, "rude": 1}}]}`. A score on a session: `POST /v1/scores {"scores": [{"sessionId": "s1", "name": "resolved", "value": 1, "type": "boolean"}]}`. The share of true: `{"score": {"name": "resolved"}}` gives `"avg": 0.75` for 3 of 4. Two groups compared (two experiments): the same request with `"traces": {"root": {"attributes": {"experiment": "A"}}}`, then with `"B"`.
  * The trace side is a join when the query runs: nothing is copied onto a score when it is written. A group is read from the trace as it is now; a trace with two models is in both groups; a score with no trace in the store (on a session, or before its trace came) has the key `null`, and does not count with `traces`. It reads the columns of the matching scores, one trace summary per distinct trace of those scores, and for `rootAttribute` one span per trace. Both routes need the `read` right.
* `span` and `score`: the magpiedb `Span` and `Score` types (`traceId`, `spanId`, `parentSpanId`, `startedAt`, `endedAt`, `inputTokens`, `status`: `"unset" | "ok" | "error"`, ...). In `POST /v1/scores`, `at` may be left out: it is then the time the server receives the score.

Example:

```sh theme={null}
curl -s localhost:4318/v1/traces/find -d '{"filter": {"hasError": true}, "anySpan": [{"text": {"words": "refund"}}], "limit": 10}'
```

## API keys and rights

`--auth keys --keys-file keys.jsonl` (`src/auth.rs`). Every request needs a key, except `GET /healthz`.

* Send it as `Authorization: Bearer <key>` (HTTP), or as the gRPC metadata `authorization: Bearer <key>`. The OpenTelemetry SDKs send it from `OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20<key>"`.
* A key belongs to one tenant and has the right `read` (queries: search, count, find, aggregate, get a trace, its span list, one span, get scores, sums of scores, the two exports), `write` (OTLP exports, `POST /v1/scores`, `POST /v1/traces/delete`, `POST /v1/purge`), or both. An app that only sends traces needs `write`; a dashboard needs `read`.
* No key, a key that is not in the file, or not `Bearer <key>`: `401` with `WWW-Authenticate: Bearer`. A key without the right: `403`. An `x-magpie-tenant` header that is not the key's tenant: `403`, and nothing is read or written. A key never decides more than its own tenant's store.
* A wrong method on a path of the API is `405` with `Allow`, as without keys, before the key is looked at.

More on keys, tenants and TLS: [Tenants, API keys and TLS](https://docs.magpiedb.com/reference/tenants-and-keys.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.