Metadata-Version: 2.5
Name: envlib-api
Version: 0.5.0
Summary: The envlib data API service: an OGC API - EDR server for envlib datasets, and the refresher mirroring the envlib catalogue and dataset indexes into MongoDB
Project-URL: Source, https://github.com/envlib/envlib-api
Author-email: Mike Kittridge <mullenkamp1@gmail.com>
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Programming Language :: Python :: 3 :: Only
Requires-Python: >=3.12
Requires-Dist: cfdb>=0.12.0
Requires-Dist: ebooklet[mongo]>=0.13.2
Requires-Dist: envlib>=0.1.9
Requires-Dist: fastapi>=0.115
Requires-Dist: orjson>=3.9
Requires-Dist: pyproj>=3.6
Requires-Dist: s3func>=0.10.0
Requires-Dist: sentry-sdk>=2.39
Requires-Dist: shapely>=2.0
Requires-Dist: typer>=0.12
Requires-Dist: uvicorn>=0.30
Requires-Dist: zstandard>=0.22
Description-Content-Type: text/markdown

# envlib-api

The envlib data API service, in two processes:
- the **refresher** keeps a MongoDB copy of the public envlib catalogue and of every catalogued
  dataset's index, using `ebooklet.mongo.refresh()`;
- the **API** (`envlib-api-server`) is a read-only OGC API – EDR server that answers every request
  from that MongoDB, and fetches a chunk from B2 only on a cache miss.

Its design record is `plans/edr_api_assessment.md` §11 in the envlib repo, and the work is tracked
under "EDR API (new service)" in envlib's `OPEN_WORK.md`. The API runs locally so far. Deploying it on
the swarm is "EDR plan 6: going public".

## What runs

| Service | What it does |
|---|---|
| `mongo` | MongoDB 9.0, on one node with a named volume, with auth and no published port. It holds only data derived from B2, so it has no backups. |
| `refresher` | Every 60 s it refreshes the catalogue, syncs the set of mirrored datasets with it, then refreshes every dataset. It is pinned to MongoDB's node. |
| `api` (local only so far) | The EDR API: station (`ts_ortho`) and grid collections, and the envlib catalogue at `/catalogue`, with its docs site at `/docs/`. See "The API" below. |

Each cycle, in order:
1. **Refresh the catalogue.** It is an ebooklet RemoteConnGroup, mirrored like any dataset under the
   id `catalogue`.
2. **Sync** (`envlib_api/mirror.py`):
   - Membership is the catalogue index's keys.
   - A new or changed entry is refreshed first and listed afterwards, in the `catalogue` collection.
   - A removed entry is **retired**: its `datasets` document is tombstoned, never deleted, and its
     entries are deleted. A retire happens only when every guard passes, so a broken, empty or
     recreated catalogue, or one dropping more than 2 datasets at once, retires nothing and alerts.
     Every retire alerts, whether or not a guard was involved.
   - A changed `db_url` (a re-point) is followed only when the new remote answers and the
     catalogue's uuid is acknowledged. Until then the old remote keeps being served and polled.
3. **Refresh every listed dataset**, oldest check first. Each one is isolated: a failure is logged
   and reported to Sentry once until it clears. The same goes for every other alert, except retires
   and catalogue adoptions, which alert every time.
4. **Send a Sentry cron check-in.** It is "ok" when the catalogue refresh and the sync succeeded and
   at least one dataset refreshed to `applied` or `nochange`, and "error" otherwise. A missed check-in
   alerts too.

MongoDB collections:
- from `ebooklet.mongo`: `datasets`, `entries` and `chunks` (ebooklet's `docs/ops.md`, "The MongoDB
  read path");
- from this repo: `catalogue` (one document per dataset version) and `state` (the acknowledged
  catalogue uuid).

## The API

`envlib-api-server` runs uvicorn with one worker; scale it with replicas. Each request builds its own
`MongoStore` and cfdb dataset. The process shares only the MongoDB client and the B2 HTTP session, so
nothing is cached in the process. Its code is in `envlib_api/api/`, and the refresher's CLI never
imports it.

**The user documentation is the docs site** (`docs/`, `mkdocs.yml`; plan EDR plan 7). The API serves
it at `/docs/`, built into the image, so the docs always describe the API they are deployed with. It
holds the routes, the query rules, stations, grids, the catalogue, the formats, CORS, the limits and
every answer. Every example on it runs as a test in the default `uv run pytest`, against a local API
over a docs world that carries the live dataset ids (`envlib_api/tests/docs_support.py`). This README
keeps what an operator or a developer needs. Build the site with `uv run mkdocs build`; a server finds
it at `[api] docs_dir`, and without one it serves no `/docs`, links to no docs and claims no `oas31`.

**The route specs** (`envlib_api/api/routes.py`). Each route has one spec: its query parameters, the
required ones, its `f` and `crs` values, and its statuses. The handlers validate every request through
it, and `/api` (`envlib_api/api/openapi.py`) and the docs' Reference page are built from it, so the
three cannot disagree. A test probes every route with every parameter name, and another makes each
documented status happen; a recorder at the outermost layer fails the suite on any answer `/api` does
not document (`envlib_api/tests/recorder.py`).

**CORS** is one ASGI middleware (`Cors` in `envlib_api/api/app.py`), which adds the headers to every
answer as it starts: errors, `/api`, `/docs` and Starlette's trailing-slash redirects included (Mike,
2026-11-25). The unexpected 500 is sent outside every middleware, so its handler sets them itself (code
review `edr-api-code-5`). Exposing `ETag` and allowing `If-None-Match` wait for plan 6's conditional
requests, and `HEAD` is plan 6's too.

**The caps** (`[api]` in the API's TOML; `envlib_api/config.py` has the defaults):
- `max_values`: the values returned (stations or cells × levels × time steps × parameters);
- `max_decoded_bytes`: the data chunks a request touches × their decoded size;
- `max_csv_rows`: CSV rows.

They are counted from each dimension's chunk spans after the coordinates are read, before any key is
built or data chunk read. A request over one answers 413, naming the limit, the dataset's `db_url`
and an envlib snippet for reading it directly. The key list is then built from the same spans and
feeds the one batched fetch (`store.load_items`), so the estimate is exactly what is fetched. On the
live WRF grids the bytes cap (100 MB) is about 51 chunks: one cell over about 4.9 years, or a cube of
about 300 km square at one hour. A full WRF map at one hour touches 322 chunks (623 MB) and answers
413, deliberately: bulk reads belong to envlib (Mike, 2026-11-25).

### Grids

The rules for `/position` and `/cube` are the docs' Grids page (`docs/grids.md`). Their code is
`envlib_api/api/grid.py` (plan 4, its review `edr-api-plan-4` and code review `edr-api-code-4`).
- **Decided by Mike, 2026-11-25:** no reprojection; geographic grids served only on WGS 84; the edge
  tolerance of 0.1% of the edge spacing; the cube unmasked; a cube in CoverageJSON only; the cached
  transformers (below).
- On each axis the cell is the nearest stored centre, found by `searchsorted` on the midpoints.
- **The cost before the caps:** the cube's rectangle is found by projecting every cell centre to CRS84,
  before the caps are checked. That is 15 ms on WRF's 168,210 cells, but about 2 s and 784 MB on a
  16-million-cell grid. Bounding it first is the backlog item "[new service] Bound the cube hull's
  projection on large grids", triggered by the first projected grid over about 1 million cells.
- Grid `/area` and netCDF output are the item "EDR grid `/area` and netCDF output" in envlib's
  `OPEN_WORK.md`.
- The pyproj transformers are cached per CRS (an `lru_cache` keyed by the WKT; Mike, 2026-11-25):
  building them cost about 25 ms per request. pyproj builds its PROJ object per thread, so sharing
  one is safe, but a `from_crs` transformer repeats PROJ's operation search in every new thread. So
  the cache holds a `from_pipeline` transformer of the operation PROJ chose, which a new thread
  rebuilds in 0.2 ms. That works when PROJ resolves one operation, as on the WRF CRS. For a CRS where
  PROJ keeps several (EPSG:27200 or 27700, for example), the `from_crs` transformer is cached instead:
  it is correct, but it pays about 30 ms in each new thread.

### The catalogue

The rules for `/catalogue` and `/catalogue/distinct/{field}` are the docs' catalogue page
(`docs/catalogue.md`). They serve the envlib catalogue as the mirror holds it
(`envlib_api/api/catalogue.py`; plan 5 and its review `edr-api-plan-5`): each request reads every
mirrored catalogue document and calls envlib's own matching functions.
- A `bbox`'s numbers are parsed strictly here and passed to envlib as given, and envlib reads 0–360
  boxes itself, so `Catalogue.query(bbox=...)` gives the same entries.
- The `limit` default and clamp is `catalogue_limit` in `[api]`.

**Operator limits:**
- the mirror never lists an entry it refuses (one with no http(s) `db_url` or no `dataset_id`, or an
  integer of 2⁶³ or more), and a changed entry whose member refresh keeps failing keeps its old
  metadata until it succeeds;
- a new entry appears within one poll of its first successful mirror;
- every request reads the whole mirrored catalogue: 41 KB for today's 18 entries, and about 48 ms at
  5,000 entries on loopback (plan review `edr-api-plan-5`);
- `/catalogue/distinct/{field}` answers 500 if a stored value of that field is a list or an object,
  as envlib's `distinct()` raises on it. Only a hand-damaged entry holds one, since `Metadata` would
  not publish it (code review `edr-api-code-5`).

**Consistency** (`envlib_api/api/resolve.py`). Every attr is read first, then the selection and the
cap, then the batched fetch and the reads, then `store.verify()`. `verify()` runs before every answer
computed from the store, a 413, 204 or 404 included.

| Raised | Answer |
|---|---|
| A refresh overlapped the request (a refused store build, or a failed `verify()`) | A new store after `retry_wait_ms`, up to `retry_attempts` times; then 503 with `Retry-After` |
| The remote is ahead of the mirror (a chunk fetch found a newer commit, and nothing was applied since) | 503 with `Retry-After` at once: only the refresher's next poll helps |
| `RemoteMissingError` | No version of the `dataset_id` left: 404. Another version is now the latest: retry. Otherwise 503 |
| `RemoteIntegrityError`, or chunk bytes that do not decode | 500, logged at ERROR |
| Another B2 failure | 502 |
| MongoDB unavailable (selection times out after 5 s) | 503 with `Retry-After` |
| The request deadline passed | 503 with `Retry-After` |

The deadline (`request_deadline_seconds`) is checked between attempts and after the batched fetch.
It cannot interrupt a fetch in progress, so a request can overrun it by one B2 read: `read_timeout` ×
(`retries` + 1), plus s3func's backoff.

A collection whose store cannot be built is left out of `/collections` and logged. It never fails
the listing. A catalogue entry whose `created_at` does not parse counts as the oldest version, with a
warning; the rule is envlib's (`envlib.latest_per_dataset`, since envlib 0.1.9), and the API has no
copy of its own. The warning is envlib's `warnings.warn`, routed to the log by
`logging.captureWarnings`, so it is logged once per process for each damaged entry, not on every
request. A latest version whose remote is `missing` hides an older working one, as envlib's
`query()` would.

**The API's MongoDB user** is `api`, with the role `envlib_api_reader` (`mongo/api-role.json`): `find`
on `datasets`, `entries`, `catalogue` and `chunks`, and `insert` on `chunks`. It never calls
`ensure_schema`. ebooklet only logs a WARNING when a chunk insert is refused, so a cache that refuses
inserts would serve correct data, always cold. Two checks make that loud (at ERROR, so Sentry reports
it):
- at start, the API reads its own privileges (`connectionStatus`) and reports any that are missing;
- at run time, the first refused insert of the process (a missing privilege, a validator, anything
  else) is re-reported at ERROR.
- On a new volume, `init-users.js` creates the user when the secret
  `envlib_api_mongo_api_password` is mounted.
- On the existing production volume, create it by hand as root in the `mongo` container, with the
  privileges from `mongo/api-role.json` (`<password>` is the API TOML's):
  ```
  db.getSiblingDB("envlib_api").createRole({role: "envlib_api_reader", roles: [], privileges: [
    {resource: {db: "envlib_api", collection: "datasets"}, actions: ["find"]},
    {resource: {db: "envlib_api", collection: "entries"}, actions: ["find"]},
    {resource: {db: "envlib_api", collection: "catalogue"}, actions: ["find"]},
    {resource: {db: "envlib_api", collection: "chunks"}, actions: ["find", "insert"]}]})
  db.getSiblingDB("envlib_api").createUser({user: "api", pwd: "<password>", roles: [{role: "envlib_api_reader", db: "envlib_api"}]})
  ```
- The API's credential can write bytes under a chunk id that is not cached yet. That is inherent in a
  cache the API fills itself, and plan 6 should weigh it.

**Running it locally:** `docker compose up -d mongo`, a refresher (`docker compose up refresher`, or
`uv run envlib-api refresher`), then `docker compose up api`, or
`ENVLIB_API_TOML=<the API's TOML> uv run envlib-api-server`.
- **Ports:** compose publishes the API on `127.0.0.1:8000`. The venv server binds `0.0.0.0:8000`
  unless `ENVLIB_API_HOST` and `ENVLIB_API_PORT` say otherwise.
- **Secrets:** compose's `mongo` service now mounts the API's password secret, so
  `mongo-api-password` must exist in the local secrets directory, even for the refresher alone.
- **The docs:** the image serves them at `/docs/`. The venv server needs `uv run mkdocs build` and
  `[api] docs_dir` set to the built `site/`.

## Rules that must not be broken

- **Exactly one refresher, ever.** Two overlapping refreshers can leave MongoDB permanently
  inconsistent with B2 while every check says it is current (ebooklet `docs/ops.md`). There is no
  lock. The stack prevents Swarm from running two: `replicas: 1`, stop-first updates, an exit within
  seconds of SIGTERM, and pinning to MongoDB's node. **Never run a second refresher by hand.** That
  means no `docker run … refresher`, and no development machine pointed at the production MongoDB.
  There is deliberately no one-shot refresh command.
  - If two refreshers are ever seen, build the lease the plan review designed (`planning/`): a
    server-clock expiry via `$$NOW` with a bootstrap insert and a non-upsert update, a uuid4 owner, a
    conditional release, and a 5-minute TTL renewed before each refresh. It is not built, because
    nothing above can start a second one.
- **Never add Cloudflare cache rules on the `b2.*` hosts.** The refresher and the API rely on db-object
  HEADs and GETs, and on 404s, never being cached. On 2026-11-23, every catalogued db object and 404s on
  both hosts answered `cf-cache-status: DYNAMIC`. A refresh status of `stale_get` (HEAD and GET
  disagree) means a cache has appeared, and it alerts.
- Cloudflare refuses Python's default `urllib` User-Agent with a 403, though ebooklet's sessions pass.
  A new bot rule could block the refresher, which would show as error check-ins and an unhealthy
  task.

## Deploy (Docker Swarm, on the manager)

**Where it runs (since 2026-11-24):** both services are on `uswest11.tethys-ts.xyz`, the manager, which
carries the `envlib_mongo` label. The checkout the stack is deployed from is
`~/git/envlib-repos/envlib-api` on that host. The live close-checks are
`planning/close-checks-live-2026-11-24.md`.

One time, on the manager:
1. **Pick MongoDB's node and label it.** The volume is node-local, and the refresher follows it.
   Label **exactly one** node: with two, `mongo` and `refresher` could be placed apart, and a
   restarted `mongo` could start on an empty volume.
   ```bash
   docker node ls
   docker node update --label-add envlib_mongo=true <node>
   ```
2. **Create the three secrets.** Generate the two passwords first, for example with
   `python -c "import secrets; print(secrets.token_hex(24))"`.
   - Hex needs no escaping. A password containing `@ : / %` must be percent-encoded in the URI, or the
     refresher fails at start with `InvalidURI`.
   - The refresher password goes in the TOML's URI, and it must match its secret.
   - Pass each secret on stdin (`-`) or from a file you delete afterwards, so nothing stays on disk.
   ```bash
   docker secret create envlib_api_mongo_root_password -        # paste, then Ctrl-D
   docker secret create envlib_api_mongo_refresher_password -
   docker secret create envlib_api_toml - <<'EOF'
   [mongo]
   uri = "mongodb://refresher:<refresher password>@mongo:27017/envlib_api?authSource=envlib_api"

   [sentry]
   dsn = "https://<key>@<org>.ingest.sentry.io/<project>"   # without it nothing alerts (the log says so at start)
   monitor_slug = "envlib-api-refresher"
   EOF
   ```
   - `envlib_api/config.py` has every TOML key.
   - The `dsn` must be a full `https://` URL. Anything else (a placeholder left in, for instance) makes
     the refresher crash-loop at start with sentry-sdk's `BadDsn: Unsupported scheme ''`, which is what
     happened on the first deploy.
   - The Sentry cron monitor is created by the first check-in (`monitor_config`), so it needs no setup.
3. **Build and push the image** from a checkout whose lock comes from PyPI (the Dockerfile's header
   explains why):
   ```bash
   docker build -t mullenkamp/envlib-api:0.1.0 . && docker push mullenkamp/envlib-api:0.1.0
   ```

Then, from the checkout on the manager:
```bash
git pull
docker stack deploy -c docker-swarm.yml envlib-api
```
Bump the image tag with every code change, and bump a config's `name:` with every change of its
file, because configs are immutable.

**Replacing a secret** (they are immutable too). A service holds the secrets it uses, so detach first:
```bash
docker service update --detach --secret-rm envlib_api_toml envlib-api_refresher
docker secret rm envlib_api_toml
docker secret create envlib_api_toml -          # the corrected TOML on stdin
docker stack deploy -c docker-swarm.yml envlib-api   # re-attaches it and restarts the refresher
```

## Operations

- **Status:** `docker exec -it $(docker ps -qf name=envlib-api_refresher) envlib-api status`. It
  shows one row per dataset and exits 1 if any is stale (`checked_at` older than 3 polls), missing,
  unapplied, or stuck applying. Retired datasets are listed but not flagged.
- **A blocked retire** (logged and alerted once): check the catalogue. If the removal is intended, run
  `envlib-api allow-retires` in the refresher container.
  - It acknowledges the current catalogue uuid.
  - It allows **one** retire pass that ignores the cap and the empty-catalogue guard.
  - That pass must come within an hour, and it is consumed when used.
  - It refuses while the catalogue mirror is not applied.
- **Never mirrored:** `status` also lists catalogue entries that have no dataset document. A new
  entry shows that way for up to one cycle; one that stays is failing, and Sentry has its error.
- **Changing the refresher password:** Swarm secrets are immutable, and `init-users.js` runs only on
  an empty volume.
  1. As root in the `mongo` container, run
     `db.getSiblingDB("envlib_api").changeUserPassword("refresher", "<new>")`.
  2. Create new secrets under new names (e.g. `envlib_api_toml_v2`), both the password and the TOML.
  3. Point `docker-swarm.yml` at the new names, and redeploy.
- **If `mongo`'s first start fails** (for example, `init-users.js` could not read a secret), the volume
  is already initialised and the script will not run again. Remove the stack and the volume
  (`docker volume rm envlib_api_mongo` on its node), fix the cause, and deploy again.
- **Stopping the refresher:** `docker service scale envlib-api_refresher=0`, and `=1` to restart it.
  While it is stopped, `checked_at` ages, `status` flags every dataset, and Sentry alerts on the missed
  check-ins.
- **Rebuilding MongoDB**, for example after a lost volume or a suspected divergence:
  1. scale the refresher to 0 (and the API);
  2. drop the database: `docker exec -it <mongo container> mongosh -u root -p --authenticationDatabase admin --eval 'db.getSiblingDB("envlib_api").dropDatabase()'`;
  3. scale the refresher back to 1.

  Its start re-creates the schema, and the first cycle re-mirrors everything: about 220 MB of indexes
  from B2, in about 75 s. Never drop collections under a running refresher, because it would
  recreate them without validators, compressors or the TTL index. The refresher's role and user
  survive `dropDatabase` (checked on 9.0.8). On a new, empty volume, `mongo/init-users.js` creates
  them; it runs by itself only then.
- **Upgrading MongoDB:** follow the binary-then-feature-compatibility-version pattern in
  `dshg/mvp/web_app/MONGO_DEPLOY.md`. Or, since the data is derived, rebuild on the new version.
- **autoheal is not running on the cluster** (checked 2026-11-24: no service, and no container on
  uswest11), although `tethys-docker-swarm/autoheal/` defines one with `AUTOHEAL_CONTAINER_LABEL=all`.
  Swarm replaces an unhealthy task itself, and waits for the old container to exit first. If autoheal is
  ever deployed, its in-place restart of the old container beside Swarm's replacement could make a second
  refresher. The refresher therefore carries the container label `autoheal=False`, which is autoheal's
  opt-out according to the code review's reading of its source. The label is on the running container,
  checked with `docker inspect`. Whether a deployed autoheal honours it is untested.
- **Seeing how a task stopped:** scaling a service down deletes its tasks, together with their logs,
  so `docker service ps` and `docker service logs` no longer show them. Docker's event log still does:
  `docker events --since 30m --until 0s --filter label=com.docker.swarm.service.name=envlib-api_refresher`
  shows each `kill` (with its signal) and `die` (with its exit code).
- **The role** is `readWrite` plus `collMod` on `envlib_api` (`mongo/refresher-role.json`). It includes
  `dropCollection`, which the refresher never uses. It is kept that broad because a hand-written action
  list would break silently the first time ebooklet's schema code needs another action.
- **Local runs** (`docker-compose.yml`) take their secrets from `~/.envlib/envlib-api-local`, never
  production's directory. Give the local TOML its own Sentry environment, or no DSN.

## Development

```bash
uv sync
docker run -d --rm --name envlib-api-test-mongo -p 127.0.0.1:27092:27017 --tmpfs /data/db \
  -e MONGO_INITDB_ROOT_USERNAME=root -e MONGO_INITDB_ROOT_PASSWORD=testpw mongo:9.0.8
ENVLIB_API_TEST_MONGO_URI='mongodb://root:testpw@127.0.0.1:27092/?authSource=admin' uv run pytest
```
- The tests use real ebooklet remotes on a moto S3 server and a real MongoDB with auth, connecting
  as the production roles (`mongo/refresher-role.json`, `mongo/api-role.json`).
- The API tests build their station datasets with envlib-ingest-base's `build_and_publish`, the real
  producer, and compare every answer with a direct cfdb read and with the producer's input
  (`envlib_api/tests/api_support.py`). The schema tests validate against the CoverageJSON and EDR 1.2
  schemas vendored in `envlib_api/tests/schemas/`.
- **The docs examples are tests.** `testpaths` includes `docs/`, so `uv run pytest` runs every
  example on every page (`envlib_api/tests/docs_support.py`; plan EDR plan 7). They need node (18.18 or
  later, for `--import`) and curl. Under CI a default run fails if no docs example ran.
  - They run against a docs API on loopback, over a docs world that carries the live dataset ids
    (`envlib_api/tests/docs_world.json`, copied from the live catalogue). The clients are fail-closed to
    it:
    - httpx is rewritten at its transport and guarded in-process (names and connections; the test
      MongoDB's own host is let through);
    - curl takes an allowlist of flags and only the API's URL, runs with `-q` (no `.curlrc`), and goes
      through a dead proxy;
    - node goes through `envlib_api/tests/docs_preload.mjs`, which models a browser on another site: GET
      only, no request header that would need a preflight, `Access-Control-Allow-Origin: *` required, and
      no hidden response header readable;
    - python and javascript blocks may not start processes or open sockets (`subprocess`, `socket`,
      `process`, …).
  - Every shown output is compared exactly, and a block that gets a non-200 answer must show its status in
    its shown output. A python block is a doctest with no blank line; an output marker sits on the line
    directly before its text fence. `test_docs_inventory.py` checks the page rules, and checks that each
    built page renders exactly the code blocks the harness runs (an indented or `~~~` block, or one a
    snippet pulls in, fails it). The illustrations and ELLIPSIS uses must equal
    `envlib_api/tests/docs_manifest.txt`. `test_docs_harness.py` plants a wrong page for each rule.
  - A page that shows a 413 or a 5xx switches the docs API with a hidden `docs.use(<mode>)` block.
  - `test_docs_inventory.py` also builds the site (`mkdocs build --strict`), fails on anything a page would
    load from outside the API, and checks the Reference page against `/api` row by row.
  - The run fails if it changed anything in the real `~/.envlib` (its file stats are compared).
  - **Known limits** (code review `edr-api-code-7`): a status number that happens to appear in a shown
    output (a quality code 400 in a CSV row) counts as shown; `NORMALIZE_WHITESPACE` is global, as in
    envlib, so a shown output's spacing and line breaks are not compared; UDP is not guarded.
- `planning/mutate.py` runs the mutants in `planning/mutants.json` (the refresher) and
  `planning/mutants_api.json` (the API). Every one must be KILLED except the documented equivalent
  (`planning/mutants_result.txt`, `planning/mutants_api_result.txt`).
- The catalogue's mutants are `planning/mutants_catalogue.json` (the API side) and
  `planning/mutants_envlib.json` (envlib's matching, run by `planning/mutate_envlib.py` on a copy of
  envlib). `mutate.py` keeps an existing `PYTHONPATH` after the copy, so a mutant run can import an
  envlib that is not on PyPI yet (for example `PYTHONPATH=../envlib MUTATE_ENVLIB_VERSION=<its version>`).
- The docs harness's and `/api`'s mutants are `planning/mutants_docs.json` (plan 7). Since plan 7, a
  mutant with an `expect` must fail that test: one killed by another test reports `KILLED ELSEWHERE`,
  which counts as a failure. The copy also takes the root `conftest.py`, `docs/` and `docs_hooks/`.
- `planning/close_check_docs.py` checks a running API's docs site, `/api` and every docs example against
  the live commons.
- `planning/close_check_api.py` compares a running API with direct envlib reads of the live datasets.
- `benchmarks/` times the API's hot paths, and an A/B of the previous release against the candidate
  is a release step (`benchmarks/README.md`).
