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

# Import old traces

> Load old traces from files into a Magpie store with magpie-server import: flags, formats, memory, time order and limits.

`magpie-server import` loads traces from files into a store (`src/import.rs`). It is for a company that moves to Magpie and wants its old traces too.

```sh theme={null}
# Magpie's own export: span lines and score lines, in one file or in many, in any order
curl -sN localhost:4318/v1/export -d '{}' > spans.ndjson && curl -sN localhost:4318/v1/export/scores -d '{}' > scores.ndjson
magpie-server import --dir ./new-store --format magpie spans.ndjson scores.ndjson
# OTLP/JSON files of the OpenTelemetry Collector's `file` exporter, into the store of one tenant, with 4 GB of memory
magpie-server import --tenants-dir ./tenants --tenant acme --format otlp --memory-mb 4096 traces-1.json traces-2.json
# LangSmith runs, one run per line, from a pipe
gunzip -c runs.jsonl.gz | magpie-server import --dir ./traces --format langsmith -
# a gzip file as it is; stop at the first bad line; the temporary files on another disk
magpie-server import --dir ./traces --format magpie --strict --temp-dir /mnt/scratch export.ndjson.gz
```

| flag | default | meaning |
| - | - | - |
| `--dir`, or `--tenants-dir` with `--tenant` | (required) | The store. Made if it does not exist. With tenants: the store `<tenants-dir>/<tenant>`. |
| `--format` | (required) | `magpie`, `otlp` or `langsmith`: see "Formats" below. |
| files | (at least one) | Read in the order given. `-` is the standard input. A name that ends in `.gz` is read as gzip. |
| `--memory-mb` | `1024` | The memory limit of the import, at least 64. See "Memory". |
| `--temp-dir` | next to the store | Where the temporary folder `<store name>.import-tmp` goes. |
| `--strict` | off | Stop at the first bad line. |
| `--durability` | `none` | As for the server. `none` is right for an import: after a crash, run it again. |
| `--prices` | (none) | The price table of the server (`--prices` there). A span that comes with tokens and no cost then gets the cost that live ingest gives it, with `costComputed`. Without it a span keeps the cost it comes with, or has none. |
| `--mask` | (none) | The mask policy of the server (`--mask` there). Old traces are then masked as live ingest masks them, before they are stored. See [Masking](https://docs.magpiedb.com/reference/mapping-cost-masking.md#masking). |
| `--pieces` | off | As the server's `--pieces`: keep a repeated piece of a long text once (a pointer). A store opens with either value. |

**The server must not run on the same store.** A store has one writer, and the import is a writer: with a server on the store, the import ends with an error and writes nothing. Stop the server, import, start it again. Or import into a new store, and point the server at it after.

**Time order.** A store is fast when each of its files holds one stretch of time: lists stop early, a time filter skips files, and old data goes as whole files (FINDINGS F28, F29). So the import writes the spans in the order of their start times, whatever the order in the files. It reads every line once and sorts the spans in pieces that fit the memory limit, each piece in a temporary file; then it merges the pieces and writes them to the store. Inside one minute the spans of one trace follow each other, so a short trace is written whole. A trace that is longer than a minute comes in pieces, as in live traffic, and is one trace with the right totals at the end.

**Safe to run again.** Every span is written with `upsert`: it replaces the stored span with the same trace id and span id. A score replaces the one with the same trace, span, name and source. So:

* An import that stopped (a crash, Ctrl-C, a full disk) is run again with the same command. Nothing is stored twice. It starts from the first line again: there is no resume.
* A file with spans that the store already has (from live traffic, or from an earlier import) replaces them.
* The same span twice in the input: the copy with the later start time stays; of copies with one start time, the later one in the input.

**Bad lines.** A line that is not JSON, is of another format, or holds a span the store refuses (no ids, no start time, an end before the start, `attributes` or `events` nested deeper than 64 levels) is skipped. A store that was made by a build from before the depth rule can hold spans with `attributes` or `events` of 65 to 126 levels: such a store opens, answers and exports as before (and as before, a store with no pieces that has a span of 124 to 126 levels in its write log does not open after a crash: its log record is deeper than the reader of JSON goes), but an import of its export skips those lines (they are counted and named, as every skipped line). No such store is known: nothing is published. The import goes on, counts it, and names the first 10 with file, line number and reason in its summary. In an OTLP line a refused span is skipped alone, as in live ingest. With `--strict` the first bad line ends the import. Bad lines are found while the files are read, before the store is written to; only a score that the store refuses is found later, when it is written.

**Output.** Progress goes to stderr, one line per second: lines, bytes and spans read (pass 1), then spans written and the time up to which every span is written (pass 2). At the end one line of JSON goes to stdout:

```json theme={null}
{"format": "magpie", "files": 1, "lines": 809982, "bytes": 1228119427, "spans": 809982, "scores": 0, "skippedLines": 0, "refused": 0, "firstProblems": [],
 "from": 1790899266272, "to": 1793491199889, "runs": 10, "tempBytes": 1283198203, "commits": 25, "spansInStore": 809982, "tracesInStore": 90000, "seconds": ...}
```

(The summary of the import in `results/import-small.json`.) A bad line is `{"file": "export.ndjson", "line": 17, "reason": "not JSON: ..."}` in `firstProblems`. `skippedLines`: lines that gave nothing. `refused`: spans and scores refused inside lines that were read. `from`, `to`: the earliest and the latest start time (ms) of the spans written. `runs`: temporary files. `tempBytes`: the most bytes the temporary folder held. `seconds`: how long the import took. Exit code 0: done (also with skipped lines; they are in the JSON). 1: an error, or no line could be imported (then check `--format`). 2: wrong flags. 130: stopped by SIGINT or SIGTERM.

**Memory.** `--memory-mb` is the limit of the import's own buffers: half of it holds the spans in memory while the files are read. It also sets the store's write buffers for the second pass (a quarter each for the index writer and the write queue). It is not a limit of the store: while the store takes writes it merges its files in the background, and its memory for that does not follow these numbers. One line must fit in memory several times (an OTLP line is a whole request). More memory makes fewer temporary files and bigger first files in the store.

Measured with `--memory-mb 256` on 809,982 spans, 1.23 GB of lines (`bench/import/run.sh small 256`; the peak `phys_footprint` of each process; two runs, `results/import-small.json` and `results/import-small-run2.json`):

| import | peak memory, MB |
| - | - |
| the reading pass alone | 159 and 160 |
| into an empty store | 256 and 232 |
| the older half of the time range, into a store that has the newer half | 222 and 246 |
| one half of the lines, into a store that has the other half (most spans join a trace that the store has) | 809 and 842 |
| the same file a second time (every span replaces a stored span) | 1,851 and 1,488 |
| for comparison: a plain load of the same data with `write` and the store's default buffers (`bench/magpie`) | 432 and 436 |

So an import of traces that the store does not have stays near the limit; it is not a hard bound (one of the two runs was 0.3 MB above it). The limit does not hold when the import replaces spans or adds spans to stored traces: each such `upsert` is a delete in the index, and the index keeps every delete in memory while one of its merges runs. A span of a new trace needs no delete (`store.rs`, `apply`); before that rule was in the store, the import into an empty store took 613 MB (`results/import-small-before-the-upsert-fix.json`, from the code before that rule).

**Disk.** The temporary folder holds every span once as JSON: about the size of the input (for `otlp` and `langsmith`: of the spans after the mapping). With more than 64 temporary files, 64 of them are first merged into one, and the folder holds that one twice for a moment. The folder is removed at the end, also after an error or Ctrl-C. After a kill it stays; the next import of the same store removes it. The import never removes a folder that holds anything but its own files.

**A store that already has data.** The import gives the right answers on any store. What changes is how well the store's files follow time. Measured on the same data (`magpie-scale segments`, `results/segments-import-small-*.json`): the number of span files that cover one moment, as a mean over the time range (1.00 is the best) and at most.

| store | span files | files that cover one moment: mean (most) |
| - | - | - |
| a plain load in the order of the file (traces at random times) | 3 | 3.00 (3) |
| the same spans, shuffled, imported into an empty store | 4 | 1.00 (1) |
| the newer half of the time range imported, then the older half | 12 | 1.21 (2) |
| one half of the lines imported, then the other half (the same time range) | 5 | 1.18 (2) |
| the whole file imported two times | 11 | 1.00 (1) |

* Into an empty store: every moment is in one file.
* Old data into a store that has newer data: not as good (1.21). The cause: while the import runs, the store merges the first imported files with its own oldest file, because at that moment these are neighbours in time. The rest of the import then lies inside the time range of that merged file.
* Data of the time range that the store already has: two files cover a part of the time.
* So: **import first, into an empty store, then go live.** If the server is live already: export the live store, import the history and that export into a new store, and point the server at the new store. An import into the live store works and loses nothing; lists and time filters on the stretches with two files read both.
* The server's `--retention` holds for imported spans too: spans older than the limit are dropped when the server opens the store.

## Formats

* `magpie`: the lines of `POST /v1/export` and `POST /v1/export/scores` (FINDINGS F36): one span or one score per line, in the JSON shape of `span` and `score`. Span lines and score lines can be in one file. Every field of a span comes back as it was exported: also `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `timeToFirstTokenMs`, `inputCost`, `outputCost`, and a cost that the first store computed from its price table (`costComputed` stays `true`, and no price table is needed for the import).
* `otlp`: OTLP/JSON, one `ExportTraceServiceRequest` (`{"resourceSpans": [...]}`) per line. That is what the OpenTelemetry Collector's `file` exporter writes by default (`format: json`, no compression). The OTLP/JSON rules hold: ids as hex text (upper or lower case), 64-bit numbers as text, enums as numbers, unknown fields ignored; tested with the example file of the OpenTelemetry project (`tests/samples/otlp-trace.json`). The format of the exporter's file is taken from its README; a Collector binary was not run. Each line goes through the code of `POST /v1/traces` with a JSON body (`genai::spans`), so a span from a file is equal to the span of live ingest of the same request (the mapping below, with its usage fields). For the same computed costs give the import the server's `--prices` file. A request that is printed over many lines must be made one line first: `jq -c . trace.json`.
* `langsmith`: LangSmith runs, one run per line, with the field names of LangSmith's "Run (span) data format" (docs.langchain.com/langsmith/run-data-format). The runs API returns them, and the bulk export writes the same fields as Parquet (make JSON lines from it first with a Parquet tool; such a file was not tested here). The mapping table is at the top of `src/import/langsmith.rs`. In short: `id`, `trace_id`, `parent_run_id` are the ids; `run_type` `llm` is `model_generation` and `tool` is `tool_call`; tokens and cost (`total_cost`, and `prompt_cost` and `completion_cost` as `inputCost` and `outputCost`) are taken from `llm` and `embedding` runs only (LangSmith puts the totals of a trace on its parent runs); `timeToFirstTokenMs` is `first_token_time` minus `start_time`; cached and reasoning tokens are not set (the run format has no field for them); the model is `extra.metadata.ls_model_name`; the session is `extra.metadata.session_id` or `thread_id` (the run's own `session_id` is the project and becomes an attribute); `feedback_stats` gives one score per key with the average as its value.

Why LangSmith and not Langfuse, Phoenix, Opik, Helicone or MLflow: it is the one export format with a sample in public docs that a test can read (`tests/samples/langsmith-run.json` is that sample). Langfuse writes JSON lines with a documented list of fields, but its docs show no line of such a file; a mapping for it needs a real export file first.

## Limits of the import

* Speed is not measured. Each span is read as JSON twice (once for its place in the order and the checks, once for the write).
* Memory: `--memory-mb` does not bound an import that replaces stored spans or adds spans to stored traces (table above).
* No resume: an import that stopped starts again from the first line. The spans it wrote before are replaced, which costs the memory of the row "the same file a second time".
* Old data into a store that has newer data leaves two files on a part of the time range (table above). Writing such an import newest first may avoid it; that is not built and not tested.
* Not through the server: there is no HTTP route, and the server must be stopped. Not in the Node and Python packages. In Rust it is a library call: `magpie_server::import::import(&store, inputs, &options, &mut progress)`.
* LangSmith: a score is the average of a run's feedback; the single feedback rows are another export and are not read. The sample of LangSmith's docs has empty inputs and outputs, so the text of real LangChain messages was not checked against a real export.
* A span with a wrong time (year 1970, year 3000) is written as it is. It makes one file of the store cover a long time.
* One span per trace id and span id: a file from a tool that uses the same span id for two spans of one trace keeps the later one.


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