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

> Keep a Magpie store in an S3 bucket, run read-only servers on it, and set up Amazon S3 the safe way.

`--s3 s3://<bucket>/<prefix>` keeps the store in a bucket too.

> [!NOTE]
>
> **Tested with MinIO on this machine, and once on Amazon S3 from one EC2 machine with an instance role** (2026-12-05, [`docs/FINDINGS.md` F95](https://github.com/intojhanurag/magpie/blob/main/docs/FINDINGS.md), the EC2 run: the S3 test list, and a deployment with 809,982 spans sent over OTLP, every one read back; one run, see [Limits](https://docs.magpiedb.com/limits.md#s3)). The faults of a real service (a lost answer, `503 SlowDown`, a slow bucket) are tested with a proxy that makes them on purpose (F88). Read the AWS part below: it says what was run on AWS and what was only read from the AWS documentation and the code.

## Set it up

The keys and the region come from the usual AWS variables:

```sh theme={null}
export AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... AWS_REGION=us-east-1
```

### The writer

The writer has the store on its local disk, as without S3, and uploads its commits to the bucket (at most one upload per 10 s):

```sh theme={null}
magpie-server --dir ./writer --s3 s3://my-bucket/traces
```

```sh theme={null}
"$REPO/scripts/send-trace.sh" --url http://127.0.0.1:4318 > /dev/null
sleep 12
curl -s localhost:4318/v1/storage | jq -c '{mode, spans, uploads: (.uploads > 0), fenced, lastError}'
```

```json theme={null}
{"mode":"s3-writer","spans":3,"uploads":true,"fenced":null,"lastError":null}
```

### A read-only server

A read-only server answers queries from the bucket, on any machine, with a block cache on its disk. Run as many as you need:

```sh theme={null}
magpie-server --s3 s3://my-bucket/traces --read-only --cache-dir ./cache --http-addr 127.0.0.1:4320 --grpc-addr 127.0.0.1:4319
```

```sh theme={null}
curl -s localhost:4320/v1/count -d '{}'
```

```json theme={null}
{"count":3}
```

## Flags

| flag | default | meaning |
| - | - | - |
| `--s3 s3://<bucket>/<prefix>` | | keep the store in this bucket too |
| `--s3-endpoint http://host:9000` | | for a service that is not AWS (MinIO, others) |
| `--s3-upload-interval` | `10s` | writer: at most one upload per this time. At most half of `--s3-lease`. |
| `--s3-lease` | `60s` | writer: a new writer does not start while the newest manifest in the bucket is younger than the lease of the writer that made it. An idle writer makes a manifest every half of it. |
| `--s3-take-over` | off | writer: start although another writer may hold the store. That writer then stops accepting writes. |
| `--s3-gc-grace` | `30m` | writer: an object that the store no longer needs is deleted after this time |
| `--s3-gc-interval` | `10m` | writer: how often old objects are deleted |
| `--read-only` | | start a read-only server on the bucket |
| `--cache-dir` | | read-only server: the folder of the block cache |
| `--s3-refresh` | `5s` | read-only server: how often it looks for a newer manifest. At most half of the writer's `--s3-gc-grace`. |

Every flag and every case of folder against bucket: [Server reference, "S3"](https://docs.magpiedb.com/reference/server.md).

## How it works for you

* **One writer per prefix.** A second writer is refused while the first one's lease (60 s) is fresh. `--s3-take-over` starts it anyway; the old writer then refuses writes (`503`, "fenced").
* An empty `--dir` with a store in the bucket: the writer downloads the store and goes on.
* The server checks at start that the bucket refuses a second create of one object (`If-None-Match`). Without that it does not start.
* A read-only server is behind the writer by up to the upload interval plus 5 s. It looks for a newer manifest every `--s3-refresh`. Each answer is from one commit of the writer.
* When the look at the bucket of a read-only server fails, it goes on answering from what it has: `lastRefreshAgeMs` and `lastRefreshError` in its `GET /v1/storage` say since when and why.
* **`--s3-refresh` of a read-only server must be at most half of the writer's `--s3-gc-grace`** (5 s against 30 min with the defaults). With more, it does not start: the writer's cleanup could delete a file under it.
* An error of the S3 service is shown as its kind, its HTTP status and its error code only, for example `S3 request failed (PUT seg): no permission, HTTP 403 AccessDenied`: never a URL, a key id or the body of the answer.

### The cleanup

The writer deletes what no reader can need, every `--s3-gc-interval`, right after an upload. A manifest is kept while it is the newest and for `--s3-gc-grace` after the NEXT one was made. A file under `seg/` goes when no kept manifest names it and it is older than that time. So a reader has the grace time to move on from a manifest. Only Magpie's own cleanup may delete under `manifest/`, `seg/` and `probe/`.

### What can be lost

> [!WARNING]
>
> If the writer's disk is lost, the writes after its last upload are lost (about 10 s with the defaults, **while the bucket can be reached**). The write log is not in the bucket. If only the process dies, nothing is lost: start it again on the same folder.

> [!WARNING]
>
> **While the bucket cannot be reached, the writer goes on taking writes**, and the bucket falls behind for as long as that lasts. No flag refuses writes. After the lease (60 s) another writer may start from the bucket; the first one is then fenced, and its writes since its last upload are in its folder only.

`GET /v1/storage` says how far the bucket is behind: `walSeq` is the last write in the bucket, `localWalSeq` the last one on the disk, `notUploadedForMs` how long the oldest commit that is not in the bucket has waited (`null`: nothing waits), `lastError` why. Watch `notUploadedForMs`.

## On Amazon S3

Read from the AWS documentation and from the code, and **run once on AWS** from EC2 with an instance role and the writer policy below ([`docs/FINDINGS.md` F95](https://github.com/intojhanurag/magpie/blob/main/docs/FINDINGS.md), the EC2 run: a writer, a restarted writer, a read-only server and a new writer from the bucket ran under that policy). Every other point here is read, not run. The whole list, with a link to the AWS page for each point: [`docs/S3.md`, section "Amazon S3: what to set up, and what is not supported"](https://github.com/intojhanurag/magpie/blob/main/docs/S3.md#7-amazon-s3-what-to-set-up-and-what-is-not-supported).

### The bucket

* A **general purpose bucket** in a commercial AWS region, storage class S3 Standard, with the bucket's default encryption (**SSE-S3**).
* **SSE-KMS** as the bucket's default encryption, with the key permissions below. Not run by any test (no KMS on MinIO).
* A bucket with versioning off. With versioning on, the store works, but deletes cost more than they look (see "Versioning").
* Turn on all four settings of [Block Public Access](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-control-block-public-access.html). Magpie never makes an object public.
* `AWS_REGION` must be the region of the bucket: it is never looked up, and without it `us-east-1` is taken.
* A prefix can be any text up to 800 bytes with no empty part, no part `.` or `..` and no control character. The key in the bucket is exactly the prefix that was given: the keys are exactly `<prefix>/manifest/...`, `<prefix>/seg/...` and `<prefix>/probe/...`. A prefix that cannot be a key is refused at the start, with the reason.

### Not supported: do not use

* **Directory buckets (S3 Express One Zone).** `magpie-server` refuses a bucket whose name ends in `--x-s3`, and refuses `AWS_S3_EXPRESS`.
* **Object Lock with a default retention.** Such a bucket wants a checksum header on every PUT, which Magpie does not send, so the start-up check fails and the server does not start. With a checksum turned on by hand the uploads work, but the cleanup's deletes only add delete markers and the locked versions stay and cost. Not tested.
* **Access points, multi-region access points, other AWS partitions (China, GovCloud).** `--s3` takes `s3://<bucket>/<prefix>` with a plain bucket name. Not tested.
* **A profile or an SSO login alone.** The server does not read `~/.aws/credentials`, `~/.aws/config`, `AWS_PROFILE`, the SSO cache or `credential_process`. See "Credentials".
* **Archive storage classes** (Glacier, Deep Archive, Intelligent-Tiering's archive tiers) for objects under the prefix: a GET of an archived object fails until it is restored.

### Credentials

What `magpie-server` can use, in the order `object_store` tries them:

| where it runs | what to set |
| - | - |
| anywhere, with keys | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` for a session. They are read once and never renewed: a session that ends stops the uploads (`lastError` shows `HTTP 400 ExpiredToken` or `HTTP 403`). They win over every role below. |
| EKS, with a role for the service account (IRSA) | nothing by hand: EKS sets `AWS_WEB_IDENTITY_TOKEN_FILE` and `AWS_ROLE_ARN`. Renewed by itself. [IRSA](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html) |
| ECS, with a task role | nothing by hand: ECS sets `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`. [container credentials](https://docs.aws.amazon.com/sdkref/latest/guide/feature-container-credentials.html) |
| EKS Pod Identity | nothing by hand: `AWS_CONTAINER_CREDENTIALS_FULL_URI` and `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`. |
| EC2, with an instance role | nothing: the role is read from the instance metadata service (IMDSv2) and renewed. Set no keys in the environment, or they win. [instance roles](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-metadata-security-credentials.html) |
| a laptop with a profile or `aws sso login` | export the keys of the profile into the environment: `eval "$(aws configure export-credentials --profile <name> --format env)"`. They end when the session ends. For a server that runs for long, use a role. |

**The region is never looked up.** Set `AWS_REGION` (it wins over `AWS_DEFAULT_REGION`) to the region of the bucket; without it `us-east-1` is taken. **The endpoint:** `AWS_ENDPOINT_URL_S3` wins over `--s3-endpoint` and over `AWS_ENDPOINT_URL`: unset it when it is for another tool. Requests go to `https://s3.<region>.amazonaws.com/<bucket>/...` (path style); `AWS_VIRTUAL_HOSTED_STYLE_REQUEST=true` for the other style ([virtual hosting](https://docs.aws.amazon.com/AmazonS3/latest/userguide/VirtualHosting.html)).

> [!NOTE]
>
> The EC2 row was run (IMDSv2 only; F95, the EC2 run). A renewal of the role's keys was not seen (they lived 6.5 hours, the run 20 minutes). The other role rows are read from the source.

### The IAM policy

The least that a **writer** needs, for the bucket `BUCKETNAME` and the prefix `PREFIX` (with no prefix, leave `PREFIX/` out). Made from the calls in the code; **run on AWS** for a writer, a restarted writer, a new writer from the bucket and a read-only server, each under exactly this policy (F95, the EC2 run). The smaller read-only policy below was not run.

```json theme={null}
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ListTheStore",
      "Effect": "Allow",
      "Action": "s3:ListBucket",
      "Resource": "arn:aws:s3:::BUCKETNAME",
      "Condition": { "StringLike": { "s3:prefix": ["PREFIX/manifest/*", "PREFIX/seg/*", "PREFIX/probe/*"] } }
    },
    {
      "Sid": "ReadTheStore",
      "Effect": "Allow",
      "Action": "s3:GetObject",
      "Resource": ["arn:aws:s3:::BUCKETNAME/PREFIX/manifest/*", "arn:aws:s3:::BUCKETNAME/PREFIX/seg/*", "arn:aws:s3:::BUCKETNAME/PREFIX/probe/*"]
    },
    {
      "Sid": "WriteAndCleanUp",
      "Effect": "Allow",
      "Action": ["s3:PutObject", "s3:DeleteObject"],
      "Resource": ["arn:aws:s3:::BUCKETNAME/PREFIX/manifest/*", "arn:aws:s3:::BUCKETNAME/PREFIX/seg/*", "arn:aws:s3:::BUCKETNAME/PREFIX/probe/*"]
    },
    {
      "Sid": "GiveUpAMultipartUpload",
      "Effect": "Allow",
      "Action": "s3:AbortMultipartUpload",
      "Resource": "arn:aws:s3:::BUCKETNAME/PREFIX/seg/*"
    }
  ]
}
```

* A **read-only server** needs only `s3:ListBucket` for `PREFIX/manifest/*` and `s3:GetObject` on `PREFIX/manifest/*` and `PREFIX/seg/*`.
* Magpie lists with the prefixes `PREFIX/manifest/`, `PREFIX/seg/` and `PREFIX/probe/` exactly, so the condition can also be `StringEquals` on those three values. **Use `StringEquals` when PREFIX holds `*` or `?`**: `StringLike` reads them as wildcards, and the statement then allows more prefixes than the one of the store.
* The start, the parts and the end of a multipart upload are allowed by `s3:PutObject`; giving one up needs `s3:AbortMultipartUpload` ([multipart upload and permissions](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html)). There is no `s3:HeadObject` action: a HEAD is allowed by `s3:GetObject`.
* Not needed: `s3:CreateBucket`, `s3:ListAllMyBuckets`, `s3:GetBucketLocation`, any `...Version` action, any ACL or tagging action. Magpie makes no bucket and changes no bucket setting.
* **Without `s3:ListBucket`, a missing object answers 403, not 404** ([GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html)). The reader's "the file was deleted, load the newest manifest" path needs the 404: keep the `ListBucket` statement for readers too. Not tested with a real policy.
* **SSE-KMS:** the writer also needs `kms:GenerateDataKey` and `kms:Decrypt`, a reader `kms:Decrypt`, on the one key `arn:aws:kms:REGION:ACCOUNT_ID:key/KEY_ID`, and the key policy must allow the role ([SSE-KMS](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html)). A multipart upload needs both actions. With the bucket's default encryption set to that key, Magpie sends no header. If a bucket policy demands the header on each PUT: `AWS_SERVER_SIDE_ENCRYPTION=aws:kms` and `AWS_SSE_KMS_KEY_ID=<key ARN>` (`AWS_SSE_BUCKET_KEY_ENABLED=true` for bucket keys). Never a wildcard on KMS.

### Lifecycle rules

A lifecycle rule acts on the age of an object. It knows nothing of the manifests ([lifecycle](https://docs.aws.amazon.com/AmazonS3/latest/userguide/lifecycle-expire-general-considerations.html)).

> [!WARNING]
>
> **No rule may expire or move current objects under the store's prefix** (for example "delete everything after 30 days", or a move to Glacier). A file of the store is written once and stays in use for as long as the index needs it: a file of the first day is still read on day 400. Such a rule deletes live files: readers fail, and a new writer cannot download the store. Magpie's own cleanup is the only thing that may delete under `manifest/`, `seg/` and `probe/`.

* **One rule is wanted:** `AbortIncompleteMultipartUpload` after 1 to 7 days, on the store's prefix (or the bucket). A writer that is killed in the middle of a big file leaves parts that are billed until they are given up, and the cleanup cannot see them: it lists objects, not unfinished uploads ([the rule](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-abort-incomplete-mpu-lifecycle-config.html)). This rule never touches a finished object.
* With versioning: a rule that expires **noncurrent** versions and removes expired delete markers is safe and saves money (next section).

### Versioning

With versioning on, a delete without a version id only adds a delete marker; the old version stays and is billed ([versioning](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html)). Magpie's cleanup deletes without version ids, and its counts (`gc.deletedFiles`) are keys, not versions. So in a versioned bucket the cleanup frees no storage by itself, and data that was deleted for privacy stays as an old version: add a lifecycle rule for noncurrent versions. A file that is uploaded a second time after a failed try adds a version too. After versioning is turned on for the first time, wait 15 minutes before the first write, as AWS says ([enabling](https://docs.aws.amazon.com/AmazonS3/latest/userguide/manage-versioning-examples.html)). Not tested (the MinIO of the tests has no versioning).

### Limits of size

* **One file of the store: at most about 97.6 GiB.** A file above 10 MiB goes up in parts of 10 MiB, and S3 takes at most 10,000 parts: 10,000 x 10 MiB = 104,857,600,000 bytes = 97.65625 GiB ([multipart limits](https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html)). An upload of a larger file fails at part 10,001 and is tried again for ever (`lastError` shows it). No store of the tests is near it; a store's largest file is its largest merged segment.
* A listing of S3 has at most 1,000 keys per page, and a delete request takes at most 1,000 keys; the code handles both. No test has more than 1,000 objects under one prefix.

### What it costs

Every read-only server lists `manifest/` once per `--s3-refresh`: with the default (5 s) that is 17,280 LIST requests a day, more when the list has more than 1,000 manifests. The cleanup lists all three folders each time it runs and reads each manifest it has not read. An idle writer makes one manifest per half lease: 2,880 a day at the default. S3 bills LIST at the price of PUT ([pricing](https://aws.amazon.com/s3/pricing/)).

**The first day:** `wire` in `GET /v1/storage` counts every request to the service (each try, by the kinds of the price list). Read it before you guess the bill. With a role of EC2, ECS or EKS it also counts the requests for the role's keys (1 PUT and 2 GET each time the keys are fetched; they are free). One run on EC2 cost 0.21 USD in all, 0.06 USD of it S3 requests (F95, the EC2 run).

## Test a real bucket

`scripts/s3-real-run.sh` runs the whole S3 test list against a bucket that is there already, under one new prefix, and deletes everything it made. Help: `scripts/s3-real-run.sh --help`.

```sh theme={null}
S3_BUCKET=<bucket> AWS_REGION=<region> AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... scripts/s3-real-run.sh --out results/s3-real-<date>.json
```

* It refuses to start without a bucket, a region, credentials in the environment (a profile alone is refused, with the command that exports its keys), the AWS CLI and `jq`.
* **Before any test it proves that the credential can clean up.** A missing permission stops the run there, with exit 2 and the name of the permission, and nothing is left.
* The fault tests need the proxy, and the proxy needs plain HTTP: against AWS they are listed as NOT RUN.
* After the tests it deletes every object, every old version, every delete marker and every unfinished multipart upload under its prefix, and fails if anything is left. A stop in the middle (Ctrl-C, SIGTERM, a closed terminal) runs the same cleanup first. Not covered: `kill -9` of the script, a machine that loses power, and a network that is gone at that moment. Then delete by hand what is under the prefix that the script printed at its start.
* The run uses one credential for everything. That is more than a server needs, because the cleanup deletes versions and unfinished uploads. Use a bucket that holds nothing you would miss. The policy that passed on AWS, and the tests of the S3 test program by itself: [`docs/S3.md`, section "The run on a real bucket"](https://github.com/intojhanurag/magpie/blob/main/docs/S3.md#8-the-run-on-a-real-bucket).

## More detail

The design, the prototype numbers and the fault tests are in [`docs/S3.md`](https://github.com/intojhanurag/magpie/blob/main/docs/S3.md). Limits that apply to S3: [Limits](https://docs.magpiedb.com/limits.md#s3).


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