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.
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
Install from source
Needs Rust (stable) anduv (or any Python 3.9+ with a venv).
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, useawait asyncio.to_thread(store.search, query). Types for every call and every key are in python/magpiedb/__init__.pyi.
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 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). Inwords, 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 forLIKE '%...%'. One piece is found anywhere in a word:undfindsrefund,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 polfindsrefund policy.{"prefix": "refund pol"}: whole words, and the last one may go on (refundfindsrefunded). One character of Thai or Korean finds the runs that have it. It is not a byte-for-byteLIKE: signs and spaces are not in the index, soa-b,a banda,bare the same; a word of 256 bytes or more and theerrortext 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,containsandprefixare one phrase each; inwordseach part between spaces is a phrase of its own, sowordstakes any number of words. - text in error messages:
{"errorText": {"words": "timeout"}}finds the text in the span’serrormessage, by the rules oftext(words, phrase, contains, prefix). It is a field of its own next totext:textlooks ininputandoutputonly, as before, anderrorTextin the error message only. Both can be in one filter. Attribute values have no text search:attributesis an exact match of a whole value - sort:
"newest"(default) or"oldest" - groupBy:
"all",{"field": "model"}(alsotraceId,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",1andTrueare three groups (1.0is1). 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 keyNone. 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 (keyis the hour,key2the model).groupBymust be a time bucket;thenByis 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;approxis 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 getsNone.percentilesis in the row only when the query asks for some - aggregate sort:
{"by": "count"},{"by": {"sum": 0}}(the row’ssums[0]),{"by": {"percentile": 0}};order"desc"(default) or"asc". Ties by key;Nonevalues last. Withlimit: top-N, e.g. the 10 users with the highest cost - sort and limit with
thenByare about the series, not single rows. A series is one value ofthenByover all buckets. The series are put in order by their count, sum or percentile over all matching spans, the firstlimitseries 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 (traceIdandspanId) or a session (sessionId, and notraceId).typeis"number"(also when it is left out),"boolean"(the value is 0 or 1) or"category"(it has alabel; the value is not used, and a score with a label and no value is a category, stored with the value 0).sourceis the kind of giver ("human","llm-judge","code"),authorIdwho gave it,evalIdthe eval that made it (an evaluator and its version, a score config, or one run of an experiment),commenta 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 inget_scoresof its traces and not inanyScore. They go withdelete_session, and when adelete_tracesor adrop_beforeremoves the last trace of their session;delete_traceleaves 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 namescore["name"].scoreis a score filter:name,min,max,label,source,authorId,evalId, andfrom,toon the score’s own timeat(not the time of its trace).countis every score of the group.avgis the average of the numbers and booleans (of a boolean: the share of true;Nonefor a group of categories); it is the exact sum, rounded once, divided by the count, so it is the same on every run.labelscounts 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).thenBywith a time bucket ingroupBygives a series per value;"sort": {"by": "count"}(or"avg", with anorder) andlimitare then about the series, as inaggregate.tracesis a trace filter (the one offind_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}]), thenstore.get_session_scores("s1") - the share of true:
{"score": {"name": "resolved"}}gives"avg": 0.75for 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 average per day:
- 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 atracesfilter. The join reads the columns of the matching scores, one trace summary per distinct trace of those scores, and forrootAttributeone 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]; andand,or,not.find_tracesalso takesroot,anySpanandanyScorenext tofilter, 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"}]}}}.rootOnlyinanySpanasks for some span with no parent;rootasks for the one root of the trace - usage of a span:
cacheReadTokensandcacheWriteTokens(input tokens read from and written to the provider’s cache),reasoningTokens,timeToFirstTokenMs(ms fromstartedAtto the first piece of the answer),inputCostandoutputCost(dollars). Cached tokens are a PART ofinputTokensand reasoning tokens a PART ofoutputTokens:inputTokensis every input token,outputTokensevery output token, andtotalTokensis 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 (addinput_tokens,cache_read_input_tokensandcache_creation_input_tokens), and Google reports output tokens without the thinking tokens (add them). A span with a part above its whole is refused.costis the total;inputCostandoutputCostare parts of it, and whencostis not given it is their sum. A trace has the sums of these (cacheReadTokens,cacheWriteTokens,reasoningTokens,inputCostNanos,outputCostNanos) and its owntimeToFirstTokenMs: 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;cacheReadandcacheWritedefault to theinputprice).writeandupsertthen 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) andcostComputed: 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 acost(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 ofmagpie-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,upsertandwrite_scoresthen 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 assk-, AWS access key ids, GitHub and Slack tokens, JWTs,Bearer <token>, PEM private keys). No rule finds names of people. Apatternis a regex of the Rustregexcrate;replacedefaults 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 inattributesandevents(all depths), and thelabelandcommentof a score. NOT masked: ids (trace, span, parent, session, user),name,kind,model,service,environment,tags, attribute keys, numbers.dropAttributesremoves 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 makesopenraise. 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 (Nonewith 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 ofmagpie-server --mask - sessions: a trace’s session is the
sessionIdof its root span, or else of its earliest span that has one. A session row hastraceCount,spanCount,errorCount, tokens andcostNanos(sums over its traces),startedAt(its first trace’s start),endedAt,userId(of its earliest trace that has one),firstTraceIdandfirstInput(the first 200 characters of that trace’s input),lastTraceIdandlastOutput(the same of the latest trace’s output; both by the rule of trace previews). First trace: earliest start, ties bytraceId; last trace: latest start, ties bytraceIdascending. Session filter:userId,from,to(the session start).find_sessionspages bycursoras the other lists;get_sessionreturns every trace of the session (for a very large one, pagefind_traceswithfilter.sessionId) - very large traces:
get_tracereturns every span with its text; for a trace of 100,000 spans that is hundreds of MB.trace_spansreturns pages of rows withspanId,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 ofget_trace(startedAt, thenspanId), with thecountof all spans of the trace.get_spangets the text of one step. Each page reads the time of every span of the trace once, so for a whole trace use a largelimit. All keys come from columns butparentSpanId, 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. Eachchunkis astrof 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 thatwritetakes: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), sostr.splitlinesis 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;breakor.close()on the iterator gives it up. A bad query raises at the call.export_scoresdoes the same for scores (a time range onat; in no promised order; the shape thatwrite_scorestakes) limit(search, find_traces, find_sessions, trace_spans): default 50.limit(aggregate): default every row.groupBy: default"all"- pages: give the
nextCursorof a page ascursorto get the next one;nextCursorisNoneon the last page. Ties:spanId, thentraceId(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 anothersort, or to another list, is an error, and so is a string that is not a cursor. - copies:
writedoes 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 itsinputand then of itsoutput, 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), forget_span(of the copies with the latest start) and forget_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. Useupsertto replace a span - previews: with
previewChars, every row hasinputPreviewandoutputPreview: the firstpreviewCharscharacters of each span’sinputandoutput(search); of the root span’sinputandoutput(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, thenTrueandFalse, then numbers.key2is in the row only withthenBy
Store.open, in snake_case:
Rules and limits
- A key the package does not know is an error, not ignored: a typo like
inputTokenmust not lose data or widen a filter. The error names the key:span 0: unknown field `inputToken`.Nonemeans “not set”. - A
strwith half of a UTF-16 surrogate pair ("\ud83d", from a JS client orsurrogatepass) 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 ofException), 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:ValueErrorfor NaN and infinity,TypeErrorfor an object such as adatetime(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 withstartedAtbefore the cutoff. The cutoff is rounded DOWN to a whole hour (the answer’scutoffis 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). Withretention_msa 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 thatfind_tracesgives for that filter (a filter with no condition is an error). A filter whose text is over the word limit ofcontainsandprefix(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), andwrite,upsertandwrite_scoresfail with an error whose text starts withio: 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_scoresor 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 (segmentsWithDeletedin the answer counts those files).purge_deleted()writes those files again now and waits for it; withsegmentsWithDeleted: 0in 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
withblock or callclose(). 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 (
jsonfrom the standard library). No asyncio API, and no wheel for the free-threaded Python build (abi3 does not support it).