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

# S3 with the server

> Keep one Magpie store in an S3 bucket with the --s3 flag: the writer, the read-only server, one-writer rules, cleanup, what can be lost and the limits.

The design and what stays open: [S3 operations](https://docs.magpiedb.com/operations/s3.md).

`--s3 s3://<bucket>/<prefix>` (the design and what stays open: [S3 operations](https://docs.magpiedb.com/operations/s3.md)). One store only: not with `--tenants-dir`.

**Tested only against MinIO on localhost.** That shows that the rules below hold in the code. It says nothing about real S3: its speed, its cost, its errors. No times were measured.

Keys and region come from the usual AWS variables (`AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_REGION`, also `AWS_SESSION_TOKEN` and the other ways the `object_store` crate knows). Another S3 service: `--s3-endpoint http://127.0.0.1:9000`, or `AWS_ENDPOINT_URL` (then also `AWS_ALLOW_HTTP=true` for `http`).

What is in the bucket: the files of the store as Tantivy writes them (`seg/<writer id>/...`), and one manifest per upload (`manifest/<20 digits>.json`): both indexes at one commit, and where each file is. The highest number is the current one. A file is never changed.

## The writer: `--dir` with `--s3`

The store is on the local disk, as without `--s3`: writes, the write log and queries do not wait for the bucket. An uploader thread copies commits to the bucket: the new files first, then the manifest.

* **At most one upload per `--s3-upload-interval`** (default 10 s). Commits that come between two uploads are uploaded as one; files that were made and merged away in between are never uploaded.
* Why 10 s: it is what is lost when the disk is lost (see "What can be lost"), and it bounds the requests: at most 8,640 manifests per day when writes never stop (arithmetic), plus the new files (`docs/S3.md`, section "Open risks, and what to check on real S3"). A shorter time loses less and costs more requests. Not measured on real S3.
* An idle writer makes a manifest every half of `--s3-lease`, so that its lease stays fresh (default: every 30 s).
* When the server stops (SIGINT, SIGTERM), it closes the store and uploads the last commit. It says `the last commit is in the bucket (manifest N)`. If that upload fails, it says so and ends with an error: the commit is on the local disk, and the next start on the same folder uploads it.
* An upload that fails (the network, the service) is tried again about every second. Writes are still accepted: they are on the local disk. `GET /v1/storage` shows `lastError`, and how far the bucket is behind: `walSeq` against `localWalSeq`, and `notUploadedForMs`. Nothing limits how far that can go while the bucket cannot be reached: the upload interval is how often a healthy writer uploads, not a limit on what can be lost.
* Commits that wait for an upload do not pile up: only the newest one waits, and the files of the ones before it are closed (F88).
* **A lost answer is not an upload** (F88, `docs/S3.md`, section "Faults of real S3, made on purpose"). When the service made a manifest and its answer was lost (a timeout, a broken connection, a `500`), the writer reads what the bucket holds under that number. `manifest` and `walSeq` of the status, and the line `the last commit is in the bucket` say no more than the bucket holds.
* An error of the S3 service is shown as what was done, the kind of the error, the HTTP status and the service's error code: `S3 request failed (PUT manifest): an error answer, HTTP 503 SlowDown, after 10 retries`. Never the URL of the request, the body of the answer or a key id.

## The folder and the bucket: who wins

When a writer starts, it compares its `--dir` with the bucket. The folder remembers its bucket in the file `s3-writer.json`.

| the folder | the bucket | what happens |
| - | - | - |
| empty, or not there | no store | A new store. |
| a store | no store | The folder's store is uploaded (the first upload is done before the server takes requests). |
| empty, or not there | a store | **The store is downloaded** from the newest manifest. Then the server goes on as the writer. |
| a store that made the newest manifest | the same store | The server goes on. The folder has the same commits, or newer ones (for example after a crash): they are uploaded. No lease to wait for: the folder holds it. |
| a store that made the newest manifest, but its last commit is older | newer | **Refused.** The disk was put back to an older state. |
| a store that this bucket never saw | a store | **Refused.** |
| a store of this bucket | another writer wrote since | **Refused.** The folder and the bucket hold different writes. |
| a store of another format version (an earlier or a later build of Magpie) | any | **Refused** before anything is written: no note, no download, no manifest. |
| any | a newest manifest of another format version | **Refused** before anything is written. A read-only server keeps the manifest it shows and says why in `GET /v1/storage` (`refused`). |

A refusal says what to do. The rule behind it: the server never picks a loser by itself. To go on from the bucket, give an empty `--dir` (move the old folder away; a server without `--s3` can still read it and export from it). To keep the folder's store, upload it to a prefix that has no store. `--s3-take-over` does not change these rules: it is only about the lease.

A second server process on the same folder is refused (`s3-writer.lock`). A download that did not finish (the server was stopped in it) is done again at the next start.

A start-up check: the server makes a test object twice with `If-None-Match: *`. If the service does not refuse the second one, the server does not start: without that refusal two writers could overwrite each other. When an answer of the check is lost, the server reads the test object to learn which create the service took (F88); the test object is deleted on every way out.

The prefix: any text up to 800 bytes whose parts (between slashes) are not empty, not `.` or `..`, and hold no control character. The keys in the bucket are exactly `<prefix>/manifest/...`, `<prefix>/seg/...` and `<prefix>/probe/...`, also for a prefix with `%`, a space or letters that are not ASCII (F88). Another prefix is refused at the start. A directory bucket (S3 Express One Zone) is refused too.

## One writer

Only one server may write to a prefix. Two things make sure:

* **The manifest number.** A manifest is made with `If-None-Match: *`: the bucket refuses a number that exists. So a writer is stopped at the point where a new manifest would become visible to readers. (That the service refuses the second create was checked on MinIO only, not on real S3.) A writer that starts takes the store by making the next number, with the same content and the next *writer epoch*. The writer that was there before then fails at its next upload: it is **fenced**.
* **The lease.** A writer on an empty folder does not start while the newest manifest is younger than its writer's lease (`--s3-lease`, default 60 s): that writer may be alive. Wait for the lease to end, or start with `--s3-take-over`.

A fenced server:

* answers every write (`POST /v1/traces`, gRPC export, scores, delete, purge) with `503` and `fenced: another writer (epoch N) took s3://... with manifest M. ...` (gRPC: `UNAVAILABLE`). OTLP clients try again on 503: put the writers behind one address that points at the live one.
* still answers queries, from its local store.
* uploads nothing more, and deletes nothing in the bucket.
* ends with an error when it is stopped. Its folder is refused as a writer from then on (the table above).

Why 60 s: an idle writer renews every 30 s, so one failed renewal does not lose the lease; and after a writer's machine is lost, a new writer can start one minute later with no flag. The lease is compared with this machine's clock and the bucket's time of the manifest: clocks that are wrong by more than the lease break the lease check. They do not break the fencing, which needs no clock.

## A read-only server: `--s3 --read-only --cache-dir`

It answers the query API from the bucket. It needs no `--dir`, and it can run on another machine than the writer. Any number of them can run.

* It reads the files in blocks (`--cache-block-kb`, default 256 KB) and keeps the blocks in `--cache-dir`, at most `--cache-mb` megabytes (default 1024). When the cache is full, the block that was used longest ago is deleted. A cache dir can be used again after a restart, for the same bucket and block size.
* Every `--s3-refresh` (default 5 s) it looks for a newer manifest and moves to it. So its answers are behind the writer by up to the writer's upload interval plus this time. Each answer is from one commit of the writer, and not from two.
* A list goes on from its cursor after the server moved to a newer manifest, as on a writer: a cursor is a place in the order, not a copy of the data (section [Query API](https://docs.magpiedb.com/reference/http-api.md#query-api)).
* The writer deletes old files (below). A read-only server that did not refresh for longer than the writer's `--s3-gc-grace` can meet a file that is gone. The query then loads the newest manifest and runs once more. Keep `--s3-refresh` at most half of the grace time. An export (`POST /v1/export`) that meets a missing file after its first chunk ends early, like any export that fails (section [Query API](https://docs.magpiedb.com/reference/http-api.md#query-api)).
* Writes are refused: `405` and `this server is read-only: ...` (gRPC: `FAILED_PRECONDITION`).
* It starts only when the bucket has a manifest.

## Cleanup

The writer deletes what no reader can need, every `--s3-gc-interval` (default 10 min), right after an upload:

* A manifest is kept while it is the newest, and for `--s3-gc-grace` (default 30 min) after the next one was made. So a reader has the grace time to move on from a manifest.
* A file under `seg/` is deleted when no kept manifest names it and it is older than the grace time. This also removes what a crashed or fenced writer uploaded and never put in a manifest.
* The newest manifest and its files are never deleted.

## What can be lost

* **The writer's disk is lost** (or its folder is deleted): the writes that the server accepted after its last manifest are lost. The write log is on the local disk, not in the bucket. (Other engines keep their write log in the bucket or in a queue. Magpie does not in this version: `docs/S3.md`, section "Design for Magpie".) With the defaults that is up to about 10 s of writes, plus the time of one upload, plus the 0.5 s to the next commit. `GET /v1/storage` shows `walSeq`: the last write that is in the bucket.
* **The writer's process dies and its disk is there**: nothing is lost (`--durability os` or `disk`). Start the server on the same folder: the write log is replayed, and the rest is uploaded.
* **A writer is fenced**: the writes it accepted between the take-over and its next upload try are in its local folder only. They are not in the store. A server without `--s3` on that folder can read and export them.

## `GET /v1/storage`

Where the store is and what the uploader or the reader did. Right: read. Every answer also has `spans` and `traces` (counts of the store) and `diskBytes` (the bytes of the store's files; on a read-only server: of the files of the manifest it shows), D231.

* A local store: `{"mode": "local", "spans": .., "traces": .., "diskBytes": ..}`.
* A writer: `mode: "s3-writer"`, `url`, `writerEpoch`, `writerId`, `manifest` and `walSeq` (the newest manifest of this writer that IS in the bucket, and the last write in it), `localWalSeq` (the last write of the newest commit on the disk), `notUploadedForMs` (how long the oldest commit that is not in the bucket has waited; `null`: the bucket has every commit), `lastManifestAgeMs` (how long ago the writer last knew its newest manifest to be in the bucket; above the lease, another writer may start), `uploads`, `leaseRenewals`, `uploadedFiles`, `uploadedBytes`, `gc` (`runs`, `deletedFiles`, `deletedManifests`), `fenced` (`null`, or why), `lastError`, `wire`.
* `wire` (writer and read-only server): every request to the S3 service, each try counted, by the kinds that the price list of S3 knows: `get`, `head`, `list` (each page), `put`, `multipartParts`, `multipartCalls` (the start and the end of a multipart upload), `deleteBatches`, `delete`, `other`, and `failed` (of all of them: no answer, or a status of 400 or above). A writer prints it when it stops.
* A read-only server: `mode: "s3-reader"`, `url`, `manifest` and `walSeq` (the manifest that queries see now, and the last write in it), `writerEpoch`, `refreshes`, `requests` (GET and LIST requests to the bucket), `fetchedBytes`, `notFound` (requests for a file that was deleted), `retries` (queries that ran again), `cache`: `bytes` (in the cache dir now), `limitBytes`, `blocks`, `evicted`, `blockBytes`, `hits` (blocks that a read took from the cache dir) and `misses` (blocks it had to fetch); `lastRefreshAgeMs` (how long ago a look for a newer manifest last worked) and `lastRefreshError` (why the last one failed; `null` when it worked): while a look fails, the server answers from the manifest it has; `refreshTooSlow` (`null`, or why `--s3-refresh` is too long for the grace time of the writer that holds the store now).

To see what a query costs: read the route before and after it. `results/s3-cold-queries-minio.json` has these counts for 10 queries on a new read-only server (a small store on a localhost MinIO: counts, no times).

## Limits of S3

* Not run on real S3. Not measured: times, request counts per day, cost, memory. What to set up on AWS, the least IAM policy, and what is not supported (directory buckets, Object Lock, access points, a profile or SSO login without exported keys, lifecycle rules that expire current objects): `docs/S3.md`, section "Amazon S3: what to set up, and what is not supported".
* `--s3-refresh` of a read-only server above half of the writer's `--s3-gc-grace`: the server does not start (the manifest names the writer's grace time; a manifest of a build before F88 does not, and is not checked).
* One file of the store can be at most about 97.6 GiB: 10,000 parts of 10 MiB (`docs/S3.md`, section "Amazon S3: what to set up, and what is not supported").
* In a bucket with versioning, the cleanup's deletes leave the old versions (`docs/S3.md`, section "Amazon S3: what to set up, and what is not supported").
* One store per server. `--tenants-dir` with `--s3` is refused: it needs a list of the tenants in the bucket, one cache limit for all tenants, and uploads that do not take one thread per open store. Not built.
* The write log is not in the bucket (see "What can be lost").
* The S3 service must refuse a second create (`If-None-Match: *` on PUT). AWS S3 does since August 2024. The server checks it at start.
* The first upload of a store that is already large (the first row of the table with a store in the folder) is done before the server takes requests.
* The cleanup lists every object of the prefix each time it runs, in the uploader's thread. With very many objects the next upload waits for it.
* A read-only server keeps the word lists of the text fields in memory for every part of the index it has opened (`docs/S3.md`, core change 7). How much: not measured.
* Each refresh of a read-only server is one LIST request: 17,280 per day at the default (arithmetic).
* `--retention` on a writer drops old spans as without `--s3`, and the drop is uploaded like any commit. Not tested with `--s3`.
* `magpie-server import` writes to a local folder. To import into a store in a bucket: stop the writer, import into its folder, start it again.


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