> ## 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`.

# Python library

> The magpiedb package for Python: install, example, every call, options, and the shapes of queries.

The Python package of Magpie (the Rust crate `magpiedb`): a trace store for AI agents in one folder. Full-text search over span input and output, whole-trace queries, and sums. Built with pyo3 and maturin. One wheel (abi3) for CPython 3.9 and newer.

> [!WARNING]
>
> Magpie is not on PyPI yet, and release 0.1.0 is not out. Until it is, you build it from the repo (see the [quickstart](https://docs.magpiedb.com/quickstart.md)). You need Rust (stable), `curl` and [`uv`](https://docs.astral.sh/uv/).

```sh theme={null}
pip install magpiedb
```

The import name is `magpiedb` too (the name `magpie` is taken on PyPI by another project). There are wheels for macOS arm64 and x64 and for Linux x64 and arm64 (manylinux). On another system pip builds the package from its source package, which needs Rust (stable).

## Example

```python theme={null}
import time
from magpiedb import Store

now = int(time.time() * 1000)  # times are Unix milliseconds
with Store.open("./traces") as store:
    store.write([
        {"traceId": "t1", "spanId": "s1", "kind": "agent_run", "startedAt": now, "input": "please refund my order"},
        {"traceId": "t1", "spanId": "s2", "parentSpanId": "s1", "kind": "tool_call", "startedAt": now, "error": "timeout"},
    ])
    store.commit()
    print(store.search({"filter": {"text": {"words": "refund"}}, "limit": 10}))
    print(store.find_traces({"anySpan": [{"kind": "tool_call", "hasError": True}], "limit": 10}))
```

## Install from source

Needs Rust (stable) and `uv` (or any Python 3.9+ with a venv).

```sh theme={null}
cd bindings/python
uv venv .venv && uv pip install --python .venv/bin/python "maturin>=1.9.4,<2"
.venv/bin/maturin develop --release --uv          # builds the module and installs it into .venv
.venv/bin/python -m unittest discover -s tests    # tests/test_store.py and the shared examples (tests/test_examples.py)
.venv/bin/python ../../bench/python/run.py dev    # the 8 benchmark checks; first run `node bench/gen.mjs dev` in the repo root
.venv/bin/maturin build --release -o dist         # a wheel for this machine: dist/magpiedb-0.1.0-cp39-abi3-<platform>.whl
```

## API

Every call blocks until the engine is done, and releases the GIL while the engine works: other Python threads run, and calls from many threads run at the same time. For asyncio, use `await asyncio.to_thread(store.search, query)`. Types for every call and every key are in `python/magpiedb/__init__.pyi`.

| call | returns | benchmark query (see the benchmark spec) |
| - | - | - |
| `Store.open(path, **options)` (same as `Store(path, **options)`) | `Store` | |
| `write(spans)` | count written. Does not look for an older version. | |
| `upsert(spans)` | count. Replaces the span with the same `traceId` + `spanId`. | |
| | The depth rule, for the spans of `write` and `upsert` and for the filter of every query and delete. 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. | |
| `write_scores(scores)` | count. Replaces the score with the same target (trace, span or session), name, source, author and eval id. | |
| `delete_trace(trace_id)` | `None` | |
| `drop_before(cutoff_ms)` | `{cutoff, spansDropped, tracesDropped, tracesCut, segmentsRemoved}`. Retention: removes every span that started before the cutoff, and commits. See below. | |
| `delete_traces(what)` | `{tracesDeleted, spansDeleted, scoresDeleted, segmentsTouched, segmentsWithDeleted}`. Deletes whole traces for privacy, and commits. `what` is `{"userId"}`, `{"sessionId"}`, `{"traceIds"}` or `{"filter"}`. See below. | |
| `delete_user(user_id)`, `delete_session(session_id)` | the same answer: `delete_traces({"userId": ...})`, `delete_traces({"sessionId": ...})` | |
| `purge_deleted()` | `{segmentsRewritten, docsRewritten, docsRemoved, segmentsWithDeleted, bytesBefore, bytesAfter}`. Takes the bytes of deleted data off the disk. See below. | |
| `commit()` | operation stamp. Writes become searchable. | |
| `search({"filter", "sort", "limit", "cursor", "previewChars"})` | `[{traceId, spanId, startedAt}]` | Q2 |
| `search_page({"filter", "sort", "limit", "cursor", "previewChars"})` | `{spans, nextCursor}` | |
| `count(filter=None)` | number of spans | Q1, Q3, Q8 |
| `get_trace(trace_id)` | every span, every key | Q4 |
| `get_scores(trace_id)` | every score of the trace | |
| `get_session_scores(session_id)` | every score on the session itself | |
| `aggregate_scores({"score", "traces", "groupBy", "thenBy", "percentiles", "sort", "limit"})` | `[{key, key2, count, avg, percentiles, labels}]`: sums of the scores with one name | Q16b |
| `trace_spans({"traceId", "limit", "cursor"})` | `{count, spans: [lightSpan], nextCursor}`: the spans of a trace without their text, oldest first | |
| `get_span({"traceId", "spanId"})` | one span with every key, or `None` | |
| `export({"filter"})` | an iterator of `str`: JSON Lines, one span per line, oldest first | |
| `export_scores({"from", "to"})` | an iterator of `str`: JSON Lines, one score per line | |
| `find_traces({"filter", "root", "anySpan", "anyScore", "sort", "limit", "cursor", "previewChars"})` | `{count, traces: [summary], nextCursor}` | Q5, Q7, Q17 |
| `aggregate({"filter", "groupBy", "thenBy", "metrics", "percentiles", "sort", "limit"})` | `[{key, key2, count, sums, percentiles}]` | Q6, Q14, Q18, Q19, Q21 |
| `find_sessions({"filter", "sort", "limit"})` | `{count, sessions: [session]}`, newest first | Q13 |
| `get_session(session_id)` | `{session, traces: [summary]}` (traces oldest first), or `None` | |
| `span_count()`, `trace_count()`, `segment_count()`, `disk_bytes()` | int | |
| `refresh()` | Read-only stores: pick up new commits now (they also do it on their own). | |
| `close()` | Commits, waits for merges, frees the folder for another writer. A `with` block calls it. | |

Method names are snake\_case. The dicts (spans, scores, queries, answers) have the camelCase keys of the `magpiedb` JSON shape (`traceId`, `startedAt`, `inputTokens`, `anySpan`, `hasError`): the same as in the Node package and in the `magpie-server` query API. [`testdata/query-examples.json`](https://github.com/intojhanurag/magpie/blob/main/testdata/query-examples.json) has examples with their answers, and the Node, server and Python tests all run them. Shapes that are not plain values:

* text: `{"words": "refund policy"}` (every word, in any order) or `{"phrase": "refund policy"}` (the words in this order). 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`, `user@example.com`, an id with dashes, a run of Thai or Chinese characters
* 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 fails with an error that says so: make the first or the last piece longer. A phrase of 4,096 positions or more is refused (`MagpieError`): 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.
* text in error messages: `{"errorText": {"words": "timeout"}}` finds the text in the span's `error` message, by the rules of `text` (words, phrase, contains, prefix). It is a field of its own next to `text`: `text` looks in `input` and `output` only, as before, and `errorText` in the error message only. Both can be in one filter. Attribute values have no text search: `attributes` is an exact match of a whole value
* sort: `"newest"` (default) or `"oldest"`
* groupBy: `"all"`, `{"field": "model"}` (also `traceId`, `kind`, `userId`, `sessionId`, `name`, `tag`), `{"attribute": "user.plan"}`, `{"time": {"bucketMs": 3600000}}`. Time buckets start at the Unix epoch (a bucket of a day is a UTC day), and only buckets with a span are returned
* group by `tag`: a span with two tags is in both groups, so the counts of the groups add up to more than the spans. A tag given twice on one span counts once
* group by `attribute`: the path is read as in the attributes filter. 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 such path, `None`, a dict) has the key `None`. Attributes have no column: every value of the path is read in each part of the store, so a path with very many values is slow
* thenBy: a second key, for a time series per value: `{"groupBy": {"time": {"bucketMs": 3600000}}, "thenBy": {"field": "model"}, "metrics": ["costNanos"]}` is the cost per model per hour, one row per hour and model (`key` is the hour, `key2` the model). `groupBy` must be a time bucket; `thenBy` is a field or an attribute. Rows come by bucket (oldest first)
* metrics (exact sums): `"inputTokens"`, `"outputTokens"`, `"totalTokens"`, `"costNanos"`, `"durationMs"`, `"errorCount"` (failed spans), `"cacheReadTokens"`, `"cacheWriteTokens"`, `"reasoningTokens"`, `"inputCostNanos"`, `"outputCostNanos"`, `"timeToFirstTokenMs"`
* percentiles: `[{"p": 95}, {"p": 99.9, "approx": True}, {"p": 95, "of": "costNanos"}]`. `of`: `"durationMs"` (default), or any metric but `"errorCount"`: `{"p": 95, "of": "timeToFirstTokenMs"}` is the p95 of the time to first token. Exact by the nearest-rank rule; `approx` is a sketch, at most 1% off. Spans with no value do not count (for the duration: spans that have not ended; for the cost and its two parts: spans with no such cost; for the time to first token: spans with none, which are never taken as 0; a token count is 0 when not given, so every span counts); a group where none has a value gets `None`. `percentiles` is in the row only when the query asks for some
* aggregate sort: `{"by": "count"}`, `{"by": {"sum": 0}}` (the row's `sums[0]`), `{"by": {"percentile": 0}}`; `order` `"desc"` (default) or `"asc"`. Ties by key; `None` values last. With `limit`: top-N, e.g. the 10 users with the highest cost
* 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, the first `limit` series are kept, and every bucket of a kept series is returned. `{"groupBy": {"time": {"bucketMs": 86400000}}, "thenBy": {"field": "userId"}, "metrics": ["costNanos"], "sort": {"by": {"sum": 0}}, "limit": 10}` is the 10 users with the highest cost in the whole time range, each with all its days
* scores: 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`; the value is not used, and a score with a label and no value is a category, stored with the value 0). `source` is the kind of giver (`"human"`, `"llm-judge"`, `"code"`), `authorId` who gave it, `evalId` the eval that made it (an evaluator and its version, a score 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, so two people, or two runs of an eval, keep one score each. A score that breaks a rule (no target or two, a boolean that is not 0 or 1, a category with no label) raises, and its batch is refused whole. `get_session_scores(session_id)` lists the scores on a session; they are not in `get_scores` of its traces and not in `anyScore`. They go with `delete_session`, and when a `delete_traces` or a `drop_before` removes the last trace of their session; `delete_trace` leaves them, and so does a trace that moves to another session
* sums of scores: `aggregate_scores({"score", "traces", "groupBy", "thenBy", "percentiles", "sort", "limit"})` gives `[{key, key2, count, avg, percentiles, labels}]` for the scores with the name `score["name"]`. `score` is a score filter: `name`, `min`, `max`, `label`, `source`, `authorId`, `evalId`, and `from`, `to` on the score's own time `at` (not the time of its trace). `count` is every score of the group. `avg` is the average of the numbers and booleans (of a boolean: the share of true; `None` for a group of categories); it is the exact sum, rounded once, divided by the count, so it is the same on every run. `labels` counts the scores per label. `"percentiles": [50, 95]` are exact (nearest rank: a value that occurred). `groupBy`: `"all"`, `{"time": {"bucketMs": ms}}` (buckets of the score's own time), `{"traceField": "model"}` (also `"userId"`, `"sessionId"`, `"name"`, `"tag"`, `"environment"`, `"service"`) or `{"rootAttribute": "prompt.version"}` (an attribute of the root span of the trace). `thenBy` with a time bucket in `groupBy` gives a series per value; `"sort": {"by": "count"}` (or `"avg"`, with an `order`) and `limit` are then about the series, as in `aggregate`. `traces` is a trace filter (the one of `find_traces`): only the scores of traces that meet it count. Examples:
  * the average per day: `{"score": {"name": "quality"}, "groupBy": {"time": {"bucketMs": 86400000}}}` gives `[{"key": 1764547200000, "count": 12, "avg": 0.71, "labels": {}}, ...]`
  * per model: `{"score": {"name": "quality"}, "groupBy": {"traceField": "model"}}`; per prompt version: `"groupBy": {"rootAttribute": "prompt.version"}`
  * counts per label: `{"score": {"name": "tone"}}` gives `[{"key": None, "count": 3, "avg": None, "labels": {"polite": 2, "rude": 1}}]`
  * a score on a session: `store.write_scores([{"sessionId": "s1", "name": "resolved", "value": 1, "type": "boolean", "at": now_ms}])`, then `store.get_session_scores("s1")`
  * the share of true: `{"score": {"name": "resolved"}}` gives `"avg": 0.75` for 3 of 4
  * two groups compared (two experiments): the same query with `"traces": {"root": {"attributes": {"experiment": "A"}}}`, then with `"B"`; two environments: `"traces": {"environment": "prod"}`, then `"staging"`; two runs of one eval on the same traces: `"score": {"name": "tone", "evalId": "run-1"}`, then `"run-2"`
* the trace side of a sum of scores is a join when the query runs: nothing is copied onto a score when it is written. So a group is read from the trace as it is now: a score that came before its trace, or before a change of the trace, is in the group that the trace has now. A trace with two models (or tags) is in both groups. A score with no trace in the store (a score on a session, a score whose trace did not come yet) has the key `None`, and does not count with a `traces` filter. The join reads the columns of the matching scores, one trace summary per distinct trace of those scores, and for `rootAttribute` one span per trace
* attributes filter: `[("user.plan", "pro")]` (pairs of path and value) or `{"user.plan": "pro"}`
* filter trees: a span filter and a trace filter can hold filters of their own shape in `"and": [filter]` (every one holds), `"or": [filter]` (at least one holds; an empty list matches nothing) and `"not": filter` (it does not hold). They are conditions like the other keys: `{"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 key 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
* trace filter: `traceId`, `userId`, `sessionId`, `name` (of the root span), `hasError`, `from`, `to`, `tag`, `service`, `environment`; a range `{"min", "max"}` of each total of the trace: `spanCount`, `errorCount`, `inputTokens`, `outputTokens`, `totalTokens`, `costNanos`, `durationMs` (both ends are included and each may be left out; one dollar is `{"min": 10**9}`; the duration is the end of the latest span minus the start of the earliest, and a trace with no ended span has none, so it is in no duration range); `"root": filter` (the root span, `rootSpanId`, meets it); `"anySpan": [filter]` (for each entry, some span meets it); `"anyScore": [scoreFilter]`; and `and`, `or`, `not`. `find_traces` also takes `root`, `anySpan` and `anyScore` next to `filter`, with the same meaning. Traces that failed or cost a dollar and have no tool call: `{"filter": {"or": [{"hasError": True}, {"costNanos": {"min": 10**9}}], "not": {"anySpan": [{"kind": "tool_call"}]}}}`. `rootOnly` in `anySpan` asks for some span with no parent; `root` asks for the one root of the trace
* usage of a span: `cacheReadTokens` and `cacheWriteTokens` (input tokens read from and written to the provider's cache), `reasoningTokens`, `timeToFirstTokenMs` (ms from `startedAt` to the first piece of the answer), `inputCost` and `outputCost` (dollars). Cached tokens are a PART of `inputTokens` and reasoning tokens a PART of `outputTokens`: `inputTokens` is every input token, `outputTokens` every output token, and `totalTokens` is their sum, so no sum counts a token twice. That is the rule of the OpenTelemetry GenAI conventions and of OpenAI's numbers. Anthropic reports input tokens WITHOUT the cached ones (add `input_tokens`, `cache_read_input_tokens` and `cache_creation_input_tokens`), and Google reports output tokens without the thinking tokens (add them). A span with a part above its whole is refused. `cost` is the total; `inputCost` and `outputCost` are parts of it, and when `cost` is not given it is their sum. A trace has the sums of these (`cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `inputCostNanos`, `outputCostNanos`) and its own `timeToFirstTokenMs`: from the start of the trace to the earliest first token of any of its spans. A session has the sums. In an answer, these fields are left out when they are 0 or not set (so read them with a default: `span.get("cacheReadTokens", 0)`)
* cost from a price table: open the store with `prices={"perMillionTokens": {"my-model": {"input": 3, "output": 15, "cacheRead": 0.3, "cacheWrite": 3.75}}}` (US dollars per one million tokens, by the exact model name, at most 6 decimals; `cacheRead` and `cacheWrite` default to the `input` price). `write` and `upsert` then compute the cost of a span that has a model of the table and tokens and comes with no cost: `inputCost` (plain input tokens, cache reads and cache writes at their prices), `outputCost`, `cost` (their sum) and `costComputed: True`. The cost is computed once, when the span is written, and stored: a new table changes new spans only. A span that comes with a `cost` (or a part of it) keeps it. A model that is not in the table gets no cost, and so does a span with no tokens: nothing is guessed. No price list comes with the package (prices change): take the numbers from the price page of your provider. It is the same table as the file of `magpie-server --prices`
* masking private data: open the store with `mask={"rules": [{"builtin": "email"}, {"builtin": "secret"}, {"name": "order", "pattern": "ORD-[0-9]{8}", "replace": "[ORDER]"}], "dropAttributes": ["user.address"]}`. `write`, `upsert` and `write_scores` then replace every match BEFORE the write goes into the write log, so no file of the store holds the original text, no search finds it and no read returns it. Off by default. Built-in rules (each off until named, narrow on purpose): `email`, `credit_card` (with a Luhn check), `ipv4`, `phone` (only numbers with `+` and 8 to 15 digits), `secret` (key shapes such as `sk-`, AWS access key ids, GitHub and Slack tokens, JWTs, `Bearer <token>`, PEM private keys). No rule finds names of people. A `pattern` is a regex of the Rust `regex` crate; `replace` defaults to the rule's name in upper case in square brackets (`[EMAIL]`) and is put in as it is. Masked: `input`, `output`, `error`, every string value in `attributes` and `events` (all depths), and the `label` and `comment` of a score. NOT masked: ids (trace, span, parent, session, user), `name`, `kind`, `model`, `service`, `environment`, `tags`, attribute keys, numbers. `dropAttributes` removes attribute values whole by path (a dot is a path step; a path names everything below it). Overlaps: all rules look at the text as it was sent; the match that starts first wins, then the longer one, then the first rule. A wrong rule makes `open` raise. It does not make a write raise. A new policy changes new writes only. Limits: text that holds JSON is masked as text, so a value with a JSON escape inside it (`bob\u0040example.com`) is not found; what no rule matches is stored. `mask_counts()` gives `{"rules": [{"name", "masked"}], "droppedAttributes"}` since the store opened (`None` with no policy): counts only. It gives no value. The rules in full, with what each does not find: [the server reference](https://docs.magpiedb.com/reference/server.md), section "Masking"; the same policy is the file of `magpie-server --mask`
* sessions: a trace's session is the `sessionId` of its root span, or else of its earliest span that has one. A session row has `traceCount`, `spanCount`, `errorCount`, tokens and `costNanos` (sums over its traces), `startedAt` (its first trace's start), `endedAt`, `userId` (of its earliest trace that has one), `firstTraceId` and `firstInput` (the first 200 characters of that trace's input), `lastTraceId` and `lastOutput` (the same of the latest trace's output; both by the rule of trace previews). First trace: earliest start, ties by `traceId`; last trace: latest start, ties by `traceId` ascending. Session filter: `userId`, `from`, `to` (the session start). `find_sessions` pages by `cursor` as the other lists; `get_session` returns every trace of the session (for a very large one, page `find_traces` with `filter.sessionId`)
* very large traces: `get_trace` returns every span with its text; for a trace of 100,000 spans that is hundreds of MB. `trace_spans` returns pages of rows with `spanId`, `parentSpanId`, `name`, `kind`, `model`, `startedAt`, `endedAt`, `hasError`, `inputTokens`, `outputTokens`, `cost`, and the usage fields that the span has (the names and values of the span's keys; no text), in the order of `get_trace` (`startedAt`, then `spanId`), with the `count` of all spans of the trace. `get_span` gets the text of one step. Each page reads the time of every span of the trace once, so for a whole trace use a large `limit`. All keys come from columns but `parentSpanId`, which is read from the stored span of each row of the page that has a parent
* export: `for chunk in store.export({"filter": f})` gives every span that matches (no argument: every span; a time range is `{"filter": {"from": a, "to": b}}`), oldest first. Each `chunk` is a `str` of whole lines, each ended by `"\n"`, at most a few MB; the next chunk is made when the loop asks for it, so memory stays small for a store of any size. A line is one span as JSON, in the shape that `write` takes: `store2.write([json.loads(line) for line in chunk.splitlines()])` loads it back. A line has no line break inside, also not U+2028, U+2029 or U+0085 (they are written as escapes), so `str.splitlines` is safe. To a file: `f.write(chunk)` for each chunk. The export reads the commit of the moment of the call (later writes and deletes are not in it) and keeps that commit's files open until the loop ends; `break` or `.close()` on the iterator gives it up. A bad query raises at the call. `export_scores` does the same for scores (a time range on `at`; in no promised order; the shape that `write_scores` takes)
* `limit` (search, find\_traces, find\_sessions, trace\_spans): default 50. `limit` (aggregate): default every row. `groupBy`: default `"all"`
* pages: give the `nextCursor` of a page as `cursor` to get the next one; `nextCursor` is `None` on the last page. Ties: `spanId`, then `traceId` (spans); `traceId` (traces); `sessionId` (sessions). 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.
* copies: `write` does not look for an older version, so a span id written twice is stored twice (two copies). Where an answer takes one copy, it takes the least by the copy order. It does not take the one that came first or lies first: first by the span's fields (root or not, `kind`, `name`, `model`, `userId`, `sessionId`, `service`, `environment`, error, `endedAt`, the token counts, the costs, the time to first token, whether it has an input and an output; not set comes first), then by the first 200 characters of its `input` and then of its `output`, then by its line of the export. This holds for the summary of a trace (root, name, user, session and the two previews, when copies have one start), for `get_span` (of the copies with the latest start) and for `get_trace` (copies with one start). A preview of more than 200 characters is of the copy whose text starts with the 200 that the summary keeps; copies whose texts are equal in their first 200 characters and differ after can give either. Lists of rows (`trace_spans`, search, the export) give every copy; copies with one start come in no promised order. Use `upsert` to replace a span
* previews: with `previewChars`, every row has `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, the rows have no such keys
* group key: the value, the bucket start, or `None` (groupBy `"all"`, or spans with no value). For an attribute the value can also be an int, a float or a bool. Rows by key: `None`, then text, then `True` and `False`, then numbers. `key2` is in the row only with `thenBy`

Options are keyword arguments of `Store.open`, in snake\_case:

| option | values | default |
| - | - | - |
| `durability` | `"none"` (no write log), `"os"` (survives a crash of the process), `"disk"` (survives a crash of the machine) | `"disk"` |
| `commit_interval` | milliseconds from the first uncommitted write to an automatic commit. `None`: no timer. | 500 |
| `compression` | `"lz4"` or `{"zstd": level}` (1 to 22). A writer uses it for the files it writes: old files stay as they are and stay readable. | `{"zstd": 9}` |
| `docstore_block_bytes` | stored spans are compressed in blocks of about this many bytes. A bigger block makes the store smaller; a read of one span decompresses its whole block. Like `compression`, for the files this writer writes. Trace summaries (with the previews), scores and session rows are in a second index that always has small blocks. | 1048576 |
| `read_only` | open without a writer. Many read-only processes can open one store. | `False` |
| `retention_ms` | keep spans this many milliseconds: the store calls `drop_before(now - retention_ms)` itself, when it opens and then every 10 minutes. | not set: keep everything |
| `prices` | a price table, `{"perMillionTokens": {model: {"input": .., "output": .., "cacheRead": .., "cacheWrite": ..}}}`: the store computes the cost of a span that comes with tokens and no cost (see "cost from a price table") | not set: no cost is computed |
| `mask` | a mask policy, `{"rules": [{"builtin": "email"}, {"name": .., "pattern": .., "replace": ..}], "dropAttributes": [path]}`: private data is replaced before it is stored (see "masking private data") | not set: nothing is masked |
| `pieces` | keep a repeated piece of a long text once (a pointer): a long text of a span is cut into pieces of about 1 KB, and a piece that an earlier span of the same trace and hour holds is stored once. A store opens with either value. | `False` |
| `max_queued_bytes`, `writer_heap_bytes`, `indexing_threads`, `cluster_by_trace`, `final_segment_bytes`, `trace_cache_spans` | the `magpiedb` options of the same name | the `magpiedb` defaults |

## Rules and limits

* A key the package does not know is an error, not ignored: a typo like `inputToken` must not lose data or widen a filter. The error names the key: ``span 0: unknown field `inputToken` ``. `None` means "not set".
* A `str` with half of a UTF-16 surrogate pair (`"\ud83d"`, from a JS client or `surrogatepass`) is stored with U+FFFD for the half; the rest of the call is stored as it is.
* Errors from the engine are `magpiedb.MagpieError` (a subclass of `Exception`), with the engine's message. That includes bad input: the engine finds it when it reads the call. A value that JSON cannot hold is Python's own error, raised before the engine sees the call: `ValueError` for NaN and infinity, `TypeError` for an object such as a `datetime` (send times as int milliseconds).
* Times are Unix milliseconds (int). Integers are exact at every size the engine stores (u64 for tokens and sums, i64 for times): Python ints have no limit, so sums above 2^53 stay exact. Larger numbers are an error.
* One writer per folder. Other processes can open it with `read_only=True`.
* Retention: `drop_before(cutoff_ms)` removes every span with `startedAt` before the cutoff. The cutoff is rounded DOWN to a whole hour (the answer's `cutoff` is the time used), so the sums per hour stay exact. A trace with no span left goes with its summary and its scores (`tracesDropped`). A trace with spans on both sides keeps the later ones, and its summary is made again from them, so its start, its root and its sums can change (`tracesCut`). Session rows and sums are exact after it. The call commits what was written before it, then the drop, and returns when the drop is durable. Old data goes as whole files (`segmentsRemoved`); the one file that crosses the cutoff keeps its old spans on disk, not in any answer, until all of it is old (if that is more than 7 days away, the file is written again without them when a third of it is old). With `retention_ms` a span is gone at most 1 hour and 10 minutes after it got too old, plus the time of the drop, while the store is open. A store that is not open drops nothing.
* Deletes for privacy: `delete_traces(what)` removes whole traces: every span, the summary and the scores. `{"userId": ...}` is every trace that has a span of that user (a trace with spans of two users goes whole); `{"sessionId": ...}` is every trace that has a span of that session; `{"traceIds": [...]}` is those traces (their scores also when a trace has no span); `{"filter": {...}}` is every trace that `find_traces` gives for that filter (a filter with no condition is an error). A filter whose text is over the word limit of `contains` and `prefix` (above) is an error too: nothing is deleted, the store goes on, and no later open runs that delete. A full disk: the store keeps free space on its volume (5% of it, at least 16 MiB and at most 1 GiB), and `write`, `upsert` and `write_scores` fail with an error whose text starts with `io: DISK_FULL:` before the disk is full; queries, deletes, drops and the purge still work then, and writes pass again when there is room. The call commits what was written before it, then the delete, and returns when the delete is durable: from then on no list, count, sum, session, `get_trace`, `get_scores` or text search gives the data. A crash leaves the store before the delete or after it. It does not leave it between. A span that is written after the call stays, also of the same user: to keep a user out, refuse their spans before they reach the store. The bytes: a deleted span is hidden at once, but its text stays in its file until that file is written again (`segmentsWithDeleted` in the answer counts those files). `purge_deleted()` writes those files again now and waits for it; with `segmentsWithDeleted: 0` in its answer, no file of the store holds data that was deleted before the call (the write log too: the call commits first). It costs the live spans of those files (`docsRewritten`): for a user with traces at all times, that is the whole store. So delete all users of one request first, then purge once. Copies outside the store folder (backups, S3) are not touched.
* Use a `with` block or call `close()`. It commits what is left and frees the folder.
* Each call sends its argument as JSON text to the engine and gets the answer back as JSON text (`json` from the standard library). No asyncio API, and no wheel for the free-threaded Python build (abi3 does not support it).


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