Skip to main content
The Node.js 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 napi-rs.
Magpie is not on npm yet, and release 0.1.0 is not out. Until it is, you build it from the repo (see the quickstart). You need Rust (stable), curl and Node 24.
npm also installs the one magpiedb-<platform> package that holds the prebuilt binary for your machine: macOS arm64 and x64, Linux x64 and arm64 with glibc 2.17 or newer. Other systems (Windows, Linux with musl such as Alpine) have no prebuilt binary yet: build from the repository (“Build and test”, below).

Example

API

Every call returns a Promise. The work runs on a worker thread, not on the JavaScript thread. Types for every call and every field are in index.d.ts. Names are the camelCase names of the magpiedb fields (traceId, startedAt, inputTokens, anySpan, hasError). The shapes are the magpiedb JSON shapes, the same as in the magpie-server query API; testdata/query-examples.json has examples with their answers, and both test suites 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 (the call throws): 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, null, an object) has the key null. 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 null. 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; null 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) is an error, and its batch is refused whole. getSessionScores(sessionId) lists the scores on a session; they are not in getScores of its traces and not in anyScore. They go with deleteSession, and when a deleteTraces or a dropBefore removes the last trace of their session; deleteTrace leaves them, and so does a trace that moves to another session
  • sums of scores: aggregateScores({ 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; null 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 } } (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' | 'avg', order } and limit are then about the series, as in aggregate. traces is a trace filter (the one of findTraces): 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: null, count: 3, avg: null, labels: { polite: 2, rude: 1 } }]
    • a score on a session: writeScores([{ sessionId: 's1', name: 'resolved', value: 1, type: 'boolean', at: Date.now() }]), then getSessionScores('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 null, 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 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
  • 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: 1e9 }; 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. findTraces 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: 1e9 } }], 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.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 writeScores 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 rejects open. It does not reject a write. 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. maskCounts() gives { rules: [{ name, masked }], droppedAttributes } since the store opened (null with no policy): counts only. It gives no value. The rules in full, with what each does not find: the server reference, 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). findSessions pages by cursor as the other lists; getSession returns every trace of the session (for a very large one, page findTraces with filter.sessionId)
  • very large traces: getTrace returns every span with its text; for a trace of 100,000 spans that is hundreds of MB. traceSpans 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 fields; no text), in the order of getTrace (startedAt, then spanId), with the count of all spans of the trace. getSpan 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 fields come from columns but parentSpanId, which is read from the stored span of each row of the page that has a parent
  • export: for await (const chunk of store.export({ filter })) gives every span that matches ({} or nothing: every span; a time range is { filter: { from, to } }), oldest first. Each chunk is a string 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: await store2.write(chunk.split('\n').filter(Boolean).map((l) => JSON.parse(l))) 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 readline reads one span per line. To a file: await pipeline(Readable.from(store.export()), fs.createWriteStream('spans.ndjson')). The export reads the commit of the moment it starts (later writes and deletes are not in it) and keeps that commit’s files open until the loop ends; break gives it up. A bad query is rejected when the loop starts. exportScores does the same for scores (a time range on at; in no promised order; the shape that writeScores takes)
  • limit (search, findTraces, findSessions, traceSpans): 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 null 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 getSpan (of the copies with the latest start) and for getTrace (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 (traceSpans, 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 null (groupBy 'all', or spans with no value). For an attribute the value can also be a number, true or false. Rows by key: null, then text, then true and false, then numbers. key2 is in the row only with thenBy
  • options: durability ('none', 'os', 'disk'), commitInterval (ms, null = no timer), compression ('lz4' or { zstd: 9 }, the default), docstoreBlockBytes (the block of stored spans that is compressed as one; default 1048576; trace summaries with their previews are not in these blocks), readOnly, retentionMs, prices, mask, pieces (keep a repeated piece of a long text once, as a pointer; a store opens with either value; default false), and the other magpiedb options
  • retention: dropBefore(cutoffMs) 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 resolves 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 the option retentionMs the store calls dropBefore(Date.now() - retentionMs) itself, when it opens and then every 10 minutes: 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: deleteTraces(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 findTraces 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 writeScores 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 resolves when the delete is durable: from then on no list, count, sum, session, getTrace, getScores 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). purgeDeleted() 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
Rules:
  • A field the package does not know is an error, not ignored: a typo like inputToken must not lose data or widen a filter. null means “not set”. So does NaN, because JSON turns it into null.
  • A string with half of a UTF-16 surrogate pair (text.slice(0, n) that cuts an emoji) is stored with U+FFFD for the half, as TextEncoder makes it; the rest of the call is stored as it is.
  • Times are Unix milliseconds. A sum, a percentile or a whole-number group key above 2^53 is an error, because a JavaScript number cannot hold it exactly.
  • One writer per folder. Other processes can open it with { readOnly: true }.
  • Call close(). It commits what is left and frees the folder.

Build and test

Needs Rust (stable) and Node 24.
.github/workflows/node-release.yml (manual run) builds the binary for macOS arm64 and x64, and Linux x64 and arm64 (glibc 2.17 or newer), then packs the five npm tarballs with scripts/pack.mjs (one per platform in npm/, and the main package) and installs them in a new folder as a user does (scripts/smoke.mjs). How to publish them: docs/RELEASE.md in the repository.