# ChloeDB > ChloeDB is a search database with SQL: full text (BM25), vectors, graphs and structured fields in tables, embedded in a process (Rust, Python, JavaScript, Java) or served by chloedb-server over HTTP, gRPC and MCP, on one machine or a cluster. Its SQL is its own dialect, not Postgres: MATCH and bm25 for words, similarity for meaning, rrf to fuse them. An agent connected to a chloedb-server over MCP (`{server}/v1/mcp`) gets these documents through its `search_docs` tool and its prompts. [Build with an AI agent](https://chloetech-ai.github.io/chloedb/guide/agents.md) says how to connect one and the prompts that work. The rendered site is https://chloetech-ai.github.io/chloedb/site/docs/. --- # ChloeDB documentation ChloeDB is an embedded search database with SQL: full text, structured columns, vectors and graph edges over the same rows, in one file, combined in one query by one planner. It runs inside your program like SQLite, or as a server and a cluster with the same SQL.
QuickstartInstall it and run your first search in five minutes. ConceptsThe file, tables, the three indexes, scores and the planner. Search guideWords, typos, filters, facets, vectors and hybrid ranking, on one small catalogue. SQL referenceEvery statement, function and option.
## Where to start | you are making | start with | then | |---|---|---| | a Python app, script or notebook, with the database in your process | [the quickstart's Python section](../quickstart.md#chloedb-from-python-with-no-server) (`pip install chloedb`, no server) | [Python](../chloedb/python.md), the [search guide](search.md), and [Build a search page](search-page.md) for a web app | | a JavaScript or TypeScript app (Node, Bun, Deno, a framework's server code) | [JavaScript](../chloedb/javascript.md): `npm install chloedb` and a database in your process | the [search guide](search.md), whose queries run as `await db.query(sql, params)` | | a server that several programs, languages or machines use | [the quickstart](../quickstart.md): install `chloedb-server`, a table, a search, the command center | [chloedb-server](../chloedb/server.md), and [Build an app on chloedb-server](../chloedb/build-an-app.md) for an app over its HTTP API | | a cluster: shards, replicas, failover | [Operate a cluster](operate-cluster.md), on one machine first | [Runbooks](../chloedb/runbooks.md) and [cluster limits](../chloedb/cluster-limits.md) | | retrieval for a language model | [Retrieval for RAG](rag.md) | [LangChain, LangGraph, LlamaIndex](frameworks.md) | | a move from Elasticsearch or OpenSearch | [the OpenSearch API](../chloedb/opensearch.md): `--opensearch-listen` answers OpenSearch's REST API, so an app on an OpenSearch or Elasticsearch 7 client indexes and searches unchanged, and its [differences](../chloedb/opensearch.md#differences) say what it refuses | the [search guide](search.md) for the same searches in SQL, and [multi-tenant isolation](../chloedb/security.md#api-keys-and-scopes) for an index per customer | | a move from PostgreSQL's SQL | [Differences from PostgreSQL](../chloedb/query-language.md#differences-from-postgresql): what answers otherwise and what is refused, with what to write instead | [Following Postgres](../chloedb/postgres.md) copies a Postgres database in and keeps it current | | long-term memory for Claude Code | [Install ChloeCtx](../chloectx/setup.md): it plugs into Claude Code, and needs neither chloedb-server nor Python | [ChloeCtx](../chloectx/index.md) | Something failed? [Troubleshooting](../chloedb/troubleshooting.md) has the usual messages, each with what to do, and `chloedb-server doctor` checks this machine for their causes. ## Cookbook Complete programs for common jobs. Each one runs, as written, every time the code changes.
Build a search pageA search box for a small web app: typos, highlights, did you mean, more like this and a filter. Retrieval for RAGChunk documents, search them by words and meaning, and hand a model the passages with their sources. Memory for an agentRemember turns and facts, recall what matters to a new message, and keep facts current. Crawl a site into searchPoint the crawler at a site, get a table with its fields, and search it. Search your logsSend syslog and OpenTelemetry logs to a table, and find the last 15 minutes' errors, a flapping interface, an IP.
## Use it from | | | |---|---| | [Python](../chloedb/python.md) | `import chloedb`: a database in your process, or a client of a server, with the same methods; [DataFrames](../chloedb/frames.md) too | | [JavaScript](../chloedb/javascript.md) | Node, Bun and Deno in-process, or a `fetch` client for any runtime | | [Java](../chloedb/java.md) | in-process over JNI, and a JDBC driver | | [HTTP and gRPC](../chloedb/server.md) | chloedb-server, its command center, and a cluster of them | ## Apps [Apps on a cluster](apps.md) run beside chloedb-server and show in its command center: the [crawler](../chloedb/crawler.md), [Sheets](../chloedb/sheets.md) and [ChloeCtx](../chloectx/index.md), memory for Claude Code. ## How these pages are tested The guide and cookbook pages are run as scripts: [`docs/guide/run.py`](run.py) runs every code block on a page, in order, in an empty directory, against the programs built from the same commit, and checks the output shown under a block against what it printed. A page that says so at its top has passed. The reference pages (SQL, server, clients, apps) are rendered from the Markdown in [`docs/chloedb/`](../chloedb/index.md) and [`docs/chloectx/`](../chloectx/index.md). --- # Quickstart: a first search in five minutes This page takes you from nothing to a full-text search with SQL in about five minutes, with nothing to compile. You install ChloeDB's server, make a table, put a few rows in it, search them, and open the command center in a browser. The last section does the same from Python, with the database inside your process and no server at all. You need macOS 11 or later (Apple silicon or Intel), or Linux on x86-64 or aarch64 with glibc 2.35 or later (Ubuntu 22.04, Debian 12 and newer), and `curl`. On Windows, use WSL 2 or Docker. ## In one minute Two commands: install, then start a server with a demo catalogue of 20,000 products. ```sh # install curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh ``` ```sh norun chloedb-server --demo ``` It makes `demo.chloedb` in the current directory and says, once it is ready, where to open it and what to try: ```text ChloeDB 0.3.11 is ready: demo.chloedb, 1 table (products), 20,000 rows Open http://127.0.0.1:7700 Query curl -s http://127.0.0.1:7700/v1/sql -H 'content-type: application/json' -d '{"sql": "SELECT * FROM products LIMIT 3"}' Load a file curl -s 'http://127.0.0.1:7700/v1/import?table=NAME' -H 'content-type: text/csv' --data-binary @FILE.csv Stop Ctrl+C (the next start opens it as it was) ``` Your own data needs no schema. Drop a CSV, JSON, Parquet or SQLite file on **Import** in the command center, or send it with the `Load a file` line above (`?table=movies` makes the table `movies` from the file's columns), or load it before you start the server: ```sh norun chloedb-server import movies.csv --db movies.chloedb # makes the table movies from the file's columns chloedb-server --db movies.chloedb ``` `chloedb-server` with no `--db` serves `chloedb.chloedb` in the current directory, made empty on the first start. The rest of this page goes step by step, with the choices each step has. ## 1. Install the server Pick one. Each gives you a `chloedb-server` program, prebuilt (a download of about 50 MB), in under a minute. **The install script** puts it in `~/.local/bin` (it says what to add to your `PATH` if that folder is not on it yet). It checks the download against the release's SHA-256 and, where [GitHub's CLI](https://cli.github.com) (`gh`) is installed, its provenance (from 0.3.8 to 0.3.10, that this repository's release workflow built it; from 0.3.11, that the public copy of the releases published it, as [SECURITY.md](../SECURITY.md#checking-what-you-download) explains), and changes nothing else. [Read it](install.sh) first if you like. ```sh # install curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh ``` If it stops behind a proxy or a firewall, or names no version, [Troubleshooting](chloedb/troubleshooting.md#the-install-script-stops-could-not-tell-which-chloedb-server-release-is-the-newest) says what to do: in short, name the version after the pipe, `curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | CHLOEDB_VERSION=0.3.11 sh`. **pipx, uv or pip** : the same server, from [PyPI](https://pypi.org/project/chloedb-server/), which asks GitHub nothing, on the same Macs and on Linux with glibc 2.34 or later. `pipx install` and `uv tool install` put `chloedb-server` on your `PATH`; `uvx chloedb-server` runs it without installing it. ```sh # install pipx install chloedb-server # or: uv tool install chloedb-server ``` In a virtualenv, pip puts it in the virtualenv's `bin`, on your `PATH` while the virtualenv is active; `"chloedb[server]"` installs the Python package beside it, for the last section of this page: ```sh # install python3 -m venv .venv && . .venv/bin/activate pip install chloedb-server # or: pip install "chloedb[server]" ``` **Homebrew** is not available yet: there is no tap to install from. Use the install script above, which works on the same Macs and Linux machines. **Docker**: skip to [ChloeDB in Docker](#chloedb-in-docker) below, which runs the same steps against the image. **By hand**: each `chloedb-server-v` [release](https://github.com/chloetech-ai/chloedb-releases/releases) has an archive per platform (`linux-x86_64`, `linux-aarch64`, `macos-arm64`, `macos-x86_64`) with a `.sha256` beside it: ```sh # install v=0.3.11 p=macos-arm64 curl -fLO https://github.com/chloetech-ai/chloedb-releases/releases/download/chloedb-server-v$v/chloedb-server-$p.tar.gz tar xzf chloedb-server-$p.tar.gz && mkdir -p ~/.local/bin && mv chloedb-server-$p/chloedb-server ~/.local/bin/ ``` From 0.3.8 each archive also has GitHub's build provenance and an SBOM of what is compiled into it: [checking what you download](../SECURITY.md#checking-what-you-download) shows the `gh attestation verify` command that checks them (the install script runs it for you where `gh` is installed). Check that it runs: ```sh chloedb-server --version ``` If it does not, or a later step stops with an error, [Troubleshooting](chloedb/troubleshooting.md) has the usual messages and what to do; `chloedb-server doctor` checks this machine for their causes. ## 2. Start it A database is a file, with its write-ahead log and the server's own logs beside it (`quickstart.chloedb-wal`, `quickstart.chloedb.logs`). Give the server a path that does not exist yet and it creates an empty database there; it listens on `127.0.0.1:7700`, which only this machine can reach. ```sh mkdir -p chloedb-quickstart && cd chloedb-quickstart chloedb-server --db quickstart.chloedb > server.log 2>&1 & server=$! until curl -sf http://127.0.0.1:7700/livez > /dev/null; do sleep 0.2; done ``` For a server you keep, rather than this try, add two flags. `--alerts alerts.json` keeps the alert rules and routes you make in that file: without it a server on its own keeps them in memory, and a restart loses them ([alerts](chloedb/server.md#alerts)). `--environment production` (or `staging`, `dev`) names what it is: the command center shows it in its header and, on production, asks for a reason before each change. A server with none is shown as a sandbox when you reach it on this machine, and as production from another. Everything below talks to it over HTTP with JSON. To keep the commands short, `sql` sends the statement it reads from its input to `POST /v1/sql`, which runs any statement: ```sh sql() { curl -sS http://127.0.0.1:7700/v1/sql -H 'content-type: application/json' --data-binary @-; echo; } ``` ## 3. Make a table and fill it Every column is indexed for what its type is for: `TEXT` for full-text search (words stemmed, so "jackets" finds "jacket"), `KEYWORD` for exact values and facets, numbers for ranges and sorting. ```sh sql <<'EOF' {"sql": "CREATE TABLE products (id KEYWORD PRIMARY KEY, title TEXT, body TEXT, category KEYWORD, price FLOAT)"} EOF ``` Rows go in with SQL (`INSERT INTO products VALUES (...)`), from files (`chloedb-server import`), or as JSON documents to `POST /v1/write`: ```sh curl -sS http://127.0.0.1:7700/v1/write -H 'content-type: application/json' --data-binary @- <<'EOF' {"ops": [ {"op": "upsert", "table": "products", "doc": {"id": "p1", "title": "Waterproof hiking jacket", "body": "A light shell that keeps rain out on long hikes.", "category": "outdoor", "price": 129.0}}, {"op": "upsert", "table": "products", "doc": {"id": "p2", "title": "Insulated winter jacket", "body": "Warm down jacket for cold city winters.", "category": "outdoor", "price": 189.0}}, {"op": "upsert", "table": "products", "doc": {"id": "p3", "title": "Trail running shoes", "body": "Grippy, waterproof shoes for muddy trails.", "category": "footwear", "price": 99.0}}, {"op": "upsert", "table": "products", "doc": {"id": "p4", "title": "Leather office shoes", "body": "Classic shoes for the office.", "category": "footwear", "price": 149.0}}, {"op": "upsert", "table": "products", "doc": {"id": "p5", "title": "Rain cover for backpacks", "body": "Waterproof cover that fits 20 to 40 litre packs.", "category": "outdoor", "price": 19.0}} ]} EOF echo sql <<'EOF' {"sql": "INSERT INTO products (id, title, body, category, price) VALUES ('p6', 'Wool hiking socks', 'Warm socks that dry fast on wet hikes.', 'footwear', 15.0)"} EOF ``` Each answer says how many rows it wrote (`"written"`), and the rows are durable once it returns. ## 4. Search The rows that mention "waterproof", best match first. `MATCH` finds them, `bm25` ranks them: ```sh sql <<'EOF' {"sql": "SELECT id, title, score() FROM products WHERE MATCH(body, 'waterproof') ORDER BY bm25(body, 'waterproof') DESC LIMIT 5"} EOF ``` The answer's `rows` are the matches, in the order of its `columns` (`"objects": true` beside `"sql"` gives each row as an object instead); `stats` says how the planner ran the statement, step by step. Full text and structured filters in one statement, which the planner runs together: waterproof things under 100 that are not shoes. ```sh sql <<'EOF' {"sql": "SELECT id, title, price FROM products WHERE MATCH(body, 'waterproof') AND price < 100 AND category <> 'footwear'"} EOF ``` Typos are forgiven when you ask: `fuzzy => 1` lets each word be one edit away, so "jaket" finds the jackets. ```sh sql <<'EOF' {"sql": "SELECT id, title FROM products ORDER BY bm25(title, 'jaket', fuzzy => 1) DESC LIMIT 3"} EOF ``` Facets are a `GROUP BY` over the matches: ```sh sql <<'EOF' {"sql": "SELECT category, COUNT(*), AVG(price) FROM products WHERE MATCH(body, 'waterproof OR warm') GROUP BY category ORDER BY 2 DESC"} EOF ``` ## 5. Open the command center Open [http://127.0.0.1:7700](http://127.0.0.1:7700) in a browser. The command center opens on **Start here**, which walks through the first steps and ticks each one off once it is done; once they are, the same address opens **Home**, the server's health. If the crawler, Sheets or ChloeCtx were installed beside `chloedb-server` (`install.sh --with`), the server started them too, as [apps](chloedb/server.md#apps-the-server-starts) (unless it was given `--start-apps off`), and their tables (`crawl_*`, `sheets_*`, `ctx_*`) are listed apart from yours, under Tables of apps. **Tables** lists `products`: its page searches it from one box (by words, by meaning, or both), shows its rows, how full each field is, and what uses it, and **Save as a saved search** keeps the query as a stored function that SQL, HTTP, Python, JavaScript and agents (over MCP) all call. The **SQL workbench** runs any SQL you type and shows the plan the planner chose; **Ask** (Ctrl+J) answers a question in words by querying the tables, with an Anthropic API key (the server's, or one you give the tab). The older query console is still at [/classic](http://127.0.0.1:7700/classic). With `--demo 20000`, a new database starts with a catalogue of 20,000 products to try it on; here a second server, on port 7710, so that both run at once: ```sh chloedb-server --db demo.chloedb --demo 20000 --listen 127.0.0.1:7710 --grpc off > demo.log 2>&1 & demo=$! until curl -sf http://127.0.0.1:7710/livez > /dev/null; do sleep 0.2; done curl -sS http://127.0.0.1:7710/v1/sql -H 'content-type: application/json' \ -d "{\"sql\": \"SELECT title, price FROM products WHERE MATCH(body, 'waterproof jacket') ORDER BY bm25(body, 'waterproof jacket') DESC LIMIT 5\"}"; echo ``` When you are done, stop the servers (the databases stay in their files, and the next start opens them as they were): ```sh kill $server $demo ``` ## ChloeDB from Python, with no server The Python package runs a database inside your process, the way `sqlite3` runs SQLite. It is a prebuilt wheel for CPython 3.10 and later on the same platforms as the server: macOS 11 or later, and Linux with glibc 2.28 or later (release 0.2.0's wheels need 2.35). Install it from PyPI: ```sh # install python3 -m venv .venv && . .venv/bin/activate pip install chloedb ``` ```sh python3 - <<'EOF' import chloedb db = chloedb.open("books.chloedb", schema={ "table": "books", "key": "id", "fields": [ {"name": "id", "type": "keyword"}, {"name": "title", "type": "text"}, {"name": "year", "type": "int"}, ], }) db.upsert([ {"id": "b1", "title": "The river and the dragon", "year": 1999}, {"id": "b2", "title": "Winter garden", "year": 2005}, {"id": "b3", "title": "Dragons of the northern rivers", "year": 2011}, ]) print(db.query("SELECT id, title FROM books WHERE MATCH(title, 'dragon') AND year > 2000").rows) # a typo, forgiven: each word may be an edit or two away, by its length print(db.query("SELECT id, title FROM books WHERE MATCH(title, :q, fuzzy => 'auto') " "ORDER BY bm25(title, :q) DESC", q="dragn").rows) db.close() EOF ``` ```text output [['b3', 'Dragons of the northern rivers']] [['b1', 'The river and the dragon'], ['b3', 'Dragons of the northern rivers']] ``` `chloedb.open` creates the database the first time and opens it after; one process at a time may open it to write. A schema with an embedded vector field that names a model ChloeDB knows (`"embed": {"from": ["title"], "model": "potion-retrieval-32M"}`) works on a new machine as written: the first open downloads the model once (about 130 MB, each file checked against its pinned SHA-256) and says so; `CHLOEDB_FETCH_MODELS=0` turns that off. The same methods talk to a server: `chloedb.connect("http://127.0.0.1:7700")` in place of `chloedb.open(...)`. [Python](chloedb/python.md) goes on from here, and [Build a search page](guide/search-page.md) makes a search box with typos, highlights and filters from these pieces. ## ChloeDB in Docker The image `ghcr.io/chloetech-ai/chloedb-server` (Linux, x86-64 and arm64) keeps its database in `/data`: mount a volume there to keep it. Inside a container the server listens on all of the container's interfaces, which it allows only with a token, so pick one. Publishing the port on `127.0.0.1` keeps it to this machine. ```sh # install docker run -d --name chloedb --user 10001:10001 -p 127.0.0.1:7700:7700 -e CHLOEDB_TOKEN=pick-a-secret -v chloedb:/data \ ghcr.io/chloetech-ai/chloedb-server:0.3.11 ``` Then every request sends the token, and the console asks for it once: ```sh sql() { curl -sS http://127.0.0.1:7700/v1/sql -H 'content-type: application/json' -H 'authorization: Bearer pick-a-secret' --data-binary @-; echo; } ``` and steps 3 to 5 run as written (the `/v1/write` call needs the same `authorization` header). Arguments after the image replace its default ones (`--db /data/chloedb.chloedb --listen 0.0.0.0:7700 --grpc 0.0.0.0:7701`): add `--demo 20000` by passing `--db /data/demo.chloedb --listen 0.0.0.0:7700 --demo 20000`. For [OpenSearch's API](chloedb/opensearch.md) too, publish its port and give the defaults again with it: `-p 127.0.0.1:9200:9200` before the image, and `--db /data/chloedb.chloedb --listen 0.0.0.0:7700 --opensearch-listen 0.0.0.0:9200` after it (the token is its password, with any user name). `docker rm -f chloedb` stops it; the volume keeps the database. ## Next - [The query language](chloedb/query-language.md): every function, with vectors (`similarity`), hybrid ranking, graph traversal, joins and aggregates. - [The server](chloedb/server.md): loading files (`chloedb-server import`), schemas, embedded vector fields, API keys, replication and shards. - [Python](chloedb/python.md), [JavaScript](chloedb/javascript.md) and [Java](chloedb/java.md): the database in your process. - [SQLite](chloedb/sqlite.md), [Parquet and S3](chloedb/parquet.md) and [Postgres](chloedb/postgres.md): bring your data in. --- # Build with an AI agent An agent such as Claude Code can do most of what this documentation describes for you. It can load a file, make it searchable by words and by meaning, answer questions from your rows with citations, write the search page or the code of your app, find out why a query is slow, and look after a server. This page shows how to connect one, the prompts that work, and what a good agent does with each, so you can tell when it goes wrong. The server gives your agent the same prompts as slash commands, and the documentation it needs as a tool. ## Connect your agent Start a server, if one is not running yet. With no flags it serves `chloedb.chloedb` in the current directory, at `http://127.0.0.1:7700`: ```sh chloedb-server > server.log 2>&1 & until curl -sf http://127.0.0.1:7700/livez > /dev/null; do sleep 0.2; done ``` Then add it to your agent as an MCP server. For Claude Code: ```sh norun claude mcp add --transport http chloedb http://127.0.0.1:7700/v1/mcp ``` A server with a token needs a key in the header: `--header "Authorization: Bearer $CHLOEDB_KEY"`. A client that starts its MCP servers as commands (Claude Desktop, Cursor and most others) runs `chloedb-server mcp`, which passes each message on to the server: ```json norun { "mcpServers": { "chloedb": { "command": "chloedb-server", "args": ["mcp", "--url", "http://127.0.0.1:7700"], "env": {"CHLOEDB_KEY": "your key, or leave it out for a server without a token"} } } } ``` What the agent can change is decided by the key it connects with, not by what you ask it: a read key explores, a write key loads rows, and an admin key also makes tables ([agents over MCP](../chloedb/server.md#agents-over-mcp)). Even with an admin key, an agent cannot drop a table or delete every row on its own. The server refuses, and the agent files the change for you to approve ([agents and administration](../chloedb/server.md#agents-and-administration)). The server tells a connected agent the prompts below. In Claude Code they are slash commands, such as `/mcp__chloedb__load-a-file data/movies.csv`, each with the steps listed under it. You can also list them yourself: ```sh curl -s http://127.0.0.1:7700/v1/mcp -H 'content-type: application/json' \ -d '{"jsonrpc": "2.0", "id": 1, "method": "prompts/list"}' \ | python3 -c 'import json, sys; print("\n".join(p["name"] for p in json.load(sys.stdin)["result"]["prompts"]))' ``` ```text output explore load-a-file search answer-with-citations search-page app-code change-a-table slow-query check-the-server ``` ## Prompts that work Each prompt below is written as you would type it. Under it is what a good agent does, and the server sends those steps along when you use the slash command. Words in braces, such as `{path}`, are yours to fill in. ### Explore what is there ```text prompt=explore Look at what is in my ChloeDB and tell me what I could search for, with an example query for each table. ``` 1. `whoami` says what the key may do, and `list_tables` gives each table's `CREATE TABLE` statement, its key, its vector fields and their models. 2. A few rows of each table (`SELECT * FROM t LIMIT 3`), and the values of its `KEYWORD` fields (`SELECT genre, COUNT(*) FROM t GROUP BY genre`). 3. For each table, a search by its words (`MATCH` and `bm25` over its `TEXT` fields) and, when it has an embedded `VECTOR` field, one by meaning (`similarity`), each run once so the example is known to work. 4. ChloeDB's SQL is its own dialect, not Postgres. Before writing anything unusual, the agent looks up the syntax with `search_docs` and checks the statement with `check_sql`. ### Load a file and search it by meaning ```text prompt=load-a-file Load {path} into ChloeDB as a table I can search by words and by meaning. ``` 1. It looks at the file's first lines and its size, and names the table after the file unless you said otherwise. 2. A file of up to a few megabytes goes through the `import` tool, its text as `data`, with `create: true`. The table is made from the file's columns: numbers become `INT` or `FLOAT`, short labels `KEYWORD`, and prose `TEXT`. A cell that says it has no value (`N/A`, `null`, `-`) in a column of numbers or dates is `NULL`, so nothing needs cleaning first. A table with prose also gets `emb`, a vector of that prose by `potion-retrieval-32M`, which the server downloads once (about 130 MB) and fills in. The answer's `create_table` is the statement it made. 3. A larger file is sent from the shell instead, which needs an admin key on a server with a token: `curl -s --data-binary @{path} -H 'content-type: text/csv' 'http://127.0.0.1:7700/v1/import?table=NAME'`. The content type is `text/tab-separated-values` for TSV and `application/x-ndjson` for JSON Lines. With the server stopped, `chloedb-server import {path} --db chloedb.chloedb` does the same ([loading rows](../chloedb/server.md#loading-rows)). 4. Search by meaning works once the model has arrived. Until then such a query answers 503 `unavailable`, saying how far the download is, or, when it failed, when the server tries again by itself. The agent waits, and `list_models` shows the download, rather than fetching the model itself. Search by words works at once. 5. It ends with one search by words and one by meaning, so you see the table work. ### Search, and say why each row matched ```text prompt=search Search the {table} table for "{question}", by meaning and by words together, and tell me why each result matched. ``` 1. Words and meaning fused: `SELECT ... FROM {table} ORDER BY rrf(bm25(body, :q, fuzzy => 'auto'), similarity(emb, :q)) DESC LIMIT 10`, with `:q` the text itself, which the server embeds with the field's own model. `body` stands for the table's `TEXT` fields, and `emb` for its vector field (`list_tables` names both). 2. `fuzzy => 'auto'` takes typos: a word in no row is read as the words near it. 3. A condition on structured fields goes in `WHERE` (`genre = 'scifi' AND year > 2000`), not in the text. 4. To say why a row matched, the agent runs `explain` with `hits`, which gives each top row's scores, or compares the row's words with the question's ([ranking](../chloedb/query-language.md#rrfs1-s2--reciprocal-rank-fusion)). 5. `MATCH(field, 'a b c')` keeps only rows with every word. When it finds nothing, the answer's `hint` suggests `OR` or `min => 2`. ### Answer a question from my rows, with citations ```text prompt=answer-with-citations Answer this from the rows in my ChloeDB, citing the rows each claim comes from: {question} ``` 1. It finds the rows as in the search above, eight or so, with their keys. 2. It answers from those rows only, marking each claim with its row as `[1]`, `[2]`, and lists the rows cited with their keys. When the rows do not answer the question, it says so rather than answering from what it knows. 3. In your own code, Python's `db.ask(question, table=...)` does the same in one call. It returns the answer with its `sources`, written by a language model through the query's `llm()`, with `ANTHROPIC_API_KEY` ([Python](../chloedb/python.md#querying)). A whole pipeline, with documents split into chunks and grounded claims, is in [Retrieval for RAG](rag.md). ### Build a search page ```text prompt=search-page Build me a search page for the {table} table: a search box that forgives typos and finds things by meaning, with filters, that I open in my browser. ``` 1. **The page cannot call chloedb-server from the browser.** The server refuses requests from a page on another origin, a page opened from a file included, and sends no CORS headers. A page written to `fetch` the server's `/v1/query` therefore fails with a CORS error. The page calls a small app instead, and the app calls the server ([why](../chloedb/javascript.md#why-a-page-cannot-call-chloedb-server)). 2. The app can be Python's standard library and `chloedb` (`pip install chloedb`): `chloedb.connect("http://127.0.0.1:7700")` and an `http.server` handler that serves the page and answers `/search?q=` with `db.search(q, table="{table}", where=..., limit=20)`. `db.search` fuses words and meaning and forgives typos. [Build a search page](search-page.md) is that app in full, with highlights, "did you mean", filters with counts, and "more like this". 3. In a JavaScript app, the route does the same with the `chloedb` package's client ([a search box in a web app](../chloedb/javascript.md#a-search-box-in-a-web-app)). 4. Filters come from the table's `KEYWORD` fields, with their counts (`SELECT genre, COUNT(*) FROM {table} WHERE MATCH(...) GROUP BY genre`). 5. It starts the app, opens the page (or fetches it with `curl`), runs a search with a typo in it, and gives you the address. ### Write the code of my app ```text prompt=app-code Write {language} code that uses ChloeDB to {task}. ``` 1. It chooses between the database in the app's own process (`chloedb.open(path)` in Python, `open()` in JavaScript, `Db` in Rust) and a client of a running server (`chloedb.connect(url)`). It uses the server when more than one process uses the data, or when the command center should show it. 2. It looks up the client's methods in that language's page, and does not guess them from other databases: [Python](../chloedb/python.md), [JavaScript](../chloedb/javascript.md), [Rust](../chloedb/rust.md), [Java](../chloedb/java.md). 3. Queries take named parameters (`:q`) bound in a mapping, never values pasted into the SQL. 4. It runs the code once against a real database and shows what it printed. ### Change a table ```text prompt=change-a-table In ChloeDB, change the {table} table: {change}. ``` 1. It reads the table's statement (`describe_table`) and finds the syntax with `search_docs` (`ALTER TABLE ... ADD`, a field's options, an embedded field). 2. It checks the statement with `check_sql` before running it with `execute`. An added field fills in for the rows already there, and an embedded vector field computes its vectors in the background. 3. It does not drop a table or a field, or delete or update every row, on its own: the server refuses an agent that tries (`change_request_required`). It asks you, or files the change for an admin to approve with `propose_change`. ### Find out why a query is slow ```text prompt=slow-query This ChloeDB query is slow. Find out why and make it faster: {sql} ``` 1. `explain` shows how the query runs: the plan of each segment, the rows a filter kept, and whether ranking stopped early (`MaxScore`). `queries` shows the latest and slowest statements, with their times. 2. The usual cause is a condition the indexes cannot answer, which tests every row the other conditions keep: a function or arithmetic of a column (`lower(brand) = 'acme'`), a `LIKE '%tent%'` or an `ILIKE` on a field without a substring index, or a comparison of a `TEXT` field's stored text ([statement shape](../chloedb/query-language.md#statement-shape)). Others are a ranking by an expression that every row must compute, and a `LIMIT` much larger than the page shows. 3. It changes one thing at a time, and times the query before and after with the same parameters. ### Check the server ```text prompt=check-the-server Check my ChloeDB server's health and tell me what needs attention, and what to do about each thing. ``` 1. `health`, `alerts` and `events` (with an admin, `ops` or `propose` key) say how the server is and what has changed. 2. For each problem, `runbook` finds what to do. 3. It acts only within what its key allows alone: a contain rule, a cancelled query, an alert silenced for a while, each with a reason. Anything bigger it files with `propose_change` for a person to approve ([agents and administration](../chloedb/server.md#agents-and-administration)). ## What every agent should know The server tells a connected agent these at the start. They are written here for an agent that reads this page instead. - **The SQL is ChloeDB's own.** `MATCH(field, 'words')` filters by text, `ORDER BY bm25(field, 'words') DESC` ranks by it, `similarity(emb, :q)` ranks by meaning, and `rrf(...)` fuses rankings. `search_docs` finds the syntax of anything else in the [SQL reference](../chloedb/query-language.md), and `check_sql` checks a statement without running it. - **Errors say what to do.** Every error has a stable `error_code`, whether trying again can work (`retryable`), a `hint`, and the documentation section that explains it (`docs`). A retryable error is waited out, not worked around ([error codes](../chloedb/server.md#agents-and-administration)). - **Meaning comes by itself.** A table made from a file with prose gets a vector of it, which the server fills in once its model has downloaded. Nothing needs to be fetched or configured by hand. - **Pages call an app, not the server.** See [Build a search page](#build-a-search-page) above. - **Writes are safe to send again with a key.** A write through a coordinator that answers `write_in_doubt` is sent again with the answer's `idempotency_key` ([failover](../chloedb/server.md#failover)). - **Ask before anything that loses data.** The server holds such a change for a person anyway. ## Tell your coding agent about ChloeDB A coding agent working on your app, with no MCP server, reads the documentation as text: - [llms.txt](https://chloetech-ai.github.io/chloedb/llms.txt) lists every page with a line on what it covers. - [llms-full.txt](https://chloetech-ai.github.io/chloedb/llms-full.txt) is the whole documentation in one file. For a project that uses ChloeDB, a few lines in its `CLAUDE.md` or `AGENTS.md` keep the agent on the right path: ```text norun This project uses ChloeDB (https://chloetech-ai.github.io/chloedb/llms.txt), a search database with its own SQL dialect, not Postgres: MATCH and bm25 for words, similarity for meaning, rrf to fuse them. Look up syntax in its SQL reference rather than guessing. The server runs at http://127.0.0.1:7700 (MCP: /v1/mcp). Browser pages call our app's routes, never the server. ``` --- # Concepts ChloeDB is a search engine and a database in one library. This page names the parts you meet when you use it: the file, tables and their fields, the three kinds of index every row gets, scores, the planner, and the server that serves the same database to many clients or many machines. [How ChloeDB works](../chloedb/index.md) goes deeper into each. ## One database, one file A database is one file plus a write-ahead log beside it (`books.chloedb` and `books.chloedb-wal`), the way SQLite keeps one in WAL mode, and a small directory (`-readers`) where processes that read it keep their place. Your program opens it as a library, from Rust, [Python](../chloedb/python.md), [JavaScript](../chloedb/javascript.md) or [Java](../chloedb/java.md), with no server and no configuration. The same file can be served by [chloedb-server](../chloedb/server.md) when many clients, or many machines, need it. ```python import os import chloedb db = chloedb.open("notes.chloedb", schema={ "table": "notes", "key": "id", "fields": [{"name": "id", "type": "keyword"}, {"name": "body", "type": "text"}], }) db.insert({"id": "n1", "body": "Water the tomatoes before nine."}) print(sorted(f for f in os.listdir(".") if f.startswith("notes"))) db.close() print(sorted(f for f in os.listdir(".") if f.startswith("notes"))) ``` ```text output ['notes.chloedb', 'notes.chloedb-readers', 'notes.chloedb-wal'] ['notes.chloedb', 'notes.chloedb-readers', 'notes.chloedb-wal'] ``` Writes are transactions with snapshot isolation: a query sees the database as it was when it started, readers never wait for the writer, and a crash leaves the last committed state. One process writes a database at a time; other processes can open it read-only and follow its commits. Back up a database that is in use with `checkpoint`, not by copying its files ([backups](../chloedb/python.md#backing-up-and-damaged-files)). ## Tables, fields and keys A database holds tables, and a table has typed fields and, usually, a primary key. A table is created from a schema, a JSON object as above or SQL: ```sql norun CREATE TABLE books ( id KEYWORD PRIMARY KEY, title TEXT, author KEYWORD, genres KEYWORD[], year INT, rating FLOAT, emb VECTOR OPTIONS(embed = 'title', model = 'potion-retrieval-32M') ); ``` | type | holds | searched with | |---|---|---| | `TEXT` | words, analysed (lowercased, stemmed, stopwords dropped) | `MATCH`, `bm25` | | `KEYWORD`, `KEYWORD[]` | exact values: ids, tags, names | `=`, `IN`, `LIKE 'p%'`, `GROUP BY` | | `INT`, `FLOAT`, `BOOL`, `TIMESTAMP` | numbers, flags and times | ranges, `ORDER BY`, aggregates | | `JSON` | documents whose keys no schema names | `attrs.color = 'red'` | | `VECTOR` | embeddings, given or computed by a model | `similarity`, `distance` | | `SPARSE` | learned term weights (SPLADE and the like) | `similarity` | | `EDGES` | typed, weighted links to other rows | `REACHABLE`, `PATH`, `ppr` | | `MEDIA` | images and sounds, by URI | the vectors and text made from them | A vector field with `embed` is filled by an embedding model from other fields when a row is written, so you insert text and search by meaning. The model runs inside ChloeDB or behind an API (OpenAI, Cohere, Voyage, Gemini, Ollama). Inside it, every build runs `potion-retrieval-32M`, a fast static model; BERT models such as `bge-small-en-v1.5` run only in a build from source with the `bert` feature, which the prebuilt server, wheels, npm package and Docker image leave out ([a BERT model does not run](../chloedb/troubleshooting.md#a-bert-model-such-as-bge-small-does-not-run)). The [SQL reference](../chloedb/query-language.md#columns-and-types) lists every type and option. ## Every row, indexed three ways Each row is indexed by every kind of index its fields call for, in the same place, so one query can use them all: - **Full text**: posting lists of each word's rows, compressed, and scored with BM25. - **Columns**: each field's values stored by column, for filters, sorting, facets and aggregates. - **Vectors**: an HNSW graph (or a flat or IVF index) over each vector field, for nearest neighbours. Rows can also hold **edges** to other rows, which turn a table into a graph that the same queries walk ([graphs](../chloedb/graphs.md)). Rows are written into immutable **segments**. A new row goes to the write-ahead log and a memory table first; full memory tables are written as segments, and segments are merged in the background, as Lucene and SQLite's FTS5 do. You do not manage segments, but `EXPLAIN` shows a plan for each. ## Queries, scores and the planner Everything is SQL. Search is a set of functions inside it: `MATCH` selects rows with words, `bm25`, `similarity` and others score them, `rrf` and weighted sums blend scores, and `score()` is the score a row was ranked by. A ranking can multiply in a column (`* (1 + 0.1 * rating)`), decay with age, run a learned model, or rerank its top rows with a cross-encoder. The [search guide](search.md) shows each in use. A cost-based **planner** decides, for each segment and from exact statistics, how to run each part of a statement: which condition to read from an index, which to test row by row, whether to search vectors before a filter or within it. You write what you want, and `EXPLAIN` says what it chose. ## From a file to a cluster The same database, and the same SQL, run three ways: | | how | when | start with | |---|---|---|---| | **In your process** | `chloedb.open("books.chloedb")` | one program owns the data: an app, a notebook, an agent | [Python](../quickstart.md#chloedb-from-python-with-no-server) or [JavaScript](../chloedb/javascript.md) | | **One server** | `chloedb-server --db books.chloedb` | many clients, other languages, a browser UI, a web app with several worker processes | [the quickstart](../quickstart.md) | | **A cluster** | a coordinator over shards, each with replicas | more data or traffic than one machine holds, or a copy to fail over to | [Operate a cluster](operate-cluster.md) | One process at a time writes a database file, so a program whose processes all write it, such as a web app run by several workers or a reloader, serves it with a server and uses the clients ([Build a search page](search-page.md) does). [chloedb-server](../chloedb/server.md) serves a database over HTTP JSON and gRPC, with a command center in the browser for queries, health and performance, and an agent that answers questions by writing SQL. Several servers run as shards behind a coordinator that answers like one database, and a primary ships its writes to replicas. The Python, JavaScript and Java clients have the same methods for a file and a server, so code moves from one to the other unchanged. ## Apps on a cluster Some programs built on ChloeDB run beside a server and appear in its command center: the [crawler](../chloedb/crawler.md), which turns a site into a table, [Sheets](../chloedb/sheets.md), spreadsheets whose cells are rows, and [ChloeCtx](../chloectx/index.md), long-term memory for Claude Code. [Apps on a cluster](apps.md) says how they attach. ChloeCtx also runs on its own, beside Claude Code on your machine, with no server: [Install ChloeCtx](../chloectx/setup.md). --- # Build an app on chloedb-server A shop in one page: search, stock that never oversells, holds that expire, and click events counted exactly once. Each part is a few lines of SQL or JSON over HTTP, with links to the reference for the rest. ## Run a server Download the server for your machine (no Rust or build needed), and start it on a new database: ```sh v=0.3.11 p=linux-x86_64 # or linux-aarch64, macos-arm64, macos-x86_64 curl -LO https://github.com/chloetech-ai/chloedb-releases/releases/download/chloedb-server-v$v/chloedb-server-$p.tar.gz tar xzf chloedb-server-$p.tar.gz && cp chloedb-server-$p/chloedb-server ./chloedb-server ./chloedb-server --db shop.chloedb --seq-no ``` The server listens on `http://127.0.0.1:7700` (HTTP JSON, and the command center in a browser) and on 7701 (gRPC). A second server on the same machine, for your tests say, needs both ports of its own: `--listen` moves only the HTTP one, and a second server left on 7701 stops with "the address is in use", so give it `--grpc` another port too, or `--grpc off`. A new `--db` starts with no tables. `--seq-no` numbers every write, which the stock below needs. [Run it](server.md#run-it) has the options, the source build (`cd chloedb-server && cargo build --release`) and the image. ## Make the tables `POST /v1/sql` takes one statement: ```sh sql() { curl -s localhost:7700/v1/sql -H 'content-type: application/json' -d "$(jq -n --arg s "$1" '{sql: $s}')"; echo; } sql "CREATE TABLE listings (id KEYWORD PRIMARY KEY, title TEXT, body TEXT, category KEYWORD, price FLOAT, stock INT DEFAULT 0, emb VECTOR OPTIONS(embed = 'title, body', model = 'potion-base-8M'))" sql "CREATE TABLE holds (id KEYWORD PRIMARY KEY, listing KEYWORD NOT NULL, buyer KEYWORD NOT NULL, until TIMESTAMP) OPTIONS(expire_by = 'until')" sql "CREATE TABLE buyers (id KEYWORD PRIMARY KEY, views INT DEFAULT 0)" sql "CREATE TABLE events (id INT PRIMARY KEY, buyer KEYWORD NOT NULL, listing KEYWORD, kind KEYWORD, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP) OPTIONS(shard_by = 'buyer')" ``` - `TEXT` is searched by words, `KEYWORD` is matched whole (filters, facets), and every column is indexed. - `emb` is computed by the server from the title and body when a row is written, by a small model (potion-base-8M, 30 MB) that it downloads from Hugging Face when the table is created. Rows written before the model is ready get their vectors once it is; `GET /v1/schema` shows it `"loaded": true`. - `expire_by` makes a hold vanish at its `until`. `shard_by` keeps a buyer's events on one shard [once there are several](#grow-to-a-cluster). The [query language](query-language.md#tables) has every type and option. ## Write rows `POST /v1/write` applies a list of operations in one transaction: ```sh curl -s localhost:7700/v1/write -H 'content-type: application/json' -d '{"ops": [ {"op": "upsert", "table": "listings", "doc": {"id": "l1", "title": "Red camping tent", "body": "Two-person tent, light and waterproof", "category": "outdoor", "price": 89.0, "stock": 3}}, {"op": "upsert", "table": "listings", "doc": {"id": "l2", "title": "Blue desk lamp", "body": "LED lamp with a dimmer", "category": "home", "price": 24.5, "stock": 10}}, {"op": "upsert", "table": "listings", "doc": {"id": "l3", "title": "Trail running shoes", "body": "Light shoes for wet trails", "category": "outdoor", "price": 120.0, "stock": 0}} ]}' # {"written":3,"seq_no":5,...} ``` `insert` fails when the key exists, `upsert` replaces the row, `set` changes one column, `add` adds to a number (and creates the row with `doc` when it is missing), and `delete` removes a row by `key`. A 200 answer means the rows are durable. Files load through [`/v1/import`](server.md#loading-rows) (JSONL, CSV, Parquet, SQLite). ## Search ```sh q() { curl -s localhost:7700/v1/query -H 'content-type: application/json' -d "$1"; echo; } # words, ranked by BM25, in stock, cheapest first among equals q '{"sql": "SELECT id, title, price FROM listings WHERE MATCH(title, :q) AND stock > 0 ORDER BY bm25(title, :q) DESC, price LIMIT 10", "params": {"q": "tent"}, "objects": true}' # {"columns":["id","title","price"],"rows":[{"id":"l1","price":89.0,"title":"Red camping tent"}],...} # meaning, not words: the vector of the query text by the field's model, fused with BM25 q '{"sql": "SELECT id, title FROM listings ORDER BY rrf(bm25(body, :t), similarity(emb, :v)) DESC LIMIT 10", "params": {"t": "shelter for two", "v": {"embed": "shelter for two"}}, "objects": true}' # facets: how many listings per category q '{"sql": "SELECT category, COUNT(*) FROM listings GROUP BY category", "objects": true}' # as you type: "camping te" filters by its last word as a prefix and ranks by the words typed whole q '{"sql": "SELECT id, title FROM listings WHERE MATCH(title, :typed) AND stock > 0 ORDER BY bm25(title, :whole) DESC, price LIMIT 10", "params": {"typed": "camping te*", "whole": "camping"}, "objects": true}' # the words a search matched, marked in each text curl -s localhost:7700/v1/highlight -H 'content-type: application/json' \ -d '{"table": "listings", "field": "title", "query": "camping te*", "texts": ["Red camping tent"]}' # {"texts":["Red camping tent"],...} ``` Rows come as lists in the order of `columns`, or as objects with `"objects": true`. A prefix filters but scores nothing in `bm25`, so a query ranked by `bm25(title, 'te*')` alone returns no rows: rank by the words typed whole, or by a column while the first word is being typed ([full text](query-language.md#full-text-match)). `POST /v1/correct` gives a "did you mean" ([did you mean](query-language.md#did-you-mean-correcting-a-querys-words)). A page in a browser cannot send these requests itself from another origin: chloedb-server refuses every `POST` from a page of another site, a query too, and sends no CORS headers, so your app's server code queries it and answers the page ([a search box in a web app](javascript.md#a-search-box-in-a-web-app)). Typo tolerance, synonyms, phrase and prefix search, geographic and time decay, and reranking by a model are in the [query language](query-language.md). ## Read one row by its key ```sh curl -s localhost:7700/v1/kv/listings/l1 # {"found":true,"key":"l1","row":{"id":"l1",...,"stock":3},"seq_no":5,"table":"listings",...} ``` No SQL is parsed: a read by key costs about what a key-value store's does ([rows by key](server.md#rows-by-key)). ## Sell stock without overselling Read the row with its `seq_no`, then write it back only if nobody wrote it since (`if_seq_no`). Of several buyers racing for the last item, exactly one write applies; the others get 409 and read again. ```python import json, urllib.request, urllib.error def call(method, path, body=None): req = urllib.request.Request("http://127.0.0.1:7700" + path, method=method, data=None if body is None else json.dumps(body).encode(), headers={"content-type": "application/json"}) with urllib.request.urlopen(req) as r: return json.loads(r.read()) def buy(listing): while True: got = call("GET", f"/v1/kv/listings/{listing}") if got["row"]["stock"] <= 0: return False # sold out op = {"op": "set", "table": "listings", "key": listing, "field": "stock", "value": got["row"]["stock"] - 1, "if_seq_no": got["seq_no"]} try: call("POST", "/v1/write", {"ops": [op]}) return True except urllib.error.HTTPError as e: if e.code != 409: # 409: someone bought meanwhile raise ``` The Python package's client has the same calls (`chloedb.connect(url).get("l1", table="listings")`, `.write(ops)`); it needs only the standard library ([Python](python.md#a-server-from-python)). More in [conditional writes](server.md#conditional-writes). ## Hold an item for ten minutes ```sh until=$(python3 -c 'import datetime as d; print((d.datetime.now(d.timezone.utc) + d.timedelta(minutes=10)).isoformat())') curl -s localhost:7700/v1/write -H 'content-type: application/json' \ -d '{"ops": [{"op": "insert", "table": "holds", "doc": {"id": "h1", "listing": "l1", "buyer": "b7", "until": "'"$until"'"}}]}' ``` From `until` on, the hold is gone from every query, count and read by key, with nothing to clean up. `SELECT COUNT(*) FROM holds WHERE listing = 'l1'` is the number of live holds. ## Count events exactly once Clicks and views come from a log (Kafka, a queue, a file). Send them to `POST /v1/stream` as NDJSON, each with its place in the log (`source`): the server keeps each source's last offset in the same transaction as the rows, so an event sent twice, after a crash or a retry, is skipped rather than counted again. ```sh printf '%s\n' \ '{"source": {"name": "clicks/0", "offset": 0}, "ops": [{"op": "insert", "table": "events", "doc": {"id": 1, "buyer": "b7", "listing": "l1", "kind": "view"}}, {"op": "add", "table": "buyers", "key": "b7", "field": "views", "value": 1, "doc": {"id": "b7"}}]}' \ '{"source": {"name": "clicks/0", "offset": 1}, "ops": [{"op": "insert", "table": "events", "doc": {"id": 2, "buyer": "b8", "listing": "l2", "kind": "view"}}, {"op": "add", "table": "buyers", "key": "b8", "field": "views", "value": 1, "doc": {"id": "b8"}}]}' | curl -s localhost:7700/v1/stream -H 'content-type: application/x-ndjson' --data-binary @- # {"batch":1,...,"written":4,"skipped":0,...} curl -s localhost:7700/v1/sources/clicks/0 # {"name":"clicks/0","offset":1,...}: resume from offset 2 ``` Send the same lines again and the answer says `"written":0,"skipped":4`. [Streams](server.md#streams) has Kafka consumers and the change feed. ## When a write fails An error means nothing of the write was applied, with one exception on a cluster (the last below): - **429**: the server refused the request for its load before doing anything (it is behind on flushing writes to disk, or its write queue is full). The [Python](python.md#a-server-from-python) and [JavaScript](javascript.md#a-server-from-javascript) clients send it again after the answer's `Retry-After`, for up to 10 seconds, and so does a coordinator for its shards; from `curl`, wait a second and send it again. - **A lost answer** (a timeout, a dropped connection): send the request again with the same `"idempotency_key"`. A server that applied it answers its first answer instead of applying it twice. Keys are kept for an hour. - **409 with `if_seq_no`**: the row changed; read it again. - **`"partial": true`**, on a cluster: some shards took their part of the write and keep it, and the others did not. The answer names each shard's part and an `idempotency_key` (yours, or one the coordinator made): send the same request again with that key, and only the shards that did not take their part apply it. [When a write fails](server.md#when-a-write-fails) has the details. ## Grow to a cluster Several servers as shards, and one more as a coordinator, answer like one database: the same tables, SQL and HTTP API. Stop the server above, then: ```sh ./chloedb-server --db s0.chloedb --seq-no --listen 127.0.0.1:7710 --grpc 127.0.0.1:7711 & ./chloedb-server --db s1.chloedb --seq-no --listen 127.0.0.1:7720 --grpc 127.0.0.1:7721 & ./chloedb-server --shards http://127.0.0.1:7711,http://127.0.0.1:7721 --listen 127.0.0.1:7700 & ``` - Rows go to shards by their key, or by the `shard_by` column, so a buyer's events sit on one shard. - A shard added later starts as the first ones did: here on a new database with no `--schema`, since this cluster began with no tables. The coordinator gives it the cluster's tables, and a rebalance [moves slots](server.md#moving-slots) onto it while rows keep being written: ```sh ./chloedb-server --db s2.chloedb --seq-no --listen 127.0.0.1:7730 --grpc 127.0.0.1:7731 & curl -s localhost:7700/v1/admin/shards -H 'content-type: application/json' -d '{"servers": ["http://127.0.0.1:7731"]}' curl -s localhost:7700/v1/admin/rebalance -X POST ``` - [Replicas](server.md#replication-a-primary-and-its-replicas) of each shard take over when its primary fails. Through a coordinator, a few things work differently: - **Graph queries** (`REACHABLE`, `PATH`, `ppr`) run on one database only ([graphs on a cluster](graphs.md#on-a-cluster)). - **`INSERT ... ON CONFLICT DO NOTHING`** and **`DO UPDATE`**, and `UPDATE` or `DELETE` with a `LIMIT`, are refused. `INSERT OR REPLACE` works. - **A write across shards** can fail on one shard after others took their part: send it again with the key its error gives ([above](#when-a-write-fails)). --- # Troubleshooting The errors people meet first with ChloeDB, each with its message as the program prints it, what it means and what to do. Search this page for a few words of your message. These are the messages of release 0.3.8. `chloedb-server doctor` checks this machine for the usual causes at once: its version against the latest release, the Python package, the models folder, port 7700 and glibc. It changes nothing, prints a `fix:` line under each check that is not `ok`, and exits 1 when one fails: ```text $ chloedb-server doctor --offline ok version: chloedb-server 0.3.11 (the latest release was not looked up) ok python package: chloedb 0.3.11 warn models: no models in /home/me/.local/share/chloedb/models: a table whose vectors ChloeDB embeds needs its model fix: chloedb-server fetch-model potion-retrieval-32M (into /home/me/.local/share/chloedb/models) ok port: 7700 is free (the guides' servers listen there) ok glibc: 2.39: the prebuilt programs and wheels run here ``` Without `--offline` it also asks GitHub which release is the latest, and says so when it cannot. `--python` names the interpreter whose package it checks (`python3` by default), `--models` the folder and `--port` the port. ## Installing ### The install script stops: `could not tell which chloedb-server release is the newest` ```text chloedb install: could not tell which chloedb-server release is the newest: https://api.github.com/repos/chloetech-ai/chloedb-releases/releases?per_page=100: The requested URL returned error: 403 https://github.com/chloetech-ai/chloedb-releases/releases/latest: The requested URL returned error: 403 https://chloetech-ai.github.io/chloedb/site/versions.json: The requested URL returned error: 403 Name the version after the pipe (the releases are https://github.com/chloetech-ai/chloedb-releases/releases, chloedb-server-v; 0.3.11 was the newest when this script was written): curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | CHLOEDB_VERSION= sh ``` Without `CHLOEDB_VERSION`, the script asks which release is the newest, in turn: GitHub's API (`api.github.com`), then the address `github.com/chloetech-ai/chloedb-releases/releases/latest` leads to, then this website's `versions.json`, and it says which one answered. It stops as above when none did, with each address and what it said: a proxy or firewall that blocks those addresses, or no network. A proxy that blocks only `api.github.com`, or an address that has used up GitHub's 60 requests an hour for clients without an account (a shared office or school network, a CI runner), no longer stops it. Copies of the script from before 18 November 2026, when it learned the other two, stop at the API instead, with these lines: ```text curl: (22) The requested URL returned error: 403 chloedb install: could not find a chloedb-server release on https://github.com/chloetech-ai/chloedb/releases (set CHLOEDB_VERSION to pick one) ``` In either case, name the version, and the script downloads it without asking. The archives come from `github.com`'s downloads, which often still work where the other addresses are refused. The variable goes after the pipe, where `sh` reads it; in front of `curl` it reaches only `curl`, and the script fails the same way. The last line the script prints is the command to run, with your `--with` and `CHLOEDB_INSTALL_DIR` kept: ```sh curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | CHLOEDB_VERSION=0.3.11 sh ``` Or install the same server from PyPI, which asks GitHub nothing: `pipx install chloedb-server`, `uv tool install chloedb-server`, `pip install chloedb-server` in a virtualenv, or `uvx chloedb-server` to run it without installing it (macOS 11+, and Linux with glibc 2.34 or later). The [quickstart](../quickstart.md#1-install-the-server) has the other ways, by hand included. ### The install script's other messages | message | what to do | |---|---| | `the prebuilt server needs glibc 2.35 or later (Ubuntu 22.04, Debian 12), and this machine has 2.31: ...` | the prebuilt archives need a newer Linux; the PyPI wheels need glibc 2.34; use the Docker image (`ghcr.io/chloetech-ai/chloedb-server`), or build from source | | `this Linux has no glibc (Alpine and other musl systems): ...` | use the Docker image, or build from source | | `Windows has no prebuilt server yet: run this inside WSL 2, or use Docker ...` | run the script inside WSL 2 | | `could not download https://github.com/.../chloedb-server-v0.3.11/... (is 0.3.11 a released version, and does it have chloedb-server? ...)` | `CHLOEDB_VERSION` names a version that has no release, or `--with` a program that release does not have: see the [releases](https://github.com/chloetech-ai/chloedb-releases/releases) | | `/home/me/.local/bin is not on your PATH. To add it, put this line in your shell's profile (~/.zshrc, ~/.bashrc): ...` | not an error: the server is installed; add the line it prints, then open a new terminal | ### `chloedb-server: command not found` ```text bash: chloedb-server: command not found ``` The folder the server was installed into is not on your `PATH`: `~/.local/bin` for the install script (it printed the line to add to your shell's profile), the virtualenv's `bin` for pip (activate it: `. .venv/bin/activate`), or `pipx ensurepath` for pipx. Until then, run it by its path, `~/.local/bin/chloedb-server`. ### `ModuleNotFoundError: No module named 'chloedb'` The Python that runs your script is not the one `chloedb` was installed into: activate the virtualenv (`. .venv/bin/activate`), or install it with that interpreter, `python3 -m pip install chloedb`. `chloedb-server doctor --python PATH` checks a given interpreter. ### `ImportError: This is chloedb 0.0.3, a placeholder ...` pip installed the placeholder that held the name on PyPI, which it falls back to when ChloeDB has no wheel for this platform or this Python. The wheels are for CPython 3.10 or later on macOS 11 or later and on Linux x86-64 and aarch64 with glibc 2.28 or later. Check `python3 --version`; elsewhere (Windows outside WSL 2, Alpine, an older Python) [build from source](python.md#from-source). On a machine the wheels cover, `pip install --upgrade chloedb` replaces an old placeholder. ## Opening a database ### `busy: the database is open elsewhere` ```text chloedb._native.BusyError: busy: the database is open elsewhere: process 3541 (python app.py), the parent of this process, has it open for writing. ... ERROR chloedb_server: open recipes.chloedb: busy: the database is open elsewhere: process 2210 (python load.py) has it open for writing, and one process writes a database at a time. ... ``` One process at a time can open a database to write it, and the file is open to write already: in another process (a script still running, a chloedb-server serving it, the second process of Flask's debug reloader, another web worker), or in this process, by an earlier `open` of the same path that was not closed (a module imported twice, a notebook cell run again, a hot reload in Next.js). The message goes on to say which, from the process id the writer keeps beside the file (`this process has it open for writing already`, `process N, the parent of this process` for a reloader, or `process N has it open`, with its command on Linux), and what to do; Python and JavaScript add the fix in their own words. Before 0.3.8 it stopped at `the database is open elsewhere`. - In one process, open the database once and share it; close it before opening it again. In JavaScript, keep it on `globalThis` (`globalThis.db ??= await open(path)`) so that a hot reload finds it. - Under a reloader (Flask's debug mode, Django's runserver, `uvicorn --reload`), open it when a request first needs it rather than at import, or run without the reloader. - To read it from other processes while one writes, open it read-only there: `chloedb.open(path, read_only=True)` in Python, `Database.open(path, { readOnly: true })` in JavaScript. - To write from several processes, serve the file with `chloedb-server --db path` and use the server's clients (`chloedb.connect(url)`), as [Build a search page](../guide/search-page.md) does. - `chloedb-server --db path` stops with the second line above while a script has the file open: stop the script first, or let it use the server too. [Python's common errors](python.md#busyerror-busy-the-database-is-open-elsewhere) has more on each case. ### `corrupt database: no valid meta slot` ```text _chloedb.ChloeDBError: corrupt database: no valid meta slot ERROR chloedb_server: open recipes.jsonl: corrupt database: no valid meta slot ``` Most often the file is not a ChloeDB database at all: a JSON Lines file, a CSV or a SQLite database given where a database was expected. ChloeDB leaves that file as it was, but makes an empty `-readers` folder beside it, which you can delete. To load such a file's rows, give it to a database: `db.import_file(path)` (JSON Lines, JSON, CSV, TSV), `db.import_sqlite(path)` or `db.import_parquet(path)` in Python, `POST /v1/import` or the command center's import on a server ([loading rows](server.md#loading-rows)). A ChloeDB database that is really damaged says which file and what is damaged, and how to recover ([damaged files](python.md#backing-up-and-damaged-files)). ### `does not exist: pass a schema to create it` ```text _chloedb.ChloeDBError: books.chloedb does not exist: pass a schema to create it ERROR chloedb_server: rec.chloedb does not exist: pass --schema (a JSON file, or the JSON) to create it ``` The first is `chloedb.open(path)` without a schema where no database is: a misspelt path, or a script started from another folder (a relative path is read from the current directory). Give the right path, or the schema to create it. The second is `chloedb-server import --db new.chloedb rows.jsonl`: a JSON Lines, JSON or CSV file does not say its types, so a new database needs `--schema`; a SQLite or Parquet file creates its tables itself. Or create the table first (`CREATE TABLE`, from Python or on a server) and import into it: `chloedb-server import` adds the rows to the database's first table, or `--table`. A running server takes files through `POST /v1/import` and the command center's **Import a file**, which proposes the types from the file's values. ## Models and vectors ### `model potion-retrieval-32M: no .../model.safetensors (fetch it first)` ```text {'emb': 'schema error: model potion-retrieval-32M: no /home/me/.local/share/chloedb/models/potion-retrieval-32M/model.safetensors (fetch it first)'} ``` A vector field names an embedding model that is not in the models folder. Python's `db.embed_errors` says so (above), a server's `GET /v1/schema` says it as each embedded field's `error`, with `"loaded": false`, and `GET /v1/models` lists what would open. Meanwhile the writes and queries that need the model fail: ```text chloedb._native.BadRequestError: schema error: notes.emb is embedded by model potion-retrieval-32M, which is not open: the row would be written without its vector, which similarity() never finds. ... chloedb._native.BadRequestError: query error: no embedded field has its model open parameter :v: no table has a field this server can embed text for; pass a vector ``` The Python, JavaScript and Java packages download a model ChloeDB knows themselves, the first time a database that names it opens, and say so on stderr: this error then means the download failed (it says why: no network, a proxy, a file whose checksum differs) or was turned off with `CHLOEDB_FETCH_MODELS=0`. Fetch it once by hand: `chloedb-server fetch-model potion-retrieval-32M` or `python -m chloedb fetch-model potion-retrieval-32M` (about 130 MB); `HF_ENDPOINT` names a mirror of Hugging Face for the packages. The models folder is `$CHLOEDB_MODELS` when that is set, else `~/.local/share/chloedb/models` (`~/.local/share/strata/models` on a machine that has that folder from before the rename); a server takes `--models DIR`, Python `chloedb.open(..., models=DIR)` and JavaScript the `models` option. Open the database again after fetching it; a running server opens a model fetched through it (its **Models** page, or `POST /v1/admin/models/fetch`). A server fetches a model it knows by itself when a table names it (unless it runs with `--no-fetch-models`, for a machine that cannot reach huggingface.co), and fills in the vectors of the rows written meanwhile; the error shows until the download ends, and `GET /v1/schema` then says `"loaded": true`. Meanwhile each embedded field in `GET /v1/schema` and `GET /v1/tables` says how its model's download goes, as `fetch` (`queued`, `running` with `bytes` of `size`, `done`, or `failed` with its `error`), and the command center's **Add meaning** shows it (`Downloading the model potion-retrieval-32M: 40.9 MB of 125 MB…`) and offers the Meaning search once it ends. ### A BERT model such as bge-small does not run ```text ERROR chloedb_server: schema error: model bge-small-en-v1.5 is a BERT model: build with the `bert` feature ``` The prebuilt programs (the install script's archives, the PyPI wheels, the npm package and the Docker image) are built without the `bert` feature, so the BERT models ChloeDB knows do not run in them: `bge-small-en-v1.5`, `snowflake-arctic-embed-m-v1.5`, the ColBERT model `answerai-colbert-small-v1`, and the cross-encoders `ms-marco-MiniLM-L-6-v2` and `bge-reranker-base`. `chloedb-server fetch-model bge-small-en-v1.5` downloads the model (about 133 MB) and then stops with the message above, and a table that names one lists it in Python's `db.embed_errors`, which refuses the writes that need it, while a server stores those rows without their vectors. Models of images, sound and ONNX exports need the `vision`, `audio` and `onnx` features, also left out of the prebuilt programs. `chloedb-server doctor` warns about each model in the models folder that its build cannot run, and names the feature. What to do instead: - **A model that runs in every build**: `potion-retrieval-32M` (Model2Vec, 512 dimensions, the one the guides use) or the smaller `potion-base-8M`, and their int8 copies ([embedded vector fields](server.md#embedded-vector-fields)). - **A hosted model**: `openai/text-embedding-3-small`, `cohere/embed-v4.0`, `voyage/voyage-3.5`, or `ollama/nomic-embed-text` from an Ollama on your own machine, with no key ([hosted models](server.md#hosted-models)). The prebuilt programs call them. - **Your own vectors**: make them with any library (fastembed, sentence-transformers) and write them into a `VECTOR` field with its `dim` and no `embed`, then pass the query's vector the same way (`ORDER BY similarity(emb, :v)`, with `v` a list of floats or a numpy array). - **A build from source with the feature**: `cargo build --release --bin chloedb-server --features bert` in `chloedb-server/` (`--features accelerate` on a Mac), or `MATURIN_PEP517_ARGS="--features bert" pip install ./chloedb-py` for Python ([from source](python.md#from-source)). ## Running a server ### `the address is in use` ```text ERROR chloedb_server: listen on 127.0.0.1:7700: the address is in use, by another chloedb-server or another program (lsof -i :7700 names it): stop it, or give --listen another port ERROR chloedb_server: listen on 127.0.0.1:7701: the address is in use, by another chloedb-server or another program (lsof -i :7701 names it): stop it, or give --grpc another port ``` Another program has the port: often a chloedb-server started earlier and still running. `lsof -i :7700` names it. A server listens on two ports, HTTP on 7700 and gRPC on 7701, so a second server on the same machine needs both moved: `--listen 127.0.0.1:7710 --grpc 127.0.0.1:7711`, or `--grpc off` when nothing uses gRPC. A server started without `--listen` does that itself: when 7700 or 7701 is taken, it takes the first free pair ten above them (7710 and 7711, then 7720 and 7721, up to ten tries) and says so, naming the chloedb-server that has the default when it is one. The error above is for an address you gave, which it keeps to. ### `is reachable beyond this machine: set --token` ```text ERROR chloedb_server: 0.0.0.0:7700 is reachable beyond this machine: set --token (or $CHLOEDB_TOKEN), make an API key, or pass --no-token to serve it open ``` A server that listens on an address other machines can reach (`0.0.0.0`, a LAN address, inside a container) must have a token or an API key, so that nobody else can change it. Give it `--token` (or `$CHLOEDB_TOKEN`) and send the token from every client, or listen on `127.0.0.1` ([security](server.md#security)). ### `401`: `missing or wrong token` ```text {"error":"missing or wrong token","error_code":"unauthenticated","hint":"send Authorization: Bearer ; a key that expired or was revoked needs a new one",...} ``` The server has a token or API keys, and the request sent none, or one it does not know. Send it as `Authorization: Bearer `: `curl -H 'authorization: Bearer ...'`, `chloedb.connect(url, token=...)` in Python and `connect(url, { token })` in JavaScript, or set `$CHLOEDB_TOKEN`, which both clients read. Python raises it as `UnauthorizedError: missing or wrong token (HTTP 401)`. A key that is known but may not do what was asked gets 403 instead, naming the scope it needs: `a write statement needs a key with the write scope; "page" has read`. ### `a page from http://localhost:3000 cannot change this server` A browser page of another origin called the server directly, and chloedb-server refuses those (403), reads included: call it from your app's own server code instead, or serve the page from the server's own origin ([JavaScript in a browser](javascript.md)). ### `URLError: ` A Python client found no server at its URL: start the server, or check the address and port its log printed (`HTTP and UI on http://127.0.0.1:7700/`). It is an `OSError`, not a `ChloeDBError` ([Python's common errors](python.md#urlerror-urlopen-error-errno-111-connection-refused)). ## ChloeCtx `chloectx doctor` prints a line per check, `ok`, `warn` or `FAIL`, and each `FAIL` line says how to fix it: [Install ChloeCtx](../chloectx/setup.md#troubleshooting) goes through them. --- # Search guide This page builds a small catalogue of books and searches it every way ChloeDB can: words, phrases and typos, filters and facets, meaning, a blend of the two, and results spread across authors. Each query is SQL, and every block runs, in order, against the code it documents. The [SQL reference](../chloedb/query-language.md) has every function and option; this page shows which to reach for. You need Python with the `chloedb` package and `chloedb-server` on your `PATH` ([quickstart](../quickstart.md)). The server program fetches the embedding model once; everything else runs in your Python process, with no server. **Running this page's SQL yourself.** Each SQL block below is one statement, with the rows it returns under it. Pass it to the database as a string: in Python, `db.query(sql)`, with a value for each `:name` placeholder as a keyword argument (`db.query(sql, q="dragon")`); in JavaScript, `await db.query(sql, {q: "dragon"})` ([JavaScript](../chloedb/javascript.md#querying)); over HTTP, `POST /v1/sql` with `{"sql": "...", "params": {"q": "dragon"}}` to a chloedb-server that serves the file (`chloedb-server --db books.chloedb`, [HTTP API](../chloedb/server.md#http-api)). The command center's SQL workbench runs them as they are. The first search below shows the Python form. ## The catalogue Twelve books, one JSON object a line: ```json file=books.jsonl {"id": "b01", "title": "The River and the Dragon", "author": "Ana Ruiz", "genres": ["fantasy"], "year": 1999, "rating": 4.1, "description": "A girl follows a river north to find the dragon that drowned her village."} {"id": "b02", "title": "Winter Garden", "author": "Tomas Berg", "genres": ["mystery"], "year": 2005, "rating": 3.8, "description": "A gardener finds a letter buried under the frozen roses and a quiet village mystery begins."} {"id": "b03", "title": "Dragons of the Salt Coast", "author": "Ana Ruiz", "genres": ["fantasy", "adventure"], "year": 2003, "rating": 4.4, "description": "Sea dragons guard the salt flats, and a smuggler crew sails into their storm."} {"id": "b04", "title": "The Last Lighthouse", "author": "Mei Chen", "genres": ["literary"], "year": 2018, "rating": 4.6, "description": "An old keeper writes letters to the ships that no longer pass her lighthouse."} {"id": "b05", "title": "Machine Hearts", "author": "Jonas Abara", "genres": ["science fiction"], "year": 2021, "rating": 4.0, "description": "A repair robot learns to grieve after its owner dies on a mining station."} {"id": "b06", "title": "Stars Over Lagos", "author": "Jonas Abara", "genres": ["science fiction", "adventure"], "year": 2016, "rating": 4.2, "description": "Engineers in Lagos build a launch site and race a rival company to orbit."} {"id": "b07", "title": "The Cartographer's Daughter", "author": "Mei Chen", "genres": ["historical", "adventure"], "year": 2012, "rating": 4.3, "description": "A mapmaker's daughter crosses the mountains with her father's unfinished maps."} {"id": "b08", "title": "Murder at the Observatory", "author": "Tomas Berg", "genres": ["mystery"], "year": 2019, "rating": 3.9, "description": "An astronomer is found dead beneath the telescope, and every guest saw the stars."} {"id": "b09", "title": "Bread and Salt", "author": "Lena Novak", "genres": ["literary", "historical"], "year": 2008, "rating": 4.5, "description": "Three generations of bakers keep a village alive through war and famine."} {"id": "b10", "title": "The Dragon Accords", "author": "Lena Novak", "genres": ["fantasy"], "year": 2022, "rating": 3.7, "description": "Diplomats negotiate a treaty between kingdoms and the last of the dragons."} {"id": "b11", "title": "Quiet Machines", "author": "Mei Chen", "genres": ["science fiction", "literary"], "year": 2024, "rating": 4.7, "description": "Household robots begin to write poems, and a lonely engineer reads every one."} {"id": "b12", "title": "Tides of Glass", "author": "Ana Ruiz", "genres": ["fantasy", "romance"], "year": 2011, "rating": 4.0, "description": "A glassblower falls for a sea witch who trades storms for memories."} ``` A table with a primary key, text to search, keywords and numbers to filter on, and a vector that ChloeDB computes from the title and description with a small embedding model. Fetch the model once (it is about 130 MB, kept in `~/.local/share/chloedb/models`, or wherever `CHLOEDB_MODELS` says; a machine with `~/.local/share/strata/models` from before the rename keeps using that): ```sh chloedb-server fetch-model potion-retrieval-32M ``` ```python file=load.py import json import chloedb db = chloedb.open("books.chloedb", schema={ "table": "books", "key": "id", "fields": [ {"name": "id", "type": "keyword"}, {"name": "title", "type": "text"}, {"name": "description", "type": "text"}, {"name": "author", "type": "keyword"}, {"name": "genres", "type": "keyword", "multi": True}, {"name": "year", "type": "int"}, {"name": "rating", "type": "float"}, {"name": "emb", "type": "vector", "embed": {"from": ["title", "description"], "model": "potion-retrieval-32M"}}, ], }) with open("books.jsonl") as f: db.insert(json.loads(line) for line in f) print(len(db), "books") db.close() ``` ```sh python3 load.py ``` ```text output 12 books ``` The same table in SQL, as `db.sql(...)` and a server's `POST /v1/sql` take it, is `CREATE TABLE books (id KEYWORD PRIMARY KEY, title TEXT, description TEXT, author KEYWORD, genres KEYWORD[], year INT, rating FLOAT, emb VECTOR OPTIONS(embed = 'title, description', model = 'potion-retrieval-32M'))`. ## Words: `MATCH` and `bm25` `MATCH` says whether a row has the words; `bm25` scores how well, and `score()` is the score a row was ranked by. Both take the field to search: ```sql db=books.chloedb SELECT id, title, score() FROM books WHERE MATCH(description, 'village') ORDER BY bm25(description, 'village') DESC LIMIT 5 ``` ```text output id | title | score() ----+--------------------------+-------- b01 | The River and the Dragon | 1.322 b09 | Bread and Salt | 1.322 b02 | Winter Garden | 1.213 ``` The same statement from Python, with the search's words as a parameter: ```python import chloedb db = chloedb.open("books.chloedb", read_only=True) r = db.query("""SELECT id, title, score() FROM books WHERE MATCH(description, :q) ORDER BY bm25(description, :q) DESC LIMIT 5""", q="village") for row in r: print(row["id"], row["title"], round(row["score()"], 3)) ``` ```text output b01 The River and the Dragon 1.322 b09 Bread and Salt 1.322 b02 Winter Garden 1.213 ``` Words are stemmed, so `dragon` finds *dragons*. `MATCH` reads a small query language: words side by side must all be there, `OR` and `-` (not) combine them, quotes ask for a phrase, `*` for a prefix: ```sql db=books.chloedb SELECT id, title FROM books WHERE MATCH(description, '(dragon OR robot) -sea') ORDER BY id ``` ```text output id | title ----+------------------------- b01 | The River and the Dragon b05 | Machine Hearts b10 | The Dragon Accords b11 | Quiet Machines ``` ```sql db=books.chloedb SELECT id, title FROM books WHERE MATCH(description, '"salt flats"') OR MATCH(title, 'mach*') ORDER BY id ``` ```text output id | title ----+-------------------------- b03 | Dragons of the Salt Coast b05 | Machine Hearts b11 | Quiet Machines ``` ### As you type: prefixes `bm25` reads a prefix as `MATCH` does: `drag*` ranks by the words of the field that begin *drag* ([weights, required and excluded words](../chloedb/query-language.md#weights-required-and-excluded-words)). So a search box can send what has been typed so far, its last word with a `*` while it is being typed, to both: ```sql db=books.chloedb SELECT id, title FROM books WHERE MATCH(title, 'drag*') ORDER BY bm25(title, 'drag*') DESC ``` ```text output id | title ----+-------------------------- b01 | The River and the Dragon b10 | The Dragon Accords b03 | Dragons of the Salt Coast ``` ```sql db=books.chloedb SELECT id, title FROM books WHERE MATCH(title, 'salt drag*') ORDER BY bm25(title, 'salt drag*') DESC ``` ```text output id | title ----+-------------------------- b03 | Dragons of the Salt Coast ``` **Changed:** `bm25` read `drag*` as the word *drag* before, which no book has, and a ranking by `bm25` returns only the rows it scores, so the first query found nothing until the last word was whole. Against a server or package of 0.3.7 or earlier, rank by the words already typed in full, or by a column while there are none: ```sql db=books.chloedb SELECT id, title FROM books WHERE MATCH(title, 'drag*') ORDER BY rating DESC ``` ```text output id | title ----+-------------------------- b03 | Dragons of the Salt Coast b01 | The River and the Dragon b10 | The Dragon Accords ``` A prefix is lowercased, and finds the words that start with it and the words it may be the start of whose stems do not. The index keeps stems (*mystery* as *mysteri*, *running* as *run*), so a prefix also looks up the stem of what was typed as a word, and in English the stems of what was typed completed by a common ending (`runni*` finds *running*). Every letter of a word typed keeps its rows: ```sql db=books.chloedb SELECT id, title FROM books WHERE MATCH(description, 'mystery*') ``` ```text output id | title ----+-------------- b02 | Winter Garden ``` **Changed:** a prefix matched only the stems that start with it before, so against a server or package of 0.3.7 or earlier a word typed in full and then `*` (`mystery*`, `battery*`, `headphone*`) finds nothing, though each letter before it found the rows. `db.search(text)` ranks with `bm25` too, so it finds nothing for a word half typed unless the word ends in `*`. To complete whole values instead (the searches people ran before, names kept as `KEYWORD`), `PREFIX(field, :typed)` reads a keyword field's sorted values, with typos if asked ([prefixes and autocomplete](../chloedb/query-language.md#prefixes-and-autocomplete)). ## Typos `fuzzy => 'auto'` lets a word be an edit or two away, more for longer words, counted on the word as typed rather than on its stem: *choclate* is one edit from *chocolate*, though its stem, *choclat*, is three from *chocol*. Ranked, it corrects a typo rather than widening every word: ```sql db=books.chloedb SELECT id, title FROM books ORDER BY bm25(description, 'lighthuose keeper', fuzzy => 'auto') DESC LIMIT 1 ``` ```text output id | title ----+-------------------- b04 | The Last Lighthouse ``` `db.search(text)` forgives a typo in each word, as the search box on a table's page in the command center does (which, when nothing is found, also offers the correction, "did you mean", if there is one); `typos=False` searches the words as written. A query of your own that should forgive typos asks for it in its SQL, or writes `~` after a word (`dragn~`), which `bm25` reads as `fuzzy => 'auto'` for that word. With a `MATCH`, a row must have every word, each as typed or within its edits, and a `bm25` of the same text on the same field takes the `MATCH`'s `fuzzy` and ranks every row the `MATCH` keeps, the words as typed first. For the text of a search box, `MATCH(description, :q, syntax => 'plain')` reads it as words alone, so a stray quote or bracket is no error ([what a visitor typed](../chloedb/query-language.md#full-text-match)): ```python import chloedb db = chloedb.open("books.chloedb", read_only=True) r = db.query("""SELECT id, title FROM books WHERE MATCH(description, :q, fuzzy => 'auto') ORDER BY bm25(description, :q) DESC LIMIT 3""", q="dragn villge") for row in r: print(row["id"], row["title"]) print(len(db.search("dragn villge", mode="text")), "rows from db.search") print(len(db.search("dragn villge", mode="text", typos=False)), "rows by the words as written") ``` ```text output b01 The River and the Dragon 5 rows from db.search 0 rows by the words as written ``` [Build a search page](search-page.md) puts this behind a search box, with the matched words highlighted and "did you mean" for a misspelt word. ## Filters and facets Text, keyword, number and list conditions mix freely in `WHERE`, and the planner picks the order. A multi-valued keyword such as `genres` matches a row when any of its values does: ```sql db=books.chloedb SELECT id, title, year FROM books WHERE genres = 'adventure' AND year >= 2010 ORDER BY rating DESC ``` ```text output id | title | year ----+-----------------------------+----- b07 | The Cartographer's Daughter | 2012 b06 | Stars Over Lagos | 2016 ``` Facets, the counts beside a search box, are a `GROUP BY` over the rows that match: ```sql db=books.chloedb SELECT author, COUNT(*) AS books, AVG(rating) AS avg_rating FROM books WHERE MATCH(description, 'dragon OR dragons OR sea OR robot') GROUP BY author ORDER BY books DESC, author ``` ```text output author | books | avg_rating ------------+-------+----------- Ana Ruiz | 3 | 4.167 Jonas Abara | 1 | 4 Lena Novak | 1 | 3.7 Mei Chen | 1 | 4.7 ``` ## Meaning: vectors `similarity(emb, :v)` scores rows by how close their vector is to a query's. In Python a parameter `{"embed": text}` is the text's vector by the field's own model, so a question finds books that share none of its words: ```python import chloedb db = chloedb.open("books.chloedb", read_only=True) r = db.query("SELECT id, title FROM books ORDER BY similarity(emb, :v) DESC LIMIT 3", v={"embed": "artificial intelligence and feelings"}) for row in r: print(row["id"], row["title"]) ``` ```text output b05 Machine Hearts b11 Quiet Machines b06 Stars Over Lagos ``` A vector search walks 200 candidates of the field's HNSW graph by default, which is fast and on some collections finds less than you want: on GloVe-100's 1.18M word vectors it finds 0.859 of the exact top 10. `similarity(emb, :v, ef => 800)` walks 800 and found 0.942 in 1.29 ms of the server's time, where hosted Pinecone took 11.0 ms of its own for that recall ([the comparison](../site/bench-vectors.html#hosted)); `similarity(emb, :v, strategy => 'flat')` scores every row exactly. ## Similar rows: more like this `{"vector_of": key}` is the vector a row already has, so ranking by `similarity` to it lists the rows nearest it in meaning: "more like this" under a product, "readers also liked" under a book. `id <> :id` leaves the row itself out, and any other condition goes in the same `WHERE`: ```python import chloedb db = chloedb.open("books.chloedb", read_only=True) r = db.query("SELECT id, title FROM books WHERE id <> :id ORDER BY similarity(emb, :v) DESC LIMIT 3", id="b01", v={"vector_of": "b01"}) for row in r: print(row["id"], row["title"]) ``` ```text output b10 The Dragon Accords b03 Dragons of the Salt Coast b07 The Cartographer's Daughter ``` The vector is read from the table the statement names (`{"vector_of": "b01", "table": "books"}` names one). The parameter is the same from JavaScript (`{vector_of: "b01"}`), in the `params` of a server's `POST /v1/sql`, and through a client of a server (`chloedb.connect`). ## Both: hybrid ranking Words find exact names and rare terms; vectors find paraphrases. `rrf` fuses the two rankings by reciprocal rank, and needs no tuning: ```python import chloedb db = chloedb.open("books.chloedb", read_only=True) q = "a story about the sea and storms" r = db.query(""" SELECT id, title, score() FROM books ORDER BY rrf(bm25(description, :q), similarity(emb, :v)) DESC LIMIT 3 """, q=q, v={"embed": q}) for row in r: print(row["id"], row["title"]) ``` ```text output b03 Dragons of the Salt Coast b12 Tides of Glass b04 The Last Lighthouse ``` When one side should count more, normalise each score to 0..1 and weigh them: `ORDER BY 0.3 * minmax(bm25(description, :q)) + 0.7 * minmax(similarity(emb, :v)) DESC`. The same blend can boost by a column, `* (1 + 0.1 * rating)`; [ranking expressions](../chloedb/query-language.md#ranking-expressions) has the rest. For the common case, `db.search(text)` writes this query itself: BM25 over the text fields fused with the vector field's similarity. ```python import chloedb db = chloedb.open("books.chloedb", read_only=True) for row in db.search("lonely robots", limit=2, columns=["id", "title"]): print(row["id"], row["title"]) ``` ```text output b11 Quiet Machines b05 Machine Hearts ``` ## Spread results out: `MAX k PER` A ranking where one author fills the page reads badly. `MAX 1 PER author` keeps each author's best row and the order of the rest: ```sql db=books.chloedb SELECT id, author, title FROM books ORDER BY rating DESC MAX 1 PER author ``` ```text output id | author | title ----+-------------+-------------------------- b11 | Mei Chen | Quiet Machines b09 | Lena Novak | Bread and Salt b03 | Ana Ruiz | Dragons of the Salt Coast b06 | Jonas Abara | Stars Over Lagos b08 | Tomas Berg | Murder at the Observatory ``` ## What the planner did Each answer says how it was found. In Python, `stats["plan"]` holds a line for each segment the query read: which conditions came from an index, which were tested row by row, and how the rows were ranked. [Reading a plan](../chloedb/query-language.md#reading-a-plan) explains the lines, and a server's `POST /v1/explain` takes the same `SELECT` and answers its plan as a tree too. ```python import chloedb db = chloedb.open("books.chloedb", read_only=True) r = db.query("SELECT id FROM books WHERE MATCH(description, 'dragon') AND year > 2000 " "ORDER BY bm25(description, 'dragon') DESC LIMIT 3") print(r.keys) for line in r.stats["plan"]: print(line) ``` ```text output ['b10', 'b03'] seg 0: bm25 MaxScore, filter Probe ``` ## Next - [Build a search page](search-page.md): this page's queries behind a search box in a Python web app, with highlights, did you mean and more like this. - [Retrieval for RAG](rag.md): the hybrid query above, feeding passages to a model. - [The SQL reference](../chloedb/query-language.md): joins, window functions, graphs, rank profiles, rerankers. - [Python](../chloedb/python.md): queries built in Python rather than SQL text, Arrow results, writes. --- # Build a search page This page builds the search page of a small shop in Python: a search box that forgives typos, the words it matched highlighted in the results, "did you mean" under a misspelt search, a filter by category with the count of each, and "more like this" under every product. The web page runs on Python's own `http.server`, so it needs nothing but the standard library and `chloedb`; the [Flask version](#the-same-page-in-flask) at the end uses the same functions. You need Python 3.10 or later with the `chloedb` package and `chloedb-server` on your `PATH`. The package's `server` extra installs both, prebuilt (from 0.3.7): ```sh # install python3 -m venv .venv && . .venv/bin/activate pip install "chloedb[server]" # chloedb, and chloedb-server of the same release ``` ## Why the page talks to a server Two parts of a search page are routes of [chloedb-server](../chloedb/server.md#http-api), not methods of a database opened in your process: highlighting (`POST /v1/highlight`) and did you mean (`POST /v1/correct`). A web app also tends to run as more than one process: Flask's debug reloader runs your module twice, and gunicorn starts several workers. Only one process at a time can open a database file to write it, and a second one fails with `BusyError: busy: the database is open elsewhere`. So the catalogue lives in chloedb-server, and the page is its client through `chloedb.connect`, which has the same methods as a database in your process (`query`, `insert`, `search`, `get`). Every process of the app can connect, and none of them holds the file. A page that needs neither highlights nor did you mean can skip the server: each process opens the file with `chloedb.open(path, read_only=True)`, and one other process writes it ([Python](../chloedb/python.md#a-database-in-your-process)). ## The catalogue Seventeen products, one JSON object a line: ```json file=products.jsonl {"id": "p01", "name": "Waterproof hiking jacket", "description": "A light shell jacket that keeps the rain out on long hikes.", "category": "jackets", "price": 129.0} {"id": "p02", "name": "Insulated winter jacket", "description": "A warm down jacket for cold city winters.", "category": "jackets", "price": 189.0} {"id": "p03", "name": "Packable rain jacket", "description": "A waterproof jacket that folds into its own pocket.", "category": "jackets", "price": 89.0} {"id": "p04", "name": "Fleece jacket", "description": "A soft fleece layer for cold mornings and campfires.", "category": "jackets", "price": 69.0} {"id": "p05", "name": "Kids' rain jacket", "description": "A bright waterproof jacket with a hood, for children.", "category": "jackets", "price": 49.0} {"id": "p06", "name": "Softshell cycling jacket", "description": "A windproof jacket for cool rides, with reflective trim.", "category": "jackets", "price": 109.0} {"id": "p07", "name": "Trail running shoes", "description": "Grippy, waterproof shoes for muddy trails.", "category": "shoes", "price": 99.0} {"id": "p08", "name": "Leather office shoes", "description": "Classic leather shoes for the office.", "category": "shoes", "price": 149.0} {"id": "p09", "name": "Hiking boots", "description": "Waterproof leather boots with ankle support for rocky paths.", "category": "shoes", "price": 159.0} {"id": "p10", "name": "Wool hiking socks", "description": "Warm socks that dry fast on wet hikes.", "category": "shoes", "price": 15.0} {"id": "p11", "name": "Rain cover for backpacks", "description": "A waterproof cover that fits 20 to 40 litre packs.", "category": "gear", "price": 19.0} {"id": "p12", "name": "Daypack, 25 litres", "description": "A light backpack for day hikes, with a pocket for a water bladder.", "category": "gear", "price": 75.0} {"id": "p13", "name": "Headlamp", "description": "A bright rechargeable headlamp for night hikes and camping.", "category": "gear", "price": 35.0} {"id": "p14", "name": "Camping stove", "description": "A small gas stove that boils a litre of water in four minutes.", "category": "gear", "price": 59.0} {"id": "p15", "name": "Down sleeping bag", "description": "A warm sleeping bag for cold nights in the mountains.", "category": "gear", "price": 219.0} {"id": "p16", "name": "Insulated water bottle", "description": "Keeps drinks cold for a day or hot for twelve hours.", "category": "gear", "price": 25.0} {"id": "p17", "name": "Trekking poles", "description": "Light aluminium poles that take the load off your knees on steep descents.", "category": "gear", "price": 65.0} ``` "More like this" compares products by meaning, with a vector that ChloeDB computes from each product's name and description by a small embedding model. Fetch the model once (about 130 MB, into `~/.local/share/chloedb/models`, or wherever `CHLOEDB_MODELS` says), then start the server on a new database file. It listens on `127.0.0.1:7700`, which only this machine can reach: ```sh chloedb-server fetch-model potion-retrieval-32M chloedb-server --db shop.chloedb > server.log 2>&1 & server=$! until curl -sf http://127.0.0.1:7700/livez > /dev/null; do sleep 0.2; done ``` On your own machine, run `chloedb-server --db shop.chloedb` in a terminal of its own instead, and leave it running. The table has the fields to show (`name`, `description`, `price`), a keyword to filter on (`category`), `body`, a text field generated from the name and the description, which is what the search box searches, and `emb`, the vector: ```python file=load.py import json import chloedb db = chloedb.connect("http://127.0.0.1:7700") db.sql(""" CREATE TABLE products ( id KEYWORD PRIMARY KEY, name TEXT, description TEXT, category KEYWORD, price FLOAT, body TEXT OPTIONS(from = 'name, description'), emb VECTOR OPTIONS(embed = 'name, description', model = 'potion-retrieval-32M') ) """) with open("products.jsonl") as f: print(db.insert([json.loads(line) for line in f], table="products"), "products") ``` ```sh python3 load.py ``` ```text output 17 products ``` ## The queries, as functions Everything the page asks the database is in one module. Values always go in as parameters (`:q`, `:category`), never into the SQL text, so nothing a visitor types can change a statement: ```python file=shop.py """The shop's search: what the page asks chloedb-server, as functions.""" import json import urllib.request import chloedb SERVER = "http://127.0.0.1:7700" db = chloedb.connect(SERVER) def where(q, category=None, max_price=None): """The WHERE clause and parameters of a search for q.""" conds, params = ["MATCH(body, :q, syntax => 'plain', fuzzy => 'auto')"], {"q": q} if category: conds.append("category = :category") params["category"] = category if max_price is not None: conds.append("price <= :max_price") params["max_price"] = max_price return " AND ".join(conds), params def search(q, category=None, max_price=None, limit=10): """The products with q's words, typos forgiven, best match first.""" cond, params = where(q, category, max_price) sql = f"""SELECT id, name, description, category, price FROM products WHERE {cond} ORDER BY bm25(body, :q) DESC LIMIT :limit""" return db.query(sql, params, limit=limit).dicts() def categories(q, max_price=None): """How many products each category has for q: the filter's counts.""" cond, params = where(q, max_price=max_price) sql = f"""SELECT category, COUNT(*) AS n FROM products WHERE {cond} GROUP BY category ORDER BY n DESC, category""" return db.query(sql, params).rows def more_like(key, limit=3): """The products nearest in meaning to the product with this key.""" sql = """SELECT id, name, price FROM products WHERE id <> :key ORDER BY similarity(emb, :v) DESC LIMIT :limit""" return db.query(sql, key=key, v={"vector_of": key}, limit=limit).dicts() def post(route, body): """Sends a JSON body to a route of the server and returns its answer.""" request = urllib.request.Request(SERVER + route, data=json.dumps(body).encode(), headers={"content-type": "application/json"}) with urllib.request.urlopen(request) as answer: return json.load(answer) def highlight(q, texts): """Each text, HTML-escaped, with the words q matches between tags.""" answer = post("/v1/highlight", {"table": "products", "field": "body", "query": q, "texts": texts, "size": 0}) return answer["texts"] def did_you_mean(q): """q with its misspelt words corrected, or None when it has none.""" answer = post("/v1/correct", {"table": "products", "field": "body", "text": q}) return answer["text"] if answer["changed"] else None ``` The sections below try each function from Python before the page puts them together. ### Typos `MATCH(body, :q, syntax => 'plain', fuzzy => 'auto')` keeps the products that have every word of the search, each spelt as typed or an edit away (two edits for words of six letters or more; none for words of one or two letters). `syntax => 'plain'` reads the search as its words alone, so what a visitor types is never an error: a stray quote or bracket (`rain jacket"`) is left out, and `-`, `OR` and `*` are no operators. `bm25(body, :q)` ranks them, and since it ranks the same text on the same field, it reads the words as the `MATCH` does and ranks every product the `MATCH` keeps, those spelt as typed first ([typos](../chloedb/query-language.md#typos-and-synonyms)). So "jaket" finds every jacket: ```python import shop for p in shop.search("jaket"): print(p["id"], p["name"], p["price"]) ``` ```text output p05 Kids' rain jacket 49.0 p02 Insulated winter jacket 189.0 p03 Packable rain jacket 89.0 p06 Softshell cycling jacket 109.0 p01 Waterproof hiking jacket 129.0 p04 Fleece jacket 69.0 ``` Typos are forgiven where a query asks for it: `db.search(text)` asks for it itself (`typos=False` turns it off), as the search box on a table's page in the command center does, and a query of your own should send the box's text with `fuzzy => 'auto'`, as `shop.search` does. Every word of the search must be there; for a box where any word will do, rank with `bm25(body, :q, fuzzy => 'auto')` and leave the `MATCH` out (a ranked `bm25` returns the rows that have any of its words). ### A filter, with its counts The filter is one more condition in the `WHERE`, and its counts are a `GROUP BY` over the same conditions, so each count is the number of products its link shows: ```python import shop print(shop.categories("waterprof")) for p in shop.search("waterprof", category="shoes", max_price=150): print(p["id"], p["name"], p["price"]) ``` ```text output [['jackets', 3], ['shoes', 2], ['gear', 1]] p07 Trail running shoes 99.0 ``` ### Highlights `POST /v1/highlight` marks the words a search matches in any texts you send it, as the field's analyzer reads them, so "waterprof" marks *Waterproof* and "jaket" marks *jacket*. The answer is HTML-escaped, with `` tags around each match, ready to put in a page (`size` cuts each text to the stretch of about that many characters with the most matches; `0` keeps it whole): ```python import shop hits = shop.search("waterprof jaket") for text in shop.highlight("waterprof jaket", [p["name"] for p in hits] + [p["description"] for p in hits]): print(text) ``` ```text output Kids' rain jacket Packable rain jacket Waterproof hiking jacket A bright waterproof jacket with a hood, for children. A waterproof jacket that folds into its own pocket. A light shell jacket that keeps the rain out on long hikes. ``` Highlighting reads typos a little more strictly than the search does: a word of four letters or fewer is marked only where it is spelt as typed. ### Did you mean `POST /v1/correct` replaces the words of a search that no product has with the word of the field they most likely meant. It suggests a word only when it is fairly sure, which on a small catalogue means a word that many products use: one edit from what was typed, and in five products or more ([did you mean](../chloedb/query-language.md#did-you-mean-correcting-a-querys-words)). Six products say "jacket", and two say "leather", so the first typo gets a suggestion and the second does not, although the search finds both: ```python import shop print(shop.did_you_mean("waterprof jaket")) print(shop.did_you_mean("lether")) print([p["name"] for p in shop.search("lether")]) ``` ```text output waterproof jacket None ['Leather office shoes', 'Hiking boots'] ``` ### More like this `{"vector_of": key}` is the stored vector of the row with that key, so ordering by `similarity(emb, :v)` lists the products nearest it in meaning. `id <> :key` leaves out the product itself, and any other condition (the same category, in stock) goes in the same `WHERE`: ```python import shop for p in shop.more_like("p01"): print(p["id"], p["name"]) ``` ```text output p03 Packable rain jacket p05 Kids' rain jacket p11 Rain cover for backpacks ``` ## The page `app.py` serves the page at `http://127.0.0.1:8000`: a form with the search box and a highest price, did you mean, the category links with their counts, and the results with their words marked and a "More like this" link each. It escapes everything it did not get from `/v1/highlight`, which escapes for it, and shows an error page when chloedb-server does not answer: ```python file=app.py """The shop's search page, on Python's own web server.""" import html from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlencode, urlparse import chloedb import shop FORM = """ Shop search
""" def link(text, **params): """A link to this page with these parameters.""" return f'{html.escape(text)}' def page(q, category, max_price, like): lines = [FORM.format(q=html.escape(q), max_price=html.escape(max_price))] if like: lines.append("

More like this

") for p in shop.more_like(like, limit=5): lines.append(f"
  • {html.escape(p['name'])}, ${p['price']:.2f}
  • ") return "\n".join(lines) if not q: return "\n".join(lines) try: price = float(max_price) if max_price else None except ValueError: price = None suggestion = shop.did_you_mean(q) if suggestion: lines.append(f"

    Did you mean {link(suggestion, q=suggestion)}?

    ") counts = [link(f"{c} ({n})", q=q, category=c, max_price=max_price) for c, n in shop.categories(q, price)] lines.append("

    " + " · ".join([link("All", q=q, max_price=max_price)] + counts) + "

    ") hits = shop.search(q, category=category or None, max_price=price) marked = shop.highlight(q, [p["name"] for p in hits] + [p["description"] for p in hits]) if hits else [] for p, name, description in zip(hits, marked, marked[len(hits):]): lines.append(f"
  • {name} ${p['price']:.2f}: {description} {link('More like this', like=p['id'])}
  • ") if not hits: lines.append("

    No products have those words.

    ") return "\n".join(lines) class Handler(BaseHTTPRequestHandler): def do_GET(self): url = urlparse(self.path) if url.path != "/": self.send_error(404) return args = {k: v[0] for k, v in parse_qs(url.query).items()} try: text = page(args.get("q", "").strip(), args.get("category", ""), args.get("max_price", ""), args.get("like", "")) body = (text + "\n").encode() except (chloedb.ChloeDBError, OSError) as e: # OSError: chloedb-server does not answer self.send_error(503, "The search is not available", str(e)) return self.send_response(200) self.send_header("content-type", "text/html; charset=utf-8") self.send_header("content-length", str(len(body))) self.end_headers() self.wfile.write(body) if __name__ == "__main__": ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever() ``` Start it, and ask it for a search with a typo, as a browser would: ```sh python3 app.py > app.log 2>&1 & app=$! until curl -sf http://127.0.0.1:8000/ > /dev/null; do sleep 0.2; done curl -s 'http://127.0.0.1:8000/?q=waterprof+jaket&max_price=100' ``` ```text output ...

    Did you mean waterproof jacket?

    All · jackets (2)

  • Kids' rain jacket $49.00: A bright waterproof jacket with a hood, for children. More like this
  • Packable rain jacket $89.00: A waterproof jacket that folds into its own pocket. More like this
  • ``` Open [http://127.0.0.1:8000](http://127.0.0.1:8000) in a browser and try "sleping bag", "lether", "warm" or "hiking boots" with a highest price. The server's own command center, at [http://127.0.0.1:7700](http://127.0.0.1:7700), shows the same table and the queries the page sent (**Queries**). The browser talks only to the app, and the app to chloedb-server. That keeps the server's address and keys out of the page, and it is also the only way that works: chloedb-server refuses requests from pages of other sites, reads included ([security](../chloedb/server.md#security)). When you are done, stop both (the catalogue stays in `shop.chloedb`): ```sh kill $app $server ``` ## The same page in Flask The functions of `shop.py` drop into any web framework. This is the page in [Flask](https://flask.palletsprojects.com) (`pip install flask`, then `flask --app flask_app run --debug`), shortened to the search and "more like this". It is shown, not run with this page, which installs nothing but `chloedb`: ```python file=flask_app.py from flask import Flask, render_template_string, request import shop app = Flask(__name__) PAGE = """
    {% if suggestion %}

    Did you mean {{ suggestion }}?

    {% endif %} {% for p, name in hits %}
  • {{ name | safe }} ${{ "%.2f" | format(p.price) }} More like this
  • {% endfor %} {% for p in similar %}
  • {{ p.name }}, ${{ "%.2f" | format(p.price) }}
  • {% endfor %} """ @app.get("/") def index(): q = request.args.get("q", "").strip() hits = shop.search(q) if q else [] names = shop.highlight(q, [p["name"] for p in hits]) if hits else [] return render_template_string(PAGE, q=q, suggestion=q and shop.did_you_mean(q), hits=zip(hits, names), similar=[]) @app.get("/like/") def like(key): return render_template_string(PAGE, q="", suggestion=None, hits=[], similar=shop.more_like(key, limit=5)) ``` `| safe` is for the highlighted names alone, which `/v1/highlight` has escaped already; Jinja escapes the rest. With `--debug`, Flask runs this module in two processes, one that watches the files and one that serves. Both are clients of the one chloedb-server, so the second starts as the first did. Had the module opened the file itself with `chloedb.open("shop.chloedb")`, the second would have failed with `BusyError: busy: the database is open elsewhere`, since the first holds it, and every request with it ([troubleshooting](../chloedb/troubleshooting.md#busy-the-database-is-open-elsewhere)). For an asyncio framework such as FastAPI, `chloedb.AsyncClient` has the same methods as coroutines ([from asyncio](../chloedb/python.md#from-asyncio)). ## Before other people use it - Give chloedb-server a token before it listens beyond this machine, and the app a key: `chloedb.connect(SERVER, token=...)`, or `$CHLOEDB_TOKEN` ([security](../chloedb/server.md#security)). A key that can only read the products table is enough for this page. - Change a product with `UPDATE` or `upsert`: `upsert` replaces the whole row, so it needs every field, while `UPDATE products SET price = 79 WHERE id = 'p03'` changes one. Writes are searchable on the next query. - [Troubleshooting](../chloedb/troubleshooting.md) has the errors people meet first, each with its message and what to do. ## Next - [The search guide](search.md): phrases, prefixes as you type, vectors, hybrid ranking and results spread across a field. - [Python](../chloedb/python.md): every method of `chloedb.connect` and `chloedb.open`, and their errors. - [The SQL reference](../chloedb/query-language.md): boosts by a column (`bm25(body, :q) * (1 + 0.1 * rating)`), synonyms and rank profiles. --- # ChloeDB's query language ChloeDB speaks standard SQL over the tables of a database: `SELECT` with functions for full text, vectors, rank fusion and graphs, aggregates, typo-tolerant and synonym searches, and subqueries, `WITH` and joins of a table with itself; `INSERT`, `UPDATE` and `DELETE`; `CREATE TABLE`, `ALTER TABLE` and `DROP TABLE`; and functions stored in the database (`CREATE FUNCTION`), which queries call. Text, structured and vector conditions mix freely in one statement, and the planner decides how to evaluate them together. It reads like PostgreSQL's SQL and gives the same answers for most queries, but it is not PostgreSQL: a few expressions give other answers, some statements are refused, and no Postgres client connects to it, since ChloeDB serves no Postgres wire protocol. [Differences from PostgreSQL](#differences-from-postgresql) lists them, and [Running SQL](#running-sql) the ways a statement gets in. ## A first look ```sql -- boolean full text and structured filters, ranked by BM25 SELECT id, title, score() FROM papers WHERE MATCH(body, 'vaccine AND (mrna OR "messenger rna") NOT animal') AND year BETWEEN 2019 AND 2021 AND category IN ('virology', 'immunology') ORDER BY bm25(body, 'mrna vaccine efficacy') DESC LIMIT 10; -- filtered vector search SELECT id FROM papers WHERE rating >= 4 ORDER BY similarity(emb, :q) DESC LIMIT 10; -- hybrid: a weighted sum of normalised scores, or reciprocal rank fusion SELECT id FROM papers WHERE year >= 2015 ORDER BY 0.2 * tmm(bm25(body, :text)) + 0.8 * tmm(similarity(emb, :q)) DESC LIMIT 10; SELECT id FROM papers WHERE year >= 2015 ORDER BY rrf(bm25(body, :text), similarity(emb, :q)) DESC LIMIT 10; -- any expression of scores and columns SELECT id FROM papers ORDER BY ln(1 + bm25(body, :text)) * (1 + 0.2 * coalesce(rating, 0)) DESC LIMIT 10; -- facets and aggregates over any result SELECT category, COUNT(*), AVG(rating), MAX(year) FROM papers WHERE MATCH(body, 'vaccine') GROUP BY category HAVING COUNT(*) >= 10 ORDER BY 2 DESC LIMIT 5; -- typos and synonyms SELECT id FROM papers WHERE MATCH(body, 'vacine~ OR mrna', synonyms => 1) LIMIT 10; -- a join along citations, ranked by one side SELECT a.id, a.title, b.id AS cited, b.title AS cited_title FROM papers a JOIN papers b ON a.cites = b.id WHERE a.year >= 2020 ORDER BY bm25(a.body, 'mrna vaccine') DESC LIMIT 20; ``` ## Statement shape ```text [WITH name AS (SELECT ...), ...] SELECT [DISTINCT | DISTINCT ON ()] FROM [JOIN
    ON ...] | | (SELECT ...) AS t [WHERE ] [GROUP BY [HAVING ]] [QUALIFY ] [WINDOW name AS (), ...] [{UNION | INTERSECT | EXCEPT} [ALL] SELECT ...] [ORDER BY [ASC | DESC] [NULLS FIRST | LAST] [, [ASC | DESC]] [MAX k PER ]] [PACK n TOKENS [OF ] [EXCERPT n] [DEDUPE x [ON ]] [FOLLOW [n HOP]] [WITH RECEIPT]] [LIMIT n [OFFSET m]] ``` - **Tables by name.** A database holds one or more [tables](#tables), and a query reads the tables it names (in any case): one, or several joined, read by subqueries or named in `WITH` ([below](#subqueries-with-and-joins)). - **Quoted names.** A table or column name in double quotes is the name inside them, so any name can be written: `"order"` (a word SQL reserves), `"doc no"`, `"say ""hi"""` (a quote doubled), and `FROM "papers"` reads papers. Python's [`table()`](python.md#queries-built-in-python) builds queries with no quoting at all. - **Strings** are single-quoted, `'sale'`. Where a value goes, a double-quoted `"sale"` is a string too, as SQLite and MySQL read it, and a bare name is an error rather than a string: `WHERE tag = sale` says `no such column: sale`. - **Clauses ChloeDB does not run are errors**, never ignored: `FETCH`, `FOR UPDATE`, `TOP`, `SELECT INTO`, `GROUP BY ... WITH ROLLUP` and the like. An error says where and why: the parser's give the line, the column and the token (`SQL syntax error at line 2, column 1 (near "FORM products"): ... found FORM (did you mean FROM?)`), and a misspelt column, table or function names the ones near it and what there is. - **Conditions the indexes cannot answer** test each row the others find: a function or arithmetic of a column (`lower(brand) = 'acme'`, `price * 2 > 100`, `CAST(price AS INT) = 5`), two columns compared (`price > rating`), `LIKE` with `%` or `_` inside the pattern, `ILIKE`, `IS NULL` of a field whose index does not keep it, a `CASE`, and a comparison of a `TEXT` field, by its stored text (`title LIKE '%tent%'`, `title = 'Tent 2'`). A field with a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) answers `LIKE` and `ILIKE` itself. The other conditions of the `WHERE` still narrow the scan by their indexes, so `year = 2020 AND title LIKE '%tent%'` reads the rows of 2020 only, and a `WHERE` of such conditions alone reads every row of the table. A field that is not stored (a generated `TEXT` field, an embedded vector) has no value to test. - **`SELECT` of no table**, `SELECT 1 + 1` or `SELECT now()`, gives one row of its values; its plan says it reads `one row of no table`. `SELECT *` of no table is an error, since there are no columns to give. - **`CAST(x AS type)`** (or `x::type`) makes an `INT` (rounded to the nearest whole number: a `FLOAT`'s value half to even, as PostgreSQL rounds a `double precision`, so `CAST(price AS INT)` of 2.5 is 2; a number written in the statement, or a value made of such numbers alone (`CASE WHEN qty > 0 THEN 2.5 END`), half away from zero, as PostgreSQL rounds a `numeric`, so `CAST(2.5 AS INT)` is 3), a `FLOAT`, `TEXT`, and of a value a `BOOL` (`'true'`, `'yes'`, `1`) or a `TIMESTAMP` (`CAST('2026-11-02' AS TIMESTAMP)`); text that is not a number is an error. - **`SELECT *`** returns every stored, non-vector column. - **`score()`** is the value of the `ORDER BY` score for each row (over a `WITH` result read without an `ORDER BY`, the score the `WITH` ranked its rows by); **`hops()`** is a row's distance in a graph traversal ([below](#graphs)); **`seq_no()`** is the sequence number of the write that last changed the row, in a database that numbers its writes, for [conditional writes](server.md#conditional-writes). It is a column of a query on one table, and cannot be aggregated or ordered by. A [ranking expression](#features-the-values-a-ranking-read) that scores each row by itself is a column too (`bm25(title, :q) AS t`), and **`features()`** stands for the inputs of the query's ranking. - **`ORDER BY`** takes one key, or several. The scan orders by the first and breaks its ties by a second that is the primary key (or, in a facet query, the group column); other keys sort the rows the `WHERE` keeps in memory, as over joined rows (`ORDER BY rating DESC, price`). Ranking by a score is always best first; a `KEYWORD` or stored `TEXT` column first sorts the rows by its text, `NULL` last either way, which the row evaluator does after reading every row the `WHERE` keeps; so does a function of a row's values without a score (`ORDER BY lower(brand)`, `ORDER BY date_trunc('day', at)`, `ORDER BY hash(id, 7)`); `ORDER BY distance(…) ASC` ranks by Euclidean distance, nearest first ([below](#similarityfield-vector-and-distancefield-vector)). `MAX k PER field` at its end keeps at most k rows of each value ([below](#at-most-k-rows-of-a-value-max-k-per)). A key may name a selected column by its alias, as in PostgreSQL: `SELECT id, bm25(name, :q) AS score FROM products ORDER BY score DESC` ranks by the `bm25` (an alias is read before a column of the same name). **Changed:** a scored alias was refused before (`no such column: score`). - **Parameters** are `:name` placeholders, bound from the API or from the shell's `--param name=value`. A vector parameter is a JSON array. - **Limits.** An expression nests at most 1,000 levels, counting parentheses and the operators of a chain such as `a OR b OR …` (SQLite has the same default); a long list of values belongs in `IN (…)`, which has no such limit. A `LIMIT` larger than the table returns every row that qualifies. A query ranked by a score without a `LIMIT` returns 100 rows, counted after its `OFFSET`, on one database and through a coordinator alike, and says so: its stats hold `implicit_limit: 100`, and `truncated: true` with a plan line (`no LIMIT: ...`) when more rows matched (`result.truncated` and `result.implicit_limit` in Python, `result.truncated` and `result.implicitLimit` in JavaScript). A `DELETE` is never cut by that default: `DELETE ... ORDER BY ` without a `LIMIT` is refused, since its order would only choose which rows a `LIMIT` keeps; write the match in `WHERE` (`DELETE FROM t WHERE MATCH(body, 'x')`) to delete every row that matches. (Before, it deleted the top 100.) - **Memory and time.** What a query builds up (its groups, `COUNT(DISTINCT)` and percentile values, the rows it orders before its `LIMIT` and the rows it returns, a graph walk's nodes, a compound query's parts and join tables) is counted against a memory budget as it grows, and a query that would go past it fails with a `memory:` error naming the budget, giving back what it held, instead of the process running out of memory. chloedb-server's queries share `--query-memory-mb` ([limits](server.md#limits)). A database opened in a program (Rust's `Db`, Python's `Database`, JavaScript's and Java's) counts its queries against one budget its whole process shares: a quarter of the machine's memory (the cgroup's limit, else RAM), or `CHLOEDB_QUERY_MEMORY_MB` MiB (`0`: none), read when the first database opens; a database or a query may be given a budget of its own (`memory` in [Python](python.md#limits-memory-deadlines-interrupting) and [JavaScript](javascript.md#limits-memory-deadlines-aborting), `ExecOptions::memory` in Rust). Such a database sets no deadline, no row window and no group cap of its own, unlike a server (`--timeout-ms`, `--max-result-window`, `--max-groups`), but for JavaScript's, which answers at most the server's 10,000 rows a query and reads past them by [cursors](javascript.md#reading-past-the-window-cursors), so that code tested on one runs on the other: a query given a deadline (`timeout_ms`), or cancelled from another thread (`interrupt()`, an `AbortSignal`, `ExecOptions::cancel`), stops within a few thousand rows of it, checking between segments and every 1,024 rows it groups, orders, walks or joins. ## Columns and types | type | indexed as | filters | |---|---|---| | `INT`, `FLOAT` (finite: no NaN or infinity) | frame-of-reference column with zone maps, range histogram | `=`, `!=`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IS [NOT] NULL` | | `KEYWORD` | dictionary codes and one docID list per value; with `substring = true`, a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) too | `=`, `!=`, `IN`, `NOT IN`, `IS [NOT] NULL`, [prefixes](#prefixes-and-autocomplete) (`LIKE 'p%'`, `PREFIX`), `<`, `<=`, `>`, `>=` and `BETWEEN` (a single-valued field); `GROUP BY`; with a substring index, any `LIKE` and `ILIKE` | | `BOOL` | an `INT` column of 1 and 0 | the field alone (`WHERE done`, `NOT done`), `=`, `!=`, `IS [NOT] TRUE`, `IS [NOT] FALSE`, `IS [NOT] NULL`; `GROUP BY` | | `TIMESTAMP` | an `INT` column of microseconds since 1970-01-01 UTC | as `INT`, with times written as text: `at >= '2026-10-01'` | | `TEXT` | inverted index (optionally with positions); may be generated from other text fields; with `substring = true`, a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) too | `MATCH`; with a substring index, `LIKE` and `ILIKE` | | `VECTOR(d)` | float32 rows plus 8-bit codes (or 1-bit codes, `"codes": "binary"`, or RaBitQ codes of 1, 2 or 4 bits, `"rabitq1"`, `"rabitq2"`, `"rabitq4"`), with HNSW, IVF or flat search; may be declared as a model's embedding of other fields ([embedded vector fields](server.md#embedded-vector-fields)) | ordering by `similarity` / `distance`; a similarity graph | | `VECTOR(d)[]` | several vectors per row (a page's patches, a song's frames): 1-bit codes searched, 8-bit codes to score (float32 too with `keep_f32`), and maps from rows to their vectors and back | ordering by `maxsim` | | `SPARSE` | inverted index of learned term weights (SPLADE and similar) | ordering by `similarity` | | `MEDIA` | a file by reference: URI, SHA-256, type, size; a `KEYWORD` index of the hashes | `=`, `IN` on the hash; `GROUP BY` | | `EDGES` | out-edge CSR and reverse index per segment | `REACHABLE`, `PATH`, `ppr` | | `JSON` | an object's keys no schema names: one sorted dictionary of `path, type, value` terms with a docID list each ([JSON fields](#json-fields-keys-no-schema-names)) | on paths (`attrs.color`): `=`, `!=`, `<`, `<=`, `>`, `>=`, `BETWEEN`, `IN`, `NOT IN`, `LIKE 'p%'`, `PREFIX`, `IS [NOT] NULL`, `IS TRUE`, the path alone | Predicates combine with `AND`, `OR`, `NOT`, [`AT_LEAST`](#some-of-the-conditions-at_least) and parentheses, across all of these, and [`max_rows`](#as-many-as-fit-min_rows-and-max_rows) lets an `AT_LEAST` choose its count. A `KEYWORD` compares with text: `k = 1` is an error that points to `k = '1'`, as `n = '2'` is on an `INT` (a write still stores the number 1 in a `KEYWORD` as `'1'`). `INT` values are 64-bit integers and compare exactly: `id = 9007199254740993` finds that row and not 9007199254740992, which a double cannot tell apart. Arithmetic of `INT`s (`+`, `-`, `*`, `%`) is exact while its result fits in 64 bits; a result that does not is a `FLOAT`, not an error (`n * 9223372036854775807` of an `n` of 3 is `2.7670116110564327e19`), `/` always gives a `FLOAT`, and dividing by 0 (with `/` or `%`) gives `NULL`. A client that reads such a column as integers gets a float where a result overflowed. A fraction bounds integers by rounding inward (`n > 2.5` is `n >= 3`, `n = 2.5` matches nothing). A write gives an `INT` a float with no fraction as its whole number (`2.0` is 2, as pandas writes whole numbers in a column with gaps), from SQL, JSON and CSV alike, and refuses `2.5`. `NULL` follows SQL's three-valued logic. A comparison with a missing value is neither true nor false, and so is its negation: `rating != 2` and `NOT rating > 2` leave out the rows without a rating. Ask for them with `rating IS NULL` (`IS NOT NULL` for the others). So does a comparison no value can meet, such as `passengers != 1.5` on an `INT` field. `MATCH` and graph predicates are always true or false, so `NOT MATCH(body, 'x')` includes rows without a body. A filter on a multi-valued field holds when some value matches, and its negation when none does, so `tags != 'red'` includes rows without tags (`tags IS NULL` finds those). `rating = NULL` is an error that points to `IS NULL`. `rating IN (1, NULL)` is TRUE where the rating is 1 and UNKNOWN elsewhere, so `rating NOT IN (1, NULL)`, like `NOT IN` a subquery that returns a `NULL`, keeps no row; a multi-valued field's `IN` is TRUE or FALSE (the `NULL` matches none of its values). `LIKE '%'` and `PREFIX(f, '')` hold for every row with a value and are UNKNOWN for the others, so their `NOT` keeps no row of a single-valued field. A scalar subquery that finds no row is `NULL`, and a comparison with it keeps no row either way. A `BOOL` is `TRUE` or `FALSE`; a write also takes 1 and 0 and the text `'true'`, `'false'`, `'t'`, `'f'`, `'1'` and `'0'`, and refuses anything else. A field named alone is a condition (`WHERE done AND NOT archived`), with `NULL` neither true nor false: `NOT done` and `done != TRUE` leave out the rows without a value, `done IS NOT TRUE` takes them in. `SUM(done)` counts the trues, and answers come back as booleans. A `TIMESTAMP` is a moment, kept to the microsecond in UTC and written as ISO 8601 text: a date (`'2026-10-01'`, midnight UTC) or a date and time (`'2026-10-01T12:30:00Z'`, `'2026-10-01 14:30:05.25+02:00'`), with an offset or none (UTC). A number is refused, so seconds are not mistaken for microseconds. Comparisons, `BETWEEN`, `IN`, `ORDER BY`, `MIN`, `MAX` and `COUNT` work on it (`SUM` and `AVG` do not), and answers are ISO 8601 text in UTC, such as `2026-10-01T12:30:05.250Z`. In `decay(at, origin, scale)` on a `TIMESTAMP`, the origin is a time or `now()`, and the scale and offset are seconds: `decay(published, now(), 2592000)` halves a row's weight for each 30 days of age. `date_trunc`, `EXTRACT` and `strftime` take [parts of times](#parts-of-times-date_trunc-extract-and-strftime), for `GROUP BY` a day, a week or a month, and [intervals](#times-later-and-earlier-interval) move a time (`now() - INTERVAL '15 minutes'`). A `DATE` column is a `TIMESTAMP`: a date written alone is its midnight UTC, and a time given is kept. A database whose tables use `BOOL` or `TIMESTAMP` is written in [file format 3](index.md#wal-memtable-and-snapshots), which versions of ChloeDB before these types refuse. `KEYWORD` and `INT` fields may be multi-valued (`"multi": true` in the schema): a row holds a list, such as `ARRAY['red', 'blue']`, and a filter matches a row if any of its values matches. A facet counts each distinct value once per row. A multi-valued field also compares with a list of values as a set, by PostgreSQL's array operators. The list is `ARRAY[...]` of values or a list parameter (`:groups`), and its values are written as the field's are: | condition | holds where | read from the index as | |---|---|---| | `tags @> ARRAY['red', 'sale']` | the row has every value of the list (contains all) | an `AND` of equalities; every row for an empty list | | `tags && ARRAY['red', 'sale']` | the row has a value of the list (overlaps) | `IN` the values; no row for an empty list | | `groups <@ :allowed` | each value of the row is in the list (contained by), on an `INT[]` field | `NOT` of the ranges between the list's values | The list may come first: `ARRAY['red'] <@ tags` is `tags @> ARRAY['red']`. A row without values is the empty set, so `@>` an empty list and `<@` any list hold for it, and `NOT` of a set operator holds where the set operator does not, as for other conditions on a multi-valued field. `<@` is how a row lists what it needs and a query what it has: with `required INT[]` holding the groups a reader must belong to, `WHERE required <@ :user_groups` keeps the documents whose every required group is one of the user's (and those that require none), and it filters a vector or text search as any condition does. A `KEYWORD[]` field does not take `<@` yet, since its index cannot list the values outside a list; an `INT[]` of ids does. Over rows in memory (a `WITH` result), `&&` compares any two lists, and `@>` a list column with a list written out. A `KEYWORD[]` field may hold the [semantic ID](server.md#semantic-ids) of a vector field: every prefix of a code such as `12.7.201.0`, filled in by the writer, so `sid = '12.7'` finds the rows under a prefix. `sid_at(sid, n)` is the first `n` numbers of a code (`sid_at(sid, 2)` is `'12.7'`), in `SELECT`, `WHERE` and `GROUP BY`. A `SPARSE` value is a JSON object of terms and non-negative weights, `{"tok": 1.25, "##en": 0.4}`, as a learned sparse model (SPLADE, BGE-M3's sparse output, OpenSearch's neural sparse models) writes it. Terms are taken as given, not analysed, and weights are stored in steps of 1/1024. A `MEDIA` value names a file, `{"uri": "https://cdn.example.com/a.png", "sha256": "…", "mime": "image/png", "bytes": 48213, "width": 640, "height": 480}`, and a write may give only its URI, `'https://cdn.example.com/a.png'`, or its bytes, `'{"data": ""}'`, for the server to fill in ([media fields](server.md#media-fields)). Its index holds the hash: `image = '9f86d0…'` finds the rows of that file. `OPTIONS(kind = 'image')` takes only images (`'audio'`, `'video'`, `'pdf'`), whose vectors a `VECTOR` field can hold: `emb VECTOR OPTIONS(embed = 'image', model = 'siglip-base-patch16-224')` ([vectors of images](server.md#vectors-of-images)), `sound_emb VECTOR OPTIONS(embed = 'recording', model = 'clap-htsat-unfused')` ([vectors of sound](server.md#vectors-of-sound)), and whose captions or transcripts a `TEXT` field can: `caption TEXT OPTIONS(derive = 'image', model = 'blip-image-captioning-base')`, `transcript TEXT OPTIONS(derive = 'recording', model = 'whisper-small')` ([text from media](server.md#text-from-media)). A language model can make a `TEXT` field of another's text, told what by a prompt: `product TEXT OPTIONS(derive = 'body', model = 'anthropic/claude-haiku-5-5', prompt = 'Name the product this review is about.')` ([text from text](server.md#text-from-text)). ### Parts of times: `date_trunc`, `EXTRACT` and `strftime` ```sql SELECT date_trunc('day', at) AS day, COUNT(*), AVG(price), MIN(price) FROM snapshots GROUP BY day ORDER BY day; SELECT EXTRACT(dow FROM at) AS dow, AVG(price) FROM snapshots WHERE item = 'i42' GROUP BY dow; SELECT strftime('%Y-%m', at) AS month, SUM(price) FROM sales GROUP BY month; SELECT date_bin('5 minutes', ts) AS b, severity, COUNT(*) FROM logs WHERE ts >= '2026-11-12' GROUP BY b, severity; -- A moving average of daily prices: groups by day in a WITH, a window over them. WITH daily AS (SELECT item, date_trunc('day', at) AS day, AVG(price) AS px FROM snapshots GROUP BY item, day) SELECT item, day, px, AVG(px) OVER (PARTITION BY item ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS ma7 FROM daily; ``` - **`date_trunc(unit, t)`** is the time cut to the start of its `second`, `minute`, `hour`, `day`, `week` (from Monday, as ISO 8601 and PostgreSQL count weeks), `month`, `quarter` or `year`, a `TIMESTAMP`. The unit is text in any case, and a plural (`'days'`) is taken too. - **`date_bin(width, t [, origin])`** is the start of the bucket of a fixed `width` that the time is in, a `TIMESTAMP`, as PostgreSQL's `date_bin`: buckets are counted from `origin` (a `TIMESTAMP` or ISO 8601 text; 1970-01-01 without one), so `date_bin('15 minutes', at, '2026-01-01T00:05:00Z')` starts buckets at :05, :20, :35 and :50. The width is a whole number and a unit: `microseconds` (`us`), `milliseconds` (`ms`), `seconds` (`s`), `minutes` (`m`), `hours` (`h`), `days` (`d`) or `weeks` (`w`), singular or plural, as `'5 minutes'`, `'30s'` or `'1 day'`; months and years are not a fixed width, and are `date_trunc`'s. `date_bin('1 day', t)` is `date_trunc('day', t)`. OpenSearch's `date_histogram` with a `fixed_interval` runs as one. - **`date_part(part, t)`**, and **`EXTRACT(part FROM t)`** which is the same function, is a number: `year`, `isoyear`, `quarter` (1 to 4), `month` (1 to 12), `week` (the ISO week, 1 to 53), `day` (of the month), `doy` (of the year, 1 to 366), `dow` (0 for Sunday to 6 for Saturday, as PostgreSQL counts), `isodow` (1 for Monday to 7 for Sunday), `hour`, `minute`, and as a `FLOAT`, `second` (with its fraction) and `epoch` (seconds since 1970). - **`time_bucket(width, t)`** is another name for `date_bin(width, t)`, as TimescaleDB spells it: `time_bucket('5 minutes', ts)` gives 03:00, 03:05, 03:10. The width can also be an `INTERVAL '5 minutes'`. - **`date_diff(unit, start, end)`** (and `datediff`) is an `INT`, how many boundaries of the unit there are from `start` to `end`, negative when `end` is earlier: `microsecond`, `millisecond`, `second`, `minute`, `hour`, `day`, `week` (from Monday), `month`, `quarter` or `year`, singular or plural. It counts as DuckDB's and Snowflake's `date_diff` do, by the two times cut to the unit, so `date_diff('month', '2026-01-31', '2026-02-01')` is 1 and `date_diff('day', '2026-01-01 23:00', '2026-01-02 01:00')` is 1; PostgreSQL has no `date_diff`, and its `end - start` is an `INTERVAL`, which ChloeDB does not have. For the whole days or seconds between two times, `date_diff('day', a, b)` or `date_diff('second', a, b)`. - **`strftime(format, t)`** is text, written as SQLite's `strftime` writes it: `%Y` year, `%m` month 01-12, `%d` day 01-31, `%H` hour 00-23, `%M` minute, `%S` second, `%f` seconds with milliseconds (`SS.SSS`), `%j` day of the year 001-366, `%w` day of the week 0-6 from Sunday, `%u` 1-7 from Monday, `%W` week of the year 00-53 from the first Monday, `%V` the ISO week 01-53 and `%G` its year, `%s` seconds since 1970, `%F` for `%Y-%m-%d`, `%T` for `%H:%M:%S`, and `%%` for a `%`. - **A day.** `CAST(t AS DATE)`, `DATE(t)` and `date_trunc('day', t)` are the same, the start of the time's day; ChloeDB keeps it a `TIMESTAMP` (there is no separate `DATE` type). **`CURRENT_DATE`** is the start of today, `date_trunc('day', now())`, so `WHERE at >= CURRENT_DATE - INTERVAL '7 days'` keeps the last seven days and today, and `GROUP BY CAST(at AS DATE)` counts by day. They all read times in UTC. A `NULL` time gives `NULL`, text is read as a time (`date_trunc('month', '2026-11-05')`), and any other value is an error, as are a unit, part or directive they do not have (the message lists the ones they do). A **`GROUP BY` of one of them over a `TIMESTAMP` field of the table** (indexed, one value per row) runs in the executor, as a `GROUP BY` of a column does: it reads the field's column, has no limit on the number of rows, and over shards each shard groups its own rows and the coordinator merges the groups. The rows without a time form the group `NULL`. Anywhere else, in `SELECT`, `WHERE` and over joined or derived rows, they are computed row by row; in `WHERE` they are a [condition the indexes cannot answer](#statement-shape), so a range of times is faster written on the field (`at >= '2026-11-01' AND at < '2026-12-01'`) than as `EXTRACT(month FROM at) = 11`. A plan that uses them needs the plan feature `dates`, which shards of a version without these functions refuse, and one with `date_bin` also needs the plan feature `date_bin`, one with `date_diff` the plan feature `sql_functions`. ### Text and numbers: `substr`, `trim`, `replace`, `concat`, `nullif`, `floor` and `ceil` ```sql SELECT substr(sku, 1, 3) AS family, COUNT(*) FROM products GROUP BY family; SELECT id, trim(name), replace(phone, '-', ''), concat(first, ' ', last) FROM customers; SELECT SUM(total) / nullif(COUNT(*), 0) FROM invoices; -- NULL, not an error, for no rows SELECT floor(price / 10) * 10 AS band, COUNT(*) FROM products GROUP BY band ORDER BY band; ``` They answer as PostgreSQL's do: - **`substr(s, start [, count])`**, **`substring(s, start [, count])`** and **`SUBSTRING(s FROM start [FOR count])`** are the characters of `s` from the `start`-th on (the first is 1), at most `count` of them. A `start` before the first character takes as many fewer (`substr('hello', 0, 2)` is `'h'`), one past the end gives `''`, and a negative `count` is an error. They count characters, not bytes. - **`trim(s)`**, **`ltrim(s)`** and **`rtrim(s)`** take the spaces off both ends, the start or the end; with a second argument, the characters it holds instead: `btrim('xxaxx', 'x')` is `'a'`, `ltrim(body, 'fs')` takes any `f` and `s` off the start. **`TRIM([BOTH | LEADING | TRAILING] [chars FROM] s)`** is the same, as SQL writes it. Only spaces, not tabs or line breaks, are taken without a second argument, as in PostgreSQL. - **`replace(s, from, to)`** replaces every `from` in `s` by `to`; an empty `from` replaces nothing. - **`concat(a, b, …)`** is its arguments as text, one after the other, leaving out the `NULL`s, so it is `''` when all are `NULL`; `a || b` is `NULL` when either is. A number or a time is written as `||` writes it. - **`nullif(a, b)`** is `NULL` where `a = b`, and `a` elsewhere (`CASE WHEN a = b THEN NULL ELSE a END`). - **`floor(x)`** and **`ceil(x)`** (`ceiling`) are the whole numbers below and above `x`, `INT`s as `round(x)` is: `floor(2.7)` is 2, `ceil(-2.5)` is -2. A whole number beyond an `INT`'s range is an error. Text functions take text: a number is an error (`substr(CAST(n AS TEXT), 1, 2)` takes its digits). Any `NULL` argument gives `NULL`, except in `concat`. Over one table they are computed row by row, in `SELECT`, `WHERE`, `GROUP BY` and `ORDER BY`, as over joined and derived rows, and in a `WHERE` they are a [condition the indexes cannot answer](#statement-shape) (`substr(sku, 1, 3) = 'ABC'` reads every row the other conditions keep; `sku LIKE 'ABC%'` reads the index). A plan with `substr`, `trim`, `ltrim`, `rtrim`, `replace`, `floor`, `ceil` or `date_diff` needs the plan feature `sql_functions`, which shards of a version without these functions refuse; `concat` and `nullif` are written with `||`, `coalesce` and `CASE`, which every version reads. ### Samples, splits and shuffles: `hash` ```sql -- about a tenth of the rows, the same tenth every time SELECT * FROM events WHERE hash(id, 7) % 10 = 0; -- a train/test split, 80/20: every row in one part SELECT * FROM events WHERE hash(id, 7) % 10 < 8; -- train SELECT * FROM events WHERE hash(id, 7) % 10 >= 8; -- test -- the same thousand rows in the same random order SELECT * FROM events ORDER BY hash(id, 7) LIMIT 1000; -- the rows a search finds, in a random order of their own SELECT * FROM events ORDER BY bm25(body, :q) * 0 + hash(id, 7) DESC LIMIT 10; ``` **`hash(x [, seed])`** is an `INT` from 0 to 263 - 1 that only `x` and `seed` (an `INT`, 0 without one) decide: the same on every machine, in every version of ChloeDB, and on a file and over shards, so a sample or a split made with it is the same rows wherever and whenever it runs. Another seed gives another sample. A `NULL` value or seed gives `NULL`, so a row whose `x` is `NULL` is in no part; hash a column every row holds, such as the key. `x` is one value: text, a number, a `BOOL` or a `TIMESTAMP` (a list is an error). To hash several columns, chain them through the seed: `hash(item, hash(user, 7))`. It is the 64-bit FNV-1a of the seed's 8 bytes (little-endian) and then the value's, through SplitMix64's finalizer, shifted right by one. A text's bytes are its UTF-8; an `INT`, a `BOOL` (1 or 0) and a `TIMESTAMP` (microseconds since 1970) are their integer's 8 bytes, little-endian; a `FLOAT` is its IEEE 754 bits, little-endian (-0 as 0). So it is the same value elsewhere, in Python for instance: ```python def chloedb_hash(data: bytes, seed: int = 0) -> int: # data: "u42".encode(), (42).to_bytes(8, "little", signed=True) m, h = (1 << 64) - 1, 0xcbf29ce484222325 for b in seed.to_bytes(8, "little", signed=True) + data: h = ((h ^ b) * 0x100000001b3) & m h = ((h ^ (h >> 30)) * 0xbf58476d1ce4e5b9) & m h = ((h ^ (h >> 27)) * 0x94d049bb133111eb) & m return (h ^ (h >> 31)) >> 1 ``` In `WHERE`, `hash` is a [condition the indexes cannot answer](#statement-shape): the other conditions narrow the rows by their indexes, and those rows are hashed one by one. `ORDER BY hash(id, 7)` sorts the rows by it, as `ORDER BY lower(name)` or a part of a time sorts them: the rows the table's query finds, in memory. In a [ranking expression](#ranking-expressions) with a score, `hash(field, seed)` of the key or a stored field is the same number, a value of each row the score finds: `bm25(body, :q) * 0 + hash(id, 7)` shows what a search finds in a seeded random order (an arm of an experiment that shuffles its results, or a sample of a search's rows), and a small share of it breaks ties at random. `rrf` does not fuse it. A plan that uses it needs the plan feature `hash`, which shards of a version without the function refuse, and a shard of a version from before it in rankings refuses it there. A [frame](frames.md) samples and splits with it: `frame.sample(fraction=0.1, seed=7)`, `train, test = frame.split(0.8, seed=7)`. ### Places on the Earth: trigonometry, `haversine`, H3 cells and shapes ```sql -- The 10 fires nearest a point, in kilometres. SELECT id, haversine(lat, lon, 37.7749, -122.4194) AS km FROM fires ORDER BY km LIMIT 10; -- A count per H3 cell of resolution 4 (about 1,770 km² each), with each cell's outline to draw. SELECT h3_cell_to_boundary(h3_latlng_to_cell(lat, lon, 4)) AS cell, COUNT(*) FROM fires GROUP BY cell; -- The fires inside a shape given as WKT or GeoJSON, and those within 20 km of a point. SELECT id FROM fires WHERE st_contains(:perimeter, st_point(lon, lat)); SELECT id FROM fires WHERE st_dwithin(st_point(lon, lat), 'POINT(-122.42 37.77)', 20000); ``` ChloeDB has no geometry type: a place is two `FLOAT` columns, or a shape kept as `TEXT`, and these functions compute with them row by row. - **`sin`, `cos`, `tan`, `cot`, `asin`, `acos`, `atan` and `atan2(y, x)`** are in radians, and **`radians(x)`**, **`degrees(x)`** and **`pi()`** convert, as PostgreSQL's do. `asin` and `acos` of a number beyond -1 to 1 are `NULL` (PostgreSQL's are an error). - **`haversine(lat1, lon1, lat2, lon2)`** is the great-circle distance between two points given in degrees, latitude first, in kilometres on a sphere of radius 6,371 km, as Snowflake's `HAVERSINE` is to the last digit. Over the Earth's real shape it is within about 0.5% of the truth. - **The H3 functions** are those of [H3](https://h3geo.org) version 4, the hexagonal grid of the Earth, with Snowflake's names. A cell is an `INT` or its hex text (`'8928308280fffff'`); a resolution is 0 (cells of about 4.4 million km²) to 15 (about 1 m²). - `h3_latlng_to_cell(lat, lon, resolution)` is the cell holding a point, an `INT`, and `h3_latlng_to_cell_string` the same as text. - `h3_cell_to_parent(cell, resolution)` is the coarser cell holding it, of the kind its argument is. - `h3_get_resolution(cell)` is its resolution, and `h3_grid_distance(a, b)` how many steps from cell to cell there are between two cells of one resolution (`NULL` where H3 cannot tell, as across a pentagon). - `h3_cell_to_point(cell)` is its center and `h3_cell_to_boundary(cell)` its outline, as WKT. - `h3_int_to_string(cell)` and `h3_string_to_int(cell)` convert, and `h3_is_valid_cell(x)` says whether `x` is a cell. - **Shapes** are `TEXT` in WKT (`POINT(-122.42 37.77)`, `LINESTRING`, `POLYGON` with holes, the `MULTI` kinds, `GEOMETRYCOLLECTION`, an `SRID=4326;` before it, Z and M values ignored) or GeoJSON (a geometry, a `Feature` or a `FeatureCollection`), with longitude before latitude in degrees (WGS 84), as PostGIS and GeoJSON write them. - `st_point(lon, lat)` is a point as WKT, and `st_x(p)` and `st_y(p)` its longitude and latitude. - `st_contains(a, b)` is whether `b` is inside `a` (a point on the outline is not, as in PostGIS), `st_within(a, b)` is `st_contains(b, a)`, and `st_intersects(a, b)` whether they meet at all, outlines included. - `st_distance(a, b)` is the shortest distance between them in metres, 0 when they meet, and `st_dwithin(a, b, metres)` is `st_distance(a, b) <= metres`. - `st_area(s)` is a shape's area in square metres. - `st_astext(s)` and `st_asgeojson(s)` write a shape as WKT or GeoJSON. Whether shapes contain or meet each other is decided with their edges straight on a flat map of longitude and latitude, as GeoJSON and PostGIS's `geometry` draw them; a shape across longitude 180 is written as two, split there, as GeoJSON asks. Distances and areas are on a sphere of the Earth's mean radius, 6,371,008.8 m, as BigQuery's and Turf's are; PostGIS's `geography` measures on the ellipsoid, within about 0.5%. Any `NULL` argument gives `NULL`. A text that is not a shape, a cell that is not one and a resolution beyond 0 to 15 are errors that say which. Over one table they are computed row by row, in `SELECT`, `WHERE`, `GROUP BY` and `ORDER BY` (`ORDER BY haversine(…)` is nearest first, and `DESC` farthest), as over joined and derived rows. In a `WHERE` they are a [condition the indexes cannot answer](#statement-shape): give the rows a range of `lat` and `lon` as well (`lat BETWEEN 37 AND 38 AND lon BETWEEN -123 AND -122`) and only the rows in the box are tested. A long shape written out in a query (a perimeter of thousands of vertices) is read once and kept while queries use it, not once per row. A join needs an equality, so to join points to the shapes they fall in, join on a coarse key both have (a region, or an H3 cell the shapes are listed under) and test `st_contains` in the `WHERE`. In a [ranking expression](#ranking-expressions), the trigonometric functions and `haversine` of numeric columns are values of each row the score finds: `bm25(body, :q) / (1 + haversine(lat, lon, :lat, :lon))` ranks a search by its relevance and nearness. A plan that uses any of them but `radians`, `degrees` and `pi` needs the plan feature `geo`, which shards of a version without these functions refuse. ### JSON fields: keys no schema names A `JSON` field holds an object whose keys are not declared, for attributes that only a few rows have and that nobody knew when the table was made: a product's `voltage`, `certs` or `dims.w`. A row adds keys by holding them, and filters on any key run from the field's index: ```sql CREATE TABLE products (id KEYWORD PRIMARY KEY, title TEXT, attrs JSON); INSERT INTO products (id, title, attrs) VALUES ('p1', 'charger', '{"voltage": 5, "certs": ["CE", "UL"], "dims": {"w": 40.5}}'), ('p2', 'lamp', '{"color": "black", "a.b": true}'); SELECT id FROM products WHERE attrs.voltage >= 5 AND attrs.certs = 'UL'; SELECT id, attrs.dims.w FROM products WHERE attrs.color IN ('black', 'red') ORDER BY attrs.dims.w DESC; SELECT attrs.color, COUNT(*) FROM products GROUP BY attrs.color; ``` - **Paths.** `attrs.dims.w` is the key `w` of the object at `dims`; `attrs['a.b']` names a key that holds a dot, and `json_extract(attrs, 'dims.w')` is the same path as a function, `'$.dims.w'` too, as SQLite and DuckDB write it, in `SELECT`, `ORDER BY` and `GROUP BY` as in `WHERE` (`'$'` is the whole value). **Changed:** 0.3.8 and earlier read a `'$.'` path as `NULL` outside `WHERE`. In a join, qualify the field: `p.attrs.color`. An array holds its elements at its own path, as a multi-valued field does: `attrs.certs = 'UL'` matches `["CE", "UL"]`, and `{"items": [{"sku": "x"}, {"sku": "y"}]}` holds `x` and `y` at `items.sku`. JSON `null` and an empty array are no value. - **Types.** A comparison sees the values of its literal's type only, as if the path were a column of that type: `attrs.voltage > 5` reads the numbers at `voltage` (integers and doubles alike), `attrs.voltage = 'n/a'` its strings, `attrs.ok` and `attrs.ok = TRUE` its booleans. A row with no value of that type there is `NULL` to the comparison, so `NOT (attrs.voltage > 5)` and `attrs.voltage != 5` leave out rows whose voltage is missing or a string, and `IS NULL` finds rows without the path at all. An `IN` list of several types reads each type for its own values. No row is refused for holding a type other rows do not. - **Reads.** `SELECT attrs` returns the object as compact JSON text with sorted keys. A path in `SELECT`, `ORDER BY`, `GROUP BY` or an aggregate returns its value, in a column named as the query writes the path (`attrs.dims.w`): a string, an integer, a double or a boolean; a list for an array of values or for several values through an array; an object as its JSON text; `NULL` where the row has none (an empty array included). A list makes a group per value, as a multi-valued column does, and a boolean is a group apart from the number 1. - **Groups, aggregates and sorts read the index.** `GROUP BY attrs.color`, `AVG(attrs.price)` and `ORDER BY attrs.price` read each row's value from the field's terms, as a declared column's are read, so they take no row's object: a path's counts come from its terms' docID lists, as a facet's do. A row holds one value term per path; where that term is not the whole of the value (an object, an array, a string longer than 256 bytes, a number such as `5.0` or 2^53 + 1 that its term would give as another), the index marks the row, and those rows alone are read from their objects. On a million rows with 1,000 sparse keys (a 4-core cloud VM, [`chloedb/results/json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/json)), `GROUP BY` the most held key takes 2.7 ms, against 2.4 ms for a declared column and 1.9 s when each row's object was read, and `AVG` of a number key held by 82,000 rows 22 ms, against 14 ms and 552 ms. Selecting a path reads it from the objects of the rows returned. A query that mixes paths with what the executor does not run itself (a join, a function of a path, `GROUP BY lower(attrs.color)`) reads them from the rows' objects instead, in memory (up to a million rows), as over [joined rows](#subqueries-with-and-joins); the answer is the same either way. - **Writes.** A value is a JSON object, given as text (`'{"k": 1}'`), as an object in JSON Lines or the HTTP API, or as a dict from Python; `NULL` is no object. A write is refused, naming the limit, for anything else, for an empty key, and for an object nested more than 16 levels, with a path longer than 256 bytes or with more than 1,000 values and objects. A string longer than 256 bytes is kept and returned, and `IS NOT NULL` sees it, but comparisons do not: its value is not indexed (its words are, with [text](#json-fields-keys-no-schema-names)). - **Text.** `attrs JSON OPTIONS(text = true)` also indexes the strings of each row's object as text, one a line in path order, long ones included, so `MATCH(attrs, 'charger NOT lamp')` finds rows by the words of any of their strings and `bm25(attrs, 'usb charger')` ranks them as it ranks a `TEXT` field holding the same lines (with a cluster's statistics through a coordinator). Keys, numbers and booleans are not text: a path reads them. The option takes an `analyzer` (`'english'`, the default, or another a `TEXT` field takes), and the text has positions, so a phrase may span two strings that follow each other. A database with such a field needs the feature `json_text` besides `json`. - **The index** is one sorted dictionary per segment of terms `path \0 type value` (strings as UTF-8, numbers in an order-preserving encoding of doubles), so `=` and `IN` read one term's docID list, a range or `LIKE 'p%'` one run of terms, and `IS NOT NULL` the path's own term. A row pays only for the paths it holds, which is what keeps thousands of sparse keys cheap where as many declared columns would each take a slot in every row. A `JSON` field is stored; it cannot be the primary key, multi-valued, have a default, or be generated or the source of a generated or embedded field. A database with a `JSON` field is written in [file format 3](index.md#wal-memtable-and-snapshots) with the feature `json`, and plans that read paths carry the plan feature `json`, and `json_columns` when a Search groups, aggregates, orders or selects by them, which a version of ChloeDB from before it refuses by name. A segment written before marks (its section `json..marks` missing) reads every row holding the path from its object, until a merge rewrites it. #### Which paths a field holds: `json_paths` Nobody declared the keys, so the table says what they are. `json_paths` lists every path a `JSON` field's objects hold, with how many rows hold each, the types of its values and what they are, read from the field's index (its terms and their docID lists) without reading a row: ```sql SELECT * FROM json_paths('products', 'attrs'); SELECT * FROM json_paths('products', 'attrs', 'dims'); -- dims and the paths below it SELECT * FROM json_paths('products', 'attrs', filter => 'MATCH(title, ''charger'')'); ``` For the two rows above, the first gives: | path | rows | share | strings | numbers | bools | min | max | distinct | values | |---|---|---|---|---|---|---|---|---|---| | `a\.b` | 1 | 0.5 | 0 | 0 | 1 | | | 1 | `[[true,1]]` | | `certs` | 1 | 0.5 | 1 | 0 | 0 | | | 2 | `[["CE",1],["UL",1]]` | | `color` | 1 | 0.5 | 1 | 0 | 0 | | | 1 | `[["black",1]]` | | `dims` | 1 | 0.5 | 0 | 0 | 0 | | | 0 | `[]` | | `dims.w` | 1 | 0.5 | 0 | 1 | 0 | 40.5 | 40.5 | 1 | `[[40.5,1]]` | | `voltage` | 1 | 0.5 | 0 | 1 | 0 | 5.0 | 5.0 | 1 | `[[5,1]]` | - **A row per path**, in path order, a key's dot escaped (`a\.b`). `rows` counts the rows that hold the path at all (an object there counts), `share` is their share of the rows read, and `strings`, `numbers` and `bools` count the rows holding a value of each type, so a path whose rows disagree on its type says so. `min` and `max` are its numbers' range; `distinct` counts its values, and `values` lists them as JSON with their rows, most first, when there are at most 100 (past that both are `NULL`). - **The third argument** narrows the listing to a path and the paths below it (`'dims'`, `'$.dims'`, `'a\.b'`). **`filter =>`** counts only the rows a condition keeps, any condition a `WHERE` could hold: `json_paths('products', 'attrs', filter => 'attrs.color IS NOT NULL')` tells which other keys the rows with a color have. - **The listing is read whole**: `SELECT *` and nothing else, at most 10,000 paths (past that, the first 10,000 in order). A string longer than 256 bytes is not indexed, so it counts at its path in `rows` but in no type. Rows deleted or updated count as they are now. - **Over HTTP**, `GET /v1/tables/T/paths?field=attrs&path=dims&where=...` gives the same as JSON, each path with its `keys`, and a [coordinator](server.md#sharding-one-coordinator-many-shards) sums its shards' listings, so the counts are the cluster's. The [command center](server.md#the-ui) draws the listing as a tree in **Schema**, completes `attrs.` in the workbench with the keys at each level, and lists the paths in the query builder as fields to filter, group, measure and sort by. ## Some of the conditions: `AT_LEAST` `AT_LEAST(n, c1, c2, …)` holds where at least `n` of the conditions do. A condition is anything `WHERE` takes: a comparison, `IN`, `IS NULL`, `MATCH`, a graph predicate, a subquery condition, a group in parentheses, another `AT_LEAST`. ```sql -- two of three signals, ranked by the text SELECT id, title FROM papers WHERE AT_LEAST(2, MATCH(title, 'covid'), year >= 2020, venue IN ('nejm', 'lancet')) ORDER BY bm25(body, :q) DESC LIMIT 20; -- rows meeting more of the conditions rank higher SELECT id FROM papers ORDER BY bm25(body, :q) * (1 + 0.1 * count_true(year >= 2021, venue IN ('nejm', 'lancet', 'jama'))) DESC LIMIT 20; ``` - **`n`** is a count, a percentage of the conditions (`'75%'`, rounded down) or a parameter (`:n`), 1 or more (`0` and `'0%'` are errors: none of the conditions is no condition). Either is clamped to between 1 and the number of conditions, as [`MATCH`'s groups](#full-text-match) are: `AT_LEAST(1, …)` is the `OR` of the conditions, and a count past the end is their `AND`. - **`NULL`.** A condition that is UNKNOWN (a comparison with a `NULL`) is not met. Under `NOT`, `AT_LEAST` follows SQL's three-valued logic: `NOT AT_LEAST(n, …)` holds where fewer than `n` conditions would be TRUE even if every UNKNOWN one were, so it never returns a row whose answer depends on a `NULL`. With `a = 1` and `c` `NULL`, `AT_LEAST(2, a > 0, c = 'x')` leaves the row out, and so does `NOT AT_LEAST(2, a > 0, c = 'x')`. - **`count_true(c1, c2, …)`** is how many of the conditions hold, a number for [ranking expressions](#ranking-expressions) and `SELECT`, exactly the sum of `CASE WHEN c THEN 1 ELSE 0 END` over them: a condition on a `NULL` counts 0. In a `SELECT` over rows in memory (a join, a `WITH` result) its conditions cannot use `MATCH` or graph predicates, which only a table's indexes answer. - **How it runs.** Each condition becomes the set of rows it holds for, as `WHERE` evaluates it, and a counter adds the sets up 64 rows to a machine word, in ⌈log2(y + 1)⌉ words for each 64 rows; sets with few rows are merged instead. A ranking that checks its candidates one at a time tests their conditions in turn, until the count is reached or out of reach. The cost grows with the number of conditions, not with `n`: over 1,000,000 rows where each condition holds for an independent 20% of them, counting the rows took 3.0 ms for 2 of 4 conditions, 4.1 ms for 4 of 8 and 9.3 ms for 8 of 16, against 0.37 ms for one condition. The same conditions written as an `OR` of every `AND` of `n` took 8.2 ms for 2 of 4 (6 `AND`s) and 114 ms for 4 of 8 (70), and 8 of 16 would need 12,870 (`chloedb-at-least-bench` on a 4-core cloud VM, Intel Xeon @ 2.10GHz, `chloedb/results/strata/at_least.json`). - A plan with `AT_LEAST` or `count_true` needs the plan feature `at_least`. From Python, [`at_least(2, match("title", "covid"), col("year") >= 2020)`](python.md#queries-built-in-python) and `count_true(…)` build them. ## As many as fit: `min_rows` and `max_rows` An "x of y" condition can choose its own x. With `max_rows` or `min_rows`, an `AT_LEAST`, a `MATCH(…, min => n)` or a `bm25(…, min => n)` asks for all y of its items first, and relaxes towards `n` while the rows are too few, stopping before a level that would match more than `max_rows`: ```sql -- as many of the signals as keep the candidates to 2,000 or fewer SELECT id, title FROM papers WHERE year >= 2015 AND AT_LEAST(2, MATCH(title, 'covid'), venue IN ('nejm', 'lancet'), cited > 100, max_rows => 2000) ORDER BY bm25(body, :q) DESC LIMIT 20; -- all four words if 50 rows have them, else three, else two SELECT id, score() FROM docs ORDER BY bm25(body, 'mrna vaccine trial phase', min => 2, min_rows => 50) DESC LIMIT 10; ``` - **The bounds** are counts of rows, 1 or more, and `min_rows` is at most `max_rows` (else no level could meet both, an error). - **The level.** From the strictest level, all y items, a guard relaxes one item at a time while the level matches fewer than `min_rows` rows and the next looser one no more than `max_rows`, down to `n`. With `max_rows` alone that is the loosest level that fits, and with `min_rows` alone the strictest with enough rows. If even all y match more than `max_rows`, the query runs at y. The rows counted are those the rest of `WHERE` keeps; `LIMIT` does not cut them. - **Where.** A guard is an `AT_LEAST` or a `MATCH` joined to the rest of `WHERE` by `AND` (not one under `OR`, `NOT` or another condition), or a `bm25` of the first ranking of `ORDER BY`. `MATCH` and `bm25` need a `min`, the loosest level; `AT_LEAST`'s is its `n`. A query has one guard at most, and a [rerank phase](#rerank-phases) none. A `SELECT` over a `WITH` result that is not a rerank phase counts that result's rows. - **The plan line** gives each level's rows and the level chosen: `guard: AT_LEAST 3 of 4 (4: 12, 3: 340, 2: 5120, 1: 23000; max_rows 2000)`. - **Its cost** is counting the rows of every level, over all the rows the rest of `WHERE` keeps, before running at one: a guarded query costs about what counting its matches does, whatever its `LIMIT`. Over 1,000,000 rows where each condition holds for an independent 20% of them, `AT_LEAST(1, …, max_rows => 10000) LIMIT 100` took 2.5 ms over 4 conditions, 6.1 ms over 8 and 11.6 ms over 16, against 0.25, 0.51 and 0.98 ms for the same query written at the level chosen. For four words of different frequencies, over rows of 12 words drawn by Zipf's law from 5,000, `bm25(body, …, min => 1, max_rows => 1000)` took 2.4 ms at the median of 50 queries (`LIMIT 10`), against 1.4 ms at the level chosen and 0.75 ms without `min`, and a `MATCH` guarded alike 2.3 ms against 1.3 ms. A text's words are counted once each, as `AT_LEAST`'s conditions are, unless it has required or excluded words, when each level is counted in turn (`chloedb-guard-bench` on a 4-core cloud VM, Intel Xeon @ 2.10GHz, `chloedb/results/strata/guard.json`). - **What it keeps.** BEIR's queries are sentences, and few rows hold all of a sentence's words. On five BEIR collections the top 100 rows by `bm25(body, :q, min => '100%')` held 0.03 to 0.40 of the relevant rows (recall@100), against 0.13 to 0.97 for any of the words; `min => 1, min_rows => 100`, all the words while 100 rows have them, else as many as 100 rows have, held 0.10 to 0.96, within 0.4 to 7.7 points of any word, with nDCG@10 within 0.013 of it, at a median of 0.15 to 2.05 ms a query, 0.8 to 1.6 times the any-word query's (`chloedb-bm25-eval`, the `_r100` variants, 3 runs each on a 4-core cloud VM, Intel Xeon @ 2.10GHz, `chloedb/results/text/bm25_guard.json`). - **Over shards**, a coordinator first asks every shard for its counts (protocol 8, so a shard of an older server is refused by name), adds them up, chooses the level as one database would, and sends the shards the query at that level: one round more. A shard answering a coordinator runs the level it is sent, never one of its own. With rows like those above split over 4 shards on one machine, the guarded `AT_LEAST` of 4, 8 and 16 conditions took 4.3, 7.4 and 12.6 ms through the coordinator (1.6, 2.6 and 1.8 ms at the level chosen) against 2.3, 3.9 and 7.7 ms on one database, and the guarded `bm25` 4.3 ms against 1.7 ms, medians of 50 queries (`chloedb-guard-shards-bench`, the same VM, `chloedb-server/results/guard/shards-4.json`). - A plan with a guard needs the plan feature `guard`. From Python, `at_least(2, …, max_rows=2000)`, `match(field, query, min=2, max_rows=500)` and `bm25(field, text, min=2, min_rows=50)`. ## Full text: `MATCH` `MATCH(field, query)` is a boolean predicate. The query grammar follows SQLite FTS5: ```text query := and ("OR" and)* and := unary (["AND"] unary)* juxtaposition is AND unary := ("NOT" | "-") unary | primary "a NOT b" is "a AND NOT b" primary := "(" query ")" ["@" n | "@" p "%"] | ("\"phrase\"" | word | word* | word~ | word~N) ["^" weight] ``` | query | matches | |---|---| | `vaccine mrna` | both words (juxtaposition is `AND`) | | `vaccine OR vaccination` | either | | `vaccine -animal`, `vaccine NOT animal` | the first without the second | | `"messenger rna"` | the phrase (needs positions on the field) | | `vacc*` | every indexed term with that prefix | | `vacine~`, `vacine~1` | the word and the indexed terms an edit or two from it ([typos](#typos-and-synonyms)) | | `vaccine AND (mrna OR "messenger rna") -animal` | any combination, with parentheses | | `(mrna vaccine trial phase)@2`, `(…)@50%` | at least 2 of the group's items, or half of them | Operators are uppercase; lowercase `and`, `or` and `not` are ordinary words (and stopwords). Parentheses and `NOT`s nest at most 100 deep. Words and phrases are analysed like the field's documents, by its [analyzer](#tables): a word that analyses to several terms (`e-mail`) becomes a phrase, and one that analyses to none (a stopword) is dropped. A prefix is lowercased and folded, and matches the indexed terms that start with it and the stems of the words it may be the start of that do not: the stem of the prefix as a word (`battery*` takes `batteri`, the stem of *battery* and *batteries*) and, with `english`, the stems of the prefix completed by a common ending, whole or the rest of one already begun (`runni*` takes `run`, for *running*). Those are looked up as whole terms, not as prefixes, so `cart*` does not take `car`. **Changed:** a prefix matched only the terms that start with it before, so `battery*`, `headphone*` and `running*` found nothing where every letter typed before them found the rows. A weight (`vaccine^2`, `"messenger rna"^0.5`) is read and ignored, since `MATCH` only says whether a row matches: `vaccine^2 mrna` matches what `vaccine mrna` does, so one text can go to both `MATCH` and [`bm25`](#weights-required-and-excluded-words). A weight of 0 is read and ignored too, while `bm25` scores nothing for that word. A `^` before something that starts like a number but is not a weight (`vaccine^1e308`, `vaccine^-1`, `vaccine^2x`), and a `~` with more than 2 typos (`apple~9`), are errors in `MATCH`, where they would otherwise be searched as words; `bm25` reads its text leniently, and there they are words. **A prefix filters; it does not score.** `bm25` scores a text's whole words and passes over its prefixes (`bm25(name, 'leather sof*')` scores `leather` alone), so a query ranked by `bm25(name, 'sof*')`, which has no whole word, returns no row, even where `MATCH(name, 'sof*')` keeps many, and neither does a ranking expression with it in (`bm25(name, 'sof*') + rating`). For search as you type, filter by what was typed with its last word as a prefix and rank by the words typed whole, or, while the first word is still being typed, by a column: ```sql -- typed "lether so": the prefix in MATCH, the whole words in bm25 (with the same fuzzy, given again) SELECT id, name FROM products WHERE MATCH(name, 'lether so*', fuzzy => 'auto') AND in_stock ORDER BY bm25(name, 'lether', fuzzy => 'auto') * (1 + 0.1 * rating) DESC LIMIT 10; -- typed "so": no whole word yet SELECT id, name FROM products WHERE MATCH(name, 'so*') AND in_stock ORDER BY rating DESC, id LIMIT 10; ``` A `bm25` takes its `MATCH`'s `fuzzy` only when its text is the `MATCH`'s ([typos](#typos-and-synonyms)), so here it names its own. A `KEYWORD` field of whole values (a product's name, a past query) completes with [`PREFIX`](#prefixes-and-autocomplete) instead, ordered by a column. **What a visitor typed: `syntax => 'plain'`.** A search box's text is seldom written in this grammar, and a stray quote, bracket or sign in it (`"soup`, `soup (easy`, `soup)`, `soup -`) is an error that says what is wrong (`MATCH query "soup)" has a ) without its (`). `MATCH(name, :q, syntax => 'plain')` reads the text as words alone: each run of it between spaces a word (several words, `t-shirt`, as a phrase), all of them needed, none of it an operator, so `-easy` is the word *easy* and `OR` the word *or*; a text of no words matches nothing. It takes `fuzzy`, `synonyms` and `min` as the query syntax does, and a [`bm25`](#bm25field-text) of the same text on the same field reads it as plain words too. `syntax => 'query'` is the default. **Changed:** `MATCH` refused `syntax` before, and its errors named the parser's tokens (`unexpected RParen in MATCH query`). ```sql SELECT id, name FROM recipes WHERE MATCH(name, :q, syntax => 'plain', fuzzy => 'auto') ORDER BY bm25(name, :q) DESC LIMIT 10; ``` A group with `@n` matches a row with at least `n` of its items: its operands, whether juxtaposed, joined by `AND` or by `OR`, each a word, a phrase, a prefix, a typo-tolerant word or a parenthesised query (`vaccine AND (mrna "messenger rna" trial~ (phase OR stage))@2`). A negated item (`-animal`) is not counted: the row must not have it. An item written twice is one item, as in `bm25`'s `min` (`(apple apple cherry)@2` needs both words), and so are words that analyse to the same term. A stopword is not an item, and a word's synonyms and typo neighbours count as it does. `@p%` asks for p percent of the items, rounded down; a count or percentage of 0 is an error, and either is clamped to between 1 and the number of items, as Lucene's `minimum_should_match` is, so `@1` is any of them and a count past the end is all of them. `MATCH(body, 'a b c d', min => 2)` (or `min => '75%'`) treats the whole query as one group. A group nests anywhere a parenthesised query does. A group reads each item's matches once, so it costs about what an `OR` of its items does. ## Prefixes and autocomplete `kw LIKE 'p%'` and `PREFIX(kw, 'p')` select the rows of a `KEYWORD` field whose value starts with `p`, byte for byte (no case folding). A field's values are sorted in its dictionary, so the values with a prefix are one run of it, found by two binary searches per segment: a short run unions its values' lists, and one of more than 1,024 values of a single-valued field scans the code column, as a range of numbers does. A multi-valued field matches a row when one of its values starts with the prefix, and `NOT` when none does. A single-valued `KEYWORD` compares by order too, byte for byte as `ORDER BY` sorts it: `id > 't007-006015'`, `id <= :last`, `id BETWEEN 'a' AND 'm'` are one run of the dictionary each, as a prefix is, and a row without a value is `UNKNOWN` to them. So a keyset page of `ORDER BY created_at DESC, id` starts after the last row of the one before with `WHERE created_at < :at OR (created_at = :at AND id > :id)`. A `KEYWORD[]` keeps to `=`, `IN` and prefixes. A plan with such a comparison names the feature `keyword_ranges`, which a server from before it refuses. **Changed:** an order comparison of a `KEYWORD` was refused before. ```sql -- autocomplete: the ten most asked queries that start with what was typed SELECT id, n FROM queries WHERE PREFIX(id, :typed) ORDER BY n DESC, id LIMIT 10; -- a user's own history first: keys of the form '|' SELECT id, n FROM user_queries WHERE PREFIX(id, 'u42|how to') ORDER BY n DESC LIMIT 3; -- with typos: 'hwo to ins' still finds 'how to install' SELECT id, n FROM queries WHERE PREFIX(id, :typed, fuzzy => 'auto') ORDER BY n DESC, id LIMIT 10; -- the same, exact completions first, then those one edit away, then two SELECT id, n FROM queries WHERE PREFIX(id, :typed, fuzzy => 2) ORDER BY CASE WHEN PREFIX(id, :typed) THEN 2 WHEN PREFIX(id, :typed, fuzzy => 1) THEN 1 ELSE 0 END * 1000000 + n DESC LIMIT 10; SELECT id FROM files WHERE path LIKE 'src/query/%' AND path NOT LIKE 'src/query/ir/%'; ``` - `LIKE` on a table's own `KEYWORD` field reads its index for a value (no wildcard: `=`) or text followed by `%`. Another pattern (`_` anywhere, or `%` before the end) and `LIKE` on a `TEXT` field test each row the other conditions keep, as over joined or derived rows. A field with a [substring index](#substrings-like-and-ilike-anywhere-in-a-value) answers every pattern from it. - `ESCAPE 'c'` makes the character after `c` literal: `LIKE 'snake!_%' ESCAPE '!'` is the prefix `snake_`. `PREFIX` needs no escaping. - `ILIKE` tests each row the other conditions keep. To find values in any case among many rows by an index, give the field a [substring index](#substrings-like-and-ilike-anywhere-in-a-value), or store the value lowercased (and a display form beside it) and use `LIKE`. - `PREFIX(x, p)` also works over joined or derived rows, as a test of each value; `PREFIX(kw, '')` and `LIKE '%'` are `IS NOT NULL`. - **`PREFIX(kw, p, fuzzy => 1 | 2 | 'auto')`** also selects the values that start with a prefix within that many edits of `p` whose first letter is `p`'s own, with the edits `MATCH` counts ([typos](#typos-and-synonyms)); `'auto'` goes by `p`'s length, as it does for a word: none up to 2 letters, 1 up to 5, else 2. The dictionary is walked as a trie, one row of the edit-distance table per letter, jumping past every value whose start is already too far from `p` and past the whole run of a start close enough, so the cost follows the values near what was typed rather than the dictionary's size. The values found are a few runs of the dictionary, read as an exact prefix's one is. A value's edits are the fewest of any of its prefixes, so a completion of `p` itself has none even when a shorter prefix is also close enough. Typo matches rank by the `ORDER BY` like exact ones; to rank completions by their edits, exact ones first and each tier by its count, put the tiers in the ranking expression: `ORDER BY CASE WHEN PREFIX(id, :typed) THEN 2 WHEN PREFIX(id, :typed, fuzzy => 1) THEN 1 ELSE 0 END * 1000000 + n DESC` (the factor larger than any count). `LIKE` takes no typos. - Counts kept with `UPDATE ... SET n = n + 1` or a write's `add` change in place, so a query log's popularity stays current without rewriting rows. A plan with a prefix needs the plan feature `prefix`, and one with typos also `prefix_edits`, so a shard of an older version refuses it rather than misreading it. The same run of the dictionary answers [semantic-ID next codes](server.md#semantic-ids). **Cluster a completion table by its key.** `ORDER BY n DESC LIMIT 10` reads the count column's blocks best first ([ordering by a column](#a-column)), and with `OPTIONS(cluster_by = 'id')` a prefix's rows sit together in each segment, so the ten most asked queries under a prefix read about ten blocks whatever the prefix's length: ```sql CREATE TABLE queries (id KEYWORD PRIMARY KEY, n INT) OPTIONS(cluster_by = 'id'); ``` Over ORCAS's 10.4 million queries, loaded in no particular order and merged by the default policy (11 segments), 2,000 typed queries drawn by clicks, one thread on a 4-core cloud VM (Intel Xeon @ 2.10GHz), p99 in ms: | characters typed | 1 | 2 | 3 | 4 | 6 | 8 | 12 | |---|---:|---:|---:|---:|---:|---:|---:| | rows matching (median) | 560,354 | 64,887 | 9,461 | 2,418 | 415 | 68 | 6 | | every match read | 46.7 | 25.4 | 18.2 | 17.1 | 9.9 | 9.1 | 2.6 | | blocks best first | 9.5 | 13.0 | 8.8 | 9.7 | 6.3 | 6.5 | 2.6 | | blocks, clustered by `id` | 0.27 | 0.53 | 0.48 | 0.38 | 0.35 | 0.33 | 0.28 | The full runs, with medians and the 105 segments straight after the load, are [`results/text/complete-orcas.json` and `complete-orcas-clustered.json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/text) (`chloedb-complete-bench`). Typos cost the walk of each segment's dictionary, which finds each value's fewest edits. On the same clustered table, the median top 10 with `fuzzy => 'auto'` takes 1.9 ms at 3 letters and 2.7 ms at 4, where it allows one edit, and 8.2 to 11.9 ms from 6 letters, where it allows two (p99 up to 24 ms); with `fuzzy => 1` it takes 3.3 to 4.1 ms from 6 letters (p99 up to 8.5 ms). Up to 2 letters `'auto'` allows none, so it costs what an exact prefix does. Straight after a load, with 105 segments, the same queries take 2.7 to 3.9 times as long. Ranked exact completions first (the `CASE` above), the median is 5.1 to 15 ms from 2 letters and 28 ms at 1 (p99 up to 62 ms), since a ranking expression is not a column whose blocks can be read best first: every completion is ranked. Results: `complete-orcas-clustered-fuzzy.json`, `complete-orcas-clustered-fuzzy1.json` and `complete-orcas-clustered-fuzzy-exact-first.json` (one thread of the 4-core cloud VM, Intel Xeon @ 2.10GHz). ## Substrings: `LIKE` and `ILIKE` anywhere in a value A `TEXT` or `KEYWORD` column declared with `OPTIONS(substring = true)` gets a substring index, and `LIKE` and `ILIKE` on it are answered from that index, whatever the pattern. It finds what `MATCH` cannot, because it has no tokenizer: part of a word, an IP address, a path, an identifier, punctuation, text in a script the analyzer does not split. ```sql CREATE TABLE logs ( id INT PRIMARY KEY, ts TIMESTAMP NOT NULL, host KEYWORD OPTIONS(substring = true), body TEXT OPTIONS(substring = true) ); SELECT ts, body FROM logs WHERE body LIKE '%173.234.31.186%' ORDER BY ts DESC LIMIT 20; SELECT count(*) FROM logs WHERE body ILIKE '%break-in attempt%' AND ts >= '2026-11-01'; SELECT id FROM logs WHERE body LIKE '%Failed password%from 119.4.203.64%' AND host NOT LIKE '%.internal'; ``` - **The answer is the one a test of every row gives.** `%` is any run of characters and `_` one character; `LIKE` compares byte for byte, and `ILIKE` compares both sides lowercased a character at a time, as PostgreSQL does and as it does [over joined or derived rows](#subqueries-with-and-joins): a capital `Σ` matches `σ` and the final `ς` wherever it stands, and a capital `İ` is one `i` . A row without a value matches neither a pattern nor its `NOT`, and a NULL pattern (`LIKE :p` with `:p` NULL) matches no row, nor does its `NOT` . The index only changes how long the answer takes. - **How it answers.** Each segment holds an FM-index of the field's values: the Burrows-Wheeler transform of their bytes in a wavelet tree, with a sample of the suffix array that says which row a match is in. Counting the places a string occurs takes time by the string's length, not by the table's size, and each row found then costs one to a few microseconds. A pattern with one string (`'%lit%'`, `'lit%'`, `'%lit'`, `'lit'`) is answered from the index alone, under `LIKE` and `ILIKE` : `ILIKE` searches the spellings that exist (`error`, `Error`, `ERROR`), not every combination of cases. A pattern with several strings (`'%a%b%'`) or with `_` takes its candidates from the string that occurs least and tests their stored values, read in the order the table keeps them. A `LIMIT` without an `ORDER BY` on such a column stops at the first rows it needs . - **A pattern in too many rows reads the values instead.** Where a string occurs in more than about one row for every 2 KiB of a segment's stored rows (4 KiB where each candidate's value is tested), listing its rows from the index would cost more than testing each value, so the query tests the values, as a table without the index does. The rows count whole, since a test reads them whole: a title that is a sixth of its row is listed up to six times as often before the values are read. Beside conditions that leave few rows (`pid = 24200 AND body LIKE '%e%'`), the pattern is tested on those rows' values alone, whichever of the two the index's counts say is cheaper. - **What the column must be**: one value per row and stored (the stored values answer for rows not yet in a segment's index, and for the candidates above). It need not be searched by `MATCH`: `body TEXT OPTIONS(substring = true, indexed = false)` keeps only the substring index. `ALTER TABLE ... ADD COLUMN` takes the option. In JSON it is `"substring": true`. - **A `KEYWORD` column's value or prefix** (`LIKE 'abc'`, `LIKE 'abc%'`) still reads its dictionary, which is faster, and takes `ESCAPE`. A pattern the substring index answers does not take `ESCAPE`. - **Rows just written** are tested by their values until a flush writes their segment; a segment gets its index when it is flushed or merged. - **What it costs.** On three logs of 0.7 to 4.7 million lines the index took 0.94 to 1.02 of the bytes of the text it indexes, which made the file 1.8 to 2.3 times as large; loading took 1.3 to 2.6 times as long and a merge 2.2 to 3.6 times, since each segment's index is built when it is flushed and again when it is merged. A pattern in few rows took 0.02 to 2 ms where a test of every row took 0.6 to 4 s, and a pattern in very many rows a sixth to an eighth of that test ([`results/substring`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/substring), on a 4-core cloud VM, Intel Xeon @ 2.10GHz). - It makes the database [file format 3](index.md#wal-memtable-and-snapshots) with the feature `substring:1`, which a version of ChloeDB from before it refuses by name. The format is specified in [`chloedb/notes/substring.md`](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/notes/substring.md). ## Scores Each function below takes the options its section lists, as `name => value`. An option it does not take, or a value it cannot (`k1 => 'x'`, `b => 2`, `ef => 'x'`), is an error that lists the options it takes: `unknown option bogus for bm25: k1, b, algo, ...`. **Changed:** such an option was ignored before, so a misspelt one (`fuzy => 1`) gave an answer as if it had not been written. ### `bm25(field, text)` BM25 of the analysed terms of `text`, disjunctively: a row scores if it contains any of them, unless the text [requires or excludes words](#weights-required-and-excluded-words). Ranked queries drop English function words (NLTK's 153-word list), except that its single letters (`d`, `m`, `o`, `s`, `t`, `y`) are kept unless they end a contraction: "vitamin d" and "T cell" keep their letter, "don't" and "it's" drop it. A term written twice weighs twice. Used in `ORDER BY` without a `MATCH`, it is a ranked search; with one, it ranks the matching rows. | option | default | effect | |---|---|---| | `k1`, `b` | 1.2, 0.75 | BM25 parameters (`k1 >= 0`, `0 <= b <= 1`) | | `algo` | planner's choice (MaxScore) | `'maxscore'`, `'bmw'` (Block-Max WAND) or `'exhaustive'` | | `stopwords` | 1 (0 on a `simple` field) | `0` keeps English function words in the query, `1` drops them | | `fuzzy` | 0 | `1`, `2` or `'auto'`: also score the indexed terms that many edits from each word; `'auto'` corrects only the words that look like typos ([typos](#typos-and-synonyms)) | | `synonyms` | 0 | `1`: also score each word's synonyms | | `syntax` | `'query'` | `'plain'` reads `+`, `-`, quotes and `^` as punctuation: the text is words alone; `'terms'` reads analysed terms, each weighted by `^w`, as they are written ([query expansion](#query-expansion-expand)) | | `min` | none | `n` or `'p%'`: rank only the rows with at least that many of the text's optional words and phrases | | `expand` | 0 | `n`: also rank by the terms the query's top `n` rows hold most ([query expansion](#query-expansion-expand)), with `expand_terms` (20) and `expand_weight` (0.85) | Keeping function words is better for short questions: on Quora it gains 0.055 nDCG@10, while on TREC-COVID, whose queries are full questions, dropping them gains the same amount. #### Weights, required and excluded words The text may weigh a word, require it or exclude it, as a search box does: | text | ranks | |---|---| | `vaccine mrna` | the rows with either word | | `vaccine^2 mrna` | the same rows, `vaccine` weighing twice: as `vaccine vaccine mrna` | | `+mrna vaccine` | the rows with `mrna`, by both words | | `vaccine -animal` | the rows with `vaccine` and without `animal` | | `+"messenger rna" vaccine^0.5` | the rows with the phrase (with both words, on a field without positions), by its words and half of `vaccine` | | `+covid^0 treatment` | the rows with `covid`, by `treatment` alone | | `vacc* trial` | the rows with a word that begins `vacc`, or with `trial` | | `vacine~ trial`, `vacine~1` | the rows with a word an edit or two from `vacine`, or with `trial` | - **`^w`** after a word or a closing quote multiplies its terms' BM25 by `w`, a number of at least 0 (`2`, `0.5`, `.5`). Weights add up, as a word written twice does. A word weighing 0 scores nothing, and a text whose words all weigh 0 ranks no row. - **`+`** before a word or a quoted phrase requires it, **`-`** excludes it: a row must contain every required one and none of the excluded ones, and ranks by the others too. An excluded word does not score, and a word the query drops as a stopword is neither required nor excluded. A sign counts only at the start of a word and before a letter, digit or quote: `covid-19`, a `-` alone, `+-x` and `x^` are words. Quotes alone change nothing: `"messenger rna"` scores what `messenger rna` does. - **`word*`** ranks by the words of the field that begin with `word`, as `MATCH`'s prefix matches them (lowercased and folded, with the stems of the words it may begin), scored as one word whose document frequency is the largest of theirs, as a typo's neighbours are. When more than 128 words begin so, the 128 in the most rows score, and the plan says so: `bm25 vacc*: the 128 terms in the most rows, of the 412 it begins`. **`word~`** and **`word~1`**, **`word~2`** rank by the word and the words within that many edits, as `fuzzy` does for one word (`~` alone goes by its length, as `'auto'` does). Both take signs and weights (`+vacc*^2`), and with `syntax => 'plain'` both are words as written. So `ORDER BY bm25(title, :typed) DESC` with `:typed` = `'sof*'` ranks the rows `MATCH(title, 'sof*')` keeps, for search as you type. **Changed:** `bm25` read `vacc*` and `vacine~` as the words `vacc` and `vacine` before, which ranked no row where `MATCH` found some. - With `fuzzy` or `synonyms`, a word's typo neighbours and synonyms take the highest weight the word is written with (writing it twice weighs the word twice, not them), and a required or excluded word counts as present when one of them is, as in `MATCH`. - A required or excluded word is a filter on the ranked rows: the top-k loop (all three `algo`s), a [rank-safe boost](#rank-safe-boosts), a [rerank phase](#rerank-phases) (where a row the filter drops scores 0, as one without the words does) and shards all apply it, so the rows and scores are those of the rows the text allows. - Weights and signs cost little. With each query's first word weighed 2 (`word^2`) or required (`+word`), or its last word excluded (`-word`), the median query took 0.27, 0.28 and 0.23 ms on Quora's 10,000 queries against 0.25 ms for the plain text, and 0.24, 0.18 and 0.22 ms on FiQA against 0.22 ms; a required word can make a query faster, as the filter drops rows before they are scored. Text written without operators ranks and times as the plain text does on all five collections measured (`chloedb/results/text/bm25_term_operators.json`, one core of a 4-core cloud VM while another job held the other three). The operators were put on words mechanically to time them, so these queries rank worse than the plain text: an operator helps when it says what the person searching means. - **`min => n`** (or `'p%'`) ranks only the rows with at least `n` of the text's optional words and phrases: those without a sign, each counted once however often it is written, whatever its weight (`^0` counts too). Required and excluded words are not counted; a text without optional words ignores `min`. Counts are clamped to between 1 and the number of optional words, and a percentage rounds down, as in `MATCH`'s groups: `bm25(body, 'vaccine mrna trial phase', min => 2)` ranks the rows with two of the four words, by all of them. With `syntax => 'plain'`, each word is an optional word. - `min` filters the ranked rows, as a required word does, so its cost depends on how many rows hold one of the words. With `min => 2` the median query took 0.24 ms on Quora's 10,000 queries (0.25 ms plain) and 0.41 ms on FiQA (0.23 ms plain). On TREC-COVID, whose query words appear in most of its documents, it took 1.6 ms (0.5 ms plain), because the filter counts every row that holds one of the words (`chloedb/results/text/bm25_min_match.json`, one core of a 4-core cloud VM while another job held the other three). `min` is for leaving rows out, not for ranking better. Asking every BEIR query for two of its words, or half of them, left nDCG@10 unchanged on TREC-COVID and lowered it elsewhere, by as much as 0.077 (SciFact, half the words). - **`syntax => 'plain'`** reads the text as words alone, as `bm25` did before: for text not written for a search box, such as a user's message passed through, or a benchmark's recorded queries. BEIR's hold `+1`, `-word` or `x^2` here and there, so the evaluations and benchmarks in this repository pass `syntax => 'plain'`, and so does ChloeCtx. - A plan that ranks with weights, signs, prefixes or typos (`word*`, `word~`; a shard from before them, which takes `text_operators`, reads them as words, so finish an upgrade before relying on them), or a `MATCH` with weights, needs the plan feature `text_operators`, and one with `min` or a `MATCH` group `(…)@n` needs `min_match`. From Python, `bm25("body", "+mrna vaccine^2")` reads them, `bm25("body", text, syntax="plain")` does not, and `bm25("body", text, min=2)` and `match("body", text, min="75%")` ask for some of the words. **Changed:** `bm25` read `+`, `-`, `"` and `^` as punctuation before; text with them now ranks as above, and `syntax => 'plain'` keeps the old reading. In `MATCH`, `^` separated words: `vaccine^2` matched `vaccine` and `2`, and now matches `vaccine`; and `)@2` closes a group a row needs 2 of, where `@2` was a word before. ### `similarity(field, vector)` and `distance(field, vector)` The dot product (cosine for unit vectors) and the Euclidean (L2) distance between a row's vector and the query vector, which is a bound parameter or a JSON array of the field's dimension. **Text instead of a vector.** On a field a model embeds (`OPTIONS(embed = 'body', model = '...')`), the second argument may be text, a literal or a parameter that holds text: `ORDER BY similarity(emb, 'how do I reset my password') DESC`, or `similarity(emb, :q)` with `:q` bound to a string. The text is embedded as a query by the field's own model when the query is planned, once however often the query repeats it, and the query runs as if its vector had been given (`distance` and `maxsim` take text the same way; on a multi-vector field the text is its tokens' vectors). `similarity(emb, embed(:q))` says the same. In a [rank profile](#rank-profiles-a-ranking-kept-with-its-table) too, on chloedb-server: one text parameter feeds both `bm25(title, :q)` and `similarity(emb, :q)` (the profile written out, its texts embedded, the plan still naming the profile). A string that is a JSON array of numbers is still a vector, and a `SPARSE` field's terms are still text. **`embed('model', text)`** is the query vector of a text by the model named, wherever a vector goes: against a field of no model, `similarity(raw, embed('potion-base-8M', :q))`, or in a projection, `SELECT id, embed('potion-base-8M', 'tents') AS v FROM docs`. The model is one an embedded field uses, `hash:N`, or a directory directly under the models directory, named as `llm()` names one (letters, digits, `_`, `-` and `.`, never a path; `chloedb-server fetch-model` fetches the known ones). A model behind an API (`openai/...`, an `endpoint.json`) is taken only when a field uses it, so that a query spends no key a table was not given. The text is a value or a parameter, not a column: the model runs once a query, not once a row, and a column is embedded when rows are written, by declaring its vector field `OPTIONS(embed = 'column', model = '...')`. The text is embedded where the query is planned: by the database from Rust, Python and JavaScript, and by the server (a coordinator for its shards) on the cores it embeds writes with, as a parameter's `{"embed": "text"}` is. With a static model (Model2Vec, such as `potion-retrieval-32M`) that takes tens of microseconds; the median query on SciFact, its text embedded and every row measured, took 0.45 ms ([results](../../chloedb/results/static-int8/README.md)). `similarity` is the raw dot product of the vectors as written: ChloeDB does not normalise the vectors a write supplies (the models it runs itself write unit vectors), so on vectors of other lengths long vectors rank first. For cosine similarity, write unit vectors. `ORDER BY distance(emb, :v) ASC` ranks by $\lVert v - q \rVert$, nearest first, and `score()` is minus the distance (ranking is always best first). On a field a model embeds the vectors are unit length, where distance orders rows as the dot product does, so the index searches them (`strategy => 'flat'` measures every row); on any other field every row `WHERE` keeps is measured exactly, a scan of the field's float32 vectors, since its index ranks by the dot product. **Changed:** `distance()` ranked like `similarity(...) DESC` before, which is the nearest row only for unit vectors, and its `score()` was the similarity; a shard from before this change still ranks it so. In an expression, `distance()` stays refused: use `similarity()`. | option | effect | |---|---| | `strategy` | `'auto'` (default: the planner decides, by its cost model, which sizes the work by the vectors' dimensions: an unfiltered search scans every vector exactly where that costs no more than the index, as in a segment of 20,000 vectors of 64 dimensions), `'prefilter'` (evaluate the filter, scan its members exactly), `'index'` (search HNSW or IVF with the filter inside), `'postfilter'` (search with a larger *k* and drop non-matching rows), `'flat'` (exact scan), `'partition'` (walk the graphs of the [partitions](#vector-partitions) the filter can match) | | `ef` | HNSW search breadth (default 200; 64 before). On random unit vectors of 64 dimensions, the hard case for a graph (real embeddings cluster, and need less), the index found 0.73 of the true top 10 at ef 64 and 0.96 at 200 over 20,000 rows (0.13 and 0.24 ms at the median), and 0.40 and 0.71 over 200,000 (0.24 and 0.35 ms); the default search of the 20,000, now an exact scan, finds all of them in 0.15 ms (200 queries, `cargo test --test vector_defaults -- --ignored`, one run on a 4-core Intel Xeon @ 2.10GHz shared with other builds) | | `nprobe` | IVF clusters probed | | `rerank` | how many candidates are re-scored in float32 | #### Vector partitions A filter that keeps a fifth of the rows makes an HNSW search either walk its graph testing every row it reaches, or fetch five times the candidates and drop the rest. A field partitioned by the column the filter names does neither: each segment keeps, besides the field's graph of every row, a graph per partition of the rows, and a search whose `WHERE` limits that column walks only the graphs of the partitions that can match. ```sql CREATE TABLE docs (id KEYWORD PRIMARY KEY, rating FLOAT, category KEYWORD, emb VECTOR(768) OPTIONS(partition_by = 'rating', partition_bounds = '1, 2, 3, 4')); SELECT id FROM docs WHERE rating >= 4 ORDER BY similarity(emb, :v) DESC LIMIT 10; ``` - `partition_bounds` splits an `INT` or `FLOAT` column into ranges: here below 1, 1 to 2, 2 to 3, 3 to 4, and 4 and up (1 to 63 increasing numbers). A `KEYWORD` column is partitioned by value and takes no bounds (`partition_by = 'category'`): each segment builds a graph for each of its 64 most frequent values. The column must be stored, indexed and single-valued, and the field an HNSW field of one vector a row. Rows without a value in the column are only in the field's graph. - The planner reads the first condition on the column among the filter's top-level `AND`s: a range (`>=`, `<`, `BETWEEN`), `=` or `IN`. A partition whose rows all pass it is walked with no test at all, so `rating >= 4` costs what an unfiltered search of a fifth of the rows costs; a partition that only partly matches, or a filter with other conditions, tests the rest on each row the walk reaches. The planner uses partitions when its cost model predicts them faster than its other plans, and `strategy => 'partition'` uses them wherever they apply. A search without a condition on the column uses the field's graph, as before. - On 1M MS MARCO passages (768-dimension vectors, one segment, the 4-core cloud container), the engine comparison's `rating >= 4` (20% of rows) took 176–184 µs with partitions against 364–438 µs, at recall@10 0.963 against 0.961; `rating >= 4.5` (10%) 383 µs against 674–777 µs. At 2% (`rating >= 4.9`) the partitions took 1.1 ms where the planner's exact scan of the matching rows takes 1.6–2.2 ms, finding 0.995 of the exact answers instead of 0.999 (`chloedb/results/vector/partitions-msmarco-1000000x768.json`). - The partitions' graphs take as much space as the field's graph again (128 bytes a row at `m = 16`, 3% of that table's file) but share its vectors and codes. Building that table took 320 s instead of 179 s, and merges build the partitions again from scratch. - A database with partitions is written in [file format 3](index.md#wal-memtable-and-snapshots) with the feature `vector_partition`, which versions of ChloeDB from before them refuse by name. A `VECTOR` field keeps, besides its float32 rows, a compact code per row that the search scans: 8 bits per dimension by default, or 1 bit per dimension with `"codes": "binary"` in the field's schema (or the build option `vector.codes = 'binary'`). Binary codes are 32 times smaller than the vectors and 8 times smaller than 8-bit codes; to make up for the coarser scores, the search re-scores 8 times as many candidates in float32. On synthetic 768-dimensional data that kept recall@10 at 0.985–0.994 with flat, IVF and HNSW search, at an eighth of the memory ([results](results.md#compressed-vectors)); check recall on your own embeddings before choosing them, since some models lose more to one-bit codes than others. RaBitQ codes (`"codes": "rabitq1"`, `"rabitq2"` or `"rabitq4"`, or `codes = 'rabitq4'` in `OPTIONS`) keep 1, 2 or 4 bits per dimension of the vector after a fixed random rotation, and two numbers per row that give each estimated score an error bound. The search keeps 8, 4 or 2 times as many candidates, and skips the float32 row of any candidate whose bound shows it cannot reach the top results found so far. On FiQA's Cohere embeddings, at recall@10 1.000 with a flat scan, 1-bit RaBitQ codes read 91 float32 rows a query where binary codes read 320, 2-bit codes 28 and 4-bit codes 13, against SQ8's 40 ([results](results.md#compressed-vectors)). Their scan is slower per row than binary or SQ8 codes of the same field: 4-bit codes take half the memory of SQ8 and scan about 1.5 times slower. They pay off when reading the float32 rows is the cost, as with a table larger than memory. A database with RaBitQ codes is written in [file format 3](index.md#wal-memtable-and-snapshots) with the feature `rabitq`, which versions of ChloeDB from before them refuse by name. ### `similarity(field, weights)` on a `SPARSE` field The dot product of a row's term weights with the query's, `Σ q_t · w_t` over the terms both have. The query is a JSON object of term weights, bound as a parameter or written as a string: ```sql SELECT id, score() FROM docs ORDER BY similarity(splade, '{"vaccine": 1.4, "mrna": 2.1, "efficacy": 0.6}') DESC LIMIT 10; ``` It runs on the same machinery as `bm25` (MaxScore, Block-Max WAND, the filter strategies), so `algo => 'maxscore' | 'bmw' | 'exhaustive'` applies, and it fuses with other scores in `rrf`, weighted sums and products. `distance` is not defined on a `SPARSE` field. A `SPARSE` field [embedded by a learned sparse model](server.md#term-weights-of-a-learned-sparse-model) (`sp SPARSE OPTIONS(embed = 'body', model = '...')`) gets its rows' weights from the model; the query's are the parameter `{"embed": "some words", "field": "sp"}` (from Rust, `Db::embed_query_in`), weighed by the same model. ### `maxsim(field, vectors)`: several query vectors The best similarity of a row's vector with any of several query vectors, $\max_i q_i \cdot v$: a row near any one of a user's recent items, or of a query's several phrasings. The vectors are a bound list of vectors, a tuple of vector parameters, a JSON array of arrays, or a subquery that returns one column of vectors, which runs first: ```sql -- items like any of the user's last 20, by similarity SELECT id, score() FROM items ORDER BY maxsim(emb, (SELECT emb FROM history WHERE usr = :u ORDER BY ts DESC LIMIT 20)) DESC LIMIT 10; -- and fused with text and a row's rating SELECT id FROM items ORDER BY rrf(bm25(title, :t), maxsim(emb, :recent)) * (1 + 0.1 * coalesce(rating, 0)) DESC LIMIT 10; ``` It runs one search per query vector, with the filter and the options of `similarity` (`strategy`, `ef`, `nprobe`, `rerank`), and scores the union of their top *k* exactly against every query vector. The union holds the exact top *k*: a row among them is among the top *k* of the query vector it is closest to. Each added query vector costs one more search ([what that costs](results.md#maxsim)). A row without a vector scores `NULL`, a subquery with no rows ranks nothing, and more than 64 vectors is an error unless `max_vectors => n` raises the limit. It is a score wherever `similarity` is one: in `rrf`, `minmax()` sums and ranking expressions, on one database or over shards. On a **multi-vector field** (`VECTOR(d)[]`), `maxsim` is late interaction as ColBERT and ColPali score it: the sum over the query vectors of each one's best match among the row's vectors, $\sum_i \max_j q_i \cdot v_j$. Each query vector's search returns its best `depth` vectors (64), which name candidate rows; the `candidates` rows (200, at least the `LIMIT`) with the largest sum of the matches found are scored over all their vectors, with their 8-bit codes, or float32 when the field keeps them. A row without vectors ranks nowhere. `depth => n` and `candidates => n` trade time for recall; with both at least the number of vectors, the answer is exact. `similarity` refuses a multi-vector field, and so do graph functions. ```sql -- pages by their patches' best matches with the query's token vectors SELECT id, score() FROM pages ORDER BY maxsim(patches, :tokens) DESC LIMIT 5; ``` A multi-vector field can also be the vectors of a text's tokens, which a model of late interaction (ColBERT) computes when rows are written: `tok VECTOR(96)[] OPTIONS(embed = 'body', model = 'answerai-colbert-small-v1')` ([a vector a token](server.md#a-vector-a-token)). A query gives the vectors of its own tokens as the parameter (`{"embed": "the text", "field": "tok"}` on the server, `Db::embed_query_in` from Rust). Its usual place is a rerank phase over BM25's best rows, which scores each of them over all its vectors: ```sql WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :q) DESC LIMIT 100) SELECT id, score() FROM top ORDER BY maxsim(tok, :tokens) DESC LIMIT 10; ``` On BEIR's SciFact and NFCorpus, `answerai-colbert-small-v1` over BM25's top 20 scores nDCG@10 0.738 and 0.354 (BM25 alone 0.691 and 0.329) in 80–90 ms a query on four cores, most of it encoding the query; that ranks better than the cross-encoder below, in a fifth of its time. The cost is at write: 0.1–0.16 s a document to embed, and a database about 29 times BM25's (half that with `pool_factor = 2`, which scores the same). The [results](results.md#colbert-reranking) have the details. `dot(a, b)` is the dot product of two vectors as a value, for rows in memory: `SELECT id, dot(emb, :q) FROM h` over a `WITH` result, a join, or a table's own rows. It equals `similarity` to the bit, and in a ranking expression over a table (`ORDER BY bm25(title, :q) + 2 * coalesce(dot(emb, :q), 0) DESC`) it is `similarity(emb, :q)`: `NULL` for a row without a vector. ### `rrf(s1, s2, …)`: reciprocal rank fusion Each input ranks the rows that pass `WHERE`, to a depth of 100 by default, and a row's fused score is $$ \mathrm{rrf}(d) = \sum_{i} \frac{1}{k + \mathrm{rank}_i(d)}, \qquad k = 60 $$ Options: `k => 60`, `depth => 100`, and `weights => [w1, w2, …]`, one number of at least 0 per input, which multiplies that input's terms (weighted RRF): $$ \mathrm{rrf}(d) = \sum_{i} \frac{w_i}{k + \mathrm{rank}_i(d)} $$ `rrf(bm25(body, :q), similarity(emb, :v), weights => [0.3, 0.7])` leans on the vectors; the weights are a list (`[0.3, 0.7]`, `ARRAY[0.3, 0.7]`) or a parameter holding one, and all of them 1 is plain `rrf`. A list of another length, or of weights all 0, is an error. The depth is raised to the page's `LIMIT` when it asks for more rows, as in weighted sums and products, but not by its `OFFSET`: pages of one size (`LIMIT 20 OFFSET 0, 20, 40 ...`) rank the same candidates, so they are the pages of one ranking, with no row on two pages and none skipped. A page past the candidates comes back short, with `truncated: true` and a plan line that says so; to page deeper, give the ranking a larger `depth =>`, the same on every page. **Changed:** the depth was raised to `LIMIT + OFFSET` before, so each page ranked other candidates, and paging repeated and skipped rows. ### `ranked(keys)`: a ranking from elsewhere `ranked(:keys)` is a ranking computed outside ChloeDB, given as primary keys, best first: a recommender's candidates, a reranker's order, or the rows a [semantic-ID](server.md#semantic-ids) decoder generated. It is a score like any other, so it fuses with ChloeDB's own rankings: ```sql SELECT id FROM items WHERE in_stock ORDER BY rrf(bm25(title, :q), ranked(:keys)) DESC LIMIT 20; ``` A listed row scores `-(its position)`, from `-1` for the first key; a key listed twice ranks where it is first. A row the list leaves out has `NULL`, so in an expression it ranks last unless `coalesce` gives it a value, and in a weighted sum it takes the input's worst value, as a missing column does. Times another score (`ranked(:keys) * rating`) it multiplies as arithmetic, not as a product of scores, which would count its negative values as 0. A key no live row has is skipped. On its own, `ORDER BY ranked(:keys) DESC` answers the listed rows that `WHERE` keeps, in list order. The keys are a parameter holding a list (an array of keys in the HTTP API), a tuple (`ranked(('a', 'b'))`) or an array (`ranked(ARRAY['a', 'b'])`). Over shards, each shard scores its own rows from the list and the coordinator merges them, so no extra round is needed. A plan that uses it needs the plan feature `ranked`. ### Weighted sums: `tmm()`, `minmax()` and `zscore()` A weighted sum of normalised scores is weighted (convex) fusion: `0.2 * tmm(bm25(body, :t)) + 0.8 * tmm(similarity(emb, :q))`. Weights are numeric constants; `+` and `-` combine any number of terms. Candidates are the union of each input's top 100, re-scored exactly by every input and normalised over that union ($C$). Three normalisers put a score on one scale: | normaliser | a row's value | a row without a value | |---|---|---| | `tmm(x)`, theoretical min-max | $\dfrac{x - lo}{\max_C x - lo}$, `lo` the least value `x` can take | 0 | | `minmax(x)` | $\dfrac{x - \min_C x}{\max_C x - \min_C x}$, 1 where all are equal | 0 | | `zscore(x)` | $\dfrac{x - \mathrm{mean}_C x}{\mathrm{sd}_C x}$, 0 where all are equal | the least of the candidates' | Use `tmm` unless your own judged queries say otherwise. Its lower end is fixed by what the score is, not by the candidates: a row's value depends only on the best candidate, which is the same at any depth, while `minmax` moves every row whenever the weakest candidate changes, which it does with `depth` and with what each input happens to return. Bruch, Gai and Ingber ([TOIS 2023](https://arxiv.org/abs/2210.11934)) find this convex combination beats RRF in and out of domain once its one weight is tuned, and that a few dozen judged queries tune it; the [relevance lab](server.md) tunes it on yours ([what it gives on BEIR](results.md#score-fusion)). `lo` is the score's own: 0 for `bm25`, a `SPARSE` similarity (weights at least 0, as learned models give them), `rrf`, `ppr` and `decay`; -1 for `similarity` and a one-vector `maxsim`, the least cosine of unit vectors (the vectors of an embedded field, and of most models; for vectors of other lengths, give `lo`); -n for `maxsim` of n vectors on a multi-vector field. Anything else, a column or an expression, needs it written: `tmm(rating, lo => 0)`. With `hi` too, `tmm(x, lo => a, hi => b)` is $(x - a) / (b - a)$, each row's own value (0 without one), fixed bounds that read nothing of the other candidates. Options, given on any input: `depth => 100` (candidates per input), `exact => 1` (score every row that passes `WHERE` instead of the top-100 union). The top-100 shortcut recovers 89–95% of the exact fused top 10 ([results](results.md#hybrid-ranking)). A row without a value of a column input (`0.7 * minmax(bm25(body, :t)) + 0.3 * minmax(rating)` for a row whose `rating` is `NULL`) takes that input's worst value among the candidates: its lowest when the weight is positive and its highest when the weight is negative (0 and 1 after min-max), so a missing value never lifts a row. Under `tmm` and `zscore` it takes the value in the table above. A plan with `tmm` or `zscore` needs the plan feature `score_norms`, which a version of ChloeDB from before them refuses by name. **Changed:** a sum of bare scores, `0.2 * bm25(body, :t) + 0.8 * similarity(emb, :q)`, was this fusion before ranking expressions; `+` now adds raw values, as in any expression below. Write `minmax()` around each term for the fusion. For one release, `EXPLAIN` and a query's plan lines add a note when an expression adds raw relevance scores. `norm => 'none'`, which kept raw scores in a sum, is accepted and changes nothing. ### Ranking expressions `ORDER BY` takes any expression of scores, numeric columns and numbers, ranked best first (`DESC`; negate it to rank the smallest first): ```sql -- relevance boosted by a rating, which may be missing SELECT id FROM products ORDER BY ln(1 + bm25(body, :t)) * (1 + 0.2 * coalesce(rating, 0)) DESC LIMIT 10; -- a business rule on top of similarity SELECT id FROM products ORDER BY similarity(emb, :q) + CASE WHEN in_stock THEN 0.1 WHEN category = 'outlet' THEN -0.2 ELSE 0 END DESC LIMIT 10; -- Borda-style fusion of two rankings SELECT id FROM papers ORDER BY -rank(bm25(body, :t)) - rank(similarity(emb, :q)) DESC LIMIT 10; ``` | part | meaning | |---|---| | `+ - * / %`, unary `-` | arithmetic on raw values | | `bm25`, `similarity`, `ppr`, `decay`, `rrf`, `ranked`, a numeric column, `hops()`, `seq_no()`, `hash(field, seed)` | the leaves: a row's value of each | | `ln(x)`, `log(x)` (base 10), `log(b, x)`, `exp(x)`, `sqrt(x)`, `pow(x, y)`, `abs(x)`, `round(x[, digits])`, `sigmoid(x)`, `clamp(x, lo, hi)` | numeric functions | | `least(…)`, `greatest(…)`, `coalesce(…)` | over their arguments that are not `NULL` | | `tmm(x[, lo => a][, hi => b])` | `x` from its least possible value to the best row's, put on [0, 1]: 0 where `x` is `NULL` ([above](#weighted-sums-tmm-minmax-and-zscore)) | | `minmax(x)` | `x` over the rows ranked, put on [0, 1]: 1 where all are equal, 0 where `x` is `NULL` | | `zscore(x)` | `x` less the rows' mean, over their deviation; `NULL` takes the least of the rows' | | `rank(x)` | 1 plus the number of rows ranked with a greater `x`; `NULL` places after every other | | `CASE WHEN c THEN x … ELSE y END` | the first branch whose condition holds (any `WHERE` condition), else `y`, else `NULL` | | `count_true(c, …)` | how many of the conditions hold ([`AT_LEAST`](#some-of-the-conditions-at_least)) | `NULL` is a missing value (a `NULL` column, a row without a vector, one a traversal does not reach) or a result that is not a finite number (`ln(0)`, a division by 0, an overflow). Arithmetic and functions of `NULL` are `NULL`, except `coalesce`, `least` and `greatest`, which skip it. A row whose score is `NULL` ranks after every other, and its `score()` is `NULL`. Candidates are the top `depth` (100) rows of each relevance leaf (`bm25`, `similarity`, a graph's, `ranked`), and of every input of `rrf`; an expression with no such leaf (`rating * 2 + year / 1000`), or `exact => 1` on any leaf, ranks every row that passes `WHERE`. A [rank-safe boost](#rank-safe-boosts) ranks every row its text score matches. Each leaf scores every candidate exactly, and `tmm()`, `minmax()`, `zscore()` and `rank()` are taken over the candidates. Over shards, each shard returns its candidates' leaf values and the coordinator runs the expression, so a split collection ranks like the whole one. #### Rank-safe boosts An expression with one text score (`bm25`, or `similarity` on a `SPARSE` field) whose other parts are numeric columns, `decay`, `CASE` conditions, numbers, `seq_no()` and `hash()` finds its exact top rows: the rows that scoring every row the text matches would rank first, not only the best of the text's top 100. Set functions (`tmm()`, `minmax()`, `zscore()`, `rank()`), `rrf` and `exact => 1` take the candidates above instead. ```sql -- the 10 best by BM25 boosted by importance, even a row 5,000th by BM25 alone SELECT id FROM docs ORDER BY bm25(body, :t) * (1 + 0.2 * importance) DESC LIMIT 10; ``` The text score's top-k loop (MaxScore, Block-Max WAND or exhaustive, as `algo` says) ranks by the whole expression. From the k-th best value so far and each column's smallest and largest value, it works out the lowest text score a row needs, and skips the rows below it. A row the text does not match is not a candidate. When the expression does not rise with the text score (`rating - bm25(body, :t)`), no text score can be ruled out: the loop scores every matching row, and the plan line says `every match scored`. Over shards, each shard returns its own exact top rows: its top `LIMIT + OFFSET` over all its segments, and the rows tied with the last of them. The cluster's top rows are each in their own shard's, so a split collection ranks like the whole one. A shard also returns the text score's top `depth` rows, which a coordinator from before rank-safe boosts fused from, only to a coordinator older than shard protocol 10 ([gRPC](server.md#grpc)). A plan that ranks by an expression needs the plan feature `rank_expressions`; a version of ChloeDB from before it refuses the plan by that name. Weighted sums of `minmax()`, products of scores and `rrf` are written as before, so older shards still run them. #### Rerank phases A ranking can go on in phases, as a search engine's rank profile does: a cheap first phase over every candidate, then a costlier one over its top rows. SQL writes a phase as a `WITH` that ranks a table and cuts it, ranked again by the next `WITH` or the query itself: ```sql -- BM25's top 100, ranked again by a mix of title and body relevance and rating WITH top AS (SELECT * FROM docs WHERE year >= 2020 ORDER BY bm25(body, :t) DESC LIMIT 100) SELECT id, title, score() FROM top ORDER BY bm25(title, :t) + 0.5 * bm25(body, :t) + 0.1 * coalesce(rating, 0) DESC LIMIT 10; -- three phases: similarity's top 500, its best 50 by a rating, then a fusion of the 50 WITH a AS (SELECT * FROM products ORDER BY similarity(emb, :q) DESC LIMIT 500), b AS (SELECT * FROM a ORDER BY coalesce(rating, 0) DESC LIMIT 50) SELECT id, score() FROM b ORDER BY minmax(bm25(body, :t)) + minmax(similarity(emb, :q)) DESC LIMIT 10; ``` The planner makes one search of them, with phases. Each phase ranks the rows of the one before by an expression, best first, and may read any of the table's columns, since the rows are the table's. Every row a phase reads goes on: one the expression gives no value ranks last with a `NULL` score (and a row a `bm25` phase's terms miss scores 0), and rows tied keep the order the phase before gave them. `LIMIT` and `OFFSET` on the query cut the last phase, and `score()` is the last phase's score. The first `WITH` may filter (`WHERE`) and rank as any query does; each later step reads the step before alone, with no `WHERE` or grouping, ranks by one expression `DESC` (which may hold [correlated subqueries](#correlated-subqueries-a-ranking-that-reads-other-rows)), and each `WITH` keeps the table's columns (`*`) and has a `LIMIT`. `WITH` results before the first phase, a user's history say, are computed first, for the phases' subqueries to read. Other `WITH` queries plan as before: the table restricted to the rows of the `WITH`. A phase whose expression is row-local is a second phase: over shards, each shard scores it on its own top rows by the first phase. A phase with a set function (`tmm()`, `minmax()`, `zscore()`, `rank()`), `rrf` or a weighted sum reads every row it reranks, so it is a global phase: it runs once over the merged rows (on the coordinator over shards), and so does every phase after it. The coordinator keeps the top rows of the whole collection by the first phase before it ranks them by the next, so a split collection answers exactly as the whole one does. `EXPLAIN` shows each phase and which kind it is, and a query's plan lines say how many rows each reranked. The first phase's `LIMIT` counts against the rows a query may reach (`max_rows`), and the phases against its deadline. From Python, `rerank(expr, count)` adds a phase: `t.select("id", score()).order_by(bm25("body", q)).rerank(col("rating"), 100).limit(10)`. A plan with phases needs the plan feature `rank_phases`. #### Correlated subqueries: a ranking that reads other rows A scalar subquery in a ranking may name a column of the row it ranks (`first.cat`). It is then correlated, and gives a number for each row: how often the user met the row's category, how long ago, how close the row is to what they bought. ```sql -- the user's last 50 events with their items' categories and embeddings, then -- BM25's top 1,000 reranked by what the user did with each one's category WITH h AS (SELECT e.item AS item, i.cat AS cat, i.emb AS emb, e.action AS action, e.ts AS ts FROM events e JOIN items i ON e.item = i.id WHERE e.usr = :u ORDER BY e.ts DESC LIMIT 50), first AS (SELECT * FROM items ORDER BY bm25(title, :q) DESC LIMIT 1000) SELECT id, title, score() FROM first ORDER BY bm25(title, :q) + 0.5 * (SELECT COUNT(*) FROM h WHERE h.cat = first.cat) - 0.0001 * coalesce((SELECT MIN(:now - h.ts) FROM h WHERE h.cat = first.cat), 100000) + coalesce((SELECT MAX(dot(h.emb, first.emb)) FROM h WHERE h.action = 'buy'), 0) DESC LIMIT 20; -- a table read through its indexes: the user's events in the row's category that cost less SELECT id FROM items WHERE MATCH(title, :q) ORDER BY bm25(title, :q) + 0.1 * (SELECT COUNT(*) FROM events e WHERE e.usr = :u AND e.cat = items.cat AND e.price < items.price) DESC LIMIT 20; -- as a column of the rows ranked WITH first AS (SELECT * FROM items ORDER BY bm25(title, :q) DESC LIMIT 100) SELECT id, (SELECT COUNT(*) FROM events e WHERE e.usr = :u AND e.item = first.id) AS seen FROM first ORDER BY bm25(title, :q) DESC LIMIT 20; ``` - **Where.** The rows ranked must be a bounded set: a [rerank phase](#rerank-phases), whose rows are the phase before's top rows; an `ORDER BY` over a table, or over a `WITH` result, of at most 10,000 rows (more is an error that suggests a phase); or the columns of a ranked query, alone or in an expression (`coalesce(price, 0) + (SELECT ...)`). A subquery naming the outer row in `WHERE`, `IN` or `EXISTS` is an error, but for an [`EXISTS` that names it by one equality](#subqueries-with-and-joins), a semi join. - **What it names.** `name.column`, where `name` is the outer query's table or `WITH` result (or its alias) and the column one of its columns. The subquery reads a `WITH` result in memory, compared any way an expression over rows in memory can be, or a table through its indexes, whose conditions compare one of its columns with the outer row's (`e.cat = items.cat`, `e.price < items.price`) as they would a value. - **Its value** is a number, a `FLOAT` (`COUNT`, `SUM`, `MIN`, `MAX`, `AVG` of numbers, or a boolean as 0 or 1), so a correlated `COUNT` reads `10.0` where PostgreSQL gives the integer `10`. One of no rows is `NULL` (`COUNT` gives 0), which ranks last unless `coalesce`d. A `NULL` of the outer row is compared as SQL compares it: `e.price < first.price` holds for no event when the row has no price. - **How it runs.** First the rows ranked (the phases before, or the rows a bounded `ORDER BY` reads), with the columns the subqueries name. The parts of a subquery that do not read the outer row run once (`h` above, and its rows where `h.action = 'buy'`). A subquery whose outer columns meet only equalities ANDed into its `WHERE` (`h.cat = first.cat`) then runs once, grouped by them over the values the rows hold (`h.cat IN (...)`), and a value no group has takes the subquery's value over no rows; any other runs once for each distinct value of the columns it names. Then the ranking sorts the rows, with each row's values, and the plan lines say how much ran: `correlated: 3 subqueries over 1000 rows, 597 values, 3 runs`. - **Over shards** a coordinator runs the steps before, and the subqueries over the shards' rows, and sends each row's values to the shards inside the plan, by key, so that every shard ranks with the same ones. A plan with them needs the plan feature `correlated`. - **Cost** at 1,000 candidates, measured with `chloedb-correlated-bench` on a cloud VM (4-core Intel Xeon @ 2.10GHz, 16.9 GB, Linux 6.18): 100,000 items in 200 categories, 400,000 events of 2,000 users, a history of 50 events, one thread, 300 requests of each shape. BM25's top 1,000 reranked to 20 took 1.29 ms (mean) without subqueries, and reading the history added 1.67 ms. A subquery added, over the rerank alone (with the history's read): | subquery | values | runs | added, mean | |---|---|---|---| | by category, over `h` | 199 | 2 | 4.90 ms | | three by category, over `h` | 596 | 6 | 8.14 ms | | by category, over the events table | 199 | 2 | 4.09 ms | | by item, over the events table | 992 | 2 | 21.6 ms | | by embedding (`dot(h.emb, first.emb)`), over `h` | 992 | 992 | 10.5 ms | A grouped run costs about what reading the candidates' values does. A subquery that runs once per value costs about 10 µs a run over rows in memory, and one grouped by a key reads an `IN` list as long as the candidates (`e.item IN (...)`), which is most of its cost. A second run gave the same numbers within 0.4 ms (`chloedb/results/correlated/`). #### Features: the values a ranking read A ranking expression that scores each row by itself is a column, with the value the ranking computes for the row, and `features()` lists the inputs of the query's ranking, to log beside what users chose and train a model on (Vespa's match-features): ```sql SELECT id, score(), features() FROM docs ORDER BY bm25(body, :t) * (1 + 0.2 * coalesce(rating, 0)) DESC LIMIT 10; -- columns: id, score(), bm25(body, :t), rating, bm25(body, :t) * (1 + 0.2 * coalesce(rating, 0)) SELECT id, bm25(title, :t) AS title_bm25, ln(1 + rating) AS r, year / 1000 FROM docs ORDER BY similarity(emb, :q) DESC LIMIT 10; ``` - **`features()`** stands for one column per input, each once, named by its SQL text: every leaf of the ranking (a score such as `bm25(body, :t)` or `similarity(emb, :q)`, a column, `decay(..)`, `hops()`), the first phase's first, then each phase's expression that scores a row by itself and is not a leaf. With [rerank phases](#rerank-phases) it lists every phase's. An expression with a set function (`tmm()`, `minmax()`, `zscore()`, `rank()`), `rrf` or a weighted sum ranks rows against each other, so it is not a column: its inputs are, and `score()` is its value. A ranking by `distance(..)` lists the `similarity(..)` it ranks by. `features()` takes no alias and needs an `ORDER BY`. **Changed:** `features()` refused a ranking with `tmm()` or `zscore()` before (`minmax()` it took), and so did the rank log and Explain's hits for one. - **A selected expression** may use anything a ranking expression does but the set functions: `bm25`, `similarity`, `decay`, columns, numbers, arithmetic, `ln` and the other functions, `CASE`. Its value is the ranking's, bit for bit: a row a `bm25`'s terms miss scores 0, and one without a value is `NULL`. `ORDER BY 2` ranks by the second column when it is one. - **Over shards** a feature is one database's value: a coordinator sums the shards' BM25 statistics of the terms any column scores, and its fetch round computes the columns for the page alone, with those statistics. - A plan with such a column needs the plan feature `rank_features`. From Python, `features()` goes in `select`, and so does any expression of scores (`select("id", bm25("title", q).alias("t"))`); Python names a feature as it writes the expression. #### Rank profiles: a ranking kept with its table A ranking used by many queries can be kept with its table under a name, as a search engine keeps a rank profile, and queries rank by the name: ```sql CREATE RANK PROFILE recall ON memories AS WITH top AS (SELECT * FROM memories ORDER BY bm25(body, :q) DESC LIMIT 100) SELECT * FROM top ORDER BY bm25(body, :q) * (1 + :imp * importance) DESC WITH (imp => 0.2); SELECT id, score() FROM memories WHERE kind = 'fact' ORDER BY rank_profile('recall', q => :q) LIMIT 10; CREATE OR REPLACE RANK PROFILE recall ON memories AS ...; -- replaces it DROP RANK PROFILE IF EXISTS recall ON memories; -- ON may go when one table has it ``` - **The ranking** is a query of the table that ranks every row: `SELECT * FROM table ORDER BY expression` (any [ranking expression](#ranking-expressions), or a numeric column with `ASC` or `DESC`; `CREATE` checks that every column it names is the table's), or [rerank phases](#rerank-phases) over it. It has no `WHERE`, and no `LIMIT` after its last ranking: the query that ranks by it filters and cuts. `WITH (name => value, ...)` after it gives its parameters defaults: numbers, strings, `TRUE` and `FALSE`. Names are letters, digits and `_`, in any case; `CREATE` refuses a name the table has already, and `CREATE OR REPLACE` replaces it. - **`ORDER BY rank_profile('name', parameter => value, ...)`** is the whole `ORDER BY` of a query of the profile's table, without `ASC`, a `WITH`, a join or `GROUP BY`. The query ranks as if it were written out: its `WHERE` filters the rows the first ranking reads, and its columns, `LIMIT` and `OFFSET` are the last ranking's, so `score()` and [`features()`](#features-the-values-a-ranking-read) work as with the ranking written out. Each parameter of the ranking is the call's argument (a value, or a parameter of the query: `q => :q`), else the profile's default, else the query's parameter of the same name. - **Kept and replicated as writes are**: a profile is logged in its own transaction (numbered where writes are, shipped to replicas), and dropped with its table. A database with a profile needs the format 3 feature `rank_profiles`, which a version of ChloeDB from before profiles refuses by name; once the last profile is dropped and flushed, the database no longer needs it. - **A plan names its profile** and a hash of its definition (`EXPLAIN` shows `rank profile: recall (hash ...)`) and needs the plan feature `rank_profiles`. A database whose profile of that name is another (replaced since, or a shard that missed the change) refuses the plan rather than rank otherwise. Through a coordinator, `CREATE` and `DROP RANK PROFILE` run on every shard, and the coordinator serves the profiles every replica holds alike. #### Ranking models: `gbdt('model', features…)` A gradient-boosted tree model, trained by LightGBM or XGBoost on the [features](#features-the-values-a-ranking-read) a query logged, ranks rows as a ranking expression of them: ```sql SELECT id, score() FROM docs ORDER BY gbdt('docs_ltr', bm25(title, :t), bm25(body, :t), coalesce(rating, 0), year % 6) DESC LIMIT 10; -- as a second phase over BM25's top 200, and a binary model's probability WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :t) DESC LIMIT 200) SELECT id, score() FROM top ORDER BY sigmoid(gbdt('clicks', bm25(title, :t), bm25(body, :t), rating)) DESC LIMIT 10; ``` - **The model** is the file `//gbdt.json` in the models directory, the one embedded fields' models come from (`--models` on a server, `models=` in Python, else `~/.local/share/chloedb/models` (or `~/.local/share/strata/models`, on a machine that has that folder from before the rename; before 0.3.2, always)): LightGBM's `booster.dump_model()` written with `json.dump` (numerical and categorical splits, any missing-value handling, a random forest too), or XGBoost's `booster.save_model("gbdt.json")` (a `gbtree`; categorical splits, multiclass and `dart` are refused). A name is letters, digits, `_`, `-` and `.`. A model is read when a query first uses it and again when its file changes. - **Its arguments are its features**, in the order it was trained on, each any ranking expression of the row (a score, a column, arithmetic); as many as the model reads. A `NULL` feature is a missing value, which goes where the model sends missing values (LightGBM: `NaN`; or 0 under `zero_as_missing`). - **The score is the model's raw one**, the sum of its trees, bit for bit what LightGBM's `predict(raw_score=True)` and XGBoost's `predict(output_margin=True)` give (XGBoost's in `f32`, from its base score): `sigmoid(gbdt(…))` is a binary model's probability. A random forest's score is the sum of its trees, as LightGBM's raw score is. - **Rank it over the top rows of a cheaper ranking.** In a [rerank phase](#rerank-phases) a model is a second phase, which each shard scores on its own rows, one tree at a time over them: a LambdaMART model of 300 trees over BM25's top 100 takes 0.7 to 1.0 ms a query at the median on SciFact, NFCorpus and FiQA, against 0.02 to 0.2 ms for BM25 alone (`chloedb/results/text/bm25_gbdt.json`, a 4-core cloud VM). `ORDER BY gbdt(bm25(…), columns…)` alone is exact, a [rank-safe boost](#rank-safe-boosts) bounded by the leaves each tree can reach from the text score's bound and each column's range; but summed over hundreds of trees such a bound sits well above what rows score, so the top-k loop skips few matches and scores the rest with every tree: 5.5 to 70 ms on the same collections. - **A plan names the model and the hash of its file** (`EXPLAIN` shows `ranking model: docs_ltr (hash …)`) and needs the plan feature `rank_models`. A database or shard whose file of that name is another refuses the plan rather than rank with another model; a plan without a hash runs with the file there. A coordinator scores the shards' rows with the model too, so it needs the same file in its own models directory. - `features()` lists a model's inputs' leaves and then the model's score, and from Python `gbdt("docs_ltr", bm25("title", t), col("rating"))` builds the same ranking. #### Cross-encoders: `cross_encoder('model', fields…, query)` A cross-encoder reads the query and a row's text together and scores how well the text answers it. It costs thousands of times what BM25 does per row, so it reranks the top rows of a cheaper ranking, in a rerank phase of its own: ```sql WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :q) DESC LIMIT 20) SELECT id, title, score() FROM top ORDER BY cross_encoder('ms-marco-MiniLM-L-6-v2', title, body, :q) DESC LIMIT 10; -- mixed with other scores of the row, and a phase after it WITH top AS (SELECT * FROM docs ORDER BY bm25(body, :q) DESC LIMIT 20), ce AS (SELECT * FROM top ORDER BY cross_encoder('bge-reranker-base', body, :q) + 0.1 * coalesce(rating, 0) DESC LIMIT 10) SELECT id, score() FROM ce ORDER BY bm25(title, :q) + decay(published, now(), 2592000) DESC LIMIT 5; ``` A server reranks at most 20 rows a query by default: start it with `--max-rerank 100` to rerank the top 100, as the measurements below do. - **The model** is a Hugging Face directory `/` holding `config.json`, `tokenizer.json` and its weights. A `model.onnx`, any sequence classifier with one label exported to ONNX (int8 ones too, as Hugging Face repositories ship them under `onnx/`, such as `model_qint8_avx512_vnni.onnx`), runs through ONNX Runtime in a server or Python package built with `--features onnx`, which downloads ONNX Runtime's library when it builds and links it in; its rows are sorted by length into batches of 16, so that little of a batch is padding. A `model.safetensors`, a `BertForSequenceClassification` (such as `cross-encoder/ms-marco-MiniLM-L-6-v2`) or an `XLMRobertaForSequenceClassification` (such as `BAAI/bge-reranker-base`) with one label, runs through candle in `f32` in one built with `--features bert` (`accelerate` on a Mac), as BERT embedding models do. A directory with both runs its `model.onnx`; without the feature its weights need, a query by it is refused. `chloedb-server fetch-model ms-marco-MiniLM-L-6-v2-int8` (or `gte-reranker-modernbert-base-int8`, a ModernBERT model) downloads an int8 export ready to run. A model is read when a query first uses it and again when one of its files changes. `builtin:overlap` needs no files: the share of the query's distinct words the text holds, for tests and demos. - **A model served elsewhere** is called over HTTP, a batch of rows a request (feature `hosted`, on by default), for models too large or slow for the server's CPU: a provider's by name, `cohere/rerank-v3.5`, `voyage/rerank-2.5` or `jina/jina-reranker-v2-base-multilingual`, with the key in `COHERE_API_KEY` (or `CO_API_KEY`), `VOYAGE_API_KEY` or `JINA_API_KEY`; or a server of one's own that a directory `/` names in an `endpoint.json`, such as Hugging Face TEI on a GPU (`{"api": "tei", "url": "http://gpu:8080/rerank"}`), or vLLM, Infinity or LiteLLM (`"api": "vllm"`, `"infinity"` or `"litellm"`, with a `base_url`; they answer at `/rerank` in Cohere's shape). `endpoint.json` takes the keys an [embedding model's](server.md#embedded-vector-fields) does that apply (`url` or `base_url`, `model`, `key_env`, `key_header`, `headers`, `batch`, `max_chars`, `concurrency`, `retries`, `timeout_s`), and `COHERE_BASE_URL`, `VOYAGE_BASE_URL` or `JINA_BASE_URL` sends a provider's requests to a server of its API. A request carries 1,000 rows at most (TEI's default batch, 32, for a server of one's own), four are sent at once, a rate limit or a server's error is tried twice more (pauses of at most 5 s; a request times out after 10 s), and a refused key, a server that keeps failing or an answer that misses a row fails the query. A provider's score is its `relevance_score`, between 0 and 1; TEI's is the logit (`raw_scores`), as a model run here gives it. A row with no text is not sent, and gets no score. The plan's hash is of the endpoint (its API, URL and model, not its key), so a plan made with one server is refused by another. - **The text** is the values of the fields named, stored TEXT or KEYWORD fields, joined by a space (`NULL`s left out, each value of a list), and the query is the last argument, a string or a parameter. Query and text together are cut to 256 tokens (or the model's length, if shorter), the longer of the two first, as Hugging Face's tokenizers cut a pair; a `cross_encoder.json` in the model's directory, `{"max_tokens": 512}`, sets another length. - **A language model** grades each row instead: `anthropic/` (a Claude model, such as `anthropic/claude-haiku-5-5`, its key in `ANTHROPIC_API_KEY`), `openai/`, or a chat server of one's own that an `endpoint.json` names with `"api": "chat"` (OpenAI's `/chat/completions`, as vLLM, Ollama, LM Studio and LiteLLM serve it; `base_url` is its `/v1`) or `"api": "anthropic"`. Each row is its own request, eight at once (`concurrency`), with UMBRELA's prompt (the one [`/v1/judge`](server.md#relevance-judgments) asks): the model reads the query and the row's text and answers a grade from 0 (nothing to do with the query) to 3 (the exact answer), which is the row's score. A model costs a request a row and about a second each, so it reranks a few dozen rows at most, and gives many rows the same grade: add the first phase's score to break ties (`cross_encoder('anthropic/claude-haiku-5-5', body, :q) + 0.01 * bm25(body, :q)`). An answer without a grade leaves the row without a score, and it ranks last; a request times out after 30 s. - **The score is the label's logit**, what sentence-transformers' `CrossEncoder.predict` gives with an identity activation (`sigmoid()` of it is the probability for a model trained with one), equal to PyTorch's within 1e-5. A phase may mix it with other scores of the row (`cross_encoder(…) + 0.1 * rating`), and phases after it rerank the rows it kept. - **It runs once per query, in a global phase**: on a database over the rows the phase before it kept, and through a coordinator once on the coordinator, which reads the text of the rows its shards ranked best in the fetch round of query then fetch and scores them; shards need no model. A cross-encoder is refused as the first ranking (rerank a cheaper ranking's top rows), as a column, and among `features()`. - **Its cost is per row and per token**: on four cores `ms-marco-MiniLM-L-6-v2` takes about 50 ms a row of 256 tokens in `f32` through candle, and its int8 export through ONNX Runtime about 20 ms. BM25's top 20 takes 0.9 to 1.0 s at the median on SciFact, NFCorpus and ArguAna in `f32` and 0.37 to 0.43 s in int8, and the top 100 4.4 to 4.8 s and 1.8 to 2.0 s, where BM25 alone takes 0.1 to 1 ms; cut at 512 tokens, as before, the top 20 took 1.3 to 1.6 s ([results](results.md#cross-encoder-reranking), a 4-core cloud VM). `--max-rerank` on a server (default 20, a quarter of the default deadline at p99 in `f32`) refuses a phase that would score more rows, and the query's deadline (`--timeout-ms`, 5 s) is checked between batches of 16 rows. Its layers run on the threads the queries share (one per core), so reranks running at once take turns on the cores rather than each starting a thread per core, and queries that ask for a model not yet open wait for one of them to open it. - **Whether it helps depends on the collection**: reranking BM25's top 100 by `ms-marco-MiniLM-L-6-v2`, a model trained on web questions, raises NFCorpus's nDCG@10 from 0.329 to 0.352, leaves SciFact's where it was (0.687 against 0.691) and lowers ArguAna's from 0.362 to 0.312; see [the results](results.md#cross-encoder-reranking). Measure it on your own queries before paying for it. - **A plan names the model and the hash of its files** (FNV-1a of the three, or of a served model's endpoint; `EXPLAIN` shows `ranking model: … (hash …)`), with the plan feature `rank_models`, as for [`gbdt`](#ranking-models-gbdtmodel-features). From Python, `.order_by(bm25("body", q)).rerank(cross_encoder("ms-marco-MiniLM-L-6-v2", ["title", "body"], q), 100)` builds the same query. #### The rank log: what each query served A ranking is trained on what it served. A query run with a log writes one row per row it answered to a log table, with the values its ranking read as it computed them, so a model trained later sees what serving saw, however the tables change in between: new rows that move BM25's statistics, counters that grow, rows deleted. ```sql -- what the first query logged to it makes (rank_log unless the log names another) CREATE TABLE IF NOT EXISTS rank_log ( id KEYWORD PRIMARY KEY, -- '#' request KEYWORD NOT NULL, ts TIMESTAMP NOT NULL, context KEYWORD, row_key KEYWORD NOT NULL, position INT NOT NULL, shown BOOL NOT NULL, score FLOAT, features KEYWORD OPTIONS(indexed = false), variant KEYWORD, label FLOAT, query KEYWORD OPTIONS(indexed = false), -- on a request's first row: {"sql": ..., "params": ...} propensity FLOAT, prefix_propensity FLOAT, -- the chance the row was shown where it was policy KEYWORD OPTIONS(indexed = false), took_ms FLOAT -- on a request's first row ) OPTIONS(cluster_by = 'context'); -- a label written later: a judge's grade, an agent citing the row UPDATE rank_log SET label = 3 WHERE request = :r AND row_key = :k; ``` ```sh curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) * (1 + 0.1 * coalesce(rating, 0)) DESC LIMIT 10", "params": {"t": "mrna vaccine"}, "log": {"context": "u42", "variant": "b", "candidates": 50}}' # {"columns": ["id", "title"], "rows": [...], ..., "request": "9f0c...", "logged": {"rows": 50, "seq_no": 812}} ``` - **A logged query** is one `SELECT` ranked by an `ORDER BY` ([rerank phases](#rerank-phases) and [rank profiles](#rank-profiles-a-ranking-kept-with-its-table) included) of a table with a primary key: `"log"` in the body of `POST /v1/query` or `/v1/sql` (`true`, or an object of options), `db.query_logged(sql, params, context=...)` in [Python](python.md#the-rank-log), `Db::query_logged` in Rust. It runs with `score()` and [`features()`](#features-the-values-a-ranking-read) added to its columns, answers with the columns it asked for and the request's id (`request`), and writes its rows to the log in one transaction once it has answered: a logged query costs a write. - **Options**: `context`, whom the request served (a user, a session, a query class), which the export reads events by; `request`, the request's id (a random one when left out; logging a request's id again overwrites its rows at the same positions); `variant`, the client's name for the ranking that served (an A/B arm); `candidates`, a number of rows from the query's `OFFSET` to log, more than its `LIMIT` returns, those past the `LIMIT` logged as not shown (unshown negatives); `ts`, when it was served (ISO 8601 text or microseconds; now when left out), for replaying past traffic; `table`, another log table; `interleave`, a second ranking to show in the same list ([interleaving](#interleaving-two-rankings)); `explore`, a policy that shows the top rows in a randomized order and logs each row's chance ([exploring](#exploring-a-log-that-evaluates-rankings-it-never-served)). - **A row** holds its request, time and context, the key of the row served (`row_key`, as text), its `position` from 0 (the `OFFSET` included), whether it was `shown`, its `score()`, and `features`: a JSON object of each `features()` column, named by its SQL text, whose numbers read back to the bits the ranking computed. The request's first row also keeps its `query`: the SQL as the client sent it and its parameters as they were bound (a vector as `{"$vector": [...]}`, a time as `{"$ts": microseconds}`), which the [relevance autopilot](#the-relevance-autopilot) replays. A table made by hand serves as a log if it has these columns, of these types (with `retain = '90 days'`, say); it may leave out `query`, and then keeps no query (a log made before the column was added: `ALTER TABLE rank_log ADD COLUMN query KEYWORD OPTIONS(indexed = false)`). Each row shown also keeps its `propensity`, the chance the [logging policy](#exploring-a-log-that-evaluates-rankings-it-never-served) put it where it was shown (1 for a query that does not explore), and the request's first row its `policy` (as JSON, `{"policy": "none"}` when it does not explore) and `took_ms`, how long the query took before its rows were written. A log made before these columns logs as it did and refuses `explore`, naming the statement that adds them: `ALTER TABLE rank_log ADD COLUMN IF NOT EXISTS propensity FLOAT, ADD COLUMN IF NOT EXISTS prefix_propensity FLOAT, ADD COLUMN IF NOT EXISTS policy KEYWORD OPTIONS(indexed = false), ADD COLUMN IF NOT EXISTS took_ms FLOAT`. - **Through a coordinator** the query is the coordinator's, so the values are one database's ([features over shards](#features-the-values-a-ranking-read)), and the rows go to the shards their keys place them on; the first logged query makes the table on every shard. A replica refuses a logged query, the log being a write; a primary ships the table it makes to its copies, as it ships the rows. A shard's query (`"shard": true`) is not logged. - **Cost.** Computing the values is nearly free, since the ranking computes them anyway; the write is the cost. On a 4-core cloud VM over HTTP, with 100,000 documents and one client, a query took 1.87 ms at the median plain, 1.85 ms with its values added and 4.33 ms logged (7.81 ms logging 100 candidates); writing the same ten rows alone through `/v1/write` took 1.97 ms. Without the disk's flush (`--no-sync`) the logged query took 3.50 ms: the sync is a third of the log's cost here, and the rest is the write itself. Four clients got 1,620 plain and 670 logged queries a second. A row took 152 bytes in the segments (an Intel Xeon @ 2.10GHz, 16.9 GB, Linux 6.18; `chloedb-server/results/rank_log/vm.json` and `vm-no-sync.json`, from `chloedb-rank-log-bench`). The export read 70,000 records a second, each with a history of 20 events and a label. #### Exporting the log for training The export reads a log table back from one snapshot, one record per logged row, with what happened around it as of its time, from a table of events (a user's views, clicks, purchases): the context's last events before the row (its history, for a sequence model), and a label from the events on the row's key after it, within a window. ```sh curl -s localhost:7700/v1/rank_log/export -H 'content-type: application/json' -d '{"events": {"table": "events", "user": "usr", "item": "item", "time": "ts", "action": "action"}, "history": 20, "window": "30 minutes", "grades": {"click": 1, "buy": 3}, "since": "2026-10-01"}' # {"id": "9f0c...#0", "request": "9f0c...", "ts": 1793338200000000, "context": "u42", "row_key": "d17", "position": 0, "shown": true, # "score": 7.31, "variant": "b", "label": 3.0, # "features": {"bm25(body, :t)": 6.09, "bm25(body, :t) * (1 + 0.1 * coalesce(rating, 0))": 7.31, "rating": 2.0}, # "history_items": ["d3", "d9", ...], "history_times": [...], "history_actions": ["view", "click", ...]} ``` - **Records** come as NDJSON from `POST /v1/rank_log/export`, as a list of dicts from `db.export_rank_log(...)` in Python, and from `Db::export_rank_log` in Rust, context by context, each context's rows in the order they were served. Times are microseconds since the epoch. `since` and `until` keep the rows served in `[since, until)`, and `table` names another log. - **`events`** names a table, its column of contexts (`user`, `KEYWORD` or `INT`), of the rows the events were about (`item`), of when they happened (`time`, a `TIMESTAMP` or an `INT` of microseconds), and optionally of what they were (`action`). `OPTIONS(shard_by = 'usr', cluster_by = 'usr')` keeps each user's events together, on one shard and in few pages. - **History**: with `history` set to n, the context's last n events before the row's time, oldest first. **Label**: with `window`, a period (`'30 minutes'`) or seconds, the best grade among the context's events on the row's key in the window after the row's time, `grades` giving each action's (an event whose action has none is not a label; without `grades` every event grades 1), and 0 when there is none. A label written on the row wins. A row without a context has no history and no label but its own. - **As of the row's time**, by the events' own times: an event timed before a row is in its history even when it arrived after the row was served, which a query at the time could not have seen. The features are the values served, never recomputed. - **Through a coordinator** the export and the interleaving credit run their queries over every shard, each read whole by a scroll, rather than from one snapshot ([cluster limits](cluster-limits.md)). Logs placed by context (a hand-made log with `context KEYWORD NOT NULL` and `shard_by = 'context'`) and events placed by user then give each shard every row and event of its contexts. #### Interleaving two rankings An A/B test shows each user one ranking and compares the users; interleaving shows each user both, in one list, and asks which ranking's rows the user acted on. Each request sets the two side by side for the same user and the same query, so it tells two rankings apart with ten to a hundred times fewer requests than an A/B test of the same two (Chapelle et al., "Large-scale validation and analysis of interleaved search evaluation", TOIS 2012). ```sh curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) DESC LIMIT 10", "params": {"t": "mrna vaccine"}, "log": {"context": "u42", "interleave": {"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) * (1 + 0.1 * coalesce(rating, 0)) DESC LIMIT 10", "variants": ["bm25", "rated"]}}}' # {"columns": ["id", "title"], "rows": [...], "request": "9f0c...", "teams": ["rated", "bm25", "bm25", "rated", ...], "logged": {"rows": 10, ...}} curl -s localhost:7700/v1/rank_log/interleaving -H 'content-type: application/json' -d '{"events": {"table": "events", "user": "usr", "item": "item", "time": "ts", "action": "action"}, "window": "30 minutes"}' # {"pairs": [{"variants": ["bm25", "rated"], "requests": 4120, "acted": 1630, "wins": [690, 820], "ties": 120, "delta": -0.040, "p": 0.00089}], "took_ms": 61.3} ``` - **The list** is team draft (Radlinski, Kurup and Joachims, CIKM 2008): both queries run, on one snapshot, and in each round the ranking with fewer rows in the list, or a coin's choice when they have as many, adds its best row not yet in it, up to the logged query's `LIMIT`. A row both rankings hold goes to the one that took it. The coin is seeded by the request's id, so the same request draws the same list. When one ranking runs out, the other's rows fill the list for neither team. `teams` in the answer names each row's ranking; show the rows, not the teams. - **The second ranking** is a `SELECT` of the same table answering the same columns, with the same parameters. Both need a `LIMIT` and no `OFFSET` (a draft is of a first page), and `candidates` and `variant` are left out: each row shown is logged with its own ranking's score and features and its team's name as its `variant` (`variants`, `["a", "b"]` unless named). - **The credit**: `POST /v1/rank_log/interleaving` takes the export's body and reads the log as the export does, labels included. A request is interleaved when its shown rows carry two variants, and it goes to the team whose rows its user acted on more (a label above 0), or is a tie; a request nobody acted on counts for neither. `delta` is Chapelle et al.'s Δ, (wins of the first + ties / 2) / requests acted on − 0.5, above 0 when the first ranking (by name) is preferred; `p` is the two-sided sign test of the wins, ties left out. `Db::interleaving_credit` gives the same in Rust, and the command center's Recsys eval draws it. #### Exploring: a log that evaluates rankings it never served A log of what one ranking served says little about another: a row it never showed was never clicked, and a row it always put first was clicked partly for being first. Off-policy evaluation asks what another ranking would have earned from the clicks the log holds, by weighting each by how likely the serving policy was to show it there (inverse propensity scoring and the estimators built on it: Li et al., "Offline evaluation of ranking policies with click models", KDD 2018; Joachims et al., "Unbiased learning-to-rank with biased feedback", WSDM 2017). Those estimates are only as good as the chances logged, and a ranking that always serves the same list in the same order has a chance of 1 or 0 for every row, which weights nothing. With `explore`, a logged query shows its top rows in a randomized order drawn by a policy, and logs each row's chance exactly. ```sh curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"sql": "SELECT id, title FROM docs ORDER BY bm25(body, :t) DESC LIMIT 10", "params": {"t": "mrna vaccine"}, "log": {"context": "u42", "explore": {"policy": "softmax", "tau": 0.5, "top": 20}}}' # {"columns": ["id", "title"], "rows": [...], "request": "9f0c...", "propensities": [0.61, 0.28, 0.33, ...], "logged": {"rows": 20, ...}} ``` | policy | options | what it shows | propensity | |---|---|---|---| | `none` | | the ranking as it is | 1 | | `epsilon` | `epsilon`, `top` (10) | with chance ε the top `top` in a uniform random order, otherwise the ranking | (1 − ε)·[the row's own place] + ε / `top` | | `shuffle` | `top` (10) | the top `top` in a uniform random order | 1 / `top` | | `swap` | `top` (10) | the first row swapped with a uniform place up to `top`, itself included | exact, per place | | `softmax` | `tau`, `top` (20), `by` (`score`) | the top `top` drawn one place at a time by Plackett–Luce, row i with weight exp(sᵢ / τ) | exact: per place by a one-dimensional integral, the list's prefix in closed form | - **The draw** takes the ranking's first `top` rows (the query's `LIMIT` is raised to `top` when it is smaller, and `candidates` adds rows past them), orders them by the policy and answers the query's `LIMIT` of them: those are shown, the rest are logged as not shown. A query explores its first page only: it needs a `LIMIT` and no `OFFSET`, and is not also interleaved. `softmax` reads each row's `score()` (`by: "score"`, so τ is in the score's units; a row without a score is refused) or its rank (`by: "rank"`, sᵢ = −ln(i + 1), a weight of (i + 1)^(−1/τ) whatever the scores' scale). `swap` is Joachims et al.'s intervention, which measures position bias at little cost to users; `softmax` is the stochastic policy that evaluating any other ranking needs, since every row of its top has a chance at every place. - **The chances**: `propensities` in the answer are the shown rows', in order, and each row's `propensity` in the log is the chance the policy put that row at that place. A row's `prefix_propensity` is the chance of the list down to it: of that row at that place and every row above it where it was, which a cascade estimator weights by. `softmax`'s per-place chance is the integral of its Gumbel form, ∫₀¹ P(k of the other rows' Gumbels beat this row's | v) dv, computed by tanh-sinh quadrature to within 1e-6 (1e-9 for weights less than a million times apart) and kept for the last 16 lists a thread drew; the other policies' are closed forms. The request's first row keeps the policy with its options (`policy`). - **The same request draws the same list**: the draw is seeded by the request's id, as interleaving's coin is, so replaying a logged request checks itself, and a client that names its requests by user and query shows one user the same list until the ranking's rows change. Through a coordinator the draw is the coordinator's, over the merged ranking: three shards draw what one database draws. - **Cost**: the rows past the `LIMIT` and up to `top` are logged too, as `candidates` are, so a wider `top` is a bigger write; the draw itself reads only the scores the ranking computed. #### The relevance autopilot The autopilot reads the queries the rank log kept, proposes new numbers for the [rank profile](#rank-profiles-a-ranking-kept-with-its-table) they rank by, and shows the measured before and after on the database's own data before anything changes. ```sh curl -s localhost:7700/v1/relevance/autopilot -H 'content-type: application/json' -d '{"profile": "recall", "since": "2026-11-01", "judge": true}' # {"report": {"verdict": "propose", "reason": "held-out nDCG@10 0.412 to 0.447 (+0.035, 95% interval +0.019 to +0.052): 61 queries better, 12 worse (sign test p = 0.000)", # "statement": "CREATE OR REPLACE RANK PROFILE recall ON docs AS SELECT * FROM docs ORDER BY bm25(body, :q) + 0.4 * bm25(title, :q) DESC", # "changes": [{"knob": "0.05 * bm25(title, :q)", "from": 0.05, "to": 0.4}], "snapshot": 81231, # "held_out": {"queries": 140, "before": 0.412, "after": 0.447, "better": 61, "worse": 12, "p": 0.0, "ci": [0.019, 0.052]}, # "latency_ms": {"before": {"p50": 1.9, "p95": 4.1}, "after": {"p50": 1.9, "p95": 4.3}}, "holes": [...], ...}, # "proposal": "6932a1f0-9e1b...", "judged": {"rows": 184, "model": "...", "errors": []}} curl -s -X POST localhost:7700/v1/relevance/proposals/6932a1f0-9e1b.../apply ``` (The numbers above show the shape of an answer; they were not measured.) - **The workload** is each distinct query (its SQL and parameters, named by a `qid`) that a logged request asked with `ORDER BY rank_profile(...)`, the most recent first (`max_queries`, 500), logged since `since`. The profile is the one most of them rank by unless `table` and `profile` name one. The autopilot tunes a profile because a profile is what a proposal can change; a query that ranks by an expression of its own is left out. - **Grades** are the rank log's labels (a row's mean over the query's requests) and the judgments table's, `relevance_judgments` unless `judgments` names another, which win for the same row: `{id: '#', qid, query, row_key, grade, source, ts}`, grades 0 to 3 (UMBRELA's scale and the relevance lab's). A query needs a row graded above 0 to count, and the autopilot says nothing with fewer than `min_queries` (20) such queries. - **The search** is coordinate ascent (Metzler and Croft, 2007) over the profile's numbers: the defaults of its parameters (`WITH (w => 0.2)`) and the numeric literals of its rankings' `ORDER BY` expressions, 0 and 1 left out as structure. Each number is tried at 2, 0.5, 1.25, 0.8, 4 and 0.25 times its value, and a step is taken when the training queries' mean nDCG@k (`k`, 10) rises, until no step helps or `budget` (60) candidates have been replayed. A proposal is the profile with some numbers moved, nothing else. - **The proof**: every query reads one snapshot (`snapshot` is its sequence number), so both rankings see the same rows and the same statistics. The share `held_out` (0.3) of the graded queries, picked by a seeded hash of their `qid`, is kept out of the search, and the verdict is drawn from those alone: `propose` when their mean nDCG@k rose by more than `min_gain` (0.005), more of them were made better than worse and the sign test of the two says so at `alpha` (0.05) (a few queries up by much and more down by a little is `not_significant`, though its mean rose), and the 95th percentile of the queries' time did not grow by more than `max_slowdown` (1.5 times, beyond 2 ms). Otherwise `no_change`, `no_gain`, `not_significant`, `slower`, `too_few_judged` or `no_workload`, each with a `reason`. The report has the training, held-out and overall measures, a bootstrap interval of the held-out change, each query's nDCG both ways, and the share of the top k that was graded. With the same data and `seed` a report is made again the same. - **Rows no one graded** gain nothing, which favours the ranking now (its rows are the ones people saw and graded). The report lists them (`holes`, `max_holes`, 200); with `"judge": true` the server has Claude grade them first (UMBRELA's prompt, as `POST /v1/judge` does; the server's `ANTHROPIC_API_KEY` or `api_key`), writes the grades to the judgments table with source `claude`, and measures again. - **Proposals** are kept in `relevance_proposals` with the report (`keep`, true): `GET /v1/relevance/proposals` lists them, `GET /v1/relevance/proposals/:id` gives one with its proof, `POST .../:id/apply` runs its `CREATE OR REPLACE RANK PROFILE` and `POST .../:id/dismiss` closes it. Applying is refused once the profile has changed since the measure (the proof is of another profile: run the autopilot again), and for a verdict other than `propose` unless `{"force": true}`. A proposal's row is not taken at its word: its statement is applied only when it is the profile now with some of its numbers moved (never another ranking, even with `force`), and its proof is made again first, on the log and the grades as they are, with the options it was measured with (kept in the proof as `options`); a proof made again that does not propose it is refused unless `{"force": true}`. Running, applying and dismissing need an admin key, and so does any write to `relevance_proposals` and `relevance_judgments` (a write key's answers 403 `scope_refused`). The command center's Labs have it as Relevance autopilot. - **In Rust**: `Db::autopilot(&Options)` gives the report and reads only; `Db::keep_proposal`, `Db::apply_proposal` and `Db::add_judgments` write. A coordinator does not run it, since its shards hold a snapshot each: run it on a single server or on each shard's server. #### Sequence models: `encode('model', history)` A sequence model reads what a user did, newest first, and gives a vector in the space of an item field, so that the items it ranks first are the ones the user is likely to want next: ```sql -- the next item for a user, from their last 200 events SELECT id, score() FROM items WHERE NOT id IN (SELECT item FROM events WHERE usr = :u) ORDER BY similarity(emb, encode('next', (SELECT item, action, ts FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 200), now => :now)) DESC LIMIT 10; -- as a feature of a ranking, next to the text's WITH top AS (SELECT * FROM items ORDER BY bm25(title, :q) DESC LIMIT 200) SELECT id, score() FROM top ORDER BY bm25(title, :q) + 2 * coalesce(dot(emb, encode('next', (SELECT item, ts FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 200))), 0) DESC LIMIT 10; ``` - **The history** is a subquery of the user's events, newest first: its first column is an item's primary key in the model's table, then optionally what the event was (a text column: `view`, `buy`, a rating) and when (a `TIMESTAMP`, or a number of microseconds since the epoch, as the [rank log's export](#exporting-the-log-for-training) writes them). With two columns the second is the time when it is a `TIMESTAMP` and the action when it is text; a number there is refused, since it could be either, so give microseconds as the third column (`SELECT item, NULL, micros`). Order it by time, descending: a row newer than one above it is an error rather than a history read backwards. Of its rows whose item has a vector, the model reads the newest, up to the length it was trained on, as training reads a history. `now =>` is the time of the request (a `TIMESTAMP`, microseconds or ISO 8601 text; the clock's by default): the time since the newest event is part of what the model reads. - **Where it goes**: `similarity(field, encode(…))` ranks the field's nearest items (the dot product with the model's vector: a search of the field's index, its best scored exactly, as [`maxsim`](#maxsimfield-vectors-several-query-vectors) runs one), `maxsim(field, encode(…))` the same as one query vector, and `dot(field, encode(…))` is a number in any ranking expression. A user with no events has no vector: `similarity` and `maxsim` then return no rows, and `dot` is `NULL`. The history runs once a query, however often `encode` appears in it. - **The model** is a small causal transformer (SASRec's): each event is its item's vector, projected, plus a learned vector for its action, for the time until the next event (in powers of two of seconds) and for its position; two layers of attention over the events, each seeing only the ones before it, then the last event's output, projected into the item field's space and normalized. It is the directory `//` (`config.json`, `model.safetensors` and `items.safetensors`), in the models directory [`gbdt`](#ranking-models-gbdtmodel-features)'s files come from. The config names the table and the vector field the model was trained on and their dimension: a database without that field, or with one of another dimension, refuses the model, and so do `similarity` and `maxsim` over another field. `items.safetensors` holds the item vectors it was trained with, and is part of the model's version (its hash): a history whose items have other vectors in the field is refused, naming one, since the model's vector would be in a space it never saw. An item the file does not list (one added since) is read with the field's vector. - **Training** is `chloedb.train.sequence` in Python, with PyTorch (`pip install torch`), from a table of events, the rank log's export, or lists of `(item, action, time)`: ```python import chloedb, chloedb.train db = chloedb.Database.open("shop.chloedb") out = chloedb.train.sequence(db, "next", table="items", field="emb", events={"table": "events", "user": "usr", "item": "item", "action": "action", "time": "ts"}, learn_items=True) chloedb.train.write_vectors(db, "next") # with learn_items, the items' learned vectors into items.emb ``` It trains next-item prediction over each user's events, with every item in the field (`negatives="all"`) or the other targets of a batch (`"in_batch"`, for many items; with `logq=True` and `uniform_negatives=n` it no longer learns to rank popular items low) as the negatives, and writes the model where `models=` says (the models directory by default), with the item vectors it was trained with. With `learn_items=True` the item vectors are trained too, starting from the field's: `chloedb.train.write_vectors` writes them into the field, changing nothing else of each row, and until then `encode` refuses the model. Otherwise the field's vectors are kept as they are and only the model learns. - **Equal to PyTorch's**: ChloeDB's vector is the one the PyTorch module gives for the same history, within 2·10⁻⁵ (`chloedb/tests/sequence.rs`), and the items a query ranks are the ones PyTorch's vector ranks. - **How well it ranks**: on MovieLens-1M and Amazon Beauty, leave-one-out over every item as SASRec is measured, a model of two layers that reads items only has Recall@10 0.278 and 0.066 (NDCG@10 0.159 and 0.041). That is above the original SASRec's published 0.250 and 0.061, but below SASRec trained the same way as this model, with cross-entropy over every item (SASRec+, 0.315 on MovieLens), and on Beauty below counted transitions from the same events ([`chloedb.next_items`](next-items.md), 0.069): good, not the best published. Reading times too, it has 0.319 and 0.077. Both MovieLens runs stopped at a time limit while still improving. ChloeDB's answers equal PyTorch's on every user ([`results/sequence`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/sequence), with the protocol and the published numbers), and CI checks ranking quality on MovieLens-1M against popularity and item-kNN baselines and ChloeDB's other sources (`chloedb/results/sequence/gate.py`): there a model trained for an hour has Recall@10 0.306, `ppr` over what came after what 0.242, counted transitions 0.211 and item-kNN 0.069. - **What it costs**: the model alone, on one thread of a cloud VM's Xeon at 2.80 GHz, takes 0.09 ms for 10 events, 0.28 ms for 50 and 1.5 ms for 200 (p50); the whole query, reading the history and searching the field, 0.6 to 0.7 ms on Beauty's 50 events and 2 to 3 ms on MovieLens's 200. Keep `max_len` as short as the ranking allows. - **A plan names the model and the hash of its files** and needs the plan feature `encode`; a database or shard whose files of that name are others refuses it. A coordinator runs `encode` itself, from the history its shards return, so it needs the model; the shards don't. ### `decay(field, origin, scale, …)`: closeness to a value A numeric column's closeness to `origin`, as in Elasticsearch's decay functions. With `d = max(0, |x − origin| − offset)`, the score is 1 at `d = 0` and `decay` at `d = scale`: | `shape` | score | |---|---| | `'exp'` (default) | `decay^(d / scale)` | | `'gauss'` | `decay^((d / scale)²)` | | `'linear'` | `max(0, 1 − (1 − decay) · d / scale)`, reaching 0 at `scale / (1 − decay)` | Options: `offset => 0`, `decay => 0.5`, `shape => 'exp'`. Rows without a value score 0. `now()` as the origin is the current Unix time in seconds, so `decay(published, now(), 86400)` halves a row's score for each day of age. `decay` ranks on its own, inside `rrf` and weighted sums, and in products. ### Products: boosting relevance by a row's values Multiplying scores boosts relevance by what a row holds: ```sql -- fresh news first: BM25 halved at 30 days old SELECT id FROM news ORDER BY bm25(body, :t) * decay(published, now(), 2592000) DESC LIMIT 10; -- similar products, weighted by their rating SELECT id FROM products ORDER BY similarity(emb, :q) * rating DESC LIMIT 10; ``` A product's factors are scores (`bm25`, `similarity`, `ppr`, `decay`) and numeric columns, one of them a relevance score (`bm25`, `similarity`, a graph's); a product of a row's own values alone (`rating * clicks`, `decay(..) * rating`) is arithmetic, and ranks as the numbers multiply. Candidates are the top `depth` (100) rows of each relevance factor, scored exactly by every factor; a product of one text score and row values (`bm25(..) * decay(..)`, `bm25(..) * rating`) is a [rank-safe boost](#rank-safe-boosts) and ranks every row the text matches. A factor below 0 (a negative similarity) or missing (a `NULL` column) counts as 0, so the product of two negatives cannot rank high. Over shards, each shard returns its factors' raw scores and the coordinator multiplies them, so a split collection ranks like the whole one. ### A column `ORDER BY year DESC` orders by a numeric column. Rows without a value come last in either direction (as in Elasticsearch); `ORDER BY year DESC NULLS FIRST` puts them first. Their `score()` is `NULL`. With no `ORDER BY`, rows come in storage order. With a `LIMIT`, the rows can come from the column's blocks of 128 rows, best block first by its zone map (its largest value for `DESC`, smallest for `ASC`), stopping at the first block whose best value is worse than the k-th row found. A row's filter is checked only when its value can still make the cut, and blocks the filter's own zone maps rule out are never read. So the ten most clicked of the 560,000 ORCAS queries starting with `a` read about 150 of 81,000 blocks, and about 10 when the table is clustered by query (`OPTIONS(cluster_by = 'id')`), where each prefix's rows sit together. The planner keeps the plain scan of the matches when they are a few thousand rows, or under 1 in 64 of the rows the zone maps admit (a rare prefix of an unclustered table, whose k-th best value is low enough that most blocks could hold a better one), and switches to it when the blocks have cost half of what it would (a filter that rejects the best values, `WHERE n < 3 ORDER BY n DESC`); `NULLS FIRST` always scans. Values written in place are read first, so counters kept with `UPDATE ... SET n = n + 1` rank by their current value. ## Typos and synonyms `MATCH` and `bm25` take two options that widen a search beyond the words written: ```sql SELECT id FROM papers WHERE MATCH(body, 'nueral netwrok', fuzzy => 'auto') LIMIT 10; SELECT id, score() FROM papers ORDER BY bm25(body, 'nueral netwrok', fuzzy => 1) DESC LIMIT 10; SELECT id FROM papers WHERE MATCH(body, 'gnn', synonyms => 1) LIMIT 10; ``` - **`fuzzy => 1` or `2`** also matches the indexed terms within that many edits of each word, counting an insertion, deletion, substitution or swap of two neighbouring letters as one edit (optimal string alignment). With an analyzer that stems, the edits are counted on the word as typed: a term matches when it is the stem of a word within that many edits of the typed word, so `choclate` finds `chocol` (*chocolate*, one edit), though its own stem, `choclat`, is three edits from it. **Changed:** the edits were counted between stems before, so a typo that the stemmer cut differently (`choclate`, `vegtable`) found nothing with `fuzzy => 'auto'` or `~`. **`fuzzy => 'auto'`** allows no edits for words of 1 or 2 letters, 1 for 3 to 5 letters and 2 for longer ones. In the `MATCH` grammar, `word~` is `'auto'` for one word and `word~1`, `word~2` choose. A ranked query adds the 50 nearest terms of each word, each weighted `1 − edits / length` (at least 0.1), as Lucene's fuzzy queries do. A word and its typo neighbours share one document frequency, the largest among them, so a rare misspelling scores below the word rather than above it; the expansion is found once per query over every segment's dictionary, so all segments, and the plan line `bm25 expanded with N terms`, agree. Each dictionary is walked as a trie, skipping every run of terms whose start is already too many edits away, rather than tested term by term. A skip inside a block of the front-coded dictionary passes terms by their lengths alone, and each letter's row of edits is worked out for up to 63 letters of the word at once in a machine word (Wu and Manber's bit-parallel matching, with Hyyrö's swap of two letters). For a word of a typed query looked up in the 797,472 analysed terms of ORCAS's 10.4 million queries, the median lookup takes 1.4 ms with one edit and 7.8 ms with two (2.1 and 16.5 ms before the in-block skip and the bit-parallel rows, run just before on the same machine), against 77 and 106 ms testing every term (one thread of a 4-core cloud VM, Intel Xeon @ 2.10GHz; [`results/text/fuzzy-orcas.json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/text), `chloedb-fuzzy-bench`). A query walks a copy of each segment's terms laid out flat in memory rather than the dictionary itself: each term whole, where it ends and how many bytes it shares with the one before, so a step decodes nothing and a jump past a run of terms reads only those shared counts. The copy is made at the segment's first typo query (12 ms for 530,000 terms) and kept while the segment lives, at the terms' bytes plus 5 bytes a term (6.5 MB for 2 million MS MARCO passages, against the dictionary's 4.7 MB). On a shard of 5 million MS MARCO passages in three segments, with the engine comparison's typed queries, a word's walks over the three segments take 9.4 ms against 22.6 ms over the dictionaries, the median typed query 17.0 ms against 29.1 ms, and four clients, one thread each, get 215 typed queries a second against 124 (a 4-core cloud VM, Intel Xeon @ 2.80GHz). - **A ranked query with `fuzzy => 'auto'` and no `MATCH` of its text corrects typos** rather than widening every word, by how many documents hold the word and its neighbours, as a spelling corrector does. A word in at least 1 in 10,000 of the documents, and in 2 or more, is taken as spelled right and gets no neighbours: typos are rare words. Another word gets only its neighbours in more documents than it, each weighted, besides `1 − edits / length`, by the chance it was meant: `x / (x + df)` with `x = df′ × 0.01^edits`, where `df` counts the word's documents and `df′` the neighbour's (a noisy channel that takes each term as likely as its documents and each edit as a 1 in 100 slip). A word in no document is a typo of each of its neighbours (chance 1), and a word nearly as common as its neighbour almost surely means itself. A shard chooses the neighbours by its own counts, the same in a coordinator's statistics round as in its query, and takes the chances from the collection's counts the coordinator sends. `MATCH`, and `bm25` with `fuzzy => 1` or `2`, still widen every word. - **A `bm25` of the text a `MATCH` filters by takes the `MATCH`'s `fuzzy`** (and its `syntax => 'plain'`) when it names none, **and ranks every row the `MATCH` keeps**: `WHERE MATCH(title, 'wireles hedphones', fuzzy => 'auto') ORDER BY bm25(title, 'wireles hedphones') DESC` ranks the rows the filter found, rather than scoring the words as written and dropping them all. The text must be the same (case and outer spaces aside), on the same field, with the same `fuzzy`, taken or given again. Beside such a `MATCH`, `bm25` widens each word as the `MATCH` does, to every indexed term within its edits, rather than correcting it: a word the index has gets its neighbours too, each weighted `1 − edits / length` and, with `'auto'`, by the chance it was meant, so `colour` ranks the names spelt *colour* first and those spelt *color* after them. **Changed:** with `'auto'`, `bm25` left a word the index has as written, so the rows the `MATCH` found by a neighbour scored nothing and dropped out: on 2 names with *colour* and 5 with *color*, `colour` returned 2 of the 7 rows its `WHERE` matched while the misspelling `colur` returned all 7, and on 3,970 recipes `lasagne` returned 2 of 27. - **A typo is looked up as typed too**: under a stemming analyzer such as `english`, a word the index does not hold looks for neighbours of the word as written as well as of its stem, so `wireles` (stem `wirel`, three edits from `wireless`) finds `wireless` one edit away. On 500,477 passages, half of MS MARCO's first million, with the first 300 dev queries, each given a typo as the engine comparison does (two letters of its longest word swapped; 271 queries take one), the typed query's top 10 holds 0.685 of the top 10 that plain `bm25` gives the query as written, against 0.346 widening every word and 0.383 without typo tolerance. On the queries as written, `'auto'` keeps 0.946 of plain `bm25`'s top 10, against 0.340 widening every word. The median typed query takes 10.0 ms, against 48.5 ms before this change and 20.6 ms widening every word on its faster walk and scoring, and the median query as written 0.35 ms (19 ms widening every word), since it walks no dictionary. Through a coordinator over two shards of the million passages (both halves, on the same machine), the median typed query takes 15.8 ms against 112 ms before (p99 30 against 287 ms), and four clients get 137 typed queries a second against 17.7: a shard also walks once per query rather than twice, its statistics round and its query sharing the walk. On BEIR's SciFact and NFCorpus, whose queries are spelled right, nDCG@10 with `'auto'` went from 0.673 and 0.294 widening every word to 0.693 and 0.331, level with plain `bm25` (0.691 and 0.329). The thresholds were chosen on MS MARCO's dev queries, not BEIR's test queries. One segment on a 4-core cloud VM, Intel Xeon @ 2.10GHz; `cargo run --release --example typo_queries`. - **`synonyms => 1`** also matches what the server's synonym list says a word or phrase means. The list is in Solr's format: `laptop, notebook, portable computer` makes each find the others, and `tv => television` makes `tv` find `television` but not the reverse. Both sides are analysed like documents, so `laptops` finds `notebook`. A one-word synonym of a word shares that word's document frequency, as Lucene's synonym queries do; the words of a longer synonym score on their own. [chloedb-server](server.md) loads it from `--synonyms FILE` and edits it at `/v1/synonyms`; from Rust, set `ExecOptions::synonyms`. Without a list, `synonyms => 1` is an error that says so. - **A table's own list** (experimental). `CREATE SYNONYMS ON products AS 'sofa, couch\ntv => television'` gives a table rules of its own, which `synonyms => 1` on that table's searches uses after the server's list. It is kept as the stored function `synonyms_products()`, so it has versions (`CREATE OR REPLACE SYNONYMS` makes the next, `CREATE OR REPLACE FUNCTION synonyms_products FROM VERSION 1` goes back) and a coordinator writes it on every shard; `DROP SYNONYMS [IF EXISTS] ON products` removes it. The rules are checked when the list is made. `GET /v1/synonyms` lists each table's. - **Mined synonyms** (experimental) are proposals for that list, never applied by themselves: `Db::mine_synonyms` or `POST /v1/synonyms/mine` reads the words of a stored text field and embeds the 3,000 most frequent with the model of one of the table's vector fields, proposing pairs whose vectors are close (cosine 0.6 or more) and whose spellings are not alike (a model of word pieces puts `adel` by `adela`; numbers such as `b10` and `b11` still pass); or reads a table of searches (`context`, `ts` in seconds, `text`) and proposes `a => b` where people of two or more contexts rewrote one word of a search into another within a minute. On Wayfair's WANDS (`chloedb-synonyms-eval`, `chloedb/results/text/synonyms_wands.json`, an Intel Xeon at 2.10 GHz, 4 cores), the words of 42,994 product names embedded by potion-retrieval-32M gave pairs such as `kids, children`, `bike, bicycle` and `picture, photo` beside related words that are not synonyms (`animal, dog`, `hawaii, honolulu`), and none of the lists made a measurable difference to nDCG@10 (0.4327 without; 0.4343 with the 33 rules at cosine 0.6, p = 0.31), while the 462 rules at 0.4 lowered it to 0.4231 (p = 0.007). Read the proposals before keeping them. A mining keeps to bounds whoever asks: 200,000 rows read, 5,000 words compared, a cosine of 0.3 or more and 10 proposals a word at most; on a server it takes an admin key. ## Query expansion: `expand` > **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release. `bm25(body, :q, expand => 10)` ranks by the query's words and by the words its first ranking's top 10 rows hold most: pseudo-relevance feedback (RM3). It finds rows that use other words for what the query asks, such as `antibodies` for `vaccines`. ```sql SELECT id, title FROM papers ORDER BY bm25(body, :q, expand => 10) DESC LIMIT 10; SELECT id, title FROM papers WHERE year >= 2023 ORDER BY bm25(body, :q, expand => :n, expand_terms => 10, expand_weight => 0.7) DESC LIMIT 10; ``` - **How.** The query runs in two steps. The first ranks the rows as the call would without `expand`, through the query's `WHERE`, and reads the field's text of the top `n` (`SELECT body, score() FROM papers WHERE year >= 2023 ORDER BY bm25(body, :q) DESC LIMIT 10`). Each of those rows weighs its terms by its share of the scores and each term's share of the row; the `expand_terms` best terms over all of them share `1 − expand_weight` of the weight, and the query's own terms share `expand_weight`. The second step is the query with the call rewritten to those analysed, weighted terms (`bm25(body, 'vaccin^0.85 antibodi^0.03 immun^0.03 ...', syntax => 'terms')`), and the answer's plan lines start with what was added: `bm25(body) expanded from 10 rows of papers with 20 terms: antibodi 0.031, immun 0.029, ...`. - **Options.** `expand` is the rows read, from 0 (no expansion, the call as written) to 100; `expand_terms` the terms added, up to 100; `expand_weight` the query's own share, from 0 to 1. Each may be a parameter (`expand => :n`). A call that expands takes no `min`, `min_rows` or `max_rows`. - **Where.** In a `SELECT` of one table, in its columns, `WHERE` or `ORDER BY`, and in a `WITH` or a subquery of one table. A join is refused, and so is `expand` in a rank profile or a stored function. On a coordinator over shards the first step is an ordinary query of the shards, merged, and the coordinator rewrites the query, so every shard ranks by the same terms. - **Cost.** A second query and the analysis of `n` rows' text: on BEIR's SciFact, NFCorpus and ArguAna the median query took 1.8, 1.7 and 2.9 ms against 0.09, 0.03 and 0.77 ms for plain `bm25` (one core of a 4-core cloud VM, Intel Xeon @ 2.10GHz). - **Quality.** The defaults (10 rows, 20 terms, 0.85) were chosen on SciFact's train and NFCorpus's dev judgements (`chloedb/results/text/bm25_rm3_tuning_*.json`). On the test judgements, nDCG@10 went from 0.691 to 0.693 on SciFact (p = 0.55), 0.329 to 0.346 on NFCorpus (p = 0.0001) and 0.362 to 0.369 on ArguAna (p = 0.0006) (`chloedb/results/text/bm25_rm3.json`, `chloedb-bm25-eval --variants plain,rm3`). Expansion helps most where queries are short and documents use a field's own vocabulary; a setting that keeps less of the query (0.5) lowered SciFact to 0.646, so measure before lowering `expand_weight`. ## Understanding a query's words: `understand` > **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release. `bm25(field, :q, understand => 'boost')` reads the words of a search for the values of the table's `KEYWORD` fields they name (`white`, a colour; `coffee table`, a class) and for ranges of numbers (`under $300`), and ranks by the text and by them: ```sql SELECT id, name FROM products ORDER BY bm25(body, :q, understand => 'boost', understand_fields => 'class, color, price') DESC LIMIT 10; -- :q = 'white coffee table under $300' ranks as -- bm25(body, 'white coffee table') * (1 + 0.25 * (CASE WHEN color = 'white' THEN 1 ELSE 0 END -- + CASE WHEN class IN ('Coffee Tables', 'Coffee & Cocktail Tables') THEN 1 ELSE 0 END -- + CASE WHEN price < 300 THEN 1 ELSE 0 END)) ``` - **What names a value.** A field's values are read with a query (`SELECT color, COUNT(*) ... GROUP BY color`, once per version of the table but at most once a second for a table that takes writes, one query at a time reading it while the others use the one before; on a coordinator once a minute) and analysed as the text field is. Words name a value when they are a run of its words, in its order, that ends with its last word, its head: `coffee table` names `Coffee Tables` and `Coffee & Cocktail Tables`, and `chair` every value that ends in chairs, but `table` does not name `Table Lamps`. A run inside a longer one of another field is that one's (`coffee` of `coffee table` is not the colour coffee). Values of several fields named by the same words are one condition, any of them. - **A check against the rows.** A run counts only when, of the rows whose text holds its words, at least `understand_share` (0.05) hold one of its values: `up` is not the brand Up when almost no row that says up is of it. That is one query a run, counting both (`SELECT COUNT(*), SUM(CASE WHEN .. THEN 1 ELSE 0 END) ... WHERE MATCH(..)`), and runs of the same words and values share one. A text is understood in its first 32 words, and a call uses its first 16 runs, so that a pasted page costs what a query does. - **Ranges.** `under`, `below`, `less than`, `up to`, `over`, `above`, `more than`, `at least`, `between .. and ..`, `since`, `after` and `before` followed by a number (`$1,500`, `2.5`, `10k`) are a range of a numeric field named in `understand_fields`: the one named next to them (`over 10 citations`), a field named for years for a year (`since 2020`), or the only one. Their words leave the ranked text, and a `MATCH` of the same text on the same field too (`WHERE MATCH(body, :q) ORDER BY bm25(body, :q, understand => 'filter')`, every word needed), which would otherwise need `under 100` in a row's text and keep no row. **Changed:** such a `MATCH` kept the words of a range before, so a search that needed every word found nothing when its text named a range. - **Modes.** `'boost'` multiplies the text score by `1 + understand_weight` (0.25) for each condition a row meets, a [rank-safe boost](#rank-safe-boosts). Inside a fusion (`rrf(bm25(.., understand => 'boost'), similarity(..))`, `tmm(..)`, `minmax(..)`), which fuses scores rather than a score times a boost, the boost multiplies the whole fusion instead. `'filter'` also puts each run that names a value in full, and each range, in the `WHERE` (a row without a value of the field is kept). `'off'` is the call as written. Each option may be a parameter (`understand => :mode`). - **Fields.** Without `understand_fields`, every `KEYWORD` field of the table but its key, and a field of more than 20,000 values is left out as a name rather than a facet (its read stops at 20,001); a listed field reads up to 200,000. A call that understands ranks the rows of one table, without a join, and goes with `expand` (it understands first). - `Db::understand(table, field, text, options)` (chloedb-server's [`POST /v1/understand`](server.md)) returns what a text says without ranking: its runs, the values each names, their shares, the ranges and the conditions. - **Measured.** On Wayfair's WANDS (42,994 products, 480 queries; name and description as the text, class, category, colour, style, material, shape and product type as keyword fields) `'boost'` moved nDCG@10 from 0.707 to 0.731 on the odd-numbered queries (p = 0.002), and the classes its words named held the class the query asks for in 262 of 343 queries; `'filter'` lowered it to 0.631, since a product judged relevant often lacks the value or holds another. On Amazon's ESCI (its 8,956 US test queries of the small version and the 164,900 products judged for them; brand and colour listed) `'boost'` moved it from 0.394 to 0.396 (p = 0.007): its titles already hold their brands. Without the check against the rows, ESCI's ranking fell to 0.391. The weight and share were chosen on the even-numbered queries of both. A query took 0.9 to 1.0 ms at the median, against 0.07 to 0.12 ms for `bm25` alone (`chloedb-understand-eval`, `chloedb/results/text/understand_wands.json` and `understand_esci.json`, Intel Xeon @ 2.10GHz, 4 cores). ## Did you mean: correcting a query's words > **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release. `Db::correct(table, field, text)` (chloedb-server's [`POST /v1/correct`](server.md)) returns the text with the words that look like typos of a TEXT field's terms replaced, for a search box to offer as "did you mean": ```json {"text": "mRNA vaccines for neural networks", "changed": true, "words": [{"word": "vacines", "term": "vacin", "to": "vaccin", "to_word": "vaccines", "edits": 1, "chance": 0.86}, ...]} ``` - A word is corrected only when no row holds it: a word some document uses is a word of the collection. Words with digits or capitals inside (`p150n`, `dLNs`) are names and codes, and stay. - Its neighbours are the field's terms one edit away (up to 5 letters) or two (longer), as `fuzzy => 'auto'` finds them, and it takes the one most likely meant if that chance is at least 0.5: the noisy channel of [typos](#typos-and-synonyms), with an unseen word counted as in 0.05 documents, so that a neighbour one edit away must be in 5 or more documents. The edits are counted from the word as typed to the word shown, which is the word nearest it that the analyzer reads as the corrected term (`ifnlammation` gives `inflammation`, `choclate` gives `chocolate` and `wireles` gives `wireless`, not `wirees`). **Changed:** the edits were counted between stems before, so a typo whose stem drifted from the right one's (`choclate`, `vegtable`) had no neighbour, and the word shown was the term with the typed word's ending, which could be no word. - On BEIR's queries with a typo typed in (two letters of the longest word swapped), it corrected 0.75, 0.69 and 0.88 of them back to the words as written on SciFact, NFCorpus and ArguAna (0.73, 0.66 and 0.85 when the edits were counted between stems); of the queries it changed, 0.92, 0.91 and 0.99 were corrected back; and it changed 4.0%, 2.8% and 0% of the queries as written (`chloedb/results/text/bm25_did_you_mean.json`, variant `typed_corrected`). For ranking, `fuzzy => 'auto'` stays better than ranking the corrected text: nDCG@10 0.691 against 0.674 on SciFact, as it widens each word with its likely neighbours rather than choosing one. - A coordinator corrects as one server does, by its shards' document counts summed: the words' own, then, for a word in none, those of its neighbours (each shard's nearest 50 within the edits allowed). ### Times later and earlier: `INTERVAL` ```sql SELECT host, COUNT(*) FROM syslog WHERE ts > now() - INTERVAL '15 minutes' GROUP BY host; SELECT id FROM events WHERE at >= date_trunc('day', now()) - INTERVAL '7 days'; SELECT id, due + INTERVAL '2 days' AS reminder FROM tasks; SELECT TIMESTAMP '2026-01-31' + INTERVAL '1 month'; -- 2026-02-28T00:00:00Z ``` - **`INTERVAL 'text'`** is a length of time: numbers each with a unit, `'15 minutes'`, `'1 day 12 hours'`, `'-2 weeks'`, `'90s'`, or `INTERVAL '15' MINUTE`. The units are `microseconds`, `milliseconds`, `seconds`, `minutes`, `hours`, `days`, `weeks`, `months` and `years`, singular or plural, and `us`, `ms`, `s`, `sec`, `min`, `m` (a minute), `h`, `hr`, `d`, `w`, `mon` and `y`. It is added to a time or subtracted from one; alone it is an error. - **A time written as a value** (`now()`, `CURRENT_TIMESTAMP`, `TIMESTAMP '2026-10-01'`, `CAST('...' AS TIMESTAMP)`, `date_trunc('day', now())`) moved by an interval is one value, computed once for the statement: `ts > now() - INTERVAL '2 hours'` is a range of `ts`, which the index answers, in `WHERE`, `ON` and a join's side alike. Months and years move it on the calendar, a day past the new month's end becoming its last day (January 31 plus a month is February 28 or 29), as in PostgreSQL. - **A column moved by an interval** (`due + INTERVAL '2 days'`) is computed row by row, in microseconds; a month or a year has no fixed number of them, so an interval with months moves only values. A `NULL` time gives `NULL`. - **A number added to a time** written as a value is an error that points to `INTERVAL` (`now() - 3600` could mean seconds or microseconds). Over the rows, a number added to a `TIMESTAMP` column counts microseconds: `at + 3600000000` is an hour later. ## Aggregates ```sql SELECT category, COUNT(*) FROM docs WHERE MATCH(body, 'india') AND year >= 2000 GROUP BY category ORDER BY 2 DESC LIMIT 5; SELECT category, topic, COUNT(*) AS n, AVG(rating), MIN(year), MAX(year), COUNT(DISTINCT source) FROM docs WHERE year >= 2000 GROUP BY category, topic HAVING n > 20 ORDER BY AVG(rating) DESC LIMIT 10; SELECT COUNT(*), SUM(clicks), AVG(rating) FROM docs WHERE MATCH(body, 'india'); SELECT item, MEDIAN(price), PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY price) AS p90 FROM snapshots GROUP BY item HAVING MEDIAN(price) > 100 ORDER BY p90 DESC; SELECT host, COUNT(*) FILTER (WHERE severity = 'error') AS errors, COUNT(*) AS total FROM syslog GROUP BY host ORDER BY errors DESC LIMIT 10; SELECT brand, AVG(price), STDDEV(price), CORR(rating, price) FROM products GROUP BY brand; SELECT customer, STRING_AGG(sku, ', ' ORDER BY sku) AS skus FROM orders GROUP BY customer; ``` - **`GROUP BY`** takes one or more indexed `KEYWORD`, `INT` or `FLOAT` columns, or [parts of times](#parts-of-times-date_trunc-extract-and-strftime) of a `TIMESTAMP` column (`date_trunc('day', at)`), by name, position or alias, which the index groups. A stored `TEXT` column, or a column kept without an index, groups too (`GROUP BY billing_country`, `SELECT DISTINCT billing_country`): its stored values are read with the rows and grouped in memory, as over derived rows, each distinct text its own group (case and spaces count). A multi-valued column puts a row in one group per value, over one table, joined rows or derived rows alike, and so does `SELECT DISTINCT`, which is `GROUP BY` its columns. The rows without a value form the group `NULL`, as in SQL, and `SELECT DISTINCT` lists `NULL` once. - **Aggregates** are `COUNT(*)`, `COUNT(f)`, `COUNT(DISTINCT f)`, `SUM(f)` and `AVG(f)` over numeric columns, `MIN(f)` and `MAX(f)` over numeric or keyword columns, the [percentiles](#percentiles) of numeric columns, and the statistical aggregates below. `COUNT(f)`, `COUNT(DISTINCT f)`, `MIN(f)` and `MAX(f)` of a stored `TEXT` column (or a column kept without an index) count and compare its stored values, read with the rows. Every selected column is a group column or inside an aggregate. Without `GROUP BY` they summarize every row that passes `WHERE`, in one row (`COUNT(*)` 0 and the others `NULL` when none does). - **`FILTER (WHERE condition)`** after an aggregate aggregates only the rows the condition holds for: `COUNT(*) FILTER (WHERE severity = 'error')` counts the errors of each group, beside `COUNT(*)` of all its rows. It is the aggregate of a `CASE` (`COUNT(CASE WHEN severity = 'error' THEN 1 END)`), and any aggregate takes it, in `SELECT`, `HAVING` and `ORDER BY`; a column without an alias is named as written. `FILTER` on a function that is not an aggregate, or on a [window](#window-functions) aggregate, is an error. - **`STRING_AGG(x, separator [ORDER BY …])`** is the values of `x` that are not `NULL`, as text, with the separator (a constant text) between them, in the order of its `ORDER BY` (the rows' order without one), and `NULL` when there are none, as in PostgreSQL. `x` may be any value, a number written as `||` writes it, where PostgreSQL takes text only. The aggregates of one `SELECT` order their values one way: two `STRING_AGG`s with different `ORDER BY`s are refused (compute one in a subquery). It is computed over rows in memory, as over joined rows (over shards, on the coordinator), and takes `FILTER`, but not `DISTINCT` (`STRING_AGG(x, ', ')` over `SELECT DISTINCT x` in a subquery) or `OVER`. A plan with it needs the plan feature `sql_functions`. - **Statistical aggregates**: `STDDEV(x)` and `STDDEV_SAMP(x)`, the sample standard deviation; `STDDEV_POP(x)`; `VARIANCE(x)` and `VAR_SAMP(x)`, the sample variance; `VAR_POP(x)`; `COVAR_SAMP(y, x)` and `COVAR_POP(y, x)`; and `CORR(y, x)`, the Pearson correlation. As in PostgreSQL, `NULL`s are left out (the two-variable ones take the rows with both values), the sample forms are `NULL` for fewer than two values and the population forms for none, and `CORR` is `NULL` when either variable does not vary. They are computed from sums and counts in one pass (the sum of squares less the square of the sum over n), so they merge over shards as `SUM` and `COUNT` do, and with values far larger than their spread (times in microseconds) lose digits to rounding. - **`HAVING`** filters groups by their aggregates, written out or by alias, with comparisons, `BETWEEN`, `AND`, `OR` and `NOT`, in three-valued logic: an aggregate of no values (`AVG(rating)` of a group without ratings) is `NULL`, so neither `AVG(rating) < 3` nor `NOT (AVG(rating) < 3)` keeps that group. - **`ORDER BY`** a group column, an aggregate or a position, each by name or by its alias in the `SELECT` list (`SELECT zone AS z, COUNT(*) AS n ... GROUP BY zone ORDER BY n DESC, z`), with a tie-break; without one, the largest groups come first. The group of rows without a value comes last in either direction, and first with `NULLS FIRST` (`ORDER BY passenger_count DESC NULLS FIRST`). `LIMIT` and `OFFSET` apply to groups. **Changed:** 0.3.8 and earlier refused `ORDER BY` a group column's alias, and `NULLS FIRST` after `GROUP BY` or `DISTINCT`. A `SUM` or `AVG` of `FLOAT` values is exact: the values are added without rounding and the total is rounded once, so it does not depend on the order rows are read in, nor on the [engine](#subqueries-with-and-joins) that runs it: ChloeDB's operators and DataFusion add the same way, so a total, and a `RANK` or an order over it, stay the same when a table grows past the rows at which DataFusion takes a plan over (two totals of 43.62 tie on both, where adding in order gives one of them as 43.620000000000005). **Changed:** 0.3.8 and earlier added in order on DataFusion, so such a tie broke once a query read more than 4,096 rows. A database groups its segments on several threads and merges them, and the answer is the same bits as on one thread. A coordinator over shards merges partial aggregates (sums and counts for `AVG`, the distinct values for `COUNT(DISTINCT)`), so the answers are the same as on one server, except that each shard sends its `FLOAT` sum rounded once, so a sum over shards can differ from one server's in its last bit. ### Percentiles `PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY f)` is the value a fraction `p` (0 to 1) of the way from the group's least value of `f` to its greatest, interpolated between the two values around that position, a `FLOAT`; `MEDIAN(f)` is `PERCENTILE_CONT(0.5)`. `PERCENTILE_DISC(p) WITHIN GROUP (ORDER BY f)` is the least value that at least a fraction `p` of the values are at most: one of the values, of `f`'s type (a `TIMESTAMP`'s times too). The answers are PostgreSQL's: of `n` values in order, `PERCENTILE_DISC(p)` is the one at position ⌈p·n⌉ (counting from 1, the first for `p` = 0), and `PERCENTILE_CONT(p)` the one at position p·(n − 1) counting from 0, interpolated in doubles. `NULL`s are left out, and a group without values gives `NULL`. A column without an alias is named as the call reads, `PERCENTILE_CONT(price, 0.9)`. - **Of columns and expressions.** Over one table they take indexed `INT` and `FLOAT` columns, read from the columns as the other aggregates are; over joined or derived rows, any numeric expression (`MEDIAN(s.price * 1.2)`). `p` is a constant or a parameter (`:p`); the order is ascending (`ORDER BY f DESC` is an error: write `1 - p`). They are aggregates of groups, not window functions. - **Exact, so they hold the values.** A group keeps each of its values (8 bytes each, counted against the [query's memory budget](server.md#limits)) and orders them once when it is read: a median over 5 million rows holds 40 MB. A shard sends a group's values to the coordinator as runs of equal values, so prices that repeat travel once with their count, and the coordinator's answer is one server's. Plans with a percentile carry the plan feature `percentiles`, which a version of ChloeDB from before them refuses by name. ### Approximate percentiles ```sql SELECT date_bin('5 minutes', ts) AS b, service, approx_percentile(latency, 0.99) AS p99 FROM logs WHERE ts >= '2026-11-12' GROUP BY b, service; ``` `approx_percentile(f, p)` is `PERCENTILE_DISC(p)` of the group's values (the one at position ⌈p·n⌉ in order) within 1% of it, a `FLOAT`, from a [DDSketch](https://arxiv.org/abs/1908.10693) of the group's values rather than the values themselves. `p` = 0 and 1 give the least and greatest values exactly. It takes what the exact percentiles take, `INT` and `FLOAT` columns over one table and numeric expressions over joined or derived rows, except `TIMESTAMP`s. - **A few KB a group, however many rows.** A sketch counts each value in a bucket of values within 1% of each other, and keeps at most 1,024 buckets of each sign (4 KB): the bound holds for values up to about 10⁸ times apart, as latencies are, and past that the least ones are folded together, so the low percentiles of such a spread lose it first. A p99 over 100 million rows holds a few KB rather than 800 MB. - **Exact merges.** Sketches of segments, threads and shards add up to the sketch of all the values, so the answer does not depend on how rows were split: a coordinator's answer is one server's. A shard sends a group's sketch as versioned bytes (base64 text), which a coordinator reads only in the version it knows. Plans with one carry the plan feature `approx_percentiles`, which a version of ChloeDB from before it refuses by name. ### Rollups: `CREATE ROLLUP`, a materialized view of counts over time > **Experimental.** Rollups are new in 0.3.1, and their options, columns and refresh may change in a later release. A rollup is a table of counts, sums, least and greatest values per bucket of time and per group, kept up to date from another table as rows arrive: ChloeDB's materialized view (a continuous aggregate) of a `GROUP BY` of time. Precomputed daily or hourly counts, kept up to date without a job of your own, are one: a time-bucket query over weeks of logs reads a few thousand rows of the rollup instead of millions of the table. ```sql -- Orders per day and status, kept up to date as orders arrive. CREATE ROLLUP orders_daily ON orders AS SELECT date_trunc('day', created_at), status, COUNT(*); SELECT bucket, status, count FROM orders_daily ORDER BY bucket DESC; ``` It needs an admin key that is not limited to tables, and `check_sql` checks one without making it. ```sql CREATE ROLLUP logs_5m ON logs OPTIONS(lateness = '10 minutes', retain = '400 days') AS SELECT date_bin('5 minutes', ts), service, severity, COUNT(*), SUM(latency), COUNT(latency), MAX(latency) AS worst WHERE severity <> 'DEBUG'; SELECT date_trunc('hour', bucket) AS h, service, SUM(count), SUM(sum_latency) / SUM(count_latency) AS mean, MAX(worst) FROM logs_5m WHERE bucket >= '2026-11-01' GROUP BY h, service; REFRESH ROLLUP logs_5m; -- now, without waiting for the background job REFRESH ROLLUP logs_5m FULL; -- every bucket, for rows later than the lateness REFRESH ROLLUP logs_5m REBUILD; -- fold every bucket again, after an UPDATE DROP ROLLUP IF EXISTS logs_5m; ``` - **The bucket** is `date_bin('', field)`, any whole number of seconds, minutes, hours, days or weeks counted from 1970-01-01, or `date_trunc('second' | 'minute' | 'hour' | 'day', field)`, of a `TIMESTAMP` column. The groups are `KEYWORD`, `INT`, `BOOL` or `TIMESTAMP` columns, and the aggregates `COUNT(*)`, `COUNT(f)` (the rows whose `f` is not NULL), and `SUM(f)`, `MIN(f)`, `MAX(f)` and `AVG(f)` of numeric columns (`MIN` and `MAX` of a `TIMESTAMP` too). A `WHERE` keeps some rows only; `FROM`, when written, names the table after `ON`. - **The rollup is an ordinary table**, named by the statement, with a row per bucket and group: `rollup_key` (its primary key, a number made of the bucket and the group's place in it), the bucket (`bucket`, or the name `AS` gives it), the group columns, typed as in the table, and a column per aggregate, `count`, `count_`, `sum_`, `min_` and `max_` unless `AS` names it. `AVG(f)` keeps `sum_f` and `count_f`, so the mean is `SUM(sum_f) / SUM(count_f)`, which skips NULLs as `AVG(f)` does (a rollup made before 0.3.4 keeps `sum_f` and `count` only, whose quotient counts the rows without a value too; make it again for the other). A `count` column (`COUNT(*)`) is always kept. A rollup that counts a field's values is marked `needs_chloedb_0_3_4` in its definition, which 0.3.3 refuses by name rather than refresh it wrong. Its columns are kept in the columns only, not again as whole rows (`stored = false`), which a rollup's queries never need: about 40 bytes a row. Query it by name, and add its rows up into larger buckets or fewer groups (`SUM(count)`, `MIN(min_latency)`); a query of the table is not rewritten onto it. `OPTIONS(retain = ...)` is the rollup's own [retention](#tables), kept by its bucket: a rollup outlives the rows it counts. - **How it is kept.** `CREATE ROLLUP` folds the table's rows at once, a day of buckets to a query: 20 million lines in about 8 seconds. On a server it answers what it made: the rollup, whether it is `filled`, the buckets folded and the rows written; it leaves the first fold of a table of over a million rows to its refresher, a few seconds on, and until then the rollup has fewer rows (`REFRESH ROLLUP` fills it at once). From then on a refresh compares, bucket by bucket, how many rows of the table the bucket holds with the rollup's count for it (one count by bucket for a day of buckets at a time: every bucket of 20 million lines over 30 days in a quarter of a second), and folds again the buckets that differ, each in one transaction. A plain refresh compares the buckets from the clock less the `lateness` (10 minutes by default; from the newest row, when that is older) to the newest row, and any the rollup has not folded up to now: a row dated in the future is folded, but does not take the window away from the present. `FULL` compares them all, and `REBUILD` folds them all again whatever their counts. Only buckets that hold rows, in the table or in the rollup, are compared, so a row dated in 1970 or 2099 costs a query, not a walk over every bucket between. One refresh of a rollup runs at a time; another waits for it. A server refreshes every rollup every few seconds, and all their buckets every few minutes, each rollup on its own: one whose refresh fails is logged by name, and the others go on. `GET /v1/tables` gives a rollup's table a `rollup` entry with the table it reads, its last good refresh and its last error. An embedding program calls `Db::spawn_rollups` (or runs `REFRESH ROLLUP`; `Db::rollup_health` says how each went). Buckets older than the table's `retain` are not compared again, so they keep what they counted. A bucket of a time so far from 1970 that its key would not fit in 64 bits (a time in nanoseconds stored as microseconds, say) is not folded, and the refresh says so in the log. - **For tables rows are added to**, such as logs: a change that leaves a bucket's count as it was (an `UPDATE`, or a delete and an insert into one bucket between two refreshes) is never seen by a plain or a `FULL` refresh, only by `REFRESH ROLLUP name REBUILD`. - **Its table and the one it reads stay as the rollup needs them.** `DROP TABLE` of a table a rollup reads is refused while the rollup is there (`DROP ROLLUP` first, or drop both in one `DROP TABLE logs, logs_5m`); `DROP TABLE` of a rollup's own table drops its definition too. `ALTER TABLE` that drops or renames a column a rollup reads, or that changes a rollup's own table, is refused. The definition is kept as a [stored function](#stored-functions), `rollup__()`, whose body is the statement, so it needs nothing new on disk and travels with the database. On a server with shards, each shard keeps a rollup of its own rows; rollups through a coordinator come later. ## Subqueries, WITH and joins ```sql -- IN (SELECT ...): rows of the categories that 2001's surveys are in SELECT id FROM papers WHERE category IN (SELECT category FROM papers WHERE year = 2001 AND kind = 'survey'); -- a scalar subquery SELECT id, year FROM papers WHERE year > (SELECT AVG(year) FROM papers) ORDER BY year DESC LIMIT 10; -- WITH: name a query and read it like the table WITH top AS (SELECT id FROM papers ORDER BY bm25(body, 'graph neural network') DESC LIMIT 50) SELECT category, COUNT(*) FROM top GROUP BY category; -- a WITH result as graph seeds WITH top AS (SELECT id FROM papers ORDER BY bm25(body, 'graph neural network') DESC LIMIT 20) SELECT id FROM papers WHERE REACHABLE(cites, (SELECT id FROM top), dir => 'in') LIMIT 100; -- FROM (SELECT ...) and DISTINCT SELECT category, n FROM (SELECT category, COUNT(*) AS n FROM papers GROUP BY category) AS t WHERE n > 50 ORDER BY n DESC; SELECT DISTINCT category FROM papers WHERE MATCH(body, 'graph'); -- joins of two tables: on a key, a multi-valued column (each of its values), or three tables SELECT p.id, v.name FROM papers p JOIN venues v ON p.venue = v.id WHERE v.rank >= 4 AND MATCH(p.body, 'graph'); SELECT a.name, COUNT(*) AS n FROM papers p JOIN authors a ON p.authors = a.id GROUP BY a.name ORDER BY n DESC LIMIT 10; SELECT p.id, a.name, v.name FROM papers p JOIN authors a ON p.authors = a.id LEFT JOIN venues v ON p.venue = v.id WHERE p.year = 2024; SELECT id FROM papers WHERE venue IN (SELECT id FROM venues WHERE field = 'ir'); -- joins of the table with itself: along an EDGES field, or on a shared value SELECT a.id, b.id AS cited FROM papers a JOIN papers b ON a.cites = b.id WHERE a.year >= 2020; SELECT a.id, b.id AS cited_by FROM papers a LEFT JOIN papers b ON b.cites = a.id WHERE a.id IN ('p1', 'p2'); SELECT b.id, COUNT(*) AS n FROM papers a JOIN papers b ON a.cites = b.id GROUP BY b.id ORDER BY n DESC LIMIT 10; SELECT a.id, b.id FROM papers a JOIN papers b ON a.category = b.category AND b.id != a.id WHERE a.id = 'p1'; ``` Each plans into operators over the single-table queries above ([`EXPLAIN`](#explain) shows them), all run on one snapshot, so every single-table query uses the indexes. Each is bound as it is built, never printed as SQL and parsed again: - **`IN (SELECT ...)`** and **`NOT IN`** run the subquery first and filter with its values (a multi-valued column contributes each value). **`EXISTS`** is true or false, and a **scalar subquery** must return one column and at most one row. An `EXISTS` or `NOT EXISTS` in `WHERE` whose subquery names the outer row by one equality, `WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer = c.id AND o.total > 100)`, is a semi join (an anti join for `NOT EXISTS`): it runs as `c.id IN (SELECT o.customer FROM orders o WHERE o.total > 100)`, the subquery once, with `NULL`s as `EXISTS` has them (`NOT EXISTS` keeps an outer row whose `c.id` is `NULL`). The subquery may have a `LIMIT`, not groups, aggregates or an `OFFSET`; one that names the outer row anywhere else is an error. A subquery's values reach the outer query's filter as values, so its indexes serve it: `year > (SELECT AVG(year) ...)` is a range of `year`. A scalar subquery that names a column of the outer row is [correlated](#correlated-subqueries-a-ranking-that-reads-other-rows): it ranks, and is not a condition. - **`WITH`** results and **`FROM (SELECT ...)`** are read like a table. A `WITH` whose rows are rows of the table (no aggregates) keeps their keys, so an outer query over it reads the table restricted to those rows, in the `WITH`'s order unless it orders them itself, and `(SELECT id FROM top)` can seed a graph. The outer query may name any of the table's columns (`SELECT id, category FROM top`), while `*` is the `WITH`'s own columns, as in any SQL. A `score()` or `hops()` the `WITH` selects (`score() AS s`) is read from its rows, by name or by `*`. A column a `WITH` or a `FROM (SELECT ...)` selects as `s.item`, without an alias, is its column `item`, as SQL names it, so the query reading it says `ls.item`; two columns of one name keep their tables' (`s.id`, `p.id`). `WITH RECURSIVE` is not supported: `REACHABLE` and `PATH` walk links. - **Joins** are `JOIN` (inner), `LEFT JOIN`, `FULL [OUTER] JOIN`, and `RIGHT JOIN` as the first join of a `FROM` (`a RIGHT JOIN b ON ...` runs as `b LEFT JOIN a ON ...`, and `*` keeps `a`'s columns first), of a table with another, with itself or with a `WITH` result; name each side (`papers a JOIN papers b`). `ON` needs an equality between the sides, of two columns of one kind: `KEYWORD`, or `INT` and `FLOAT` compared as numbers (`p.venue = a.id`, an `INT` with a `KEYWORD`, is an error). A multi-valued column joins each of its values. Comparing an `EDGES` field with the key follows its links (`a.cites = b.id`: *b* is a row *a* links to; `b.cites = a.id`: *b* links to *a*); links name keys of their own table, so they join a table with itself. Each `WHERE` or `ON` condition on one side filters that side's scan, and the second side reads only the rows whose join values the first side holds (`b.id IN (...)`, or for links the rows linking to them), before a hash join in memory. Groups of the second side's rows, a `GROUP BY` of its key (and of other columns of its rows) that aggregates only fields of the first side and is ordered by that key among others, are made in the first side's scan, by its join key, before the join (`SELECT p.id, p.title, COUNT(*) AS n FROM reviews r JOIN products p ON r.product_id = p.id GROUP BY p.id, p.title ORDER BY n DESC, p.id`): the join reads a row per group rather than per row. Text, vector and graph functions name one side (`MATCH(a.body, ...)`); `ORDER BY` a score ranks by that side's scan, and when the order is the first side's, scans of a growing number of its rows stop once `LIMIT` rows join. Joined columns of the answer are named by their expression (`b.title`) unless aliased, where PostgreSQL names them by the column alone (`title`): pandas and `chloedb.dbapi`'s `cursor.description` see `b.title`, so alias a column whose name a program reads (`b.title AS title`). - **`FULL JOIN`** gives the rows of a `LEFT JOIN`, then each row of the right side that matched no row of the left, with `NULL`s for the left's columns, in the right's order (`ORDER BY` orders them as any rows): `SELECT coalesce(o.sku, s.sku) AS sku, o.qty, s.qty FROM orders o FULL JOIN stock s ON o.sku = s.sku`. A `NULL` key matches nothing, so its row comes once, from its own side. Since both sides keep their unmatched rows, no condition filters either side's scan: `ON`'s other conditions decide which pairs join (a row they part from every match keeps its `NULL`s), and `WHERE` filters the joined rows, so `WHERE o.sku IS NULL` keeps the stock no order names. Both sides are read whole, without the restriction to the first side's join values or the growing scan of a `LIMIT`. Joins after it join its rows as they join any. It runs on the operators (DataFusion leaves it to them), and through a coordinator, which joins the rows its shards answer; a plan with one needs the plan feature `full_join`. - Over joined or derived rows, `WHERE`, `GROUP BY`, aggregates, `HAVING`, `ORDER BY`, `DISTINCT` and `LIMIT` also take arithmetic, `||`, `LIKE`, `ILIKE`, `CASE`, `COALESCE`, `LOWER`, `UPPER`, `LENGTH`, `ABS`, `ROUND`, `DOT`, `HASH` and the numeric functions of ranking expressions (`ln`, `pow`, `least`, ...). So does the `SELECT` list over one table (`SELECT id, rating * 2, lower(category), dot(emb, :q) FROM papers WHERE ...`): the table's query finds the rows and the columns are computed in memory, typed as over derived rows. A `SELECT` that also selects a ranking's value (`bm25(..) * 2`, `hops()`) computes its columns as ranking expressions do, as `FLOAT`s. Their conditions follow the same three-valued logic as a single table's, multi-valued columns included (`NOT (b.tags = 'red')` keeps rows without tags). Integer arithmetic is exact, and a result too big for an integer is a `FLOAT`; `/` gives a `FLOAT`, and dividing by zero gives `NULL`. `||` with a `NULL` gives `NULL`, as in PostgreSQL (`coalesce(note, '')` keeps the rest), and `LIKE` with a `NULL` side is `NULL`. `ROUND(x)` gives an `INT`: of a `FLOAT` it rounds half to even, as PostgreSQL rounds a `double precision` (`ROUND(price)` of 2.5 is 2 and of 3.5 is 4), and of a number written in the statement, or of a value made of such numbers alone (`ROUND(CASE WHEN qty > 0 THEN 2.5 END)`), half away from zero, as PostgreSQL rounds a `numeric` (`ROUND(2.5)` is 3); `ROUND(x, digits)`, `ROUND(x, 0)` included, rounds half away from zero, as PostgreSQL's `round(numeric, int)` does. A ranking expression's `round` rounds half away from zero, as it always has. `ORDER BY` puts rows without a value last in either direction unless `NULLS FIRST`, as over a single table. - **Engines.** ChloeDB's own operators run these in memory, a row at a time. With the feature `datafusion`, which chloedb-server and the Python package turn on and ChloeCtx leaves off, [DataFusion](https://datafusion.apache.org) runs them on column batches once their single-table queries read more than 4,096 rows; below that the operators answer, faster on so few, reusing the rows DataFusion's attempt already read. Both give the same rows in the same order, and the same sums of floats, which both add exactly ([aggregates](#aggregates)). On two tables of 100,000 rows, a join with a group took 285 ms on the operators and 60 ms on DataFusion. On two tables of 100 rows it took 0.6 ms on the operators and 2.9 ms on DataFusion; the default engine (`auto`) answered in 1.2 ms. Measured with `chloedb/examples/df_join.rs` on a 4-core cloud Xeon at 2.10 GHz, 2026-11-01. `CHLOEDB_ENGINE` sets the engine: - `auto`: the default; - `operators`; - `datafusion`: DataFusion, whatever the size; - `datafusion-only`: a query DataFusion does not run fails, to find what it lacks. The operators run what DataFusion does not run yet, and the plan's first line says why. Today that is joins along links, multi-valued columns as sort keys, correlated subqueries, and `maxsim` or `encode` over a subquery. chloedb-server runs them on its engine over its own tables and as a [coordinator](server.md#sharding-one-coordinator-many-shards), which runs them above the rows its shards answer for each single-table query: on DataFusion, as Arrow columns from shards of [protocol 10](server.md#grpc). - On the operators, each single-table query, `WITH` result and side of a join holds at most 1,000,000 rows. On DataFusion they hold as many rows as the query's memory budget allows, and past it sorts and groups spill to disk. `CROSS` joins, and a `RIGHT JOIN` after another join, are not supported. The executor's plan lines (`--plan`, `/v1/explain`'s `plan`) list each single-table query that ran, with its rows and its own plan. ## Window functions A window function gives each row a value computed over other rows, its *partition*, without folding them into one as `GROUP BY` does: a row's rank among its category's, the value of the row before, a running total, a moving average. ```sql -- each paper's rank in its category by citations, and its category's average SELECT id, category, cites, RANK() OVER (PARTITION BY category ORDER BY cites DESC) AS r, AVG(cites) OVER (PARTITION BY category) AS avg_cites FROM papers WHERE year >= 2020; -- the three most cited of each category: QUALIFY filters by a window SELECT id, category, cites FROM papers QUALIFY ROW_NUMBER() OVER (PARTITION BY category ORDER BY cites DESC, id) <= 3; -- a running total and a moving average of the day before, the day and the day after SELECT day, clicks, SUM(clicks) OVER (ORDER BY day) AS total, AVG(clicks) OVER (ORDER BY day ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS smooth, clicks - LAG(clicks) OVER (ORDER BY day) AS change FROM daily ORDER BY day; -- over groups: categories ranked by size, and each one's share SELECT category, COUNT(*) AS n, RANK() OVER (ORDER BY COUNT(*) DESC), COUNT(*) / SUM(COUNT(*)) OVER () AS share FROM papers GROUP BY category; -- one window, named once SELECT id, ROW_NUMBER() OVER w, LAG(year) OVER w, SUM(cites) OVER (w ROWS 2 PRECEDING) FROM papers WINDOW w AS (PARTITION BY category ORDER BY year); ``` - **Functions.** `ROW_NUMBER()`; `RANK()` and `DENSE_RANK()`; `PERCENT_RANK()` and `CUME_DIST()`, `FLOAT`s; `NTILE(n)`, buckets 1 to n as even as they can be, the first ones a row larger (as SQL says, and PostgreSQL and SQLite do); `LAG(x [, offset [, default]])` and `LEAD(..)`, `x` of the row `offset` rows before or after (1 by default), or `default` (`NULL` without one) past the partition's ends; `FIRST_VALUE(x)`, `LAST_VALUE(x)` and `NTH_VALUE(x, n)` of the row's frame; and the aggregates `COUNT(*)`, `COUNT(x)`, `SUM`, `AVG`, `MIN` and `MAX` of the frame. `NTILE`'s, `NTH_VALUE`'s and `LAG`'s numbers are constants. `COUNT(DISTINCT ..)`, `FILTER (WHERE ..)` and `IGNORE NULLS` are errors. - **`OVER (PARTITION BY .. ORDER BY ..)`.** The partition is the rows with equal values of its expressions (`NULL` equal to `NULL`); without `PARTITION BY` it is every row. The window's `ORDER BY` orders the partition, its `NULL`s last unless `NULLS FIRST` as elsewhere; rows whose order keys are all equal are *peers*, and rows that tie keep the order they came in. Both take expressions of the rows (`PARTITION BY year % 10`, `ORDER BY lower(title)`), or over groups of the groups' values and aggregates. - **Frames.** `FIRST_VALUE`, `LAST_VALUE`, `NTH_VALUE` and the aggregates read the rows of the row's frame: `ROWS BETWEEN start AND end` counts rows from the row, and `RANGE BETWEEN start AND end` takes the rows whose value of the window's one `ORDER BY` key is within the offsets of the row's (a row without a value has its peers, the other rows without one). The ends are `UNBOUNDED PRECEDING`, `n PRECEDING`, `CURRENT ROW` (in `RANGE`, the row's first or last peer), `n FOLLOWING` and `UNBOUNDED FOLLOWING`, in that order; `ROWS 2 PRECEDING` is `ROWS BETWEEN 2 PRECEDING AND CURRENT ROW`. Without a frame, a window with an `ORDER BY` reads from the partition's first row to the row's last peer, so `SUM(x) OVER (ORDER BY day)` is a running total that counts a day's rows together, and a window without one reads the whole partition. The other functions read the partition whatever the frame says. `GROUPS` frames are errors. - **Where they go.** A window function is a column of `SELECT`, a key of `ORDER BY`, or part of a condition of **`QUALIFY`**, which filters the rows after the windows are computed and may name a selected window by its alias (`QUALIFY r <= 3`). It is not part of `WHERE`, `GROUP BY` or `HAVING`, which come before, and a window function's argument, partition or order holds no other: compute that one in a subquery in `FROM`. In a grouped query the windows are computed over the groups `HAVING` keeps; `SELECT DISTINCT`, `ORDER BY` and `LIMIT` come after them, so `COUNT(*) OVER () ... LIMIT 5` counts every row. - **`WINDOW w AS (..)`** names a window that `OVER w` uses as it is, and that `OVER (w ORDER BY ..)` or `OVER (w ROWS ..)` extends with an order or a frame it lacks; a window may name one before it (`WINDOW w AS (PARTITION BY a), v AS (w ORDER BY b)`). - **Engines.** The operators sort each partition in memory; DataFusion runs windows on column batches, sorting and spilling within the query's memory budget, and both answer alike. The operators run a window DataFusion does not lower yet: a `LAG` or `LEAD` whose default is not a constant of the value's type, `FIRST_VALUE` and `LAST_VALUE` over a `RANGE` frame with an offset, `NTH_VALUE` over a `RANGE` frame that starts after the partition's first row, a `RANGE` offset of another type than its key (`0.5` over an `INT`), and windows over multi-valued columns. The plan's node is `Window` (`Window: RANK() OVER (PARTITION BY category ORDER BY cites DESC)` in `EXPLAIN`, the functions computed after the rows' own columns), and its JSON needs the plan feature `window`; a version of ChloeDB from before it refuses the plan by that name. ## UNION, INTERSECT and EXCEPT A set operation takes the rows of two queries together: `UNION` the rows of either, `INTERSECT` those of both, `EXCEPT` those of the first that the second lacks. ```sql -- the categories of 2024's papers and of the reviews' papers, each once SELECT category FROM papers WHERE year = 2024 UNION SELECT category FROM reviews; -- every row of both, repeats kept, ranked together SELECT id, cites AS n FROM papers WHERE cites > 100 UNION ALL SELECT id, downloads FROM preprints WHERE downloads > 1000 ORDER BY n DESC LIMIT 10; -- the venues 2023 had and 2024 lost SELECT venue FROM papers WHERE year = 2023 EXCEPT SELECT venue FROM papers WHERE year = 2024; -- a side ordered and cut on its own, in parentheses (SELECT id FROM papers ORDER BY cites DESC LIMIT 5) UNION ALL (SELECT id FROM preprints ORDER BY downloads DESC LIMIT 5); ``` - **Columns.** Both sides select as many columns, matched by place, and the answer's columns are named as the first side's. A column of `INT`s on one side and `FLOAT`s on the other is `FLOAT`, the wider type, as in PostgreSQL and DuckDB: `SELECT 1 UNION ALL SELECT 2.5` is 1.0 and 2.5. Rows are equal when each of their values is, `NULL` equal to `NULL` and an `INT` equal to the `FLOAT` of its value. - **`ALL`.** Without it each row comes once. With it, `UNION ALL` keeps every row of both sides; `INTERSECT ALL` keeps a row as many times as both sides have it, the fewer of the two counts; `EXCEPT ALL` as many times as the first side has it more than the second. - **Order.** `INTERSECT` comes before `UNION` and `EXCEPT`, which go left to right, and parentheses group sides: `a UNION b INTERSECT c` is `a UNION (b INTERSECT c)`. `ORDER BY`, `LIMIT` and `OFFSET` at the end apply to the whole and name its columns; a side in parentheses takes its own. Without an `ORDER BY` the rows come in the sides' order: `UNION ALL` the first side's rows, then the second's; `UNION` those rows each where it first comes; `INTERSECT` and `EXCEPT` rows of the first side in its order, the first ones of rows equal to one another. - **Anywhere a query goes**: a `WITH` result, a derived table `FROM (SELECT .. UNION ..) d`, or a subquery `x IN (SELECT .. UNION ..)`, and each side may group, join, rank, or compute windows. `UNION BY NAME` is an error. - **Engines.** Both answer alike. The operators run a set operation DataFusion does not lower: one whose sides give a column types other than an `INT` and a `FLOAT` (text and a number), and `INTERSECT`, `EXCEPT` or `UNION` without `ALL` of a multi-valued column. The plan's node is `SetOp` (`Union`, `Intersect all` and so on in `EXPLAIN`, the sides below it), and its JSON needs the plan feature `set_ops`; a version of ChloeDB from before it refuses the plan by that name. ## The first row of each group: DISTINCT ON `SELECT DISTINCT ON (keys) ...` keeps, of the rows with equal keys, the first in the query's order, as PostgreSQL does: a row per group, the groups in the order of their first rows, and `LIMIT` and `OFFSET` count groups. With rows of a long video or document in a table of segments, it answers each video once, by its best segment: ```sql -- each video's best clip, the 10 best videos SELECT DISTINCT ON (video) video, id, start_ms, score() FROM clips WHERE MATCH(transcript, 'penalty kick') ORDER BY bm25(transcript, 'penalty kick') DESC LIMIT 10; -- each user's latest event SELECT DISTINCT ON (usr) usr, item, ts FROM events ORDER BY ts DESC, id; -- the best page of each PDF, by an image query's similarity SELECT DISTINCT ON (doc) doc, page FROM pages ORDER BY similarity(emb, :q) DESC LIMIT 5; -- over groups: each country's top seller SELECT DISTINCT ON (country) country, seller, SUM(price) AS total FROM sales GROUP BY country, seller ORDER BY country, total DESC; ``` - **Keys** are expressions of the rows (`video`, `lower(lang)`, `year % 10`), or columns of the answer by name or number (`DISTINCT ON (2)`), and need not be selected. Keys are equal when their values are: `NULL` with `NULL`, and a multi-valued column's list with the same list. - **The order.** PostgreSQL requires `ORDER BY` to start with the keys; ChloeDB does not, so `ORDER BY` a score gives the best row of each group, the best groups first. When `ORDER BY` does start with the keys, the answer is PostgreSQL's. Without `ORDER BY`, which row of a group is kept is not defined. - **Reads.** When the query's order is the scan's (a score, or one numeric column), a `LIMIT` reads the scan in growing slices: four times the rows asked for (at least 32), then four times as many, until that many groups have a row or the scan runs out. A group with many rows near the top costs more reads, never a wrong answer. `DISTINCT ON` one keyword or `INT` field of a table ranked by `bm25` reads less: each segment keeps each group's first row as it scores ([`MAX k PER`](#at-most-k-rows-of-a-value-max-k-per) does the same with k rows), so the scan returns the rows asked for. Ordered by several columns, the rows are sorted in memory, and the scan holds at most 1,000,000 rows. - **Shards.** A coordinator keeps the first rows over its shards' merged rows, so three shards give what one database does, whether or not the table is placed by the keys (`shard_by`). The plan's node is `DistinctOn` (`Distinct on: video` in `EXPLAIN`), and its JSON needs the plan features `operators` and `distinct_on`; a version of ChloeDB from before it refuses the plan by that name. ## At most k rows of a value: `MAX k PER` `ORDER BY ... MAX k PER field` keeps, of the rows with equal values of `field` (a `KEYWORD` or a number of one value: a `TEXT` field is an error, as rows rarely share a whole text), the first `k` in the query's order, and the rows kept stay in that order: a ranking with at most two clips of a video, three products of a brand or two arguments of a debate. `LIMIT` and `OFFSET` count the rows kept. ```sql -- the 20 best clips, at most two of a video SELECT id, video, score() FROM clips ORDER BY bm25(transcript, :q) DESC MAX 2 PER video LIMIT 20; -- the newest products in stock, at most three of a brand SELECT id, brand, title FROM products WHERE in_stock ORDER BY added DESC, id MAX 3 PER brand LIMIT 30; -- in a subquery: of each video's two most viewed clips, those about a dog SELECT id FROM clips WHERE MATCH(transcript, 'dog') AND id IN (SELECT id FROM clips ORDER BY views DESC, id MAX 2 PER video LIMIT 1000); ``` - **It ends `ORDER BY`**, and needs one: the rows a value keeps are its first in that order. `k` is a whole number, 1 or more, and `MAX 1 PER x` is `DISTINCT ON (x)`, with the same plan. - **A field of one value.** `field` is a field of the rows (`video`, `t.brand` in a join), and `NULL` is one value of its own. A multi-valued field is refused, since a row with several values would be in several groups. - **Not with `DISTINCT`** or `DISTINCT ON`, which already keep one row of each. - **Reads.** A table's own rows ranked by `bm25` and capped by a keyword or `INT` field keep the cap as they are scored: each segment keeps each value's best k rows (and the rows tied with its k-th) and skips the rows that can no longer reach the `LIMIT`, so the query reads its rows once. Other rankings, and caps over joined or derived rows or by other fields, read growing slices of the ranking until `LIMIT` rows are kept or it runs out, as [`DISTINCT ON`](#the-first-row-of-each-group-distinct-on) does. A field whose values cannot fill the `LIMIT`, such as one row of each of 15 topics for a `LIMIT` of 20, reads every row that matches either way, and returns 15. - **Shards.** A coordinator keeps each value's first rows over its shards' merged rows, so three shards give what one database does. The plan's node is `DistinctOn` with `per` (`At most 2 per: video` in `EXPLAIN`). With `k` above 1 its JSON needs the plan feature `per_cap`, so a version of ChloeDB from before it refuses the plan rather than keeping one row of each value. Python's builder writes it `.max_per(2, "video")`. On ArguAna (BEIR's 8,674 arguments from 592 debates on 15 topics; a document's debate and topic are in its id), every one of the 1,406 queries ranked by `bm25(body, :q)`, its own argument left out as BEIR scores it, top 20. Times are the median over queries of each query's median of 3 runs, one thread on a 4-core cloud VM (Intel Xeon @ 2.10GHz): | top 20 | nDCG@10 | debates | topics | p50 ms | p99 ms | |---|---:|---:|---:|---:|---:| | uncapped | 0.489 | 7.5 | 3.8 | 1.6 | 4.1 | | `MAX 1 PER debate` | 0.307 | 20.0 | 7.2 | 2.4 | 5.4 | | `MAX 2 PER debate` | 0.379 | 14.5 | 5.9 | 2.3 | 5.0 | | `MAX 3 PER debate` | 0.419 | 12.6 | 5.4 | 2.3 | 5.5 | | `MAX 1 PER topic` | 0.301 | 14.9 | 15.0 | 2.8 | 5.7 | | `MAX 2 PER topic` | 0.376 | 16.3 | 11.4 | 2.6 | 5.4 | | `MAX 3 PER topic` | 0.416 | 14.2 | 9.1 | 2.4 | 5.4 | Debates and topics are the mean number of each in a query's answer. Each segment keeps the cap as it scores, so a cap costs about 1.5 times the uncapped query whatever the field: BM25 can skip fewer rows, since the 20th row kept scores lower than the 20th of all. One row of each of the 15 topics cannot fill 20 rows, so that query scores every argument that matches, once, and returns 15. Before the scan kept the cap, the same queries read growing slices of the ranking: 6.0 to 6.1 ms by debate, 7.1 and 18.8 ms for three and two per topic, and 549 ms for one per topic, which read every row again at each slice (with the uncapped query at 3.3 ms in that run). Caps trade relevance for spread. ArguAna's answer to a query is the argument against it, in the query's own debate, so a cap on debates also caps how many of the right debate's arguments the ranking can show: nDCG@10 falls from 0.489 to 0.307 with one per debate, and to 0.419 with three. The run is `chloedb-per-cap-bench` ([`results/text/per_cap.json`](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/results/text/per_cap.json)). ## As much as fits: `PACK n TOKENS` **Experimental:** what `PACK` reads and how it chooses may change between releases. Against the top rows of a ranking cut in the client ([measured](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/results/pack/README.md) on SciFact and NFCorpus), it reaches more of the relevant documents when the budget holds one to three (SciFact 0.74 against 0.65 at 500 tokens) and spends less of the budget on them, and the two are the same once it holds five or more. A query's answer is often the context a language model is given, and the model has a budget of tokens, not of rows. `PACK n TOKENS` at the end of a SELECT fills that budget: it reads the query's rows in its order and decides each once, so that a long row, a row that repeats one already taken and a row linked to one taken are weighed inside the query rather than by the application after a top k. ```sql -- what memory says about the task, in at most 4,000 tokens SELECT id, kind, text FROM memory WHERE superseded = false ORDER BY rrf(bm25(text, :task), similarity(emb, :q)) DESC PACK 4000 TOKENS DEDUPE 0.85 FOLLOW links 1 HOP WITH RECEIPT; ``` Each row, in the query's order, is: - **taken** whole when its text fits what is left of the budget; - **excerpted** when it is longer than one row may be (`EXCERPT n`; a quarter of the budget by default) or than what is left: the stretch of its longest text column with the most terms of the query's `bm25` and `MATCH` texts (or its start, when it has none), marked `… ` where it was cut. Terms are found as the column's analyzer makes them (stemmed for `english`, dictionary words for Chinese and Japanese under `standard`), and the text is cut between words, or inside a run without spaces (Chinese, Japanese, Thai, a URL, base64), so an excerpt never spends more than its room; - **skipped as a near-duplicate** of a row taken before it, with `DEDUPE x`: at least the share x of the shorter one's terms (as its analyzer makes them) are in the other, or, with `DEDUPE x ON emb`, the cosine of their vectors is at least x; - **skipped as over budget** when not even an excerpt of 32 tokens fits; - **skipped as no text** when none of its counted columns holds text. With `FOLLOW edges n HOP` (1 to 3 hops, 1 by default), each row taken brings the rows its [`EDGES`](#graphs) field reaches, up to 16, right after it in the order of its edges, if they pass the query's `WHERE`, decided the same way (`linked from k`). The rows are read by key, a hop at a time, so `FOLLOW` works through a coordinator, in one read per hop: a decision a file note links to is taken with the note, though it shares no word with the task. The answer is the rows taken, in that order, with two more columns: `pack_tokens`, the tokens the row spends, and `pack_decision` (`take`, `excerpt`, `linked from k`). `WITH RECEIPT` adds the rows skipped (`skip: near-duplicate of k`, `skip: over budget`, `skip: no text`), with their text columns `NULL`, so that the text of the rows answered is still what fits the budget, and the columns `pack_score`, the query's score of the row, and `pack_used`, the tokens spent up to and with it. In Rust, `Db::pack` answers the rows and a receipt with every decision and the snapshot read (`txn` and `seq_no`). - **The budget** is a whole number from 1 to 10,000,000, or a parameter that holds one: `PACK :budget TOKENS`. - **The text counted** is every column a row read holds text in, but the key's, or the columns `OF a, b` names. Tokens are an estimate (`chloedb::query::pack::count_tokens`), as the real count depends on the model's tokenizer: a run of Latin letters is a token per six letters, a run of another alphabet's (Cyrillic, Greek, Arabic, Hebrew, the scripts of India) a token per three, a run of digits a token per three, a CJK or Thai character or a punctuation mark one each. Against OpenAI's cl100k_base and o200k_base it counts English and code 13 to 27% high, the safe side; other scripts are counted high against o200k_base but low against cl100k_base, by up to 2.4 times for Hindi ([measured](https://github.com/chloetech-ai/chloedb/blob/main/chloedb/results/pack/README.md)). - **Reads.** The rows are read in growing reads, the first 64, then the first 320, 1,344 and so on, each from `OFFSET`, and the rows seen before are passed over by their keys; reading stops once what is left of the budget is too small for any row, or once 16 rows in a row were skipped over budget (what is left is too small for the rows the query finds, such as a title and a description, which need room for both and an excerpt; the rows already read are still decided), so a query whose first rows fill the budget reads once. A deeper read rather than the next page, because a fused ranking (`rrf`, a weighted sum) ranks its candidates to a depth that grows with the `LIMIT`: a deeper read is a better ranking of the same rows, and one that comes back short is the end of the ranking. (In a table without a primary key the reads are pages instead.) `LIMIT` is the most candidates read (1,000 without one), and `OFFSET` where they start. Every read, and every row followed, is a query of its own on the same snapshot: on a server, a lease held for the pack (kept for the client with `hold`, or the client's own `snapshot`), and the statement is admitted once, by its text, and held to one deadline. Through a coordinator each shard reads its latest version at each read. - **Choosing** is greedy in the query's order. A row that does not fit whole is excerpted rather than skipped, so that one long log cannot spend the budget, and a smaller row after one over the budget is still taken. - **Where.** On a file, a server and a coordinator alike: a coordinator merges each read from its shards, and packs. A key limited to tables runs it as it runs the query without the clause. `PACK` inside a subquery is not the clause (`pack` stays a name there, and anywhere it is not followed by a number and `TOKENS`). ## Graphs Rows with an `EDGES` field are nodes of a graph. Graph predicates and scores take **seeds**: a key (`'p1'`), a parameter, a tuple of keys (`('p1', 'p2')`), or a subquery, whose filters, ranking and `LIMIT` are those of any query. A subquery over the same table seeds with its rows; one over another table returns one column, whose values are the keys to start from, such as the items a user's recent events name: `ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 20))`. With `weighted => 1`, a seed's restart weight is its row's score, summed over the rows that name it: `ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY w DESC), weighted => 1)` starts from each item in proportion to the sum of its events' `w`, and ordering the events by `decay(ts, ...)` instead weighs recent ones more. ```sql -- papers within two citations of p1, either way, nearest first SELECT id, title, hops() FROM papers WHERE REACHABLE(cites, 'p1', hops => 2, dir => 'both') ORDER BY hops(), id LIMIT 20; -- one shortest path, only through surveys SELECT id, hops() FROM papers WHERE PATH(cites, 'p1', 'p9', max_hops => 6, through => kind = 'survey') ORDER BY hops(); -- vector search as the way in: what the two nearest papers cite, by similarity SELECT id FROM papers WHERE REACHABLE(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 2)) AND NOT REACHABLE(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 2), hops => 0, min_hops => 0) ORDER BY similarity(emb, :q) DESC LIMIT 20; -- personalized PageRank from the same seeds, fused with BM25 SELECT id FROM papers ORDER BY rrf(bm25(body, :t), ppr(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 5))) DESC LIMIT 20; ``` | function | what it is | options (defaults) | |---|---|---| | `REACHABLE(f, seeds, …)` | rows *v* with `min_hops` ≤ *d*(seeds, *v*) ≤ `hops` | `hops 1`, `min_hops 1`, `dir 'out'` (or `'in'`, `'both'`), `label 'a,b'`, `through `, `max_nodes 100000` | | `PATH(f, from, to, …)` | the rows of one shortest (unweighted) path | `max_hops 6`, `dir`, `label`, `through`, `max_nodes` | | `hops()` | a row's distance from the seeds, or its position on the path; `ORDER BY hops()` is nearest first | | | `ppr(f, seeds, …)` | personalized PageRank, usable wherever a score is, including `rrf` and weighted sums | `alpha 0.15`, `eps` (a row is pushed while its residual is at least `eps` times its number of edges, so scaling every weight alike changes nothing; not given, the walk starts at `1e-4` and halves it while its scores hold less than half of the walk, for at most 100,000 pushes, [below](#how-far-ppr-walks)), `dir 'both'`, `label`, `max_pushes 1000000` (a walk cut there says so: `max_pushes_reached` in the stats), `weighted 0` (`1`: the seed subquery's scores are the restart weights) | | a `VECTOR` field as `f` | `REACHABLE` and `PATH` follow similarity edges: a row's neighbours are its `k` most similar rows | `k 10`, `min_sim` | Through a [coordinator](server.md#sharding-one-coordinator-many-shards), graph queries over an `EDGES` field or an edge table are walked by the coordinator, a round of reads by key over every shard per hop, and answer as one database does ([graphs on a cluster](graphs.md#on-a-cluster)); a walk over a `VECTOR` field is refused there. The [query console](server.md#the-query-console)'s Graph tab builds these queries (seeds from keys, a search or a condition; links or similarity; neighbourhood, path or PageRank) and draws the answer. `through` restricts the rows a traversal may pass through (seeds and end points are exempt); the rest of `WHERE` filters the rows it ends at. **Changed:** a `PATH` with `through` could pass through a row that fails it, where the two halves of its search met, and so answer a path where none keeps to `through`; every middle row of a path now satisfies it. `max_nodes` bounds the rows a traversal meets besides its seeds (and a path's ends): a `REACHABLE` that would meet more, or a `PATH` that meets more before it finds a path, is an error saying so, never a part of the answer. `max_hops => 0` is a path of no hops (a seed that is also a target); `max_nodes` and `k` are 1 or more. `REACHABLE(f, seeds, hops => 0, min_hops => 0)` is the seed set itself, so `NOT` of it removes the seeds from a result. `hops()` refers to the first `REACHABLE` or `PATH` in `WHERE`. The [Graphs](graphs.md) page explains how edges are stored and what these queries cost. Edges are written as part of their row: a JSON array of target keys, each optionally with a label and a positive weight. ```text ["p2", ["cites", "p7"], ["extends", "p9", 0.5], {"to": "p11", "label": "refutes"}] ``` ### How far `ppr` walks A row's score is the share of the walk that has settled on it, and a row is pushed (its residual spread over its edges) while that residual is at least `eps` times its number of edges. From a seed whose neighbours have thousands of edges, `eps => 1e-4` pushes nothing past the seed: on the tests' user-item graph of 3,000 users with 30 items each, whose 100 items have 900 edges on average and at least 300, a user's items get 0.028 each, below 10⁻⁴ times their edges, so the walk ranks the user and no item. Without `eps`, the walk then halves it and pushes on from where it stopped, until its scores hold half of the walk (there, `eps` 3.1e-6, after 9,078 pushes), for at most 100,000 pushes; its plan line says where it went (`eps lowered to 3.1e-6, 72% settled`). With `eps`, it walks exactly as far as asked. A walk whose scores hold less than half of the walk, by its `eps` or its pushes, says so: `ppr_unsettled` in the stats, and in its plan line how much it settled and what to change. **Changed:** `eps` was 10⁻⁴ when not given, and such a walk returned only its seeds with no warning. ### Edge tables An `EDGES` field belongs to its source row, so adding one edge rewrites the row, its text and its vectors. A graph kept up as events arrive, such as items seen together, goes in an **edge table** instead: a table whose rows are edges, declared with `OPTIONS(edges = 'src, dst, w')`. A walk over the table whose keys it holds names the edge table where it would name a field: ```sql CREATE TABLE cooc ( id KEYWORD PRIMARY KEY, -- 'src>dst' src KEYWORD NOT NULL REFERENCES items, dst KEYWORD NOT NULL REFERENCES items, w FLOAT DEFAULT 0 ) OPTIONS(edges = 'src, dst, w'); SELECT id FROM items ORDER BY ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 20)) DESC LIMIT 200; ``` - Each row is an edge from the row whose key is in `src` to the row whose key is in `dst`, weighted by `w`, or by 1 without a weight column (`edges = 'src, dst'`). `src` and `dst` are stored, single-valued `KEYWORD` or `INT` columns of the type of the other table's key, and the weight is a stored `FLOAT` or `INT`. If `src` references a table, walks are over that table. - Writing an edge writes its row and nothing else: insert it, delete it, or add to its weight with an `add` operation, whose `doc` creates the row on the edge's first event ([writes](server.md#writes)). - Edges are directed, from `src` to `dst`. For a click on item *i* after the user's last items *h*₁ … *h*₅ (*h*₁ the most recent), adding 1/*g* to the edge *h*_g → *i* records what comes after what: `ppr(cooc, :x, dir => 'out')` and `REACHABLE(cooc, :x, dir => 'out')` follow the items that came after *x*, and `dir => 'both'`, `ppr`'s default, reads them as seen together. That is five `add` operations per event. For the next item alone, counts of what came after the last one or two items are cheaper and exact ([Next items](next-items.md)). - An edge is followed while its weight, as it is now, is above 0. `UPDATE cooc SET w = w * 0.9` decays every weight in place, and an edge whose weight is 0 or `NULL` stays in the table without being followed. `src` and `dst` are never changed in place: an `UPDATE` of a `KEYWORD` one rewrites the row, and `set`, `add` or an `UPDATE` of an `INT` one is refused, as for `shard_by` (delete the row and insert it again). - `REACHABLE`, `PATH`, `hops()` and `ppr` take an edge table with every option but `label`, since its edges have none. A walk over `cooc` and a walk over an `EDGES` field holding the same edges and weights find the same rows at the same hops and the same PageRank, up to rounding. - Each segment of the edge table indexes its rows by the keys they link, which flushes and merges build, so a walk finds a row's edges with one lookup of its key in each of the edge table's segments ([how, and what it costs](graphs.md#edge-tables)). ## Stored functions A function is kept in the database under a name, and any query calls it as it calls a built-in one. Its body is SQL: an expression of its parameters for a function that returns a value, a `SELECT` for one that returns rows (`RETURNS TABLE`). A function that returns rows stands where another database has a view (`CREATE VIEW` is refused here): `CREATE FUNCTION spend_by_country() RETURNS TABLE AS SELECT country, SUM(total) AS spend FROM invoices GROUP BY country`, read with `SELECT * FROM spend_by_country()`, joined or filtered like a table, and it may take parameters and keeps its versions. ```sql CREATE FUNCTION boosted(s FLOAT, importance FLOAT, w FLOAT DEFAULT 0.2) RETURNS FLOAT AS :s * (1 + :w * :importance); SELECT id FROM memories WHERE MATCH(body, :q) ORDER BY boosted(bm25(body, :q), importance) DESC LIMIT 10; CREATE FUNCTION recall(q TEXT, k INT DEFAULT 10) RETURNS TABLE AS SELECT id, body FROM memories WHERE MATCH(body, :q) ORDER BY bm25(body, :q) DESC LIMIT :k; SELECT * FROM recall('tokio runtime', k => 5); SELECT r.id, m.created FROM recall(:q) AS r JOIN memories m ON m.id = r.id; CREATE OR REPLACE FUNCTION boosted(...) RETURNS FLOAT AS ...; -- version 2 SELECT "boosted@1"(bm25(body, :q), importance) FROM memories ...; -- pins version 1 CREATE OR REPLACE FUNCTION boosted FROM VERSION 1; -- a rollback: version 3, as 1 DROP FUNCTION IF EXISTS boosted; -- a tombstone: version 4 DROP FUNCTION boosted VERSION 2; -- deletes an old version ``` - **The definition**: `CREATE [OR REPLACE] FUNCTION name(parameter TYPE [DEFAULT value], ...) RETURNS TYPE | RETURNS TABLE [LANGUAGE sql] [OPTIONS (description = '...')] AS body`, the body also between `$$` and `$$`. Types are `INT`, `FLOAT`, `TEXT`, `KEYWORD`, `BOOL`, `TIMESTAMP`, `JSON`, `VECTOR` or `VECTOR(n)`, and `KEYWORD[]` and `INT[]`; a default is a number, a quoted string, `TRUE`, `FALSE` or `NULL`, and the parameters after one with a default have one too. In the body a parameter is `:name`, as in a [rank profile](#rank-profiles-a-ranking-kept-with-its-table), so the body runs as written as a query with the same parameters. A body that returns a value reads only its parameters: a column is passed in as an argument. Names are letters, digits and `_`, in any case; the name of a built-in function (`lower`, `bm25`, `coalesce`, ...) is refused, and there is one function of a name, whatever its parameters. `CREATE` checks that a `RETURNS TABLE` body plans against the tables, its parameters given their defaults or a value of their type. A text parameter where a field's vectors go (`similarity(emb, :q)`, in the body or in the rank profile it ranks by) is checked as a vector of the field's size, since a call embeds it; a body that reads a blend (`SELECT * FROM blend('serp', q => :q) LIMIT :k`) is checked when it runs. A call whose body (or its rank profile) [understands](#understanding-a-querys-words-understand) or [expands](#query-expansion-expand) its words, reads a blend or gives text where vectors go runs as its body written out, so the server takes those steps as it does for a query's own. - **A call is written out**: binding replaces each call with its body, the arguments in place of the parameters, so the query plans and ranks as if it were written out (indexes, `score()` and a shard's pushdown included), and `EXPLAIN` begins with `calls stored function boosted@2`. Arguments are by position, then by name (`w => 0.5`); a missing one takes its default. A literal argument of another type than its parameter's is refused; any other expression is computed as the body would with it, and the value is the body's (`RETURNS FLOAT` of `:a + :b` with two `INT`s is an `INT`). A function that returns rows is called in `FROM`, alone, joined, or in `WITH`, and its arguments are values or parameters of the query, not columns. A function may call others, up to 16 deep. - **Versions never change**: `CREATE` writes version 1; `CREATE OR REPLACE` the next version, or nothing when the definition is the current one's; a new version returns what the old one did (a value, or rows). `DROP FUNCTION` writes a tombstone version, so version numbers keep rising and `"f@2"` always means one body. A query calls the current version, the highest that is not a tombstone, or pins one with its name and version in double quotes, which still runs after a drop. `CREATE OR REPLACE FUNCTION f FROM VERSION n` makes a new version with version *n*'s definition; `DROP FUNCTION f VERSION n` deletes an old version (not the current one). - **Kept as rows**: each version is a row of the system table `_functions` (`id` `name@version`, `name`, `version`, `language`, `kind`, `signature`, `body`, `hash`, `description`, `created`, `created_by`, `dropped`), written by its own transaction, so it is logged, numbered and shipped to replicas as writes are, and checkpoints and copies carry it. `SELECT * FROM _functions` reads it; it is not one of the database's tables, and only `CREATE` and `DROP FUNCTION` write it. The first function adds it, and the database then needs the format 3 feature `functions`, which a version of ChloeDB from before stored functions refuses by name. A database from before field ids keeps none (upgrade it first). - **From Rust**, `Db::sql` runs both statements, `Db::define_function` runs a parsed one and records who wrote it, and `Db::functions` lists every version. - **On chloedb-server**, `CREATE` and `DROP FUNCTION` need an admin key, whose name is the version's `created_by`; any key that may read calls them. `GET /v1/functions` lists each function with its current version and every version's definition. - **Through a coordinator**, a version has one number and one body on every shard: `CREATE` and `DROP FUNCTION` ask every replica which versions it holds, number the new one past all of them, and write it on each shard, so they wait for every replica to answer. A coordinator calls the versions every replica holds alike (a new version once every shard has it) and stops calling a dropped function as soon as any replica holds the drop. A shard added to the cluster gets every version under its number. Each shard records the coordinator's credential as `created_by`. ## Language models: `llm()` `llm(model, instructions, input, ...)` is a language model's answer to the instructions about the inputs, for each row a query returns. A stored function keeps the prompt and the model under a name, versioned as any function is: a new prompt or model is a new version, `"summarize@1"(body)` still asks the old one, and `FROM VERSION n` rolls back. ```sql CREATE FUNCTION summarize(t TEXT) RETURNS TEXT AS llm('anthropic/claude-haiku-5-5', 'Summarize this review in one sentence.', :t); CREATE FUNCTION mood(t TEXT) RETURNS KEYWORD AS llm('anthropic/claude-haiku-5-5', 'How does this review feel?', :t, choices => 'positive,negative,mixed'); SELECT id, title, summarize(body), mood(body) AS mood FROM reviews WHERE MATCH(body, :q) ORDER BY bm25(body, :q) DESC LIMIT 10; -- the stored summary where there is one, else the model's SELECT id, coalesce(summary, summarize(body)) FROM reviews ORDER BY rating DESC LIMIT 20; -- BM25's top 50, ranked by a grade the model gives each WITH top AS (SELECT * FROM reviews WHERE MATCH(body, :q) ORDER BY bm25(body, :q) DESC LIMIT 50) SELECT id, title, score() FROM top ORDER BY llm('anthropic/claude-haiku-5-5', 'Grade from 0 to 10 how well the review answers the question.', 'Question: ' || :q, body, returns => 'number') DESC LIMIT 10; ``` - **Where it runs.** A query that calls `llm()` runs in two steps: the query without the calls finds its rows (its `WHERE`, `ORDER BY` and `LIMIT` as written), computing what the calls read of each row, and then the model is asked about those rows, eight at once, and the columns are computed of the answers. A call may be part of a column, in arithmetic, `||`, comparisons, `CASE` and functions of values; a `CASE` asks only for the branch it takes, and `coalesce` only where the values before the call are `NULL`. `llm()` is a column of `SELECT` or part of `ORDER BY`; anywhere else (`WHERE`, `GROUP BY`, `HAVING`, a join, a `WITH`, a subquery, `UNION`) it is refused, as it would run for rows the query reads rather than returns. - **In `ORDER BY`** the calls rank the rows the query finds without that `ORDER BY` and its `LIMIT`: the top rows of a first ranking, as a [rerank phase](#rerank-phases) ranks them. Rows that tie keep the first ranking's order, a `NULL` ranks last, `LIMIT` and `OFFSET` cut the ranked rows, and `score()` is the first key's value. - **Arguments.** `model` is a string: `anthropic/` (a Claude model, its key in `ANTHROPIC_API_KEY`), `openai/`, or the name of a model directory whose `endpoint.json` names a chat server (`"api": "chat"` for OpenAI's `/chat/completions`, as vLLM, Ollama and LiteLLM serve it, or `"api": "anthropic"`), as for [text made of text](server.md#text-from-text). A directory's name is letters, digits, `_`, `-` and `.` (two such names joined by `/` at most): an absolute path, `..` or a backslash is refused, so a query reads no `endpoint.json` outside the models directory, and an `endpoint.json`'s `key_env` names a provider's key variable or a `CHLOEDB_MODEL_KEY_*` one. A query or a row cannot choose the model. The instructions are the system prompt, a string or a parameter; each input is a part of the user's message, apart by a blank line, and a `NULL` input is left out. A call with no input is `NULL`, and asks nothing. - **Answers** are text, trimmed. `choices => 'a,b,c'` asks for one of them and gives it as written there (the answer in any case, or the one choice an answer that says more names), else `NULL`. `returns => 'number'` gives the first number of the answer as a `FLOAT`, and `returns => 'bool'` its yes or no as a `BOOL`, else `NULL`. `max_tokens => n` bounds the answer (1024 for text, 64 otherwise). The model answers with its own sampling defaults: no temperature is sent (current Claude models refuse one). - **Cost.** Each distinct question (model, prompt and input) is asked once, and its answer kept in memory (10,000 of them), so the same query again asks nothing. A query asks about 100 rows at most, and a process makes 600 requests a minute at most for `llm()`: past either, the query fails before asking (chloedb-server's `--llm-rows` and `--llm-per-minute`, `chloedb::query::llm::set_limits` from Rust). A failed request fails the query (503), after the endpoint's retries. The answer's plan lines end with one that says how many rows were asked about, how many requests were made, and how many answers came from memory; `EXPLAIN` shows the plan of the rows. - **Inputs are data.** A row's text is the user's message and the instructions the system prompt, and the model has no tools, so a row's text can change that row's answer and nothing else. - **A coordinator** asks the model about the merged rows, on the coordinator, so no shard asks about a row the merge cuts, and its shards need no key. A body that calls `llm()` is a function that returns a value: `CREATE` refuses one in a `RETURNS TABLE` body, and checks each call's model and options. chloedb-server counts the requests in `chloedb_llm_requests_total`, `chloedb_llm_cached_total` and `chloedb_llm_failures_total`. ## Classifiers: `CREATE CLASSIFIER` and `classify()` > **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release. A classifier learns a table's labels from its rows' embeddings, and is kept as a [stored function](#stored-functions) of a vector: versioned, rolled back and dropped as any function is, and held by every shard of a cluster. It classifies rows by their stored vectors, and a query's text by the same model's vector of it. ```sql -- trains on the rows with a label; answers what it measured CREATE CLASSIFIER topic ON products(emb) LABELS category OPTIONS (method = 'logistic', holdout = 0.2) WHERE in_stock; -- each row's class, a column of the rows a query returns SELECT id, title, topic(emb) AS topic FROM products WHERE MATCH(title, :q) LIMIT 20; -- a query's class: :v is the query's vector ({"embed": "red leather sofa", "field": "emb", "table": "products"}) SELECT topic(:v), topic(:v, 'score'), topic(:v, 'labels'); SELECT id FROM products WHERE MATCH(body, :q) ORDER BY bm25(body, :q) * (1 + 0.25 * CASE WHEN category = topic(:v) THEN 1 ELSE 0 END) DESC LIMIT 10; CREATE OR REPLACE CLASSIFIER topic ON products(emb) LABELS category; -- version 2 CREATE OR REPLACE FUNCTION topic FROM VERSION 1; -- back to the first DROP CLASSIFIER topic; ``` - **Training.** `CREATE CLASSIFIER name ON table(vector_field) LABELS column [OPTIONS (...)] [WHERE condition]` reads `SELECT vector_field, column FROM table WHERE column IS NOT NULL [AND condition]`, at most `max_rows` rows (200,000), keeps the labels with at least `min_rows` rows (2), and holds out a share of them (`holdout`, 0.2, chosen by a hash of each vector, so the same rows every time) to measure the model it keeps. `method = 'logistic'` (the default) fits softmax regression (Adam, `epochs` 30, `learning_rate` 0.01, `l2` 0.0001); `method = 'centroid'` takes each label's mean vector, in one pass. The labels are the values of a `KEYWORD`, `TEXT`, `INT` or `BOOL` column, and the field a `VECTOR` field of one vector a row; a classifier has 10,000 labels at most. The statement answers one row: `labels`, `rows`, `train_accuracy`, `holdout_rows`, `holdout_accuracy`, `took_ms`. A coordinator reads the rows from its shards, trains, and writes the function on every shard. - **The function** is `name(v VECTOR, returns TEXT DEFAULT 'label') RETURNS KEYWORD`, its body a call of `classify(:v, model, returns => :returns)`, `model` the classifier as text: its labels, a row of weights a label quantized to 8 bits with a scale of its own, and a bias (about a kilobyte a label for a 512-number vector), and the table, field and embedding model it was trained on. `name(v)` is the label with the highest probability (the softmax of the scores), `NULL` for a `NULL` vector or one below the classifier's `min_score` option (0); `name(v, 'score')` that probability; `name(v, 'labels')` the best label and those whose probability is at least `min_score` and a tenth, best first. - **Where it runs.** A call of a value of no row, a parameter's vector, is computed before the query is planned, so it stands anywhere: `WHERE`, `ORDER BY`, a join (its `'labels'`, a list, is a column of the rows only). A call of a row's vector is a column of the rows a query returns, or ranks them in `ORDER BY`, as `llm()` is: computed after the query finds them, for 100,000 rows at most. To filter or group rows by their class, keep it in a column: a `KEYWORD` field `OPTIONS (derive = 'title', model = 'classifier:topic')` holds the label of each row written ([keywords made of text](server.md#keywords-made-of-text-languages-keyphrases-near-duplicates-entities)). - **Text.** `Db::classify(name, text, k)` (Rust) and `POST /v1/classify {"name", "text", "k"}` embed a text with the model of the field the classifier was trained on and give its `k` best labels with their probabilities. - **Measured** on Wayfair's WANDS (`chloedb-classify-eval`, `chloedb/results/text/classify_wands.json`, an Intel Xeon at 2.10 GHz, 4 cores): 42,994 products, `emb` potion-retrieval-32M's vector of a product's name, 501 product classes. The logistic classifier names the class of 81.9% of held-out products (centroid 81.3%) and the class of 62.9% of the 480 queries (centroid 51.0%; among its best three, 80.4%), at 0.07 ms a query's text, embedding included; it trains in 31 s (centroid 2 s), and a row's class costs 40 µs. As a boost, `bm25(body, :q) * (1 + 0.1 * CASE WHEN class = topic(:v) THEN 1 ELSE 0 END)` raised nDCG@10 from 0.433 to 0.439 (p = 0.002, the same on the odd-numbered queries not used to choose the weight), and a weight of 0.5 lowered it: a wrong class costs the rows that are right. ## Recommenders: `CREATE RECOMMENDER` and `recommend()` A recommender keeps counts of a table of events (what came right after what, what was seen together, how often each item was seen, each user's last items) as the events are written, and `recommend(name, user)` ranks items for a user by them, fused with the similarity of the user's recent items and with popularity, leaving out the user's recent items (the last `history`; an item the user had before those can come back: filter with `id NOT IN (SELECT item FROM events WHERE usr = :u)` to leave out every one). ```sql CREATE TABLE events (id KEYWORD PRIMARY KEY, usr KEYWORD, item KEYWORD, ts TIMESTAMP); CREATE RECOMMENDER shop ON events(usr, item, ts) ITEMS items(emb) OPTIONS (window = 3, history = 20); -- items for a user, as a score: filter, join and fuse it as any other SELECT id, title FROM items WHERE in_stock ORDER BY recommend('shop', :u) DESC LIMIT 10; SELECT id FROM items WHERE MATCH(title, :q) ORDER BY rrf(bm25(title, :q), recommend('shop', :u)) DESC LIMIT 10; -- the items themselves, and which list each came from (its rank there) SELECT * FROM recommend('shop', 'u42', k => 5); -- item | score | next | co | similar | popular -- 'p9' | 0.0485 | 1 | 2 | 7 | NULL DROP RECOMMENDER shop; ``` - **The definition.** `CREATE [OR REPLACE] RECOMMENDER name ON events(user, item, time) [ITEMS items[(vector_field)]] [OPTIONS (window = 3, history = 20)]`. The user and the item are stored, single-valued `KEYWORD` or `INT` columns of the events table, and the time a `TIMESTAMP`, `INT` or `FLOAT` column (a `NULL` time places the event last). `ITEMS` names the table whose keys the items are (of the item column's type), and its `VECTOR` field, if any, for the similar items. `window` (1 to 50) is how many events apart two items still count as seen together, and `history` (1 to 1,000) how many of a user's last events are kept, recommended from and left out of the answer. `OR REPLACE` counts the events again. - **What it keeps.** The statement counts the events already in the table, in one transaction, and answers one row: `recommender`, `counts`, `events`, `users`, `pairs`, `took_ms`. The counts are rows of an ordinary table, `_counts` (`id`, `kind`, `src`, `dst`, `next`, `co`, `n`, `recent`), which any query reads: a `pair` row's `next` is how often `dst` came right after `src` in one user's events, and its `co` how often the two came within `window` events of each other (both ways); an `item` row's `n` its events; a `user` row's `recent` the user's last `history` events as JSON. The definition is a [stored function](#stored-functions) `name()`, whose value is the definition (a function of that name that is not a recommender is refused), so it is versioned, kept by checkpoints and copies, and shipped to replicas as functions are. - **Fed from writes.** Every transaction that inserts rows into the events table, by SQL, `/v1/write`, an import or the Rust API, also adds to the counts at its commit, in the same transaction, so an event and its counts are written, logged and shipped together, and the next `recommend` sees them. An event placed between two older ones by its time takes back the pair they were and counts the two it makes. A row that replaces a row of its key (an upsert) is not a new event; deleting or updating events changes no count (`CREATE OR REPLACE RECOMMENDER` counts again). An event costs about `2 × window + 3` writes to the counts, each a read and a write by key, so writes of events take tens of times longer than without a recommender, and `CREATE` holds the writer while it counts the table (seconds per hundred thousand events). It also holds every pair it counts in memory until it commits: over MovieLens-1M (994,169 events, window 3, 1.78 million pairs) the process grew by about 2.6 GB while `CREATE` ran (25 s) and kept most of it once it had committed, against 130 MB for the counts on disk (measured on a shared 4-core, 15 GB Linux container, chloedb 0.3.8; since 0.3.10 `CREATE` names each item once while it counts and gives back what it held once it has committed). Give a `CREATE` over millions of events that much room, or create the recommender on an empty events table and load the events after it in batches, so that each batch's transaction counts only its own. Counting at write rather than when asked keeps a call to a few reads by key whatever the size of the events table: counting a million events at each call would read them all. A count an event changes is written in place in its row's segment, and a call reads each count it ranks by as last written, so calls take no longer as events arrive; `optimize()` on an embedded database, or `POST /v1/admin/optimize` on chloedb-server ([admin routes](server.md#http-api)), merges the counts' segments, which takes a call back to its time after `CREATE`. - **`recommend(name, user [, k => 100, next => 1, co => 1, similar => 1, popular => 0.2])`** reads the user's row and builds four lists of up to 200 items: what came next after the user's last item (and, at 0.4, after the one before), the items seen together with each of the user's recent items (the more recent weighing more, each item's counts as shares of its own), the items nearest the user's last eight by `maxsim` over the items' vectors, and the most popular items. An item scores the sum over the lists of the list's weight over 60 plus its rank there (reciprocal rank fusion); a weight of 0 leaves its list out. The user's recent items are left out, and the best `k` (at most 10,000) are the ranking: the call is then [`ranked(...)`](#rankedkeys-a-ranking-from-elsewhere) of their keys, so a row it does not list scores `NULL`, and `ORDER BY recommend(...)` on its own answers only the rows it lists (in a sum or `rrf` with other scores, the others rank by those). A user with no events gets the popular items. A call reads about two rows by key and one ranked page per recent item, some milliseconds. The answer's plan lines begin with one for each call: `recommend shop for 'u42': 100 items, from 12 next, 85 seen together, 200 similar, 120 popular; 9 of the user's items left out`. - **`FROM recommend(...)`** is a table of the items, best first, with `item`, `score`, and each list's rank of the item (`next`, `co`, `similar`, `popular`, `NULL` where it is not in a list); a `LIMIT` lowers `k`. It takes no join, `WHERE`, `ORDER BY` or `GROUP BY`: rank a table by `ORDER BY recommend(...)` for those. - **Where it runs.** On one database, on chloedb-server over its own tables (`CREATE` and `DROP RECOMMENDER` need an admin key), and through a coordinator when the events table is placed by its user column (`CREATE TABLE events (...) OPTIONS(shard_by = 'usr')`; over several shards, `CREATE RECOMMENDER` is refused otherwise). There each shard counts the events it holds in its own rows of the counts table, and `recommend(...)` reads them summed over the shards and ranks as one database does ([graphs and recommenders on a cluster](cluster-limits.md#graphs-and-recommenders)). A version of ChloeDB from before recommenders opens the database, but does not feed the counts. ## Blends: `CREATE BLEND` and `blend()` A blend makes one list from the rows of several queries, after each has ranked its own: stories and comments on one results page, sponsored rows among organic ones, fresh items beside popular ones. Each row is worth a utility, a weighted sum of values the sources name alike (its heads), each calibrated within its source, and the slots are filled best utility first under the slate's rules: a slot kept for a kind of row, a kind's share of the top rows, its spacing, a cap per value, diversity and near copies. ```sql CREATE BLEND serp AS SOURCES ( stories AS (SELECT id, title, author, emb, score() AS relevance, ln(1 + points) AS quality FROM items WHERE kind = 'story' ORDER BY bm25(title, :q) DESC LIMIT 100), comments AS (SELECT id, text AS title, author, emb, score() AS relevance, ln(1 + replies) AS quality FROM comments ORDER BY bm25(text, :q) DESC LIMIT 60) ) HEADS (relevance CALIBRATE tmm, quality CALIBRATE minmax MISSING zero) UTILITY 1 * relevance + 0.2 * quality SLOT 1 => source = 'stories' QUOTA (source = 'comments' BETWEEN 20% AND 40% IN TOP 10) DIVERSIFY 0.3 ON emb MAX 2 PER author DEDUPE 0.95 ON emb WITH (k => 10, note => 'stories first, a few comments'); SELECT slot, source, id, title, utility, blend_decision FROM blend('serp', q => :q); -- slot | source | id | title | utility | blend_decision -- 1 | 'stories' | 's9' | 'Async Rust...' | 1.18 | 'slot 1 is kept for source = ''stories''' -- 2 | 'comments' | 'c4' | 'I moved our...'| 0.97 | 'the best utility left' SELECT * FROM blend('serp@3', q => 'rust async') LIMIT 20; -- version 3 DROP BLEND serp; ``` - **The definition**: `CREATE [OR REPLACE] BLEND name AS SOURCES (name AS (SELECT ...), ...)` (a source may be a blend of its own, `name AS BLEND (...)`: [stacking blends](#stacking-blends-a-blend-as-anothers-source)) and then, each optional and in this order: - `HEADS (head [CALIBRATE tmm|minmax|rank|raw] [LO n] [MISSING neutral|zero], ...)`: the columns a row is worth by. A head is a column the sources name alike (`... AS relevance`), or `score`, each source's own ranking score, which needs no column. `tmm` (the default) divides by the source's best value, from `LO` (0 by default); `minmax` spans the source's lowest to its best; `rank` keeps only the order, as `rrf` does (61 / (60 + rank)); `raw` keeps the value. A source without the head gives its rows the mean of the others' (`MISSING neutral`, the default) or 0 (`MISSING zero`). Without `HEADS`, the one head is `score CALIBRATE tmm`. - `UTILITY 1 * relevance + 0.2 * quality - 0.1 * age`: the heads' weights (a head not named weighs 0; a name not among the heads adds one, `tmm`). `BOOST (source w, ...)` adds `w` to every row of a source. - `SLOT n => column = 'value'`, more than one: slot *n* is kept for rows of that value. - `QUOTA (column = 'value' BETWEEN a% AND b% IN TOP n, ...)`, or `AT LEAST a%` or `AT MOST b%`, `IN TOP n` the blend's `k` by default; `IF ANY` holds the least only when the sources answered a row of the kind. A kind that could only reach its least by being placed now is placed now; one at its most is passed over. - `SPACING (column = 'value' AT MOST n PER m ROWS, ...)`: at most *n* rows of the kind in any *m* in a row. - `DIVERSIFY λ ON column`: each candidate loses λ (0 to 1) of the utilities' range for its likeness to the rows placed, the cosine of a vector column's values or 1 for an equal value of another column (maximal marginal relevance). - `MAX n PER column`, more than one: at most *n* rows of one value, as [`MAX k PER`](#at-most-k-rows-of-a-value-max-k-per) does for one query. - `DEDUPE t ON vector_column`: a row whose cosine to a row placed is *t* or more is left out. - `WITH (k => 10, note => '...')`: the slots filled (1 to 1,000), and a note kept with the version. At most 16 sources, each a `SELECT` (any ranking: a rank profile, `rrf`, `recommend(...)`, a stored function), named once. The rules' numbers are checked (a quota's least at most its most, spacing's *n* under its *m*, λ from 0 to 1), and so is that the quotas' least shares and the slots kept fit in their top rows. `CREATE` answers one row: `blend`, `version`, `sources`, `k`. - **A row's key** is its table's key, or the first column where it reads none: rows of one key from two sources are one row, kept where its utility is higher (`also` in the receipts names the others). Its `source` is the source's name, and a rule's column may be `source` or any column the sources answer. - **The fill** places the rows slot by slot. A slot kept by `SLOT` takes the best row of its kind; otherwise a quota that would fall short if not met now takes its kind's best row; otherwise the best utility left (less its diversity cost) of the rows no rule bars. When no row fits every rule, the fill sets rules aside for that slot, in this order, until one does: spacing, the caps, a quota's least, the slots kept, a quota's most; the row says so (`no row fit every rule: MAX 2 PER author set aside`), so a blend fills its slots while rows are left (`DEDUPE` is never set aside). - **`FROM blend('name[@version]' [, parameter => value, ...]) [LIMIT k]`** runs each source with the call's arguments and the query's parameters as its parameters (`:q`), and answers a row per slot, best first: `slot`, `source`, the sources' columns (all of them for `*`, each source's `NULL` where it has none), `utility` and `blend_decision`, the reason the row is in its slot. A `LIMIT` fills that many slots instead of `k` (a quota's least may then not fit). A call takes no join, `WHERE`, `ORDER BY` or `GROUP BY`; select the columns, and alias them, as `SELECT id, title AS name FROM blend('serp', q => :q)`. The answer's plan lines say what it did: `blend serp@2: 2 sources, 160 rows (stories 100 rows in 3.1 ms, comments 60 rows in 1.4 ms)`, then `blend placed 10 of 10 slots in 0.04 ms: stories 7, comments 3` and a line for each quota's count. - **Versions.** A blend is a [stored function](#stored-functions) `name()` whose body is the definition, so `CREATE OR REPLACE BLEND` writes the next version, `blend('serp@1')` reads an old one, `DROP BLEND [IF EXISTS] name` writes a tombstone (its versions stay readable by number), and versions are kept by checkpoints and copies and shipped to replicas as functions are. A function of the name that is not a blend is not replaced by one. - **From Rust**, `Db::sql` runs the statements and the calls, `Db::blends` lists each blend's current definition, and `Db::blend_run(&def, version, ¶ms, k, Want { costs: true })` runs a definition, stored or not, into a `Blended` whose `receipts()` is the JSON of every row's heads, raw and as weighted parts of its utility, its slot and why, the rows passed over and what barred them, each quota's count and each rule's cost: the share of the slate's discounted utility (each slot's over log2(slot + 1), as DCG discounts) that it gives up, from filling the slate again without it. - **On chloedb-server**, `CREATE` and `DROP BLEND` need an admin key, and a key limited to tables reads a blend only when it may read every source's tables, of every version the call could read. `GET /v1/blends` lists the blends (each current version's definition, its SQL and how many versions), `GET /v1/blends/:name` every version, `PUT /v1/blends/:name {"def": {...}, "note": "..."}` writes the next version from a definition as JSON, and `DELETE /v1/blends/:name` drops it. `POST /v1/blends/preview {"name": "serp"}` (or `"version"`, or a definition not stored, `"def"`) with `"params"` and `"k"` runs it and answers the receipts, rule costs included unless `"costs": false`. The command center's **Labs → Blending** page edits a blend on these routes, previewing the draft as it changes. - **Through a coordinator** a blend's versions are written on every shard, as functions are, and each source runs as a query of the cluster, merged from the shards, before the fill: the slate is the one database's. ### Stacking blends: a blend as another's source A source may be a blend of its own, a node stacked under the one above it: `name AS BLEND ( SOURCES (...) HEADS ... WITH (k => n) )`, the same clauses as a blend's. The node runs first, into its own *k* slots under its own rules, and the rows it places are that source's rows above, so the blend above weighs, places and rules them as one source among its others. ```sql CREATE BLEND page AS SOURCES ( organic AS BLEND ( SOURCES ( stories AS (SELECT id, title, author, score() AS relevance, pop AS engagement FROM stories ORDER BY bm25(title, :q) DESC LIMIT 50), videos AS (SELECT id, title, author, score() AS relevance, pop AS engagement FROM videos ORDER BY bm25(title, :q) DESC LIMIT 30) ) HEADS (relevance CALIBRATE tmm, engagement CALIBRATE minmax) UTILITY 1 * relevance + 0.4 * engagement MAX 2 PER author WITH (k => 20) ), sponsored AS BLEND (SOURCES (ads AS (SELECT id, title, author, bid AS score FROM ads ORDER BY bid DESC LIMIT 6)) WITH (k => 3)), news AS (SELECT id, title, author, 1.0 / age AS freshness FROM news ORDER BY age LIMIT 10) ) SLOT 2 => source = 'sponsored' QUOTA (source = 'news' AT LEAST 20% IN TOP 5, via = 'organic/videos' AT MOST 30%) WITH (k => 10); SELECT slot, source, via, id, title FROM blend('page', q => :q); -- slot | source | via | id | title -- 1 | 'organic' | 'organic/stories' | 's12' | 'Async Rust...' -- 2 | 'sponsored' | 'sponsored/ads' | 'a3' | '...' -- 3 | 'news' | 'news' | 'n1' | '...' ``` - **A node's rows**, as the blend above reads them: its sources' columns, `slot` (its own), `via` and `utility`, which is also their score, so the head `score` above is the node's utility; their keys stay theirs, so a row a node and another source both give is one row above. `via` names the source a row came from, through each node on the way (`organic/stories`): every blend answers it, and a rule above may read it (`QUOTA (via = 'organic/videos' AT MOST 30%)`). - **Its rules hold among its own rows**: a node's quotas, caps and diversity shape the rows it gives, and the blend above may pass over some of them. A node is named as its source; its own `name` may be left out in JSON. - **Limits**: blends stack at most 4 deep, the top one counted, and a blend runs at most 32 queries under every node. A source that reads `blend('...')` is refused: stack the blend as a node instead. - **Logged and valued**, a stacked blend explores at the top only (each node takes its best rows), and the log keeps the rows each node gave as that source's rows, so [Value on the log](#valuing-a-blend-on-its-log-exploring-fills-cascade-doubly-robust-and-snips) and tuning work on the top blend's heads, quotas and diversity as they do for any blend. - **The receipts** of a stacked blend carry each node's own under `nodes` (`"nodes": {"organic": {...}}`, nodes of nodes within them), each row's `via`, and the SQL writes nodes back as `name AS BLEND (...)`. On chloedb-server a key limited to tables reads a stacked blend only when it may read the tables of every query under every node. ### Valuing a blend on its log: exploring fills, cascade doubly robust and SNIPS A blend served with a [log](#the-rank-log-what-each-query-served) can explore, and a log of exploring pages values any other blend of the same sources (its weights, shares and rules changed) without serving it: what people clicked is reweighted by how likely each page was. ```sql -- POST /v1/query, or Db::query_logged with a Log {"sql": "SELECT slot, source, id, title FROM blend('serp', q => :q)", "params": {"q": "rust async"}, "log": {"context": "u42", "explore": {"policy": "softmax", "tau": 0.3, "top": 5}}} ``` - **The exploring fill.** At each slot the rows that fit the rules there (the same rows the best-taken fill would weigh) are ordered by their utility, less diversity's cost, and the slot draws among the best `top` of them with chances `exp(u / (tau × range))` (the range of those utilities, so `tau` is a share of it, not a number of the heads' units). `top` 1, or no `explore`, takes the best. The draws come from the request's id (`log.request`, or a random one), so a request served again draws the same page. Only `softmax` explores a blend (`by` the score, the utility); `candidates` and `interleave` are refused. - **What is logged**: every row of every source, not only those placed, with its cells (a vector column the rules read as its numbers; text up to 256 characters), its source and rank in it and its utility as the row's `score`; the rows placed come first, in slot order, each `shown` with its slot's chance (`propensity`) and the page's chance down to it (`prefix_propensity`); the first row's `policy` names the blend, its version, `k`, `tau`, `top` and sources. The answer has the chances as `propensities`, one a slot. - **Replay.** From the logged rows, a blend's fill runs again over each logged page, the logged rows above each slot taken as placed: it gives that blend's chance of the logged row at every slot, and the rows it would have weighed. Replayed through the logging blend's own version, it gives back the chances logged (a difference is reported as drift, and the verdict is not proven: the rows or the definition changed). - **Cascade doubly robust** (Kiyohara et al., 2022) values a blend over the logged pages as `Σ_l γ_l (w_l (r_l − q̂_l) + w_{l−1} Σ_a π(a | slot l) q̂(a))`, plus the model's value of the rest of the page where the weight is cut: `w_l` is the product, down to slot `l`, of the blend's chance of each logged row over the logging blend's, `r_l` the click at slot `l`, and `q̂` a click model (ridge regression over the slot, the rows' numbers and their numbers over log2(slot + 1)) fitted on one half of the searches to value the other (two folds by request). A search whose weight passes `max(1% of the searches, 10)` is valued by the model from that slot down (the share is `switched`). Without `"discount": true` a page is worth its clicks; with it, each slot's over log2(slot + 1). - **SNIPS beside it** (self-normalized importance sampling) reweights the clicks slot by slot with no model, normalized by the weights' sum, over the top slots that each have 100 effective searches or more (`check_depth`); cascade doubly robust over those same slots is compared with it. Far apart, beyond their intervals, the model or the chances are off. - **Support and coverage.** `support` is the effective number of searches at slot 1, `(Σw)² / Σw²` (400 or more is trusted). `coverage` is the share of the blend's value, slot by slot as the model weighs it, on pages the logging blend could have drawn: a blend far from the one that logged puts some of its rows where the log never could, and that part is the model's alone (below 95% the verdict is not proven: explore wider, a larger `top` or `tau`). - **The verdict.** The first blend valued is judged against the logged blend's own value, each other one against the first, paired search by search: `better` or `worse` when the 95% interval of the difference leaves 0, `same` when it holds 0, and `not proven`, with why, when there are no exploring searches, the replay drifts, coverage is short, support is thin or the two estimates disagree. - **Tuning** tries blends near a start (each head's weight scaled, a quota's shares moved, diversity changed; one or two changes each), values each by cascade doubly robust on one half of the searches (its click model cross-fitted over that half's two quarters), and values the best of those the log covers (95% or more), with the start, on the other half, which chose nothing: that held-out estimate is the one to trust. A blend the log mostly could not have drawn is not chosen, however well the click model guesses it does. - **From Rust**, `Db::blend_requests(&export, "serp")` gathers a log's exploring requests of a blend ([`Export`](#exporting-the-log-for-training): the log, the events and the window a click counts in), `blend_eval::evaluate(&mut requests, &logging, &targets, Options { discount })` values blends (`Target { label, def, explore }`, `explore` to value an exploring fill, the best taken without), and `blend_eval::tune` tunes one; `blend_eval::versions` gives the logging blend's definition of each version. - **On chloedb-server**, `POST /v1/blends/:name/evaluate {"export": {...}, "targets": ["serp@3", {"def": {...}, "label": "draft"}], "discount": false}` and `POST /v1/blends/:name/tune {"export": {...}, "start": ..., "rounds": 24}`, with read on the log and the events; through a coordinator, the log's rows are read from every shard. The command center's **Labs → Blending** sets a draft against the serving version this way (**Value on the log**) and tunes it toward the clicks. ## Chunks of a table's text: `chunks_of()` > **Experimental.** This is new in 0.3.0, and its options and answers may change in a later release. `chunks_of(table, text_field)` is a table of the pieces of each row's text, for a table of chunks that a vector field embeds, or a budgeted context packs from. ```sql SELECT id, n, tokens, chunk FROM chunks_of(docs, body, max_tokens => 256, overlap => 32) WHERE lang = 'en' LIMIT 20; CREATE TABLE chunks (id KEYWORD PRIMARY KEY, doc KEYWORD, n INT, body TEXT, tokens INT, emb VECTOR(512) OPTIONS (embed = 'body', model = 'potion-retrieval-32M')); INSERT INTO chunks (id, doc, n, body, tokens) SELECT chunk_id, id, n, chunk, tokens FROM chunks_of(docs, body, max_tokens => 256); ``` - **Splits.** A text is cut where it says most: before a Markdown heading, then at blank lines, then after a sentence's end, then between words, and between characters only for a word longer than a chunk. The pieces are joined in order while a chunk holds at most `max_tokens` (256, from 16 to 8192), and a heading always starts a chunk. With `overlap => m` (0), each chunk after the first starts with about `m` tokens of the end of the one before, from a word's start. - **Tokens** are estimated as a quarter of the characters, rounded up: close for English and most models' tokenizers, and the same on every machine. - **Columns.** `id` (the row's key), `n` (0, 1, ...), `chunk_id` (`'#'`, a key for a table of chunks), `chunk`, `tokens` (with the overlap), and `start_char` and `end_char`, where the chunk's own text is in the row's, in characters. The query names some of them, or `*`. - **The query** is read as written: its `WHERE` is a condition of the source table's rows, and its `LIMIT` cuts the chunks. It takes no join, `ORDER BY`, `GROUP BY` or `OFFSET`: write the chunks to a table to do those. `INSERT INTO t (columns) SELECT ... FROM chunks_of(...)` writes them, as `INSERT`s of 500 rows each. A coordinator reads the rows from its shards and splits them itself. The field is a stored `TEXT` field. A call reads as many of the table's rows as its `LIMIT` needs (each row with text gives a chunk at least; when rows without text leave the `LIMIT` unfilled it reads twice as many again), 1,000,000 at most without one, and what it reads may hold 1 GiB at most (or the query memory budget, if smaller): a read the database makes for itself is not held to a server's `--max-rows`, so this bounds it. ## Running SQL A statement reaches ChloeDB from a program, over HTTP or in the command center. ChloeDB serves no Postgres wire protocol, so `psql` and the tools built on Postgres's drivers (DBeaver, Metabase, dbt's Postgres adapter, SQLAlchemy's Postgres dialect) do not connect to it. The ways in, quickest first: - **Python, on a file.** `pip install chloedb`, then `chloedb.open(path).sql(statement)` runs any statement on a database file in the process, and `chloedb.dbapi` is a DB-API 2.0 driver that pandas' `read_sql`, and tools written for `sqlite3`, take ([Python](python.md)): ```sh python3 -c 'import chloedb; print(chloedb.open("products.chloedb", read_only=True).sql("SELECT category, COUNT(*) FROM products GROUP BY category").rows)' ``` - **A server, and its SQL workbench.** `uvx chloedb-server --demo 20000 --db products.chloedb` (or `pip install chloedb-server`, then `chloedb-server ...`) serves a database on `http://127.0.0.1:7700`, whose command center has a SQL workbench (completion with the columns' types, parameters, the plan as a tree, and a check before a write). `POST /v1/sql` takes one statement, and `chloedb-server cc` is the command center in a terminal, with a SQL screen: ```sh curl -s localhost:7700/v1/sql -H 'content-type: application/json' \ -d '{"sql": "SELECT category, COUNT(*) FROM products WHERE MATCH(body, '"'"'waterproof'"'"') GROUP BY category ORDER BY 2 DESC LIMIT 5"}' ``` - **Other languages.** `db.sql` in [JavaScript](javascript.md), the JDBC driver (`jdbc:chloedb:`) in Java, and `Db::sql` in Rust, which takes any statement, on any table, writes and `CREATE TABLE` included. - **The `chloedb` shell**, built from source, runs one statement or reads statements from standard input. It opens a database that exists and does not create one; these lines read the demo catalogue the server above makes: ```sh cd chloedb && cargo build --release target/release/chloedb products.chloedb "SELECT category, COUNT(*) FROM products WHERE MATCH(body, 'waterproof') GROUP BY category ORDER BY 2 DESC LIMIT 5" --plan target/release/chloedb products.chloedb --param t='waterproof tent' < queries.sql ``` | flag | effect | |---|---| | `--param name=value` | binds `:name`: a number, a string, or a JSON array for a vector | | `--plan` | prints the plan lines the executor recorded for each statement | | `--repeat n` | runs each statement *n* times and reports the median time | | `--read-only` | opens the database read-only, to read it while another process writes it ([readers in other processes](index.md#readers-in-other-processes)); without it, the shell opens a database another process has open to write read-only, and says so | From Rust, `Db::query` takes a `SELECT` and a `Params` map. Over the network, [chloedb-server](server.md) serves the same SQL over every table of a database. ### The types of an answer's columns An answer gives each column's type, as its values have it, whatever the column is named: `int`, `float`, `bool`, `timestamp`, `text`, `vector` or `list`, and none (`null`) for a column of only `NULL`s or of values of types that do not mix (a `CASE` of text and numbers). So `MAX(ts)`, `ts AS d`, `i.ts` in a join, `date_trunc('month', ts)`, `date_bin(...)`, `CAST(ts AS DATE)` and `ts + INTERVAL '1 day'` are `timestamp`, as `ts` is, and `CAST(ts AS TEXT) AS ts` is `text`. A column of `INT`s and `FLOAT`s is `float`. Over HTTP the answer's `types` lists them beside `columns` , in Python and JavaScript `result.types`, and in Rust `ResultSet::types`; Python's [DB-API driver](frameworks.md#db-api) and `Result.to_pandas()` make a `timestamp` column's values datetimes, and an [Arrow answer](server.md#http-api) types each column as an Arrow array. The values themselves stay as JSON has them: a `TIMESTAMP` as ISO 8601 text in UTC, a `BOOL` as `true` or `false`. ## Tables A database starts with the table it was created with, and `CREATE TABLE` adds more. `SHOW TABLES` lists their names, a row each (through `db.sql` or `POST /v1/sql`; a key limited to tables sees its own), and `GET /v1/tables` their columns too. An example, a table of orders: ```sql CREATE TABLE orders (id KEYWORD PRIMARY KEY, customer KEYWORD, status KEYWORD, total FLOAT, note TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP); ``` `KEYWORD` holds exact values (ids, statuses), `TEXT` words searched with `MATCH`, `INT` and `FLOAT` numbers, `TIMESTAMP` times, and `VECTOR` embeddings; a type followed by `[]` holds a list. It needs an admin key. A larger example: Each table has its own columns, primary key, indexes and merges; the tables share the file, its write-ahead log and transactions. ```sql CREATE TABLE authors ( id KEYWORD PRIMARY KEY, name TEXT OPTIONS(analyzer = 'simple'), born INT, topics KEYWORD[], bio TEXT OPTIONS(positions = false), emb VECTOR OPTIONS(embed = 'name, bio', model = 'potion-retrieval-32M') ); CREATE TABLE IF NOT EXISTS wrote ( id INT PRIMARY KEY, author KEYWORD NOT NULL REFERENCES authors, paper KEYWORD REFERENCES papers (id), role KEYWORD NOT NULL DEFAULT 'author', added TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE events ( id INT PRIMARY KEY, usr KEYWORD NOT NULL, item KEYWORD, ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) OPTIONS(shard_by = 'usr', cluster_by = 'usr', retain = '400 days'); DROP TABLE IF EXISTS wrote, authors; ``` - **Types** are `TEXT`, `KEYWORD`, `INT` (or `INTEGER`, `BIGINT`), `FLOAT` (or `DOUBLE`, `REAL`), `BOOL` (or `BOOLEAN`), `TIMESTAMP` (or `TIMESTAMPTZ`, `TIMESTAMP WITH TIME ZONE`, `DATETIME`, and `DATE`, which is a `TIMESTAMP`: a date written alone is its midnight UTC), `VECTOR(dimensions)` (1 to 65,536 dimensions), `SPARSE`, `MEDIA` and `EDGES`; `KEYWORD[]` and `INT[]` hold lists, and `VECTOR(dimensions)[]` several vectors per row ([multi-vector fields](#maxsimfield-vectors-several-query-vectors)). A `BOOL` or `TIMESTAMP` column holds one value and is neither the primary key nor a reference. PostgreSQL's and MySQL's other names take the type that holds the same values, so a schema written for them runs as it is, its lengths and precisions ignored: `VARCHAR(n)`, `CHAR(n)`, `CHARACTER VARYING`, `NVARCHAR`, `UUID` and `CITEXT` are `KEYWORD` (exact values, as `CAST(x AS VARCHAR)` makes; write `TEXT` for a column searched by its words), `SMALLINT`, `TINYINT` and `INT2`/`INT4`/`INT8` are `INT`, `NUMERIC(p, s)`, `DECIMAL` and `FLOAT8` are `FLOAT` (a double, not an exact decimal), and `TIMESTAMP WITHOUT TIME ZONE` is a `TIMESTAMP`. `SERIAL` is refused: ChloeDB has no sequences, so a row is given its number (`INT PRIMARY KEY`) or a `KEYWORD` key such as a UUID. - **`OPTIONS(...)`** takes the options of the [JSON schema](server.md#schemas): `substring` (true: `LIKE` and `ILIKE` on the column read a [substring index](#substrings-like-and-ilike-anywhere-in-a-value)), `positions`, `stored` and `indexed` (true or false; an indexed `TEXT` or `SPARSE` field is stored unless generated, since merges rebuild its index from the stored values), `from` (the fields a generated `TEXT` field joins), `analyzer` (`'english'`, the default: stopwords dropped and words stemmed, so `running` finds `run`; `'simple'`: every word kept as written, for names and codes; `'standard'`: text in [any language and script](index.md#text-in-other-languages), Chinese, Japanese, Korean and Thai included; `'cjk'`: `standard` with pairs of characters as the terms of Chinese and Japanese; or a language, such as `'french'`, `'german'`, `'arabic'`, `'hindi'` or `'chinese'`, which is `standard` with what the language needs, a stemmer for most), `index` (`'hnsw'` with `m` and `ef_construction`, `'flat'`, or `'ivf'` with `nlist`), `partition_by` with `partition_bounds` (a graph per range or value of a column, for [filtered searches](#vector-partitions)), `codes` (`'sq8'`, `'binary'`, `'rabitq1'`, `'rabitq2'` or `'rabitq4'`; a multi-vector field searches `'binary'` by default), `keep_f32` (a multi-vector field keeps its float32 vectors to score with, four times the bytes of its 8-bit codes), `pool` (a multi-vector field merges a row's vectors whose cosine similarity is at least this, such as `0.9`, into their mean when it is written), `pool_factor` (a multi-vector field clusters a row's vectors into one group for every this many, such as `2`, by Ward's linkage, and keeps each group's mean when it is written; exclusive with `pool`), `kind` of a `MEDIA` field, `derive` (a `MEDIA` field) with `model` for [text made from media](server.md#text-from-media), `embed` with `model` for an [embedded vector field](server.md#embedded-vector-fields), which may leave out its dimensions when ChloeDB knows the model's (`VECTOR` alone), or an [embedded `SPARSE` field](server.md#term-weights-of-a-learned-sparse-model), and on a `KEYWORD[]` `semantic_id` (the vector field) with `codebook` for a [semantic-ID field](server.md#semantic-ids): `sid KEYWORD[] OPTIONS(semantic_id = 'emb', codebook = 'items-rq')`. Field lists are a string, `'name, bio'`, or `ARRAY['name', 'bio']`. - **The primary key** is one column: `PRIMARY KEY` on it, or a `PRIMARY KEY (column)` constraint. A table without one only takes plain `INSERT`. - **`REFERENCES table`**, or `FOREIGN KEY (column) REFERENCES table`, records that a `KEYWORD` or `INT` column holds primary keys of that table, which must exist (or be the table being created) and have a primary key of the column's type. References are not enforced: a row may name a key that is not there, and an inner join along the reference leaves that row out (`LEFT JOIN` keeps it). Joins along them are [ordinary joins](#subqueries-with-and-joins) (`FROM wrote w JOIN authors a ON w.author = a.id`). - **`NOT NULL`** refuses a row without a value in that column, from any write: SQL, JSON, a file or the Rust API. **`DEFAULT value`** is the value a write that leaves the column out gets: a constant of the column's type on a single-valued `TEXT`, `KEYWORD`, `INT`, `FLOAT`, `BOOL` or `TIMESTAMP` column that is not the key, or `CURRENT_TIMESTAMP` (or `now()`) on a `TIMESTAMP`, the time of the statement, the same in all its rows. An `INSERT` that leaves a column out, a JSON row without its key and a CSV file without its column give it the default; a `NULL` that a write gives stays `NULL`, and a column with `NOT NULL` refuses it. In SQL the keyword `DEFAULT` stands for a column's default, in `VALUES` and in `SET`, and `CURRENT_TIMESTAMP` (or `now()`, `LOCALTIMESTAMP`) is the time of the statement there and in conditions (`SET seen = CURRENT_TIMESTAMP`, also in `ON CONFLICT ... DO UPDATE`). The Rust API writes a row as it is given; `Schema::defaults` returns a row of the defaults to start from. The JSON schema's options are `"not_null": true` and `"default"` (`"now"` for the time of the write). - **`OPTIONS(shard_by = 'column')`** after the columns places the table's rows on [shards](server.md#tables-on-shards) by that column instead of by the primary key, so that a user's events sit on one shard together. The column is a stored, single-valued `KEYWORD` or `INT` with `NOT NULL`, other than the key, and a row keeps it: `UPDATE` does not change it (delete the row and insert it again). In JSON it is `"shard_by": "usr"`. One database places nothing, so the option only matters to a coordinator. - **`OPTIONS(cluster_by = 'column')`** stores each segment's rows sorted by that column, rows of one value in the order they were written: a flush sorts the rows it writes, and a merge sorts the rows of the segments it joins. A user's history then sits in one run of each segment instead of scattered across it, so reading it touches a few pages rather than one per row. The column is an indexed, single-valued `KEYWORD`, `INT` or `TIMESTAMP`, and a row keeps it (`UPDATE` does not change it). Queries return the same rows either way; only `ORDER BY` fixes their order. In JSON it is `"cluster_by": "usr"`. - **`OPTIONS(retain = '400 days')`** drops rows once their time is older than the period: a flush does not write them, and a merge leaves them out of the segment it writes, or drops a segment whose rows are all past it without rewriting or reading anything; the merger looks for such segments on its own. Such a table's segments merge only within windows of time, a thirtieth of the period each (from a second to a day): a segment holds rows of one window, as of its newest row, so a table kept 30 days holds segments of a day at most, and each leaves whole once its newest row is past the period rather than being rewritten as its rows expire. Until then a query still finds them, so filter on the time where that matters (`WHERE ts > '2025-10-01'`). The time is the table's only `TIMESTAMP` column, or the one `retain_by = 'column'` names (indexed, single-valued, and not changed by `UPDATE`); a row without one is kept. A period is a whole number and a unit: seconds, minutes, hours, days or weeks (`'90 s'`, `'12h'`, `'2 weeks'`). In JSON it is `"retain": "400 days"` with `"retain_by"`. - **`OPTIONS(expire_by = 'column')`** expires each row at the time its column holds, as a key-value store's TTL does: from that moment on queries, counts, joins and reads by key leave the row out, and a write by its key finds no row there (an `INSERT` of the key succeeds, an `UPDATE` changes nothing). Rows without a time never expire, and `UPDATE ... SET until = ...` (or a `set` in place) moves a row's time. A server that takes writes deletes expired rows every few seconds, and `Db::expire` (Python: `expire()`) does it at once; those deletes are logged as any delete is, so [replicas](server.md#replication-a-primary-and-its-replicas) hold the same rows without reading a clock. Unlike `retain`, which drops old rows when segments are written and leaves them visible until then, an expired row is gone for reads at once. The column is an indexed, single-valued `TIMESTAMP`, the table has a primary key, and `DROP COLUMN` keeps the column (`RENAME COLUMN` renames the option too). It makes the database format 3, feature `expire_by`. In JSON it is `"expire_by": "until"`. ```sql CREATE TABLE sessions ( id KEYWORD PRIMARY KEY, usr KEYWORD, until TIMESTAMP ) OPTIONS(expire_by = 'until'); INSERT INTO sessions (id, usr, until) VALUES ('s1', 'u7', '2026-11-02T12:00:00Z'); ``` - **`OPTIONS(compression = 'zstd')`** compresses the table's stored rows (its doc store) with zstd in 32 KiB blocks instead of LZ4 in 16 KiB ones. On four logs from Loghub the doc store took 32% to 39% less, and the database 9% to 16% less, while a read of one row by key took 12% to 40% longer (48 µs instead of 34 on 11M lines) and a scan of every row about as long (`chloedb/results/log-bytes/`, on a 4-core cloud container). It suits tables that are written far more than read row by row, such as logs; queries that count, filter, group or search without returning rows read no stored rows either way. Segments written after the option use it, and older ones keep LZ4 until a merge rewrites them. It makes the database format 3, feature `zstd`. In JSON it is `"compression": "zstd"`; `'lz4'` is the default. - **`OPTIONS(edges = 'src, dst, w')`** makes each row an edge of a graph over another table's rows, which walks over that table follow ([edge tables](#edge-tables)). In JSON it is `"edges": "src, dst, w"`. - **`DROP TABLE`** drops tables other than the first. A table that another table references goes with it (`DROP TABLE wrote, authors`) or with `CASCADE`, which removes those references. - **`CREATE TABLE ... AS SELECT`** makes a table of a `SELECT`'s rows ([below](#rows-from-a-select-insert--select-and-ctas)). - Every other clause (`UNIQUE`, `CHECK`, `ON DELETE`, constraint names, a `DEFAULT` that is an expression, `CREATE OR REPLACE TABLE`, temporary tables) is an error. `CREATE TABLE`, `ALTER TABLE` and `DROP TABLE` run through `Db::sql`, Python's in-process [`chloedb.Database`](python.md), and [chloedb-server](server.md#schemas)'s `POST /v1/sql`, where a coordinator runs them on every shard. ### Changing a table's columns ```sql ALTER TABLE products ADD COLUMN stock INT NOT NULL DEFAULT 0; ALTER TABLE products ADD COLUMN IF NOT EXISTS brand KEYWORD, ADD note TEXT; ALTER TABLE products ADD COLUMN emb2 VECTOR OPTIONS(embed = 'title', model = 'potion-retrieval-32M'); ALTER TABLE products RENAME COLUMN note TO notes; ALTER TABLE products DROP COLUMN IF EXISTS notes; ALTER TABLE IF EXISTS drafts DROP COLUMN body, DROP COLUMN title; ``` `ALTER TABLE` changes the columns of any table, the first included, while it holds rows; the changes of one statement apply in order, as one change. - **`ADD COLUMN`** (or `ADD`) takes a column as `CREATE TABLE` does, with its type, `NOT NULL`, `DEFAULT`, `REFERENCES` and `OPTIONS`, and puts it last. Rows written before it read it as its default, or `NULL` without one (a `TIMESTAMP` with `DEFAULT CURRENT_TIMESTAMP` too: the default is the time of each later write): in `SELECT`, `WHERE`, `ORDER BY`, aggregates and searches alike. Writes from then on take it. A `NOT NULL` column without a default can only be added to a table without rows. A column added with `embed` gets its model and embeds the rows written from then on; the rows before get theirs from [the backfill](server.md#embedded-vector-fields), which a server runs once the model opens, Python's `Database` before the `ALTER TABLE` (or `add_column`) returns, and Rust with `Db::embed_backfill`; until then they have none, and `similarity()` does not find them. A generated `TEXT` column, a semantic-ID column, `EDGES` and a primary key cannot be added. - **`DROP COLUMN`** drops a column and its values; a column added again under the same name is a new column, `NULL` in the older rows. The primary key, a table's only column, a column another field names (as the source of a generated text, an embedding, a caption or semantic IDs) and one the table's options name (`shard_by`, `cluster_by`, `retain_by`, `expire_by`, `edges`) stay, and the statement says what names it; so do columns a [rank profile](#rank-profiles-a-ranking-kept-with-its-table) of the table ranks by. - **`RENAME COLUMN a TO b`** keeps the column's values, and the fields and options that name it follow it; a rank profile does not, so a column a profile ranks by keeps its name until the profile is dropped or replaced. - **`IF EXISTS`** after `ALTER TABLE` skips a table that is not there; `ADD COLUMN IF NOT EXISTS` and `DROP COLUMN IF EXISTS` skip a column that is, or is not. Positions (`FIRST`, `AFTER`), `ALTER COLUMN`, `RENAME TO` (of the table) and `CASCADE` are errors. A change writes nothing but the table's schema: it waits for writes in flight, writes the memtable as segments (a write-ahead log names columns by position), and commits the new schema. A segment written before a column was added does not hold it; when it is opened, the column's index is built in memory over its rows' default, and the next merge that rewrites the segment writes the column for real. A dropped column's values stay in the older segments, unread, until merges rewrite them. The Rust API is `Db::alter_table(table, &[Alter::AddField(field), Alter::DropField(name), Alter::RenameField { from, to }])`; a database with a column added later needs the feature `added_fields`, so a version of ChloeDB from before it refuses the database. On chloedb-server, a coordinator runs `ADD COLUMN` and `RENAME COLUMN` on every shard and then serves the table as altered; it refuses `DROP COLUMN`, since its plans name a table's columns by position and a query planned while some shards had dropped the column would read the next one. A primary ships the change to its replicas in its place among the writes, as it ships `CREATE TABLE` and `DROP TABLE`, and its replicas give the table the same columns under the same field ids ([replication](server.md#replication-a-primary-and-its-replicas)). ## Writes ```sql INSERT INTO products (id, title, price, tags, emb) VALUES ('p1', 'red mug', 12.5, ARRAY['kitchen', 'gift'], :v); INSERT OR REPLACE INTO products (id, title, price) VALUES ('p1', 'red mug, large', 14.0); INSERT INTO products (id, title, price) VALUES ('p2', 'blue mug', 11.0) ON CONFLICT (id) DO NOTHING; INSERT INTO products (id, title, price) VALUES ('p1', 'red mug', 12.0) ON CONFLICT (id) DO UPDATE SET price = excluded.price, stock = stock + 10; UPDATE products SET stock = stock - 1, price = 11.0 WHERE id = 'p1'; UPDATE products SET stock = DEFAULT WHERE id = 'p2'; UPDATE products SET price = round(price * 0.9, 2), title = title || ' (sale)' WHERE tags = 'gift'; INSERT INTO products (id, stock) VALUES ('p1', 5) ON CONFLICT (id) DO UPDATE SET stock = coalesce(stock, 0) + excluded.stock; DELETE FROM products WHERE MATCH(title, 'discontinued'); DELETE FROM products WHERE stock = 0 ORDER BY price LIMIT 100; ``` - A write names its table, any table of the database. - **`INSERT`** fails on a primary key that already exists. **`INSERT OR REPLACE`** (or `REPLACE INTO`) replaces that row, an upsert. **`ON CONFLICT (key) DO NOTHING`** (or `INSERT OR IGNORE`) writes only the rows whose key is new, and the first of a key the statement repeats. **`ON CONFLICT (key) DO UPDATE SET ...`** inserts the new keys and sets fields of the rows already there, where `excluded.column` is the value the statement gave; a key that comes twice in one such statement is an error. On a cluster, a table placed by `shard_by` keeps its keys unique across shards for `INSERT`, `INSERT OR REPLACE` replaces a row only on its `shard_by` value's shard, `ON CONFLICT DO UPDATE` takes rows of one shard, and `UPDATE`/`DELETE ... LIMIT` pick their rows first ([cluster limits](cluster-limits.md)). Lists are `ARRAY[…]`; a vector is a parameter, `ARRAY[…]` or a JSON array string; a multi-vector value is a list of vectors (`ARRAY[ARRAY[…], ARRAY[…]]`, a parameter holding a list of vectors, or `'[[…], […]]'`), and one vector given to it is a list of one; a `SPARSE` value is a JSON object string, and a `MEDIA` value a URI or a JSON object string. - **`UPDATE`** takes any `WHERE` a `SELECT` of its table takes, and a `LIMIT`. A `WHERE` the table's indexes answer runs as it is; another (a `TEXT` column compared with `=`, `LIKE` of a `TEXT` column, `lower(...)`, `IN (SELECT ...)`, `[NOT] EXISTS`) picks the rows' keys with that `SELECT`, under the writer lock as the write runs, and writes those rows, so the rows a `SELECT` with that `WHERE` counts are the rows written (`EXPLAIN` says `picks its rows by key`). Through a coordinator, one whose `WHERE` has a subquery picks the keys over every shard first ([cluster limits](cluster-limits.md)). Setting only single-valued `INT` and `FLOAT` fields (`SET clicks = clicks + 1`) changes them in place, without rewriting the row, which suits counters and prices that change often. Setting any other field rewrites the row, which needs every text field stored or generated. - **`SET`** takes a value or any expression of the row: arithmetic, `||`, `CASE`, `NOT`, comparisons, `lower`, `upper`, `length`, `abs`, `round` and `coalesce` over the row's columns, and in `ON CONFLICT DO UPDATE` over `excluded.column` too. Every expression reads the row as it was, so `SET a = b, b = a` swaps two fields. The result is stored as the field's type: a whole number fits an `INT` (`clicks = price * 2`), but `7 / 2` is 3.5 and an error there (`round(clicks / 2)` fits); one value set to a multi-valued field becomes a list of it. NULL in gives NULL out, as in SQL and as a `SELECT` of the same expression reads it, in every expression (`n + 1`, `1 + n` and `n * 2` alike): a counter that starts from NULL is `coalesce(n, 0) + 1`. **Changed:** 0.3.9 and earlier counted a NULL as zero in `field + number` and `field - number` only. A multi-valued field without values is NULL to `coalesce` and `IS NULL`. Searches, scores and aggregates (`MATCH`, `bm25`, `score()`, `COUNT`) are errors in `SET`. A statement that cannot set one of its rows sets none. - **`DELETE`** takes any `WHERE` a `SELECT` of its table takes, as `UPDATE` does, and `ORDER BY` with `LIMIT` to delete the first rows in that order. `DELETE FROM t` without one deletes every row (there is no `TRUNCATE`). - **`INSERT ... SELECT`** writes a `SELECT`'s rows ([below](#rows-from-a-select-insert--select-and-ctas)). - `RETURNING`, `UPDATE ... FROM`, `DELETE ... USING`, `ON DUPLICATE KEY UPDATE` and `DO UPDATE ... WHERE` are errors. ### Rows from a SELECT: INSERT ... SELECT and CTAS ```sql CREATE TABLE refunds (PRIMARY KEY (id)) AS SELECT id, customer, amount, notes FROM tickets WHERE MATCH(notes, 'refund OR chargeback'); CREATE TABLE by_customer AS SELECT customer, COUNT(*) AS n, SUM(amount) AS total FROM refunds GROUP BY customer; INSERT INTO refunds (id, customer, amount, notes) SELECT id, customer, amount, notes FROM tickets WHERE opened > :since AND MATCH(notes, 'refund') ON CONFLICT (id) DO UPDATE SET amount = excluded.amount; ``` - **The `SELECT`** is any query: joins, `WITH`, `GROUP BY`, `UNION`, searches, parameters. It runs on one snapshot, as a query does, and every row it returns is written: it is not cut at a server's `--max-rows`, only held to the statement's memory budget. A `SELECT` ranked by a score without a `LIMIT`, which returns its best 100 rows ([limits](#statement-shape)), is refused rather than written in part: give it a `LIMIT`, or put the match in `WHERE`. - **`INSERT ... SELECT`** writes each row as `INSERT ... VALUES` would: to the columns it names, in order, or without a list to the table's columns in order; columns it leaves out take their `DEFAULT`; `ON CONFLICT`, `OR REPLACE` and `OR IGNORE` apply as to `VALUES`. Each value goes in as `SET` gives one: `NULL` stays `NULL`, a whole `FLOAT` fits an `INT`, a number goes into a `KEYWORD` as its text, and a value that fits no column of its type refuses the statement, naming the row. - **`CREATE TABLE t AS SELECT ...`** (CTAS) makes a table with a column for each of the `SELECT`'s, named as the `SELECT` names them (`a.zone` is `zone`; an expression needs `AS name`), then writes its rows. A column read from a table keeps that column's type and its options (a `TEXT` its analyzer, a `VECTOR` its dimension), but not its key, `NOT NULL`, `DEFAULT`, `REFERENCES` or what made it (an embedding, a generated text). Another column takes the type a `CAST` names (`CAST(x AS TEXT)` is `TEXT`; `AS VARCHAR` or `AS KEYWORD` is `KEYWORD`), else its values' type: whole numbers `INT`, numbers `FLOAT`, `BOOL`, `TIMESTAMP`, and text `KEYWORD` when its values are labels (none over 256 bytes, 2.5 words or fewer on average) and `TEXT` when they are prose, as a [file's import](#loading-a-file-csv-tsv-json-lines) types them. A column with no values takes its expression's type (`COUNT(*)` is `INT`, `amount * 2` `FLOAT`), and one of no known type is `KEYWORD`, as PostgreSQL makes such a column text. The table has no key unless the statement gives one, after the table's name: `(PRIMARY KEY (id))`, or columns defined with their types, `(id INT PRIMARY KEY, body TEXT OPTIONS(analyzer = 'french'))`, which take those definitions (a defined column the `SELECT` does not give is added, `NULL`). The table's `OPTIONS(...)` and `IF NOT EXISTS` (which runs nothing when the table is there) are as for any table. Rows that cannot be written (a key two rows share, a `NULL` key) refuse the statement, and the table is dropped. - **One transaction.** On one database (`Db::sql`, Python's [`chloedb.Database`](python.md), one chloedb-server) the rows are written in one transaction: all or none. A CTAS makes its table first, in a commit of its own, and drops it when its rows fail. Through a coordinator, the `SELECT` runs over every shard (a shard that does not answer fails it), then its rows go in as `INSERT`s of 500 rows each (one row each with `ON CONFLICT ... DO UPDATE`, which a coordinator runs on one shard's rows), each a write of its own: a failure part way leaves the rows written before it ([cluster limits](cluster-limits.md)). A `SELECT` of one table's rows, each by itself (no `GROUP BY`, aggregate, `ORDER BY`, `LIMIT`, ranking or join), into a table placed by its key runs on the shards instead, each writing its rows straight to the shards of their keys, so they never pass through the coordinator; so does a `GROUP BY` of the column that is the new table's key, each shard sending its partial groups to the shard of their key, which merges and writes them. There the new table needs a key the statement names, or `OPTIONS(shard_by = ...)`, which places each row on a shard: one without is refused before its `SELECT` runs. - **Changed:** 0.3.9 and earlier refused both, but an `INSERT` of [`chunks_of`](#chunks-of-a-tables-text-chunks_of)'s rows, which runs as before. ### Loading a file: CSV, TSV, JSON lines Many rows at once come from a file rather than `INSERT`s: `POST /v1/import?table=orders` with the file as the body and its content type (`text/csv`, `text/tab-separated-values`, `application/x-ndjson` or `application/json`), or the MCP tool `import` with the file's text in `data` (or the rows as objects in `rows`). A CSV's first line names the columns; columns the table does not have are skipped and named in the answer, and an empty cell is the column's `DEFAULT` (`?empty=null` makes it `NULL`). The table must exist first (`CREATE TABLE`, above), or, with an admin key, the MCP tool's `create: true` makes it from the rows: whole numbers become `INT`, numbers `FLOAT`, `true`/`false` `BOOL`, ISO dates `TIMESTAMP`, text of two and a half words or more on average `TEXT` and other text `KEYWORD` (labels too: at least 100 values, none over 256 bytes, each repeating ten times on average, however many words they have), with a column named `id` (or the one `key` names) as the primary key, and the answer shows the `CREATE TABLE` it ran. Parquet and SQLite files load the same way ([server](server.md#loading-rows)), and the command center's Import page takes a file dropped on it. ```bash curl -X POST "$URL/v1/import?table=orders" -H "authorization: Bearer $KEY" -H "content-type: text/csv" --data-binary @orders.csv ``` Each statement is one transaction, and returns the number of rows it wrote. From Rust, the transaction API (`Database::begin`, `WriteTxn::insert`, `upsert`, `set`, `delete`, `commit`, and `WriteTxn::table` for the other tables) groups several writes into one, across tables too; `WriteTxn::upsert_if_newer` keeps whichever version of a row has the highest version number, for replaying a feed out of order. ## EXPLAIN `EXPLAIN ` shows the plan of a `SELECT`, `INSERT`, `UPDATE` or `DELETE` without running it: a row per line, in a column named `plan`, the root first and each operator's input indented under it. It runs in-process (`db.sql` in Python, `Db::sql` in Rust), over HTTP through `POST /v1/sql` (and so in Python's `chloedb.dbapi`, the SQL workbench and `chloedb-server cc`), and [`POST /v1/explain`](server.md#http-api) answers the same lines as `tree`, for the statement with or without `EXPLAIN` before it. **Changed:** 0.3.9 and earlier refused `EXPLAIN` over `/v1/sql`, and `/v1/explain` took only a `SELECT`. ```sql EXPLAIN SELECT category, COUNT(*) AS n FROM papers WHERE published >= '2026-10-01' GROUP BY category HAVING COUNT(*) >= 2 ORDER BY n DESC, category LIMIT 5; ``` ```text Project: category, COUNT(*) AS n Limit: 5 Sort: COUNT(*) DESC, category Filter: COUNT(*) >= 2.0 Aggregate by category: COUNT(*) Search papers filter: published >= TIMESTAMP '2026-10-01T00:00:00Z' ``` A `Search` is the rows of one table that its `filter` holds for, ranked by its `order`; the operators above it group, keep, sort, cut and name them, and a write's operator (`Insert`, `Update`, `Delete`) sits on top. The plan is the statement as bound: values have their field's type, and a `NOT` over a field that can be null also says `x IS NOT NULL`, since a row without a value matches neither a comparison nor its negation. `EXPLAIN FORMAT JSON` (or `EXPLAIN (FORMAT JSON)`) gives the plan as one row of JSON: fields by their position in the table, typed values (`{"int": 5}`, `{"text": "5"}`), a version and the features the plan needs. ChloeDB refuses a plan from a newer version by name. `EXPLAIN ANALYZE` and other formats are refused. A compound query's plan has operators over rows in memory above its `Search`es, and its JSON needs the feature `operators`: ```sql EXPLAIN SELECT a.id, b.title FROM papers a JOIN papers b ON a.cites = b.id WHERE a.year >= 2019 ORDER BY a.year DESC LIMIT 5; ``` ```text Project: id AS "a.id", title AS "b.title" Limit: 5 Join on targets(cites) = id Project: id, year, cites Search papers filter: year >= 2019 order: year DESC Project: title, id Search papers ``` `Join` (or `Left join`) matches its two inputs on the keys after `on`, `targets(f)` being the rows an `EDGES` field links to, with any other `ON` condition after `AND`; `With` names its results, which `Ref` reads; `Key order of top` puts rows in the order of the `WITH` result `top`; `Distinct` keeps each row once, and `Distinct on: video` the [first row of each group](#the-first-row-of-each-group-distinct-on). A subquery sits in its condition: `IN values of (...)` (its values), `IN keys of (...)` (its rows' keys), `EXISTS (...)` and a scalar `(...)`, each shown on one line with `;` between its operators. `SELECT DISTINCT` of the table alone is a `GROUP BY`, a single-table query. Every statement runs as its plan, and a plan in JSON runs on its own: `Db::run` in Rust, `Database.run` in [Python](python.md#querying) and [`POST /v1/plan`](server.md#http-api) over HTTP take one, and check it against the table's schema as the SQL binder checks a statement. ## Reading a plan `--plan` shows what the planner decided, segment by segment. The same statement can get different plans as the data changes. In the evaluation, an `OR` filter matching about 15% of documents was scanned exactly on SciFact's 5,183 documents, but on the larger collections the planner measured 11% near the query and post-filtered the HNSW result. An RRF query's topic filter matched 11% of Quora globally but only 3.4% near the query, so the planner switched to an exact scan of its 58,767 members, at 3.1 ms. [Planning and execution](index.md#planning-and-execution) describes the choices. ## Differences from PostgreSQL A query written for PostgreSQL mostly runs here and gives the same rows, but not always. These are the differences people porting SQL from PostgreSQL meet most, as this release has them: first the answers that differ without an error, then what is refused (most refusals' messages say what to do instead). The list of refusals is not complete: a statement it does not name can still be refused, and its message says so. **Connecting.** There is no Postgres wire protocol: `psql`, DBeaver, Metabase, dbt's Postgres adapter and SQLAlchemy's Postgres dialect do not connect, and there is no dbt adapter or SQLAlchemy dialect of ChloeDB's own. [Running SQL](#running-sql) lists the ways in: Python's `chloedb.dbapi` (DB-API 2.0, which pandas' `read_sql` reads), JDBC, HTTP and the SQL workbench. [Following Postgres](postgres.md) copies a Postgres database into ChloeDB; it does not let Postgres's clients in. **Answers that differ, with no error:** | expression | ChloeDB | PostgreSQL | to get PostgreSQL's | |---|---|---|---| | `7 / 2` | `3.5`: `/` always gives a `FLOAT` | `3` for two integers | `(7 - 7 % 2) / 2` (3.0) | | `ORDER BY x DESC` with `NULL`s | `NULL`s last | `NULL`s first | `ORDER BY x DESC NULLS FIRST` | | `greatest(1, 2)`, `least(1, 2)` | `2.0`, `1.0` (`FLOAT`) | `2`, `1` | `CAST(greatest(a, b) AS INT)` | | `floor(x)`, `ceil(x)` of a `FLOAT` | an `INT` (`floor(2.7)` is 2) | a `float8` (`2`) | `floor(x) * 1.0` | | `concat('a', TRUE)` | `'atrue'` | `'at'` | `CASE WHEN b THEN 't' ELSE 'f' END` | | `SELECT a.id, b.title FROM a JOIN b ...` | columns `a.id`, `b.title` | `id`, `title` | `a.id AS id, b.title AS title` | | a correlated `(SELECT COUNT(*) ... WHERE t.a = o.a)` | `10.0` (`FLOAT`) | `10` | alias it and read it as a number | Ascending order puts `NULL`s last in both. [Following Postgres](postgres.md#how-postgres-columns-become-fields) makes a `numeric` column a `FLOAT`, so `CAST` and `round` take its halves to the even neighbour (2.5 to 2), where PostgreSQL rounds a `numeric`'s away from zero (to 3). **Changed:** 0.3.7 and earlier rounded every half away from zero, kept the rows without a value in `n != 1.5` on an `INT` column, and gave `'a'` for `'a' || NULL`; each now answers as PostgreSQL does. **Changed:** 0.3.8 and earlier refused `ORDER BY` the alias of a group column after `GROUP BY` or `DISTINCT` ("no such column") and `NULLS FIRST` there, read `json_extract(doc, '$.a.b')` as `NULL` outside `WHERE`, and on DataFusion (a query over more than 4,096 rows) added `FLOAT` sums in order, so totals that tie on fewer rows could differ in their last digit and a `RANK` over them change; each now answers as PostgreSQL does, and as on fewer rows. **`TEXT` and `KEYWORD`.** A `TEXT` column is text searched by its words (`MATCH`, `bm25`), and a `KEYWORD` a value compared whole; PostgreSQL's `text` is both. A stored `TEXT` column also groups (`GROUP BY country`, `SELECT DISTINCT country`) and compares with `=` and `LIKE`, by its stored text read row by row, where a `KEYWORD`'s index answers both. Imports make a column of prose a `TEXT` one, by its values (more than two and a half words a value on average: [SQLite](sqlite.md#how-sqlite-columns-become-fields), [Parquet](parquet.md#how-parquet-columns-become-fields)), and following Postgres makes every `text` and `varchar` one: create the table first with `KEYWORD` for the columns you group and filter by often. **Writes.** An `UPDATE` or a `DELETE` takes any `WHERE` a `SELECT` of its table takes ([writes](#writes)); one the indexes cannot answer (a subquery, a `TEXT` column compared, a function of a column) picks the rows' keys first, under the writer lock. **Changed:** 0.3.7 and earlier refused such a `WHERE` in a write. `INSERT ... SELECT` and `CREATE TABLE ... AS SELECT` run ([above](#rows-from-a-select-insert--select-and-ctas)), their rows in one transaction on one database. Refused: `UPDATE ... FROM`, `DELETE ... USING`, `RETURNING`, `TRUNCATE` (`DELETE FROM t` deletes every row), a subquery as a value in `SET` (`SET x = (SELECT MIN(y) FROM t)`: run it first and pass its answer as a parameter), and `ON CONFLICT ... DO UPDATE ... WHERE` (put the condition in the value: `SET x = CASE WHEN n > 3 THEN excluded.x ELSE x END`). **Transactions.** `BEGIN`, `COMMIT` and `ROLLBACK` are refused: each statement is a transaction of its own. Several writes commit together as the operations of one `POST /v1/write` (or `write(ops)` in Python and JavaScript), and through Rust's transaction API ([Loading a file](#loading-a-file-csv-tsv-json-lines), at its end). **Tables, views and indexes.** Refused: `CREATE VIEW` and `CREATE MATERIALIZED VIEW` (a [stored function](#stored-functions) `RETURNS TABLE` is a view with parameters, and a [rollup](#rollups-create-rollup-a-materialized-view-of-counts-over-time) keeps counts up to date), temporary tables (the message says what to write instead), `CREATE INDEX` (every column is indexed by its type when the table is made), `ALTER COLUMN ... TYPE`, `ALTER TABLE ... RENAME TO`, `UNIQUE`, `CHECK`, and a primary key of more than one column. `REFERENCES` are recorded, not enforced. The first table of a database cannot be dropped. **Queries.** Refused: `WITH RECURSIVE` (walk a graph with [`REACHABLE` and `PATH`](#graphs)), `GROUP BY ROLLUP`, `CUBE` and `GROUPING SETS` (a `UNION ALL` of `GROUP BY`s), `CROSS JOIN`, tables listed with commas, `LATERAL`, `JOIN ... USING`, `NATURAL JOIN`, a join whose `ON` has no equality of the two tables' columns, and a window frame `RANGE` with an `INTERVAL` offset; the messages of the `ROLLUP` and `USING` refusals show the query to write instead. Also refused, with what to write: | refused | write instead | |---|---| | `a IS DISTINCT FROM 'x'` | `(a != 'x' OR a IS NULL)` | | `<`, `>`, `BETWEEN` on a `KEYWORD` (`sku BETWEEN 'A' AND 'C'`, `month >= '2023-01'`) | `IN`, `LIKE 'prefix%'`, or the value kept as a number or a time (`month` as the `INT` 202301, or a `TIMESTAMP`), which compares by range | | `SUM(DISTINCT x)`, `AVG(DISTINCT x)` | `SELECT SUM(x) FROM (SELECT DISTINCT x FROM t) d` | | `COUNT(DISTINCT a, b)` | `SELECT COUNT(*) FROM (SELECT DISTINCT a, b FROM t) d` | | a subquery as a value in `HAVING` (`HAVING SUM(x) > (SELECT AVG(x) FROM t)`) | run the inner query first and pass its answer as a parameter | | `LIKE ... ESCAPE` | none yet: `%` and `_` in a pattern are always wildcards | | `ILIKE ANY (ARRAY[...])` | `a ILIKE '%x%' OR a ILIKE '%y%'` | | `doc->>'color'`, `doc->'a'` | `doc.color`, or `json_extract(doc, '$.color')` ([JSON fields](#json-fields-keys-no-schema-names)) | `INTERVAL '1 month'` moves a time written as a value, not a column's, and two times do not subtract: [`date_diff('second', a, b)`](#parts-of-times-date_trunc-extract-and-strftime) is the seconds between them (`'day'` the days), and `EXTRACT(epoch FROM b) - EXTRACT(epoch FROM a)` the seconds with their fractions. **Functions.** Over rows ChloeDB computes `lower`, `upper`, `length`, [`substr` (`SUBSTRING`), `trim` (`TRIM`, `btrim`), `ltrim`, `rtrim`, `replace`, `concat`, `nullif`](#text-and-numbers-substr-trim-replace-concat-nullif-floor-and-ceil), `abs`, `round`, `floor`, `ceil`, `coalesce`, `ln`, `log`, `exp`, `sqrt`, `pow`, `least`, `greatest`, `sigmoid`, `clamp`, `dot`, `date_trunc`, `date_part` (`EXTRACT`), `date_diff`, `strftime`, `date_bin`, `time_bucket`, `hash`, `CASE` and `CAST`, besides its search, vector and JSON functions; over groups, the [aggregates](#aggregates), `STRING_AGG` among them. Among those PostgreSQL has and ChloeDB does not: `left`, `right`, `position`, `split_part`, `regexp_replace`, `lpad`, `initcap`, `concat_ws`, `trunc`, `mod`, `sign`, `random`, `md5`, `to_char`, `age` and `array_agg`. An unknown function's error lists those that exist. **Changed:** 0.3.8 and earlier refused `substr`, `trim`, `replace`, `concat`, `nullif`, `floor`, `ceil`, `date_diff` and `STRING_AGG`. **The catalog.** There is no `information_schema` or `pg_catalog`, and `DESCRIBE` runs in the SQL workbench only. `SHOW TABLES` lists the tables, and `GET /v1/tables` gives each table's columns and the `CREATE TABLE` that makes it. --- # Graphs in ChloeDB Rows can link to other rows. A traversal, a shortest path or personalized PageRank runs in the same SQL statement as BM25, filters and vector search, and can start from any of them. On arXiv, the papers cited by a new paper's two nearest neighbours find twice as many of its references as vector search alone. A graph built from the vectors themselves does not help. ## Rows are nodes Graph databases keep nodes and edges in stores of their own. ChloeDB keeps them in a table: a row is a node, and an `EDGES` field holds the row's outgoing edges as a JSON array of targets, each a primary key of the same table, optionally with a label and a positive weight. ```sql -- id KEYWORD PRIMARY KEY, title TEXT, body TEXT, year INT, emb VECTOR(512), cites EDGES INSERT ... ('p1', 'Attention is all you need', ..., 2017, [...], '["p7", ["extends", "p9"], ["refutes", "p11", 0.5]]') ``` Formally, a snapshot *S* holds rows *V* with keys κ : *V* → *K*, and edges $$ E \subseteq V \times K \times L \times \mathbb{R}_{>0}, \qquad (u, k, \ell, w):\ \text{row } u \text{ points at key } k \text{ with label } \ell \text{ and weight } w $$ An edge is resolved when a query follows it: $$ \rho_S(k) = \text{the live row } v \in V \text{ with } \kappa(v) = k, \text{ if there is one} $$ A key has at most one live row in a snapshot, so ρS is a function. When it has none (the target was deleted, or never existed), the edge dangles and traversals skip it, as a foreign key without a constraint would. Edges belong to their source row and point at keys, not storage positions. They are written, logged, updated, deleted, merged and snapshotted with the row, and nothing else in the engine had to change. A merge rewrites every docID and an update moves a row to a newer segment, but neither changes a key, so no edge is ever rewritten. The price is a lookup per hop, and most of the engineering below goes into making it cheap. ## Storing edges ![One segment's graph section: out-edges as a CSR over local docIDs, a reverse index grouped by target key, and same-segment hints](../assets/img/strata-graph-section.png) Every segment, on disk or built from the memtable, gets one section per indexed `EDGES` field, read in place through `mmap`: - **Out-edges.** A CSR over local docIDs: offsets, then per edge its source, its target key (an `i64`, or offsets and bytes for string keys), a label code and a weight. Labels and weights are stored only when some edge has one. - **Reverse index.** Edges grouped by target key, the groups ordered by the key's 64-bit hash under the radix directory of the primary-key index, with each edge's source stored in group order. "Which rows point at key *k*" is one directory read and one key comparison per group, then a sequential read. Integer hashes are a bijection and need no comparison; colliding string keys form separate groups. - **Same-segment hints.** Per edge, the docID its target had in this segment when the segment was built. Since ρS has one answer, a hinted row that is still live is that answer, and the hop needs no lookup. A hop from *u* along its edges therefore costs, per edge, $$ c_{\text{out}} = p_{\text{hint}}\,c_{\text{live}} + (1 - p_{\text{hint}})\Bigl(p_{\text{memo}}\,c_{\text{memo}} + (1 - p_{\text{memo}}) \sum_{i \le j^*} c_{\text{probe},i}\Bigr) $$ where *p*hint is the share of targets built into the same segment and still live, *p*memo the share already resolved earlier in the query, and *j*\* the segment where the key is found. A hop against the edges costs one reverse-index probe per segment for *u*'s key, then a liveness check per source. The section takes about $$ b \approx \underbrace{8}_{\text{target}} + \underbrace{4}_{\text{source}} + \underbrace{4 + 4}_{\text{reverse}} + \underbrace{4}_{\text{hint}} + \frac{8\,\lvert V \rvert + 16\,\lvert K_E \rvert}{\lvert E \rvert}\ \text{bytes per edge} $$ with *K*E the distinct targets. That comes to 27 bytes per edge on arXiv, where the graph is under 5% of the file: ![Sizes of the arXiv table: vectors 453.3 MB, doc store 129.4 MB, graph section 31.1 MB at 27.0 bytes per edge, full-text index 20.1 MB, file 639.0 MB](../assets/img/table-graph-size.png) ## The SQL Two predicates, a column and a score join the existing functions. Each takes seeds: a key, a parameter, a tuple of keys, or any subquery over the same table, so a vector search, a BM25 query or a facet filter can be the way into the graph. ```sql -- papers within two citations of p1, either way, nearest first SELECT id, title, hops() FROM papers WHERE REACHABLE(cites, 'p1', hops => 2, dir => 'both') ORDER BY hops(), id LIMIT 20; -- one shortest path, only through surveys SELECT id, hops() FROM papers WHERE PATH(cites, 'p1', 'p9', max_hops => 6, through => kind = 'survey') ORDER BY hops(); -- the way in is a vector search: the papers its two best hits cite, by similarity SELECT id FROM papers WHERE REACHABLE(cites, (SELECT id FROM papers ORDER BY similarity(emb, :q) DESC LIMIT 2)) ORDER BY similarity(emb, :q) DESC LIMIT 20; -- personalized PageRank from hybrid hits, fused with both rankings SELECT id FROM papers ORDER BY rrf(bm25(body, :t), similarity(emb, :q), ppr(cites, (SELECT id FROM papers ORDER BY rrf(bm25(body, :t), similarity(emb, :q)) DESC LIMIT 2), weighted => 1)) DESC LIMIT 20; ``` The functions and their options are listed in the [query language reference](query-language.md#graphs). ## Planning and traversal ![Graph first, then the usual plan: seeds and options feed a traversal over the whole snapshot, whose result becomes an exact document set per segment](../assets/img/strata-graph-plan.png) A traversal does not respect segment boundaries, so graph computations run first, over the whole snapshot. Seeds are resolved (a seed subquery runs as a query of its own on the same snapshot), and the traversal runs. Its result becomes, per segment, a materialised document set with exact cardinality, plus each row's distance and PageRank score. The planner then sees a graph predicate as a filter whose size it knows exactly: a vector search over a neighbourhood of a few hundred rows becomes an exact scan of those rows. ```mermaid flowchart LR SD["seeds
    keys, a tuple or a subquery"] --> TR["traversal over the snapshot
    BFS · bidirectional path · PageRank push"] TR --> PS["per segment
    exact document set
    hops() and ppr() by row"] PS --> PL["usual plan
    probe or materialise filters
    vector, BM25, fusion, facets"] ``` The traversals: - **Reachability:** breadth-first search, frontier by frontier; a search that would meet more than `max_nodes` rows besides its seeds is an error rather than an answer that depends on the order of the edges. - **Shortest paths:** bidirectional breadth-first search, always expanding the smaller frontier, forward along the edges or backward against them. With `through`, each side keeps the rows it meets that fail it as dead ends, and the halves meet only at a row that passes it or at an end, so every middle row of the path passes `through`. - **Personalized PageRank:** forward push (Andersen, Chung and Lang, 2006). The vector π solves $$ \pi = \alpha\, e_S + (1 - \alpha)\, \pi W, \qquad W_{uv} = \frac{w_{uv}}{\sum_{x} w_{ux}} $$ where *e*S is the restart distribution over the seeds. Every row has an estimate *p* and a residual *r*, with *r* = *e*S at the start, and pushing a row *u* does $$ p(u) \mathrel{+}= \alpha\, r(u), \qquad r(v) \mathrel{+}= (1 - \alpha)\, r(u)\, W_{uv}\ \ \forall v, \qquad r(u) \leftarrow 0 $$ while some *r*(*u*) ≥ ε·deg(*u*). Each estimate is then within ε·deg(*u*) of π(*u*), and the work is bounded by 1/(αε) pushes whatever the graph's size. A row is queued only once its residual reaches ε, the least any threshold can be. Rows that merely received a little mass are never resolved, and resolving them had been most of the original cost. The estimates add up to the share of the walk that has settled, Σ *p*; the rest is residuals no push spread. A fixed ε stops the walk at the seeds when their neighbours have many edges, since ε·deg(*u*) is then far above the residual a neighbour gets: from a user of the tests' user-item graph, whose 30 items have at least 300 edges each, ε = 10⁻⁴ settles the user's 15% and ranks no item. Without `eps` the walk starts at 10⁻⁴ and, while Σ *p* < ½, halves ε and pushes on from the residuals it has (an estimate only grows, so the walk at the lower ε continues the one at the higher), for at most 100,000 pushes; on that graph it stops at 3.1·10⁻⁶ with 72% settled, after 9,078 pushes. A walk that ends with Σ *p* < ½, at a given `eps` or out of pushes, reports `ppr_unsettled` in its stats. ## Speed Two graphs, each queried from 200 random seeds on a warm cache, on one thread of an Apple M2 MacBook Air, through SQL (parsing and planning included; `COUNT(*)`, so that no rows are fetched): - **arXiv:** 168,343 papers (ogbn-arxiv, less 1,000 held out) with 1,148,979 citations, in two segments. - **Synthetic:** a power-law graph of 1,000,000 rows and 9,998,469 edges, in four segments. Row *i* links to 10 earlier rows, each the target of a random earlier edge with probability ½ and a uniform earlier row otherwise. The baselines answer the same queries, and the benchmark checks that every count and path length agrees: - **SQLite:** an edge table `(src, dst)` as a `WITHOUT ROWID` primary key, an index on `(dst, src)`, and recursive CTEs. - **CSR:** the same traversal code on two in-memory arrays. This is the lower bound: no keys, no segments, no SQL. ![Graph query latency on arXiv: ChloeDB, SQLite and an in-memory CSR, p50 and p95, for REACHABLE, PATH, ppr and vector-seeded queries](../assets/img/table-graph-speed.png) *arXiv, 200 seeds per query. Source: `chloedb/results/graph/latency_arxiv.json`.* On the million-row graph (`chloedb/results/graph/synthetic_1000000.json`; loaded in 2.7 s into a 307 MB file, 27 bytes per edge): | query (200 seeds) | result | ChloeDB p50 / p95 ms | SQLite p50 / p95 ms | CSR p50 / p95 ms | |---|---|---|---|---| | `REACHABLE`, 1 hop out | 10 rows | 0.017 / 0.022 | 0.012 / 0.013 | 0.001 / 0.001 | | `REACHABLE`, 2 hops out | 108 rows | 0.032 / 0.045 | 0.061 / 0.066 | 0.004 / 0.005 | | `REACHABLE`, 3 hops out | 890 rows | 0.098 / 0.153 | 0.597 / 0.680 | 0.030 / 0.037 | | `REACHABLE`, 1 hop in | 8 rows | 0.014 / 0.019 | 0.010 / 0.017 | 0.001 / 0.001 | | `REACHABLE`, 2 hops both ways | 1,586 rows | 0.104 / 0.468 | 0.471 / 3.26 | 0.019 / 0.110 | | `PATH` either way | 200 of 200 found | 0.079 / 0.145 | — | 0.025 / 0.071 | | `ppr`, ε = 10−4 | 133 pushes | 3.49 / 4.13 | — | 0.66 / 0.80 | | `ppr`, ε = 10−5 | 1,020 pushes | 25.6 / 30.1 | — | 5.47 / 6.32 | **Against SQLite**, one-hop queries cost about the same, roughly 10–15 µs, mostly parsing and planning on both sides. From two hops on, the gap opens, and the tail is where it shows most: two hops both ways on arXiv touch 3,790 rows on average and up to tens of thousands, and their p95 is 1.6 ms in ChloeDB against 14.8 ms in SQLite. The recursive CTE re-expands rows reached at several depths and joins through a B-tree per row, where ChloeDB reads a CSR slice. Shortest paths and PageRank have no practical CTE form. **Against the CSR**, ChloeDB pays two costs. About 10 µs of SQL per query dominates small traversals. Key resolution dominates large ones: PageRank takes 2.4 times the CSR's time on arXiv and 5.3 times on the million-row graph, because a target outside its own segment is a hash probe into each segment's primary-key index until found, a cache miss each. Three changes found by profiling on the Xeon VM that first ran these benchmarks cut PageRank on the million-row graph from 21.4 to 5.8 ms there (3.5 ms on the M2): 1. reverse groups by key, with the sources stored inline; 2. same-segment hints and a per-query memo; 3. queueing only rows that can pass the push threshold. ## Does the graph help search? The rows here are nodes with text, vectors and edges at once. The question the engine cannot answer by itself is whether the edges add anything to a search that already has the text and the vectors, and whether edges made from the vectors (each row linked to its nearest rows) add anything. **The task:** for a new paper, find the papers it cites from its title and abstract. This is citation recommendation, and the same shape as finding the records a new question depends on. - 1,000 papers of OGB's test split (809 from 2019, 191 from 2020, each citing at least five papers) are held out of the table. - Each held-out paper's title and abstract is the query. Its references in the table (15.3 on average) are the relevant rows. - Vectors come from a static embedder (Model2Vec potion-retrieval-32M, 512 dimensions), the same one ChloeCtx uses. - Each method returns 20 papers. Methods that start from vector seeds have one parameter, the number of seeds *S*, swept from 1 to 50. Papers with even ids choose *S* by nDCG@20 (516 queries) and papers with odd ids report it (484 queries), so no reported number was tuned on its own queries. - Comparisons are paired over the same queries, with a 95% bootstrap interval and a two-sided sign-flip test. $$ \mathrm{recall@}k = \frac{\lvert R_k \cap T \rvert}{\lvert T \rvert}, \qquad \mathrm{nDCG@}k = \frac{\sum_{i \le k} \mathbb{1}[r_i \in T] / \log_2(i + 1)}{\sum_{i \le \min(k, \lvert T \rvert)} 1 / \log_2(i + 1)} $$ ![Finding a paper's references on the 484 report papers: following the citations of the two nearest papers reaches nDCG@20 0.253, against 0.123 for vector search, 0.161 for BM25 and 0.160 for hybrid search](../assets/img/table-graph-quality.png) *Source: `chloedb/results/graph/quality_stats.json`. Times are from the quality runs on the M2, after one untimed pass per method.* **The graph doubles what vector search finds.** The best method is also the simplest: take the two papers nearest the query, follow their citations, and rank what they cite by similarity to the query. It reaches nDCG@20 0.253 against 0.123 for vector search (+0.130, 95% interval 0.111–0.149, p < 0.0001), 0.161 for BM25 and 0.160 for hybrid search, in 0.2 ms. Papers on the same topic cite the same work, and the nearest papers' reference lists are a better candidate set than the nearest papers themselves. PageRank from the same seeds reaches 0.211 at its best (from one seed), below the plain one-hop expansion: on this graph the papers two or three hops away dilute the direct citations. Fusing PageRank with the vector ranking lowers it to 0.179, because the vector ranking's own top results are mostly not references. Fusing BM25, vectors and PageRank from hybrid seeds also reaches 0.211, at the cost of BM25 over long queries (48 ms). ![nDCG@20 by number of vector seeds: the citation expansion peaks at two or three seeds and falls below vector search beyond 20](../assets/img/chart-graph-seeds.png) **Fewer seeds are better.** With more seeds, the citations of papers less similar to the query crowd out those of the nearest ones. In a first version of the experiment the seeds themselves stayed in the candidate set; ranked by similarity they took the top places, and from 20 seeds on the "graph" method returned exactly the vector search's results. Every graph method above removes the seeds with `NOT REACHABLE(cites, seeds, hops => 0, min_hops => 0)`. **A graph made of vectors adds nothing.** A `VECTOR` field can be traversed as a graph, each row's 10 most similar rows being its neighbours. On this task it returns what vector search already found when the seeds are kept (recall@20 0.112 against 0.111 at 10 seeds, on all queries), and is worse when they are removed (nDCG@20 0.079). A similarity graph only re-expresses the vector space, while citations carry information the text does not. Rows with vectors are useful as the way into a graph of real relations, not as a replacement for one. The implicit similarity graph stays in ChloeDB for exploratory queries, at 0.12 ms per hop of 10 neighbours. ## Edge tables An [edge table](query-language.md#edge-tables) keeps a graph whose edges change one at a time, such as items seen together, apart from the rows it links: each of its rows is an edge, and adding one, changing its weight or deleting it writes that row alone. Each of its segments indexes its rows by the keys they link, in a section of its own (`edge_table`): - the distinct keys its rows name, numbered in the order of their hashes, with the same radix directory as the primary-key index; - each row's source and target as key numbers, and its weight when the segment was built; - for each key, the rows that leave it and the rows that reach it, in row order. A hop from row *u* looks up *u*'s key in each segment of the edge table, then reads the rows that leave it (or reach it, or both, by direction). For each row it checks that the row is live and reads its weight as it is now, in-place writes included, so a decayed or zeroed weight counts at once. The neighbour is the row's other end, a key number, which the walk resolves to a row of the walked table once per segment. Two shortcuts keep a long walk cheap without costing a short one anything. A segment's key numbers get a dense memo once the walk has resolved a thirty-second of them. A segment whose weights were written in place gets a flat copy of its weights once the walk has read a sixteenth as many as its in-place layers hold. The section is smaller than an `EDGES` field's graph for the same edges, because a key is stored once per segment rather than once per edge. A hop costs more, because an `EDGES` field's out-edges sit with their row and most targets resolve through a same-segment hint. `chloedb-edges-bench` (in `chloedb-server`) measures both: - **Writes.** It streams 300,000 click events of 10,000 users on 50,000 items (Zipf 1.0) through `/v1/stream`. Each event adds 1 to the weight of the edges between its item and the user's last five items, both ways, with `add` operations whose `doc` creates an edge's row on its first event. That is 9.0 edge operations per event and 1,896,100 edges in the end. - **Walks.** `ppr` is seeded with a user's last 20 items, for 1,000 users, over the edge table and over an `EDGES` field of `items` holding the same edges and weights. Each query runs once to warm up, then once timed. | | edge table | `EDGES` field | |---|---|---| | bytes per edge (index) | 20.6 | 33.2 | | `ppr` p50 ms | 21.9 | 15.3 | | `ppr` p90 ms | 30.1 | 26.6 | | `ppr` p99 ms | 38.7 | 37.4 | - **Walks cost about 1.4 times as much at the median, and about the same at p99.** Both rank the same 200 rows in the same order in all 1,000 walks. The edge table had 10 segments here. In a first run whose merges had left it 15, its p50 was 28.5 ms against 17.6, since a hop looks up its key in every segment. - **Writes.** The events alone take 14.1 µs each (71,155 per second). With the edges, they take 190.2 µs (5,257 per second): 19.6 µs per edge operation, most of which create a row. - **Weights as counts.** 54 of the 1,000 walks found nothing over either graph, when `ppr` pushed a row only once its residual reached `eps` times its weighted degree: at the default `eps` of 10⁻⁴, a seed whose edges' weights added up to more than 500 was never pushed. It now compares the residual with `eps` times the row's number of edges, so that scaling every weight alike (counts against frequencies) changes nothing; the weights still divide what a push spreads. Those numbers were measured before the change. A walk that stops at `max_pushes` says so in its plan line (`stopped at max_pushes`) and in the stats (`max_pushes_reached: true`). *Cloud VM: 4 cores of an Intel Xeon at 2.10 GHz, 16.9 GB, Linux 6.18. Source: `chloedb-server/results/edges/vm.json`.* ## On a cluster Graph queries run through a [coordinator](server.md#sharding-one-coordinator-many-shards) too, and answer as one database does. On a sharded cluster a row's edges point at rows that other shards hold, so no shard can walk its part alone. The coordinator walks instead: 1. It runs the walk one database runs (the same breadth-first walk, bidirectional search or forward push) over the rows it has read so far, and notes each row the walk needed and did not have: its out-edges (an `EDGES` field's JSON text), its in-edges, whether it exists, and whether it passes `through`. 2. It reads all of them in one round over every shard, keys in batches of 2,000, four reads at a time (each goes to every shard, so a round of many reads takes its turns beside other queries): `SELECT id, cites FROM papers WHERE id IN (...)` for out-edges, `WHERE REACHABLE(cites, (...), hops => 1, dir => 'in')` for in-edges (each shard answers that from its own rows' edges, by the reverse index), and `SELECT src, dst, w FROM cooc WHERE src IN (...)` (or `dst IN`) over an [edge table](#edge-tables). 3. It walks again from the start, until a walk misses nothing. That walk is the one database's walk. 4. Each shard is then given the walk's answer for its own rows (hops for `REACHABLE`, place for `PATH`, score for `ppr`, in the plan as `graph_given`), and the rest of the query runs as any query does: filters, `bm25`, vector search, `GROUP BY`, joins. `REACHABLE` and `hops()` take about one round per hop, `PATH` one per hop from either end, and `ppr` one each time its pushes reach rows it has not read. The plan says `walked by the coordinator in N rounds`. `ppr` over an edge table whose `src` and `dst` both reference the table walked (`src KEYWORD REFERENCES users`) counts a row's edges first (`SELECT src, COUNT(*) FROM replies WHERE src IN (...) GROUP BY src`) and reads them only to push the row, as one database reads a row's edges only as far as the push test needs. Most rows a walk meets are not pushed, and a well-connected row's list is long: on a reply graph of 887,000 people and 2.6 million edges over 4 shards (all on one 4-core Intel Xeon at 2.10 GHz), `ppr(replies, (24 of the busiest people), max_pushes => 2000)` read every list it met, 2.7 million edges in its fourth round, and was refused after 2.6 s; counting first it took 7 rounds and 0.7 s (0.25 to 0.5 s on one database), and queries beside it waited 110 ms at most where they had waited up to 850. The plan says `N rows' edges counted first`. The count takes `REFERENCES` at its word: an edge to a key that is no row counts toward its row's edges, where one database leaves it out, so keep such a table's references whole or give it no `REFERENCES`. An edge table that does not say so has each list read in full. Two answers can differ from one database's: `PATH` may pick another path of the same length, and `ppr` scores may differ in the last digits (by about 10⁻⁸ in the tests), since it pushes rows in the order it read them; with no `eps`, the `eps` it adapts to can differ too (the tests' top five agree within 10⁻³). A walk is refused past `max_nodes`, as on one database, and after 256 rounds. A walk over a `VECTOR` field (its nearest neighbours as edges) is refused on a cluster, since each shard's neighbour graph is its own. On 20,000 rows of 5 links each, split over 3 shards with the coordinator in one process (gRPC on loopback, a 4-core Intel Xeon at 2.10 GHz, medians of 25 seeds), a 2-hop `REACHABLE` took 4.3 ms in 3 rounds against 0.23 ms on one database, 3 hops 6.3 ms in 4 rounds against 0.30 ms, `PATH` 9.0 ms against 0.20 ms, and `ppr` at `eps => 1e-4` 83 ms in 6 rounds against 1.8 ms; an application's own walk, a read of the frontier's links per hop with no check that its rows exist, took 2.1 ms for 2 hops (`cargo test --profile ci --test all graph_bench:: -- --ignored`, `chloedb-server/results/graph/cluster.json`). Between machines each round adds a network round trip. A coordinator of one shard that holds every slot, with no move in progress, sends graph queries to that shard, which walks them itself. Joins along links (`JOIN papers b ON b.cites = a.id`) run on a cluster as well. ## Limits and next steps - **One quality task, one embedder.** With a stronger embedder, vector search would score above 0.123 and the relative gain over it would likely shrink. The gains over BM25 (+57%) and hybrid search (+58%) are the more robust numbers. - **Cross-segment hops cost lookups**, two to five times the in-memory CSR on these graphs. A snapshot-wide resolved CSR, rebuilt when the segment set changes, would close the gap for read-mostly tables; merging into fewer segments narrows it today. - **No patterns.** There is no multi-hop pattern matching with a predicate per step; `through` and labels cover one constraint per traversal. SQL/PGQ's `MATCH` would be the standard syntax for more. - **Unweighted paths.** Weights are used by PageRank only. - **Walks across shards cost a round trip per hop** ([above](#on-a-cluster)), and a large `ppr` many rounds. A small edge table kept whole on every shard would let each shard walk it alone, in one round; that is not built yet. - **ChloeCtx.** Its records have natural edges the store does not keep yet: a distilled note to the turn it came from, a superseded decision to its replacement, an error to the edit that fixed it. The arXiv result suggests the pattern to try (recall's best hits as seeds, then the records linked to them), but ChloeCtx's earlier study found that widening a hit to its neighbouring records gained little, so this needs its own measurement first. The full report, with every table, is [ChloeDB graphs](https://chloetech-ai.github.io/chloedb/reports/graph.html). [Reproducing the results](../reproduce.md#chloedb-graphs) has the commands. --- # Next items What a user will open, watch or buy next, from what came after the same items before: counts kept in an ordinary table as events arrive, read with backoff from the last two items to the last one. They update with every event, explain themselves, and are the baseline that a learned sequence model has to beat. ## Counts in a table Each row counts how often one item came right after one context: the last item, or the last two. The key is the context's items and then the next item, so with `cluster_by = 'id'` a context's rows sit together. ```sql CREATE TABLE next ( id KEYWORD PRIMARY KEY, -- the context's items, then the next item ctx KEYWORD NOT NULL, -- the last item, or the last two nxt KEYWORD NOT NULL, n FLOAT DEFAULT 0 -- how often (or a decayed weight) ) OPTIONS(cluster_by = 'id'); ``` In Python, `chloedb.ngrams` writes the statement (`ngrams.create_table()`) or the schema (`ngrams.schema()`, for `chloedb.open` or `chloedb-server --schema`), the writes of an event and the read: ```python import chloedb from chloedb import ngrams db = chloedb.open("next.chloedb", ngrams.schema()) # after each event: item "c" after the user's history [..., "a", "b"] db.write(ngrams.ops(["a", "b"], "c")) chloedb.next_items(db, ["a", "b"], k=10) # [("c", 1.0), ...] ``` `ngrams.ops(history, item)` returns one `add` per order, each of which creates its row on the context's first event, so an event costs two writes; `order=3` also counts the last three items. They are the operations chloedb-server's `/v1/write` takes ([writes](server.md#writes)), so `Client.write` sends them and `Database.write` applies them in-process. Items are strings without the two separators the keys use (`\x1f` between a context's items, `\x1e` before the next item). Counts can decay in place, so that recent behaviour weighs more: `UPDATE next SET n = n * 0.9` rewrites no row, and a row whose weight reaches 0 is no longer read. ## Reading with backoff `next_items(db, history, k=10, order=2, backoff=0.4)` scores each item by stupid backoff ([Brants et al., 2007](https://aclanthology.org/D07-1090/)): an item seen after the last two items scores its share of that context's weight; one seen only after the last item scores its share there times 0.4; a pair never seen backs off the same way. It returns `(item, score)` pairs, best first, ties by item. The answer is the same as scoring every item of both contexts, but it reads less. Per context it runs a sum and then reads rows best first, a page at a time, and stops at the first row that cannot reach the top `k`. Then it checks that the items it takes from the last item's context have no row in the pair's context, by their keys. Over a server it is the same SQL, which any language can run: ```sql SELECT SUM(n) FROM next WHERE ctx = :c AND n > 0; SELECT nxt, n FROM next WHERE ctx = :c AND n > 0 ORDER BY n DESC, id LIMIT 64 OFFSET 0; -- ties by key: by item SELECT nxt FROM next WHERE id IN (...) AND n > 0; -- the candidates' keys under the longer context ``` ## Measured On Amazon Beauty (22,363 users' reviews of 12,101 products in time order, the 5-core set sequential recommenders report on), each user's last item predicted from the items before it, ranked among all items, with the counts in-process on one thread of a 4-core cloud VM (Intel Xeon @ 2.10GHz): | counts from | order | Recall@10 | NDCG@10 | p50 ms | p99 ms | |---|---:|---:|---:|---:|---:| | every transition before each user's last item | 1 | 0.0688 | 0.0459 | 0.57 | 1.46 | | | 2 | 0.0694 | 0.0450 | 0.64 | 1.69 | | only those before the last two, as SASRec trains | 1 | 0.0607 | 0.0404 | 0.49 | 1.23 | | | 2 | 0.0613 | 0.0398 | 0.57 | 1.38 | SASRec's published numbers on the same split are 0.0605 and 0.0318 (as [TIGER](https://arxiv.org/abs/2305.05065) reports them, from P5), so counted the way SASRec trains, counts match its recall and beat its NDCG: a strong baseline on this data. Two caveats: 43.5% of users wrote their last two reviews on the same day, which the usual preprocessing leaves in product order and which favours counted transitions; and with under nine reviews per user, the pair's context adds little over the last item's (order 3 adds nothing). Answers were the same as scoring every item for the first 2,000 users. Fewer than 10 scored items were filled with the most frequent ones. Script and results: [`results/sequence/ngrams_beauty.py` and `ngrams-beauty.json`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/sequence). A sequence model ([`encode()`](query-language.md#sequence-models-encodemodel-history)) trained on the same split, reading items only, has 0.0662 and 0.0406 ([results](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/sequence)), at 0.6 ms a query. On Beauty, Sports and Toys, the walk of the next section ranks above both that model and a generative decoder over [semantic IDs](server.md#semantic-ids), and `rrf` of the model's scores and the walk's ranks above the walk: on Beauty, Recall@10 0.0834 and NDCG@10 0.0511, and Recall@10 0.0855 with the decoder's answer added ([results](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/generative)). ## Several steps ahead Counts predict the next item. For items further ahead, or for "seen together", the same events can feed an [edge table](query-language.md#edge-tables), whose edges are directed: adding 1/*g* to the edge from the item *g* steps back to the new one records what comes after what, and `ppr(cooc, :x, dir => 'out')` walks forward from the last items. `dir => 'both'`, `ppr`'s default, reads the same edges as seen together. ```sql SELECT id FROM items ORDER BY ppr(cooc, (SELECT item FROM events WHERE usr = :u ORDER BY ts DESC LIMIT 5), dir => 'out', eps => 1e-6) DESC LIMIT 20; ``` A walk runs on one database: a coordinator refuses `ppr` and the other graph queries ([graphs on a cluster](graphs.md#on-a-cluster)), while the counts above run anywhere. Personalized PageRank pushes a row only while its share of the walk is at least `eps` times its number of edges. Without `eps`, the walk starts at 1e-4 and lowers it until half of the walk has settled, so seeds whose neighbours have thousands of edges still reach rows past them ([how far `ppr` walks](query-language.md#how-far-ppr-walks)); a given `eps`, as above, walks exactly that far, and a walk that stopped near its seeds says so in its stats (`ppr_unsettled`). ## Kept for you: `CREATE RECOMMENDER` `CREATE RECOMMENDER shop ON events(usr, item, ts) ITEMS items(emb)` keeps the counts of order 1 and items seen together from the writes of an events table, and `ORDER BY recommend('shop', :u)` fuses them with the similarity of the user's recent items and with popularity, leaving out the user's recent items (the last `history` of them), not every item the user has had ([recommenders](query-language.md#recommenders-create-recommender-and-recommend)). To leave out everything the user has an event for, filter it: `SELECT id FROM items WHERE id NOT IN (SELECT item FROM events WHERE usr = :u) ORDER BY recommend('shop', :u, k => 500) DESC LIMIT 10`. Events keep feeding the counts as they are written without slowing the calls, and `optimize()` (`POST /v1/admin/optimize` on chloedb-server) merges what they wrote. It runs on one database, and through a coordinator when the events table is placed by its user column ([on a cluster](cluster-limits.md#graphs-and-recommenders)); the tables of this page work on any cluster. ## Which to use Counts are exact and live: an event changes the next answer, and each suggestion is explained by a count. They know only the last one or two items and nothing about a context never seen, where they fall back to the last item alone. A walk over directed edges reaches several steps ahead and related items, at five writes per event. Learned sequence models, which read long histories and combine what they have not seen together, are the next step; these counts are the baseline they have to beat. --- # Slices: search on the device, the server as fallback A slice is a copy of the rows of a table near a device's user, which the device searches itself: near in space (a geo slice, for "near me" search) or near in meaning ([a vector slice](#vector-slices-more-like-this-on-the-device), for recommendations and "more like this"). chloedb-server builds a geo slice from a table with a text field and a latitude and longitude: a manifest (the schema, a grid of square tiles, the text field's statistics) and one file of rows per tile. An app fetches the manifest and the tiles around its user, and searches them with the server's statistics, so every place it holds scores exactly as on the server. When it can prove that its answer is the server's, nothing leaves the device; otherwise it sends the same query to the server. Each answer says where it was answered and why. ## When an answer comes from the device The server ranks by `bm25(text, q) / (1 + d² / d0²)`, where `d` is the distance to the user and `d0` the distance at which a place counts half. A place the device does not hold is at least `e` away, the distance to the nearest tile it lacks, so it scores at most the sum of the query words' best scores (in the manifest) divided by `1 + e² / d0²`. When the k-th score on the device reaches that, the device's top k is the server's. Each answer's `why` is one of: | why | where | what it means | |---|---|---| | `proved` | device | the k-th local score beats the most a place not held could score | | `no_match` | device | no place in the table has a word of the search | | `short` | server | the device holds fewer than k matching places | | `bound` | server | a place beyond the tiles held could have scored higher | | `stale` | server | the table changed since the slice was built | So a device answers short searches for common things near its user (pizza, a pharmacy) itself, and asks the server for rare things, for large k, and for wide `d0`. ## Turn it on Slices exist only on a server started with `--slices DIR`. Build one from the command center (**Data → Slices → Build a slice**) or over HTTP: ```bash chloedb-server --db places.chloedb --slices ./slices --slices-rebuild-s 300 & curl -X POST localhost:7700/v1/admin/slices -H 'content-type: application/json' \ -d '{"text": "body", "lat": "lat", "lon": "lon", "lat0": 40.7, "lon0": -73.98, "tile_m": 1000}' ``` `lat0`, `lon0` are the grid's origin (the middle of the area, usually), `tile_m` the side of a tile in metres. `POST /v1/admin/slices` with `{"table": "places"}` alone rebuilds a slice as it was built, and `--slices-rebuild-s N` rebuilds every stale slice each N seconds. Without a slice the helpers below fail to open, and an app sends its searches to the server as it would without them. ## Fresh or stale Before a device trusts its slice it asks `GET /v1/slices/
    /status` (every 30 seconds by default), which answers the slice's version and whether the table changed since the build. A device fetches a slice of another version, and while the table has changed it sends every search to the server (`max_lag` lets it keep answering for a while). A slice is a snapshot: a row written after the build is not on any device until the next build. ## From Python ```python import chloedb near = chloedb.nearby("http://127.0.0.1:7700", "places", "./slice") near.move_to(40.7484, -73.9857) # fetches the tiles around the user r = near.search("pizza", k=10, d0=1000) print(r.where, r.why) # "device" or "server", and why for row in r: print(row["name"]) near.close() ``` `chloedb.nearby(url, table, dir, token=None, reach=2, status_every=30, max_lag=0, report_every=20)`: `reach` is how many tiles each way it holds (2 is a 5 by 5 square), `dir` a cache it may delete. The result is a `Result` with `where`, `why`, `bound`, `edge_m`, `device_ms`, `server_ms`, and `ask`, the request that asks the server. ## From JavaScript ```js import { openNearby } from "chloedb"; const near = await openNearby("http://127.0.0.1:7700", "places", "./slice"); await near.moveTo(40.7484, -73.9857); const r = await near.search("pizza", { k: 10, d0: 1000 }); console.log(r.where, r.why); for (const row of r) console.log(row.name); await near.close(); ``` It runs where the native addon does (Node, Bun, Deno), with the same options as Python's in camel case (`statusEvery` and `maxLag` in milliseconds). ## Vector slices: "more like this" on the device A slice can also cut a table by meaning: its VECTOR field into k-means clusters, each a file of rows. A device holds the clusters nearest its user's taste (a vector, such as the user's history summed) and answers `similarity` searches itself (recommendations for the user, tracks like the one playing) when it can prove that no row it lacks could beat its k-th. ```bash curl -X POST localhost:7700/v1/admin/slices -H 'content-type: application/json' -d '{"table": "tracks", "vector": "emb"}' ``` `clusters` sets their number (about the square root of the rows by default, at most 4,096 then). The server's search is exact (`similarity(emb, :v, strategy => 'flat', rerank => )` re-scores every row), so a device's proved answer is the server's to the last bit. The manifest holds each cluster's centre, radius, angular radius and longest and shortest vector, from which a device bounds the most a row of a cluster it lacks could score. In many dimensions that bound is loose (a cluster's rows point every way from its centre, so none comes near the worst case), and on its own it proves few answers. So the slice also holds `codes.bin.gz`: every row's vector as one byte a dimension (64 bytes a row for 64 dimensions, a sixteenth of the rows' JSON), which bounds each row within half a step a dimension. A device that fetched the codes proves most searches near its user's taste, and when it cannot, the answer names the few clusters (`need`) whose rows could still beat its k-th. Once it holds them its answer is proved, so the helpers fetch them when they come to at most `refine` bytes (2 MB by default) and answer on the device. ```python tracks = chloedb.nearby("http://127.0.0.1:7700", "tracks", "./tracks") tracks.focus(taste, rows=20_000) # the clusters nearest the taste, up to 20,000 rows r = tracks.similar(taste, k=10) # or any vector print(r.where, r.why, r.fetched) # "device", "proved", clusters it fetched to prove it ``` ```js const tracks = await openNearby("http://127.0.0.1:7700", "tracks", "./tracks"); await tracks.focus(taste, { rows: 20000 }); const r = await tracks.similar(taste, { k: 10 }); ``` `focus` keeps the clusters that fit in `rows` rows and drops those that fall beyond half as many again, so a taste that drifts does not fetch and drop the same clusters over and over. A cluster dropped is deleted from the device's database, and once the rows deleted since the last time outnumber the rows held (and are 1,000 or more), the database is compacted, so the folder stays within about twice what the device holds however far the taste drifts; a geo slice's tiles go the same way. `codes=False` (`codes: false`) skips the codes; `{"codes": false}` builds a slice without them. On Yambda's 629,298 tracks (64-dimension vectors, 4,599 users, measured in a cloud container; [the replay](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/slices#vector-slices-on-yambda-proving-similarity-search-on-the-device) has every number), with 4,096 clusters and 20,000 tracks on the device: | search | proved by the clusters' centres | proved with the codes | proved after fetching what the codes name | |---|---:|---:|---:| | recommend for me, top 10 | 4.5% | 94.9% | 100%, a median 64 KB when it fetches | | recommend for me, top 100 | 2.1% | 61.3% | 100%, a median 157 KB | | more like the last track, top 10 | 4.6% | 54.6% | 100%, a median 340 KB | The codes are 30 bytes a track gzipped (19 MB for the catalogue). No proved answer was wrong. More clusters (smaller ones) make each fetch smaller and the manifest larger: 4,096 clusters of this catalogue make a 3.6 MB manifest, the default 793 a 0.7 MB one with fetches about seven times as large. ## What the server sees Each helper reports its counts every 20 searches (`POST /v1/slices/
    /usage`: searches, why, time on the device and on the server), and the server counts the manifests and tiles it serves. The command center's **Slices** view shows them since the server started: the share answered on the device, the devices, a map of the tiles by rows, size or downloads, the reasons searches went to the server, the last hour by minute, the busiest tiles, and the slice's version with Rebuild and Delete. ![The Slices view: eight devices around New York, 65% of their searches answered on the device, the tiles they downloaded on the map, and why the rest went to the server](../assets/img/slices-view.png) For a vector slice the map is a grid of its clusters, busiest first: ![The Slices view of a vector slice: 629,298 Yambda tracks in 1,024 clusters, eight listeners answering 77% of their searches on the device, and the clusters they downloaded](../assets/img/slices-vector-view.png) | route | what | |---|---| | `POST /v1/admin/slices` | builds a geo slice (`text`, `lat`, `lon`, `lat0`, `lon0`) or a vector slice (`vector`, `clusters`, `codes`), or with `{table}` alone rebuilds one as it was built | | `GET /v1/admin/slices` | every slice, with its counts, and the tables that could have one | | `GET`, `DELETE /v1/admin/slices/
    ` | a slice's tiles and last hour; deletes it | | `GET /v1/slices/
    /manifest.json`, `/tiles/_.jsonl.gz`, `/codes.bin.gz` | the files a device fetches (read scope); a vector slice's tile `x` is its cluster | | `GET /v1/slices/
    /status` | version, built, fresh, changed | | `POST /v1/slices/
    /usage` | a device's counts | `chloedb-slice` (in the chloedb crate) writes the same files from a database file without a server, for any web server or CDN to serve. `chloedb-server/demo/nearby` is a demo over New York's places. --- # ChloeDB: design ChloeDB is to search what SQLite is to relational data: a library that keeps a whole database in one file, needs no server or configuration, gives ACID transactions, and is queried with SQL. Every table is indexed for full text (posting lists), structured columns (a columnar forward index) and vectors, rows can hold graph edges to other rows, and a cost-based planner combines all of it in one statement. This page is the design: the file format, transactions, every index and the planner. To use ChloeDB, start with the [README](../../README.md) or [Build an app](build-an-app.md). ## Goals - **Embedded and single-file.** One `.chloedb` file plus a `-wal` sidecar, like SQLite in WAL mode. Opening a database maps the file and loads nothing eagerly, so databases larger than RAM work and a cold open costs the same whatever the size. - **ACID with snapshot isolation.** One writer, any number of readers. Readers never block and always see a consistent snapshot; a crash at any point leaves the last committed state. Threads that write at once take turns, and those that wait share the next commit. - **SQL with search extensions.** `SELECT … WHERE … ORDER BY … LIMIT`, `GROUP BY` for facets, plus `MATCH` (boolean full text), `bm25()`, `similarity()` and `distance()` (vectors and learned sparse weights), `rrf()`, weighted sums and products (fusion and boosts), `decay()` (closeness to a value or a time) and graph traversal, and `INSERT`, `UPDATE` and `DELETE`. The [query language](query-language.md) page is the reference. - **Index families, freely combined.** Full text (BM25, boolean and phrase queries), structured fields (equality, `IN`, ranges, facets) and vectors (approximate and exact nearest neighbours), in any combination: filtered vector search, filtered BM25, hybrid ranking, facets over any result. - **Graphs over the same rows.** A row can hold typed, weighted edges to other rows. Traversals, shortest paths and personalized PageRank run in the same statement as everything else ([Graphs](graphs.md)). - **Disk-aware.** Every structure is read in place through `mmap`, with no deserialisation, and laid out so that a query's I/O is proportional to its work. One process writes a database at a time; other processes can [read it while it is written](#readers-in-other-processes). Joins across tables, and sharding and replication in [chloedb-server](server.md), came later; [current limits](#where-it-fits) has where they stand. ## Architecture ![ChloeDB's layers: SQL is parsed and bound, a per-segment planner chooses operators, and operators read immutable segments in one file plus a WAL](../assets/img/strata-layers.png) A statement goes through four stages. The binder turns SQL into a predicate tree and a scorer; the planner picks, per segment and from exact statistics, how to evaluate each part; operators run against zero-copy views of the segment's sections; per-segment results are merged. ```mermaid flowchart LR SQL["SQL text"] --> B["parser + binder
    (sqlparser, MATCH grammar)"] B --> L["bound query
    predicate tree · scorer · projection"] G["graph traversal
    (across segments, first)"] -.-> P L --> P["cost-based planner
    per segment"] ST["statistics
    df · histograms · list sizes · ANN params"] --> P P --> T["text operators
    MaxScore · Block-Max WAND · boolean"] P --> S["structured operators
    range scan · postings · facets"] P --> V["vector operators
    flat · IVF · HNSW · pre / in / post-filter"] T --> F["fusion and output
    RRF · weighted · top-k merge"] S --> F V --> F ``` ## Storage engine ### Immutable segments, not a B-tree SQLite updates B-trees in place. Compressed posting lists, bit-packed columns and vector graphs do not survive that: inserting one docID into a compressed partition means re-encoding it, and the best encodings are chosen per whole list. SQLite's own FTS5 already stores its index as immutable segments merged in the background, as do Lucene, Tantivy and PISA. ChloeDB uses that log-structured design for the whole table: every index lives in immutable segments, writes go to a WAL and an in-memory memtable, and segments are merged in the background. ### One file ![One file plus a WAL: two meta slots name the current manifest; a commit writes new extents, syncs, then flips to the other slot](../assets/img/strata-file.png) Pages are 4 KiB. Pages 0 and 1 are two meta slots (magic, format version, transaction id, manifest and freelist locations, page count, CRC32); the rest are extents, runs of pages holding segment data, manifests, delete sets and freelists. Segments are written once, never modified, and freed only when no snapshot references them. **Backups.** While a database is open, its rows since the last flush are in the `-wal` sidecar only, so a copy of the file alone misses them, and copying both while it is written is not consistent either. The safe ways: `Database::checkpoint(dest)` (Python `db.checkpoint(dest)`, chloedb-server `POST /v1/admin/checkpoint`) writes a consistent copy while the database is in use, checking every segment against its checksum first, so that damage is never copied into a backup under a fresh checksum, and checking the copy before naming it; and a clean close (`Db::close`, `close()` in the bindings) flushes the rows in memory into the file and leaves the log empty, so the file alone is then a complete copy, as `Database::flush` makes it at any moment until the next write. The file is read through one `mmap`. Sections read at random positions (the HNSW graph and its codes, float32 vectors for re-ranking, dictionaries, the doc store, the key index) are advised `MADV_RANDOM`, so a cold page fault reads one page instead of the kernel's read-around of up to 32. Sections read a run at a time (postings, document lengths, columns, IVF clusters) keep read-ahead. Readers open lazily per field, so a query touches only the headers of the fields it uses. ### Commits by shadow paging ```mermaid sequenceDiagram participant W as writer participant F as data extents participant M as meta slot (txn+1) mod 2 W->>F: write segment data, delete sets, manifest, freelist (free pages or file end) W->>F: fsync W->>M: new txn id, manifest location, checksum W->>M: fsync: committed Note over F,M: recovery takes the valid slot with the larger txn id ``` A torn meta write fails its checksum and the other slot still names the previous, fully written state. Nothing reachable from a valid meta slot is ever overwritten (the LMDB discipline), so there is no rollback journal. When the newest version itself is damaged (its meta slot, manifest or free list fails its checksum, a segment it names does not open, or the file is shorter than it says), the version in the other slot is still whole, but falling back to it is right only if the write-ahead log still holds what the newer version had flushed: otherwise the log, emptied after that flush, would be replayed onto a version it does not follow, and acknowledged rows would be gone without a word. Opening falls back only when the log's transactions show it covers the gap (the newer version flushed nothing, the log still holds a transaction it flushed, or it holds the first transaction after the older version's), says so in `Database::damaged`, and the next commit overwrites the damaged slot. Otherwise it fails, naming the file, what is damaged and the way out, and changes nothing (it no longer cuts the newer version's pages off the file first): restore a backup, or open with `DbOptions::recover` (Python `recover=True`, chloedb-server `--recover`), which copies the file to `.damaged-
    .`, `classifier:`) are kept in the schema, so what each built-in model makes of a text is part of the format too: a later version keeps those names meaning what they do now, and a changed model gets a new name. A `keyword` field can hold values that a built-in model makes of a text, which need no model files and cost microseconds a row: ```sql CREATE TABLE news ( id KEYWORD PRIMARY KEY, body TEXT, lang KEYWORD OPTIONS(derive = 'body', model = 'builtin:lang'), -- 'en', 'de', 'zh', or 'und' phrases KEYWORD[] OPTIONS(derive = 'body', model = 'builtin:keyphrases'), -- its five main phrases dup KEYWORD[] OPTIONS(derive = 'body', model = 'builtin:minhash'), -- bands of near duplicates brands KEYWORD[] OPTIONS(derive = 'body', model = 'dict:brands.name') -- values of brands.name it names ) ``` - **`builtin:lang`** (a `KEYWORD`) is the text's language as an ISO 639-1 code: by its script (Han, kana, Hangul, Cyrillic, Arabic, Greek, Devanagari, Thai and others), then for Latin and Cyrillic letters by the function words it uses most. On the 10,000 test texts of `papluca/language-identification` (20 languages; reviews, news and single sentences) it named 96.1% right, from 85% for Italian (taken for French or Spanish) to 100% for Japanese and Vietnamese, in 32 to 42 µs a text (`chloedb-content-eval`, `chloedb/results/text/content_lang.json`; the Bulgarian word list was added after a first run on this set, which had 94.8%). `chloedb::content::analyzer_name` maps a code to the analyzer for that language. - **`builtin:keyphrases`** (a `KEYWORD[]`) holds the text's five main phrases by RAKE: runs of words between stopwords and punctuation, each scored by its words' co-occurrence degree over their frequency (`linear diophantine equations`), for facets and tag clouds. - **`builtin:minhash`** (a `KEYWORD[]`) holds 8 bands of a 32-hash MinHash of the text's word 3-grams. Two rows that share a value are likely near duplicates: texts whose 3-grams overlap by a Jaccard similarity of 0.8 share a band 98.5% of the time, by 0.5 40%, by 0.2 1.3%. `SELECT dup, COUNT(*) FROM news GROUP BY dup HAVING COUNT(*) > 1` lists the groups, and a self-join on `dup` the pairs. - **`dict:
    .`** (a `KEYWORD[]`) holds the values of another table's `KEYWORD` field that the text names in full, read as [query understanding](query-language.md#understanding-a-querys-words-understand) reads values (analysed as the source field is): a table of brands, places or products tags the rows that mention them. The values are those the table holds when the row is written, read once per version of it. The dictionary is another table's: one of the derived field's own table is refused, since each write would read it again. A coordinator refuses the field for now, since each shard would tag its rows from its own share of the dictionary's rows: derive it on one server. - **`classifier:`** (a `KEYWORD`, or a `KEYWORD[]`) holds a [classifier](query-language.md#classifiers-create-classifier-and-classify)'s label of the text: the text embedded by the model of the field the classifier was trained on, and the best label (`NULL` below its `min_score`), or for a `KEYWORD[]` the labels whose probability is at least a tenth. A text written before the classifier exists, or after it is dropped, has none; a row keeps the label the version of its write gave, and a new version labels the rows written after it. The source is a stored `TEXT` or `KEYWORD` field of one value, as for a language model. The values are made before the write queues for the writer, kept as given when a write gives them, made again by an `UPDATE` of the source, and stored and logged with the row, so merges and replicas never run the model. The table needs the `derive_keyword` feature, which a version of ChloeDB without it refuses to open. ## Semantic IDs A semantic ID is a short code for a row's vector, such as `12.7.201.0`, that nearby vectors share a start of: rows whose codes start with `12` are alike, those that start with `12.7` more so. Generative recommenders predict an item's code a number at a time; a filter on a prefix finds every row under it. A `KEYWORD[]` field declares that it holds the semantic ID of a `VECTOR` field, by a named codebook: ```json {"name": "sid", "type": "keyword", "multi": true, "semantic_id": {"from": "emb", "codebook": "items-rq"}} ``` `sid KEYWORD[] OPTIONS(semantic_id = 'emb', codebook = 'items-rq')` declares it in `CREATE TABLE`. - **The code.** The codebook is residual k-means: up to 4 levels of up to 256 centroids (3 of 256 by default). The first number is the vector's nearest first-level centroid, the next the nearest second-level centroid to what is left, and so on. The last number is a tie that tells apart rows with the same levels: the first such row gets 0, the next 1. A tie is never given twice under the same levels, also after its row is deleted and merged away. - **The value.** The field holds every prefix of the code, shortest first (`["12", "12.7", "12.7.201", "12.7.201.0"]`), so `WHERE sid = '12.7'` finds every row under `12.7`, through the keyword index, and combines with any other condition. `sid_at(sid, n)` is the first `n` numbers of a code, as text (`sid_at(sid, 2)` is `'12.7'`; NULL past its length), for grouping and for columns: `SELECT sid_at(sid, 1), COUNT(*) FROM items GROUP BY sid_at(sid, 1)`. A query with `sid_at` computes it over the rows its scan returns, as a join does, so the scan holds at most 1,000,000 rows. - **Writes.** The writer fills the field in from the vector, after an embedded vector is computed: a row's code is its own from then on. An upsert keeps the code while the vector's levels stay the same, and gets a new tie when they change. `UPDATE` cannot set the field (set the vector instead), and a write that brings a whole code keeps it, so a copy or a replica holds the same codes. - **The codebook** is a model, kept in the models directory as `/codebook.safetensors`. The field records its name and the SHA-256 of its file when the table is created, which fails if the codebook is not there; opening the database later checks the file against it. A database whose codebook did not open still reads, but writes that need a new code fail. A name holds one codebook, and a new codebook means a new field (or table). Train one in Python with [`chloedb.train.codebook`](python.md#semantic-id-codebooks), on a table's vectors or on your own (`balanced=True` uses every level's numbers evenly, so fewer rows share a code), and read what it makes of your vectors with `chloedb.train.codebook_report` before a field names it; from Rust, `Codebook::train`, `Codebook::report` and `Db::train_codebook`. **The next codes.** A decoder that writes a semantic ID a number at a time, by beam search, asks which numbers can come next and still lead to a row that passes a filter. `POST /v1/sid/next` answers it for up to 64 prefixes at once, `""` asking for the first number: ```sh curl -s localhost:7700/v1/sid/next -H 'content-type: application/json' -d '{ "field": "sid", "prefixes": ["", "12", "12.7"], "where": "in_stock AND price < :p", "params": {"p": 50} }' # {"next": [{"prefix": "", "next": [{"code": "3", "count": 120}, {"code": "12", "count": 87}, ...]}, # {"prefix": "12", "next": [{"code": "12.0", "count": 4}, {"code": "12.7", "count": 31}, ...]}, ...]} ``` Each prefix's next codes come in the order of their last numbers, with the rows under each that `where` matches (every row without it), and a code no matching row has is left out. The filter is worked out once per segment; the codes below a prefix are found by jumping through the field's sorted dictionary, where every prefix is a value, and each is counted against the filter. `Db::sid_next` answers the same from Rust. A coordinator asks every shard (gRPC `SidNext`, protocol 7) and adds their counts. Each shard numbers the ties of its own rows, so on a coordinator a full code can name one row on each shard: the counts of the levels are the table's, and a tie's are those of every row with that code. **Paths of tokens.** The same call answers a `KEYWORD[]` field that is not a semantic ID's, whose values the writer gives as every prefix of a code of up to 256 numbers, such as a title's token ids by a language model's tokenizer (`["15277", "15277.1841", "15277.1841.198"]`). A decoder that asks it at each step writes only titles that some row has, among the rows that pass `where` (a tenant, a date, the candidates a search found), so a row written is a title it can write at once and a row deleted one it no longer can, with no model trained again ([research/constrained-decoding](https://github.com/chloetech-ai/chloedb/tree/main/research/constrained-decoding)). **With a decoder.** A TIGER-style decoder over these codes, each step's numbers from `sid_next` among the items a user does not have, comes within 0.0023 Recall@10 of published TIGER on Amazon Beauty and Sports (0.0085 below it on Toys). Alone it ranks no better than a sequence model's [`encode()`](query-language.md#sequence-models-encodemodel-history), at 30 to 40 times its time, most of it the decoder's own; its answer, given to a query as `ranked(:gen)` and fused with `rrf`, adds to that model's and to a walk's ([results](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/generative)). A database with a semantic-ID field needs the manifest feature `semantic_id`, and a plan that uses `sid_at` the plan feature of the same name, which versions of ChloeDB before them refuse by name. ## HTTP API Every request and answer is JSON. Every answer carries the request's id in an `x-request-id` header: the one the client sent, if it is 1 to 64 letters, digits, `-`, `_`, `.` or `:`, or a new one. The [logs](#logs) name it, and a coordinator passes it on to its shards (as gRPC metadata of the same name), so one id finds a request in every server it reached. Parameters bind `:name` placeholders: a number, a string, an array for a vector, an object of term weights for a `SPARSE` field, `{"vector_of": "key", "field": "emb"}` for a stored row's vector (more like this), or `{"embed": "text", "field": "emb"}` for the text's vector by an [embedded field](#embedded-vector-fields)'s model (`{"embed": {"image": ""}, ...}` for an image file's, by a [model of images](#vectors-of-images), and `{"embed": {"audio": ""}, ...}` for a sound file's, by a [model of sound](#vectors-of-sound)); both take `"table"` for a field of another table than the first. | route | body | answer | |---|---|---| | `POST /v1/query` | `{sql, params?, timeout_ms?, min_seq_no?, min_seq_nos?, log?, trace?, steps?, profile?, objects?, format?, page_size?, keep_alive_ms?}`, or a scroll's next page: `{cursor, format?, objects?, keep_alive_ms?, timeout_ms?}` | `{columns, types, rows, keys, scores, stats, took_ms, warnings?}` (`types` gives each column's type as its values have it, `"timestamp"` for `MAX(ts)` and `ts AS d` too, `null` for a column of only NULLs: [the types of an answer's columns](query-language.md#the-types-of-an-answers-columns); `warnings` names a field of the body that is not one of these, such as a misspelt `timeout_ms`, which is left out; a field of the wrong type, `"timeout_ms": "100"`, is refused): each row a list of its values in the order of `columns`, or with `"objects": true` an object keyed by column (`{"id": "p1", "price": 9.5}`; a column named as an earlier one is keyed `id_2`, `id_3`, ...), or with `"format": "arrow"` the rows as an Arrow IPC stream (`application/vnd.apache.arrow.stream`), each column of one Arrow type as [`query_arrow`](python.md#querying) types it in a client's own process, with `x-chloedb-took-ms` and `x-chloedb-stats` headers (not with `log`), with `"steps": true` the query's [profile](#what-the-server-is-doing-now) in `stats.steps` (with `profile`, each step's CPU time and the request's `trace` too); `min_seq_no` and `min_seq_nos` name a write the read must see ([reads that see a write](#reads-that-see-a-write)); with `log` (`true` or `{context?, request?, variant?, candidates?, ts?, table?}`), a ranked query also writes what it served to a [rank log](query-language.md#the-rank-log-what-each-query-served) and answers `request` and `logged: {rows, seq_no?, seq_nos?}`; with `page_size`, a [scroll](#reading-past-the-window-scrolls)'s first page and, while rows are left, its `cursor` (with `"format": "arrow"`, the `x-chloedb-cursor` header) | | `DELETE /v1/query/cursors/ID` | | `{closed}`: ends a [scroll](#reading-past-the-window-scrolls) before its last page (false when it was not open, or is another key's) | | `POST /v1/sql` | `{sql, params?, timeout_ms?, min_seq_no?, min_seq_nos?, log?, objects?, idempotency_key?}` | rows for a `SELECT` (`log` and `objects` as for `/v1/query`), and for `SHOW TABLES` the tables' names (a column `name`, the tables the key reads, as `GET /v1/tables` lists them); `{written, seq_no?, seq_nos?}` for `INSERT`, `UPDATE`, `DELETE` | | `POST /v1/rank_log/export` | `{table?, since?, until?, events?: {table, user, item, time, action?}, history?, window?, grades?}` | NDJSON: one record per logged row, with its context's history and its label as of its time ([exporting the log](query-language.md#exporting-the-log-for-training)), or `{error, status}` at a failure; a coordinator refuses it (400) | | `POST /v1/rank_log/interleaving` | the export's body | `{pairs: [{variants, requests, acted, wins, ties, delta, p}], took_ms}`: which of two [interleaved rankings](query-language.md#interleaving-two-rankings) the users preferred; a coordinator refuses it (400) | | `POST /v1/relevance/autopilot` | `{table?, profile?, since?, k?, max_queries?, budget?, held_out?, seed?, min_gain?, alpha?, max_slowdown?, min_queries?, max_holes?, log?, judgments?, judge?, model?, api_key?, keep?}` | `{report, proposal, judged}`: the [relevance autopilot](query-language.md#the-relevance-autopilot)'s report of new numbers for a rank profile, measured on held-out logged queries replayed on one snapshot; admin; a coordinator refuses it (400) | | `GET /v1/relevance/proposals`, `GET /v1/relevance/proposals/:id`, `POST /v1/relevance/proposals/:id/apply` `{force?}`, `POST /v1/relevance/proposals/:id/dismiss` | | the proposals kept, latest first; one with its proof; applied (`CREATE OR REPLACE RANK PROFILE`, refused when the profile changed since it was measured) or dismissed; admin to change | | `GET /v1/blends`, `GET /v1/blends/:name`, `PUT /v1/blends/:name` `{def, note?}`, `DELETE /v1/blends/:name` | | the [blends](query-language.md#blends-create-blend-and-blend): each with its current version's definition (`def`, as JSON), its `sql` and how many `versions`; one blend's versions, oldest first, with `current`; the next version written (an admin's), `{name, version, sql}`; dropped, a tombstone version | | `POST /v1/blends/preview` | `{name?, version?, def?, params?, k?, costs?, timeout_ms?}` | a stored blend's run, or a draft's (`def`, not stored), with its receipts: `rows` (each with its `source`, `slot`, `kind`, `why`, `utility`, its heads' `parts` and `raw` values, its `cells`), `passed` (the rows the rules passed over and why), `quotas`, `costs` (each rule's share of the slate's utility, unless `costs: false`), `sources` (rows and time each), `plan` and `sql`; with read on every source's tables | | `POST /v1/blends/:name/evaluate` | `{export, targets?, discount?}` | blends [valued off-policy](query-language.md#valuing-a-blend-on-its-log-exploring-fills-cascade-doubly-robust-and-snips) over blend `name`'s exploring pages in a rank log (`export` is `/v1/rank_log/export`'s body, with its `events` and `window`): each target (`"serp@3"`, or `{def, label?, explore?}`; the current version without `targets`) by cascade doubly robust with SNIPS beside it, `{gathered: {requests, not_exploring, other, broken}, estimates: [{label, cdr, snips, cdr_top, logged, lift, against, check_depth, support, coverage, switched, slots, verdict, why}], model}`, each value `{value, se, lo, hi}`; with read on the log and the events | | `POST /v1/blends/:name/tune` | `{export, start?, rounds?, seed?, discount?}` | blends near `start` (a target as `evaluate` takes one) tried on half the searches and the best valued against the start on the other half: `{gathered, tried: [{change, sql, def, train}], best: {def, sql, estimate}, start}` | | `GET /v1/kv/TABLE/KEY?min_seq_no=n` | | `{table, key, found, row, seq_no}`: the row with that primary key, read without SQL ([rows by key](#rows-by-key)); 404 with `found: false` when no live row has it | | `POST /v1/kv/get` | `{keys, table?, columns?, timeout_ms?, min_seq_no?, min_seq_nos?}` | `{table, columns, rows, seq_nos, took_ms}`: per key, in their order, its row as an object (`null` for none) and its sequence number; of `columns` alone when given | | `PUT /v1/kv/TABLE/KEY?if_seq_no=n` | the row's fields as an object (the key may be left out) | `{written, seq_no?}`: the row, written in place of any with that key | | `DELETE /v1/kv/TABLE/KEY?if_seq_no=n&routing=v` | | `{deleted, written, seq_no?}` | | `POST /v1/write` | `{ops: [...], table?, idempotency_key?, strict?}` | `{written, skipped?, seq_no?, seq_nos?, receipt, warnings?}` ([conditional writes](#conditional-writes); `skipped` for [stream events](#streams) written already; `seq_nos` from a coordinator; `receipt` and `strict`: [write receipts](#write-receipts)) | | `POST /v1/stream` | operations as NDJSON, one a line, or one event's several as `{ops, source}` ([streams](#streams)) | NDJSON: a line per batch once it commits, `{batch, ops, written, skipped, lines}`, then `{done, batches, lines, written, skipped}`, or `{error, status, lines}` at the first failure | | `GET /v1/admin/connectors`, `POST /v1/admin/connectors`, `/v1/admin/connectors/NAME` (`GET`, `POST`, `DELETE`), `POST /v1/admin/connectors/NAME/run`, `POST /v1/admin/connectors/NAME/key`, `POST /v1/admin/connectors/NAME/start` and `/stop`, `POST /v1/admin/connectors/test` | a connector's settings | [connectors](connectors.md): their health, state and runs; a new one (its push key's secret once); a change; a pull now; a new push key; a Kafka connector's consumer on or off; a dry run | | `/v1/admin/kafka/test-broker` (`GET`, `POST`, `DELETE`), `POST /v1/admin/kafka/test-broker/produce` | `{listen, topic, partitions, rate, username, password}`; `{topic, messages: [{key, value, headers}]}` | [the test Kafka broker](connectors.md#the-test-broker) in this process: its topics and counts; started (on loopback) or its rate set; stopped; events added | | `POST /v1/connectors/NAME/push` | any body: JSON, or a raw email | what a push connector took: `{records, rows, skipped, dropped}`, written with the sender's key ([connectors](connectors.md)) | | `GET /v1/sources`, `GET /v1/sources/NAME` | | `{sources: [{name, offset, updated}]}`: each stream source's last offset written ([streams](#streams)); for one, `{name, offset, updated}`, `offset` null for a source not written from | | `POST /v1/plan` | `{plan, timeout_ms?, min_seq_no?, min_seq_nos?, objects?}`: a [plan](query-language.md#explain) in JSON, as `/v1/explain` gives it in `ir` | rows for a read, a compound query's plan included, `{written}` for a write; a coordinator runs reads, and refuses a write plan (400) until its shards take write plans | | `POST /v1/import?format=F&table=T&strict=true&empty=default` | rows as JSON Lines, JSON, CSV or TSV ([loading rows](#loading-rows)) | `{written, skipped_fields, ragged_rows?, took_ms, receipt}`, with `table` and `create_table` when it made the table (`create=false` refuses a missing table instead, `meaning=false` makes it without a vector of its prose); `empty` says what an empty CSV or TSV cell is: `default` (the column's DEFAULT, else NULL; the default), `null`, or `text` (the empty string in a text or keyword column); `strict`: [write receipts](#write-receipts) | | `POST /v1/import?format=sqlite&tables=A,B&plan=true&blobs_base64=true` | a SQLite database file ([SQLite in and out](sqlite.md#over-http-and-in-the-ui)) | `{tables: [{source, table, rows, created, notes}], skipped, written, took_ms}`; with `plan`, what it would do, writing nothing | | `GET /v1/export?tables=A,B&fts=false&indexes=false&schemas=false` | | the database (or those tables) as a new SQLite file, `application/vnd.sqlite3`; `x-chloedb-tables` names the tables (admin) | | `GET /v1/export?format=jsonl\|csv\|arrow\|parquet&tables=T` | | one table's rows, read by a scroll over every shard on a coordinator (Parquet from one snapshot on a server, as before): JSON Lines and CSV stream a page at a time, Arrow (one batch, at most 1,000,000 rows) and Parquet (with the table's schema kept, so an import reads it back) once every page is read; a key with read on the table may ask | | `POST /v1/schema/check` | a schema, in either form | `{schema, short, sql}` (`sql` the `CREATE TABLE` that makes it), or the error | | `POST /v1/sql/check` | `{sql, params?}` | `{runs, deployment, kind, error?, status?, notes}`: whether the statement would run here (`deployment` `single` or `cluster`), bound against the tables served and planned, without running it; `notes` what a cluster does differently ([cluster limits](cluster-limits.md)) | | `POST /v1/explain` | `{sql, params?, hits?, profile?}` | runs the query and returns its plan IR as JSON (`ir`) and as lines (`tree`, as [`EXPLAIN`](query-language.md#explain) shows it), the executor's plan lines (`plan`), the timed steps of the run (`steps`, its [profile](#what-the-server-is-doing-now)), the bound query (`logical`) and counts; with `hits: n`, a ranked query's top `n` rows as objects with their `score()` and [`features()`](query-language.md#features-the-values-a-ranking-read), the values each was ranked by (a query that does not rank rows, one without an `ORDER BY` or one that groups, aggregates or orders by a value it computes, `ORDER BY revenue` of `SUM(price * sold) AS revenue`, has none, and returns no `hits`); the statement may start with `EXPLAIN`, and an `INSERT`, `UPDATE` or `DELETE` is planned and not run: its `tree`, `ir` and `logical`, with `"ran": false` | | `POST /v1/embed` | `{text, image or audio, field?, table?}` | `{table, field, vector}`: the vector of the text, or of the image or sound file (`image` or `audio`, base64, for a model of images or of sound), by an embedded field's model (the first whose model is open, unless `table` and `field` name one), as an `{"embed": text}` parameter gets it; for plans, whose vectors are values. A [multi-vector field](#a-vector-a-token)'s model gives `vectors`, a vector a token of the text | | `GET /v1/models` | | `{dir, fetches, models: [{name, dim, hosted, what, ready, error, technique, precision, bytes, made_of, known, fields, job}]}`: the embedding models a schema can name (those ChloeDB fetches, the hosted ones it knows, and the directories of `--models`), and whether each would open here: fetched, its key set, its feature built; how each makes its vectors (`technique`: `static`, `transformer`, `late-interaction`, `image-text`, `sound-text`, `hosted`, `hash`), a static model's table (`precision`: `F32`, `F16`, `BF16`, `I8`), its size here, the model an int8 or F16 copy was made of, the embedded fields that name it (`[{table, field}]`), and a fetch or conversion asked for here (`job`: `action`, `state` `running`, `done` or `failed`, `error`); `fetches` is whether fields fetch the models they name (not with `--no-fetch-models`); nothing is loaded or sent | | `POST /v1/admin/models/fetch` | `{model}` | fetches a model of the ones ChloeDB fetches (`fetch-model`'s names; not a path, nor another Hugging Face repository) into `--models`, in the background: `{model, state: "running"}`, and `GET /v1/models` says how it went; then the fields that name it open it and fill in their rows' vectors | | `POST /v1/admin/models/convert` | `{model, to?}` | writes static model `model`'s table again in `I8` (the default) or `F16`, as model `-int8` (or `-f16`) beside it, in the background, as `quantize-model` does: `{model, from, state}`. A name in `--models`, never a path; 409 when the copy is there already | | `POST /v1/admin/slices`, `GET /v1/slices/TABLE/...` | `{text, lat, lon, lat0, lon0, tile_m?}` (geo), `{vector, clusters?, codes?}` (vector), or `{table}` to rebuild | a table's [slice](slices.md) for devices to search near their user or their user's taste, built into `--slices DIR` and served with its status (fresh or stale) and the devices' counts; `--slices-rebuild-s N` rebuilds stale slices | | `GET /v1/media/` | | the bytes of the file a row's `media` value names, by the file's SHA-256, read as writes read files (the media store, or a place `--media-fetch` lists) and checked against the hash, so a UI can show it; only files that rows name, 404 otherwise; a coordinator refuses (400): ask a shard server. The type is the value's for a PNG, JPEG, GIF, WebP, BMP or AVIF image, a sound or a video; a PDF keeps its type but is a download (`Content-Disposition: attachment`), and any other file (HTML, SVG, XML, JavaScript, text, ...) is `application/octet-stream`, a download. Every answer has `X-Content-Type-Options: nosniff` and `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox`, so a stored file never runs as a page of the server's origin | | `POST /v1/term_stats` | `{sql, params?, timeout_ms?, min_seq_no?, min_seq_nos?}` | BM25 statistics and a snapshot lease for the query round that follows (it lasts for the deadline and a second), for a coordinator | | `POST /v1/classify` | `{name, text, k?}` | the classes of a text by a [classifier](query-language.md#classifiers-create-classifier-and-classify) `CREATE CLASSIFIER` made: `label` (`null` below its `min_score`), `score`, `top` (the `k` best, 3 by default, as `[label, probability]`), `classifier`, `version`, `table`, `field`, `labels_from`; the text embedded by the model of the field it was trained on | | `POST /v1/understand` | `{table, field, text, mode?, fields?, weight?}` | what a search's words say for the table's keyword and numeric fields, as [`bm25(.., understand => ..)`](query-language.md#understanding-a-querys-words-understand) takes them: `spans` (the words, the values each names, their `share` of the rows that say the words), `dropped`, `ranges`, `ranked` (the text left to rank), `filters`, `boosts` and the plan `line`; a coordinator reads its shards' values | | `POST /v1/correct` | `{table, field, text}` | ["did you mean"](query-language.md#did-you-mean-correcting-a-querys-words): `{text, changed, words}`, the words in no row taken for typos of the field's terms; a coordinator counts by its shards' term statistics | | `POST /v1/funnel` | `{sql, params?, timeout_ms?}` | the query run once and its [funnel](#a-querys-funnel): `stages` (each stage's `ms` and `share`, summing to `took_ms`), `text` (`understood` and `expanded` lines, each BM25 search's `terms` with the rows that hold each and whether it is a `word` of the text, a `typo`, a `prefix` or a `synonym`, its `corrected` "did you mean", the texts `embedded`), `rows` (the rows left after each stage and every row seen with its `fate`, the `stage` it left at and `why`), `blend` (a blend's receipts), `answer`, `steps` and `spans`; the probes it runs after the query are quiet; a coordinator's over its shards | | `POST /v1/highlight` | `{table, field, query, texts, size?, pre?, post?}`, or `keys` (and `key`, default `id`) in place of `texts` | `{texts, took_ms}`: with `keys`, the field's text is read from the table's rows with those keys (at most 200; a missing row gives `""`), in the keys' order, as the caller's key may read them; each text with what a search `query` of the TEXT field matches marked, as the field's analyzer and synonyms read it (stems, synonyms, typos, prefixes, phrases, and code such as `C++` where its characters are), cut to the stretch of about `size` characters with the most matches (160; `0`: the whole text), HTML-escaped between `` tags, or between `pre` and `post` as given; at most 10,000 texts a request; a read key's route | | `POST /v1/sid/next` | `{field, prefixes, where?, params?, table?, timeout_ms?, min_seq_no?, min_seq_nos?}` | the codes that can follow each prefix of a [semantic-ID field](#semantic-ids) among the rows `where` matches: `{next: [{prefix, next: [{code, count}]}], took_ms}` | | `POST /v1/snapshot` | | a snapshot lease for 60 s: `{snapshot, txn, ttl_s}` (at most 10,000 are held at once; more get 429) | | `POST /v1/agent` | `{question, model?, effort?, api_key?, max_steps?}` | an answer and the queries it ran | | `POST /v1/judge` | `{query, keys, table?, fields?, model?, api_key?}` | `{grades: [{key, grade, error?}], model, prompt, fields, usage, took_ms}`: each row graded 0 to 3 by a Claude model, one request a row ([relevance judgments](#relevance-judgments)); a write key | | `POST /v1/mcp` | a JSON-RPC message or a batch | the [Model Context Protocol](#agents-over-mcp): tools for an agent, each a route of this table called with the caller's key; 202 for a notification | | `POST /v1/admin/checkpoint` | `{name, layout?, link_from?}` | writes a checkpoint named `name` in `--backup-dir`, with the cluster map and API keys beside it ([backups](#backups)): `{checkpoint: {name, files, txn, tables, segments, segments_linked, live_docs, bytes_written, seconds, slots?, keys?}}`; on a coordinator, one of every shard, each on its primary: `{name, slot_epoch, shards: [{shard, url, short, backup_dir, checkpoint}]}` | | `POST /v1/admin/check` | | checks every byte against its checksums (writes wait meanwhile): `{ok: true}`, or the damage | | `POST /v1/admin/scrub` | `{rate_mib_s?}` | reads every segment against its checksum while writes go on ([scrubbing](#replication-a-primary-and-its-replicas)): `{scrub: {txn, segments, bytes, damaged, seconds}}`; 409 while one runs | | `GET /v1/admin/disk` | `?copy=` on a coordinator | the disk under the database ([the disks](#the-disks)): its file system (with the room above Kubernetes' eviction line when the kubelet shares it), the probe's readings over the last hour, and what fills it, the database's own files apart from every other entry beside them, the largest first | | `POST /v1/admin/disk/probe` | `{copy?}` | times reads of the database's file now: `{reading: {read_ms, read_max_ms, mb_s, busy, await_ms}}`; 409 while one runs | | `POST /v1/admin/disk/clean` | `{copy?, paths: [{path, modified_ms}]}` | deletes the entries named, as `GET /v1/admin/disk` listed them, never the server's own nor one changed since: `{deleted, refused, freed_bytes, filesystem}`; audited, and a person's alone (tier 3) | | `POST /v1/admin/optimize` | | writes the rows the memtables hold and merges each table's segments into as few as the merge policy allows, without their deleted rows (reads and writes go on meanwhile): `{merges, segments_merged, docs_merged, docs_dropped, bytes_written, took_ms}`. It restores the latency of `recommend(...)` and of searches after many small writes ([recommenders](query-language.md#recommenders-create-recommender-and-recommend)); a database's own `optimize` in Python, JavaScript and Java also vacuums, which is `POST /v1/admin/vacuum` here; not on a coordinator: ask each shard server | | `POST /v1/admin/vacuum` | | returns free pages to the file system: `{bytes_freed}`. The file grows while it runs, by what lies above its first free gap ([the disk is filling](runbooks.md#the-disk-is-filling)) | | `POST /v1/admin/verify` | `{timeout_ms?}` | on a primary: compares each replica's rows with the primary's now ([replication](#replication-a-primary-and-its-replicas)), waiting up to `timeout_ms` (60 s): `{replicas: [{url, in_sync, compared, seq_no, differing_slots, first_differing_slot?, error?}]}`; 409 elsewhere | | `POST /v1/admin/promote` | `{replicas?, write_acks?, force?}` | on a replica: makes it the primary of a new term once a majority of its shard's copies vote for it ([failover](#failover)), shipping to `replicas` (gRPC URLs; none: the shard's other copies, or without a cluster map the replica's `--replicas`; with a key, only the copies it knows) under `write_acks` (`all`): `{term, seq_no, replicas: [{url, role, term, seq_no} or {url, error}], votes}`; 409 while a copy holds a later transaction or a newer term, or when it is not elected (unless `force`), and on a server that is not a replica | | `GET /v1/synonyms`, `PUT /v1/synonyms` | `{text}` for `PUT` | the server's synonym list: `{text, rules, file, tables}`, `tables` each table's own list (`CREATE SYNONYMS ON table AS '...'`: `[{table, text, rules, version}]`) | | `POST /v1/synonyms/mine` | `{table, field, vector?` or `log?, min_cos?, per_word?, max_words?, min_df?, window?, min_support?}` | synonyms of a text field mined from the vectors of its words (by the model of vector field `vector`) or from a table of searches (`log`: `context`, `ts`, `text`): `{proposals: [{from, to, rule, score, from_count, to_count}], rules, rows, words, took_ms}`, proposed, never applied ([mined synonyms](query-language.md#typos-and-synonyms)); experimental; an admin's, within bounds whoever asks (`max_rows` 200,000, `max_words` 5,000, `min_cos` 0.3 or more, `per_word` 10); on a server of its own, not a coordinator | | `GET /v1/schema?table=T` | | `{table, schema, short, primary_key, shard_by, embeddings, derived}` of the first table, or of `T` | | `GET /v1/tables/T/paths?field=F&path=P&where=W` | | the paths a [`JSON` field](query-language.md#which-paths-a-field-holds-json_paths) `F` of table `T` holds (those at and below `P`, in the rows `where` keeps), from its index: `{table, field, rows, paths: [{path, keys, rows, types: {string, number, bool}, distinct, min?, max?, values?: [{value, rows}]}], truncated, took_ms}`; 400 for a field that is not an indexed `JSON` field; a coordinator sums its shards' | | `GET /v1/tables` | | `{tables: [...]}`: every table's schema (`short` and `schema`), the `CREATE TABLE` statement that makes it (`sql`) and its [rank profiles](query-language.md#rank-profiles-a-ranking-kept-with-its-table) (`profiles`), the first first | | `GET /v1/health` | | `{status, docs, segments, ...}` (`docs`: the default table's rows), with 503 when the status is `down` or `failing` ([health](#health)) | | `GET /livez`, `/readyz` | | `{status}`, with 503 when the server must be restarted; `/readyz` also while it drains before it stops ([health](#health)) | | `GET /v1/index?table=T&sample=N&seed=S&terms=B&top=K` | | the [index inspector](#the-index-inspector)'s statistics (admin scope) of table `T` (the first without one): on a server its own, on a coordinator each replica's, each shard's and the cluster's | | `POST /v1/index/reads/reset` | | the inspector's read counts start again from zero, on this server only (admin scope) | | `GET /v1/stats`, `/v1/config` | | JSON | | `GET /metrics` | | Prometheus text | | `GET /`, `/classic`, `/ui/*` | | the [command center](#the-ui), the [query console](#the-query-console) and their files | ```sh curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{ "sql": "SELECT id, title, price, score() FROM products WHERE category = :c ORDER BY 0.5 * minmax(bm25(body, :t)) + 0.5 * minmax(similarity(emb, :v)) DESC LIMIT 5", "params": {"c": "kitchen", "t": "quiet espresso", "v": {"vector_of": "p0011051"}} }' ``` `/v1/write` takes a batch of operations, applied in one transaction: ```json {"ops": [ {"op": "insert", "doc": {"id": "p1", "title": "red mug", "price": 12.5, "tags": ["kitchen", "gift"]}}, {"op": "upsert", "doc": {"id": "p2", "title": "blue mug"}}, {"op": "upsert_if_newer", "doc": {"id": "p3", "title": "green mug", "version": 7}, "version": "version"}, {"op": "set", "key": "p1", "field": "price", "value": 11.0}, {"op": "add", "key": "p1", "field": "sold", "value": 1}, {"op": "delete", "key": "p9"}, {"op": "insert", "table": "events", "doc": {"id": 7, "usr": "u3", "item": "p1"}}, {"op": "delete", "table": "events", "key": 6, "routing": "u3"} ]} ``` An operation writes the first table (on a database made with no tables, the first one people made, [above](#run-it)) unless it names another (`"table"`), and one batch may write several tables in its transaction. A `"table"` beside `"ops"` is the table of the operations that name none: `{"table": "events", "ops": [...]}`. The body takes `ops`, `table`, `strict` and `idempotency_key`, and any other field is refused (400) rather than ignored. **Changed:** a top-level `"table"` was ignored before, and its rows went to the first table. On a coordinator, an operation by key (`delete`, `set`, `add`) on a table placed by a column ([tables on shards](#tables-on-shards)) gives that column's value as `"routing"`, since the key alone does not say which shard holds the row. A compound query (`WITH`, a subquery, a join, `SELECT DISTINCT`) runs as its plan: operators over single-table queries, all on one snapshot, on the engine `CHLOEDB_ENGINE` chooses ([above](#run-it)). On a coordinator they run there, and each single-table query goes to the shards as its plan (typed from protocol 2, JSON before; see [gRPC](#grpc)). From protocol 10, on DataFusion, the shards answer a single-table query whose rows the coordinator puts one after another (one without an order, groups or scores, as a side of a join that reads a table whole) with Arrow columns rather than rows. Its plan lines list the single-table queries that ran. A coordinator has no synonym list of its own: start each shard with `--synonyms FILE`. A table's own list (`CREATE SYNONYMS ON table`) is a stored function, which a coordinator writes on every shard. `set` and `add` change a numeric field (`INT`, `FLOAT`, `BOOL`, `TIMESTAMP`) in place, without rewriting the row; `set` of any other single-valued field (`{"op": "set", "key": "p1", "field": "status", "value": "SOLD"}`) writes the row again with the value, keeping its vectors, so a field that a model embeds or another field is derived from is refused (an `UPDATE` or an `upsert` makes those again); `upsert_if_newer` writes the row only if its version field is higher than the stored row's, so a feed replayed out of order keeps the newest. An `upsert` writes the whole row, as `INSERT OR REPLACE` does: a field its doc leaves out is `NULL` (or its default) in the row it replaces, not the value the row had. When one does that, the answer says so in `warnings` ("an upsert writes the whole row: 1 row was replaced, and each takes NULL (or the field's default) in the fields its upsert left out (name, color of p) ..."); to change some fields and keep the others, use `set` (one field an operation) or SQL `UPDATE`. Operations see the ones before them in the batch: an `add` after an `upsert` of the same key adds to the upserted value. An `add` to an `INT` field takes an integer and fails on overflow (exact over the whole 64-bit range); one to a `FLOAT` field must stay finite; a missing value counts as 0. An `add` with a `"doc"` creates the row when no row has its key: the row is the doc, its field plus the value (a missing value counting as 0), and when the row exists the value is added to it as before. So a counter, or the weight of an edge in an [edge table](query-language.md#edge-tables), starts with its first event and needs no write beforehand: `{"op": "add", "table": "cooc", "field": "w", "value": 1, "doc": {"id": "i1>i7", "src": "i1", "dst": "i7"}}`. The key is the doc's (a `"key"` that differs from it is refused). With `--token`, `--cluster-token` or an API key, every route except the UI's (`/`, `/classic`, `/ui/*`), `/v1/health`, `/livez` and `/readyz` needs `Authorization: Bearer `; the UI asks for it. Without a credential it takes (none, or a wrong one), every server answers `/v1/health` with `{status}` alone, since its full answer names its tables and their rows, and a coordinator's its copies' internal addresses; a [key limited to tables](#security) sees its own tables there. ### When a write fails An answer of 200 means the batch is durable. On one server an error means that nothing of it was written, so a client can retry on an error. A 429 refuses it for the server's load before any work, with `Retry-After` saying when to send it again ([streams](#streams)). When an answer is lost (a timeout, a dropped connection, a coordinator whose other replica failed), send the retry with the same `idempotency_key` (or an `Idempotency-Key` header), 1 to 256 characters: a server that already applied that batch answers with its first `written` instead of applying it again, so an `add` counts once and an `insert` does not fail as a duplicate of itself. The same key with other operations is refused (422), and while the first attempt still runs a retry gets 409. A server remembers keys for an hour, or for `--idempotency-ttl-s` seconds (at least 60): a retry later than that is a new write, and is applied again. It records the key of each write that wrote a row in the write's own transaction, as a row of `_sources` named `_strata/idempotency ` that its lists of sources leave out, so the copy promoted when a primary fails before answering knows the key, and so does a server restarted since. It also keeps the latest 100,000 keys in memory, with their whole answer, and forgets them all when its role changes (promoted, elected, stepped down, configured): a primary that steps down may be sent a copy of its new primary that lacks a write it answered, and its database's row, which goes with the write, answers a retry from then. Memory is not what keeps a write from being applied twice: the writer looks each key's row up before it applies a write, so a retry that memory no longer knows while its first attempt is still queued (the oldest keys are forgotten, and every key at a change of role) is answered from the first, unapplied. A retry answered from the row gets the rows the write wrote and the server's last `seq_no`, which follows the write's. Rows older than the keys' lifetime are deleted every minute. A coordinator passes the key to each shard as `key/shard`, and gives every write and statement that has none a key of its own (`auto-...`) before it sends it anywhere: when a shard's primary does not answer and the coordinator sends the write again to the primary that replaced it, the new primary, which may hold the write already, answers it as before rather than apply it twice. A shard of protocol 19 says whether a write it refused was applied as a code (gRPC metadata `x-chloedb-write`: `not-applied` or `in-doubt`), which the coordinator reads to decide whether to send it again; an older shard's message is read as before. Over gRPC, `WriteRequest.idempotency_key` does the same. `/v1/sql` takes one too (in the body, or the header), for `INSERT`, `UPDATE` and `DELETE`: the same statement with the same parameters sent again answers its first `written`. **A write across shards that fails partway.** Through a coordinator, a write whose rows are on several shards is one transaction on each of them, not one transaction over all. Before it sends a write of operations that spans shards, the coordinator asks each shard to check its part without writing it (`WriteRequest.validate`, protocol 19): an `insert` of a key that exists, an `if_seq_no` that does not match, a type or schema error, a `NOT NULL` column left empty. When one refuses, nothing is written on any shard, and the error says which operation of the request failed and why (`nothing was written: shard 1 refused operation 3 of the request (...)`). A part whose key a shard recorded already passes the check, so a retry with the key still finishes a write that failed partway. What remains: nothing is held between the check and the write. Another client's write that lands in between (it inserts the same key, or changes the row an `if_seq_no` names) can still make one shard refuse its part after others applied theirs, and so can a shard that stops, a shard of an older protocol (which is not asked), a shard that does not answer the check, one whose writer is still busy after 100 ms or one that already holds a newer slot map (each of which the coordinator sends its part unchecked); `UPDATE` and `DELETE` statements are not checked. Such a write fails partway, as before, and a deterministic refusal then cannot be finished by sending it again: read the rows back and repair them. Any shard can fail (it stopped, or its primary is being replaced) after others committed their part, which they keep. The error says so: `"partial": true`, `shards` with each shard's `rows` or `error`, and an `idempotency_key`, the client's or one the coordinator gave the write (`auto-...`, for any write of several operations, or statement, without one). Send the same request again with that key, within the hour (or `--idempotency-ttl-s`) the shards keep keys for: the shards that took their part answer it as before, and the others apply theirs, so every row is written once. A shard asked again after slots moved gets other operations under its key, which it refuses (422). The coordinator's keys, one for each write and statement, are kept as its clients' are, each a row of `_sources` for the keys' lifetime. ### Writes from many clients A server has one writer per database, a thread that applies write requests in the order they arrive. Requests that arrive while it commits wait, and the next transaction takes them all, up to 4,096 operations: one commit and one disk flush for the group, each request answered on its own. When a group's transaction fails, each of its requests runs again alone, so only one at fault fails. `/v1/write`, gRPC `Write` and stream batches group with each other. SQL `INSERT`, `UPDATE` and `DELETE` statements group with each other when no two can touch the same row: a statement finds its rows in the last committed version, which does not show its transaction's own changes, so two `UPDATE`s of one row in one transaction would lose one's change. An `INSERT` names its rows' keys, and an `UPDATE` or `DELETE` names them when its `WHERE` pins the key (`id = :k`, `id IN (...)`, an `OR` of those, or an `AND` with one): those group when their keys differ. An `UPDATE` whose `WHERE` is the key alone (`WHERE id = :k`, nothing more) reads its row in the transaction itself, not in the last committed version, so such updates group even when they name the same row, and apply in turn: 64 clients adding 1 to one counter share commits, and none of their adds is lost. That `UPDATE` also skips the planner and the scan: it finds the row by its key, and a key that is not there, or a row expired, updates nothing. Any other statement has its table to itself in a group, and statements of other tables join it. The embedded database does the same for threads that write at once (`Db::write_ops` and SQL writes, which the Python, JavaScript and Java packages use). With 64 clients each sending single-row SQL `INSERT`s or `UPDATE`s by key, about 6 statements shared each commit and the server answered 4,900 to 5,500 a second, against 1,600 to 1,800 when each committed alone, with the median latency down from 34–38 ms to 11–12 ms (4 cores shared with the clients; [results](https://github.com/chloetech-ai/chloedb/tree/main/chloedb-server/results/many-writers)). ### Rows by key A table with a primary key is also a key-value store. `GET /v1/kv/TABLE/KEY` reads one row by its key without SQL, `POST /v1/kv/get` reads up to 10,000 at once (an MGET), and `PUT` and `DELETE` on `/v1/kv/TABLE/KEY` write and delete one; gRPC has `Get` for the reads. A row comes back as `SELECT *` gives it (the stored columns but vectors, typed as a query types them), with the sequence number of the write that last changed it on a server started with `--seq-no`, which a `PUT` or `DELETE` can pass back as `if_seq_no` ([conditional writes](#conditional-writes)). An `INT` key in a path is its digits. ```bash curl -s -X PUT localhost:7700/v1/kv/sessions/s1 -H 'content-type: application/json' -d '{"usr": "u7", "until": "2026-11-02T12:00:00Z"}' # {"written": 1, "seq_no": 41, "took_ms": 0.9} curl -s localhost:7700/v1/kv/sessions/s1 # {"table": "sessions", "key": "s1", "found": true, "row": {"id": "s1", "usr": "u7", "until": "2026-11-02T12:00:00Z"}, "seq_no": 41, "took_ms": 0.1} curl -s localhost:7700/v1/kv/get -H 'content-type: application/json' -d '{"table": "sessions", "keys": ["s1", "s2"]}' # {"table": "sessions", "columns": ["id", "usr", "until"], "rows": [{"id": "s1", ...}, null], "seq_nos": [41, null], "took_ms": 0.1} curl -s localhost:7700/v1/kv/get -H 'content-type: application/json' -d '{"table": "sessions", "keys": ["s1", "s2"], "columns": ["usr"]}' # {"table": "sessions", "columns": ["usr"], "rows": [{"usr": "u7"}, null], ...} ``` `columns` reads only the columns named, as a ranker reading a few features of a thousand candidates wants: when each of them is a single-valued `KEYWORD`, `INT` or `FLOAT`, the rows are read from those columns and the doc store is not touched. A coordinator reads the shards' whole rows and keeps the columns. A read by key probes each segment's key index, newest first, and reads the rows the memtable holds as they were written: it parses no SQL and builds nothing, so a read after each write costs what any read does. Segments of more than 4,096 keys keep a Bloom filter of their keys in memory (built from the key index on the first lookup; nothing on disk changes), so a segment that lacks the key mostly answers from one cache line. A write commits without indexing the memtable's newest chunk, which a query that needs its indexes builds first, once per change. A row whose [`expire_by`](query-language.md#tables) time has passed is none. Through a coordinator, each key is asked of the shard its slot is on, all of a shard's keys in one call (every shard for a table placed by `shard_by`). A query whose condition pins the key, or the `shard_by` column, to values (`WHERE id = 'u7'`, `id IN (...)`, `usr = 'u3' AND ts > ...`) asks only the shards those values are on, as writes are routed, and says so in its plan (`routed by key: 1 of 4 shards`); a query ranked by BM25 still asks every shard, for the collection's statistics. ### Write receipts Every answer of `/v1/write`, `/v1/kv` and `/v1/import` carries a `receipt` beside `written`: `received` (the operations or rows sent), `inserted` (no row had the key), `replaced` (a document written over a row that was there), `updated` (a `set` or an `add` of a row that was there), `deleted`, `collapsed` (a document whose key an earlier operation of the same request wrote: a key twice in one batch leaves one row, and `written` counts it once) and `not_found` (a `set`, `add` or `delete` of a key no row has). Through a coordinator `per_shard` gives each shard's `rows` and counts. A shard from before protocol 21 does not count them, and its counts are `null`. A SQL statement's answer has no receipt. With `"strict": true` in the body of `/v1/write` (or `?strict=true` on `/v1/import`), any operation that would replace a row, write a key an earlier one wrote, or find no row is refused, and nothing is written: 409 for a row there or a key twice, 404 for a key not found. A strict import reads every row first and asks for their keys before it writes, and writes them as inserts, so a row written meanwhile fails it too. A strict write through a coordinator goes only to shards of protocol 21. An operation can ask the same alone: `"strict": true` on it, or `"if_missing": "error"` (or `"skip"`) on a `set`, `add` or `delete`. ### Conditional writes A server started with `--seq-no` numbers its database's writes (`Database::start_seq_no`): every write transaction gets the next sequence number, and each row keeps the number of the write that last changed it. It cannot be undone, and versions of ChloeDB from before it refuse to open the database rather than lose the numbers. The answer to a write that changed something carries its number, `{"written": 1, "seq_no": 42}` (`WriteResponse.seq_no` over gRPC); requests the writer commits together share one, and a retry with an idempotency key gets the first attempt's, or, answered from the key's row, the server's last, which follows it. `SELECT id, seq_no() FROM t` reads each row's number. Rows written before numbering started, and rows loaded in bulk (`--demo`, an import into an empty table), have 0. An operation with `"if_seq_no": n` applies only while its row's number is n, so a client that read a row can write it back without losing a write made in between: ```json {"ops": [{"op": "set", "key": "p1", "field": "price", "value": 10.5, "if_seq_no": 42}]} ``` Every operation but `insert`, which fails if the row exists, takes it. When the row has another number, has no row, or was written by an earlier operation of the same request, the request writes nothing and gets 409 (`FailedPrecondition` over gRPC), naming the key and its number. Of several requests writing a row with the same `if_seq_no`, exactly one applies. Without `--seq-no`, `if_seq_no` and `seq_no()` are refused. ### Streams A stream is a long write: `POST /v1/stream` takes operations as NDJSON (`application/x-ndjson`) for as long as the client sends them, and writes them in batches as they arrive: the server reads ahead while a batch commits, and the next batch takes the lines that came meanwhile, up to 4,096 operations (one line at a time while the client trickles, so a slow stream waits for no batch to fill). Each batch is one transaction; the next is applied once it has committed, and every batch is answered by a line of the answer, which streams back as NDJSON too; the line's `offsets` give the last offset of each source in the batch, which a consumer may commit to its log once the line arrives. The first batch that fails ends the stream with an `{"error": ..., "status": ..., "lines": n}` line, nothing after its `lines` lines applied. gRPC `WriteStream` does the same with a message per batch: the first that fails ends the stream with its error. An operation from an event stream (Kafka, Kinesis, a log) names its event's place in it: `"source": {"name": "clicks/0", "offset": 81234, "ts": "2026-10-30T06:00:01.250Z"}`, `ts` being when the event happened (ISO 8601 text, or milliseconds since the epoch, as Kafka gives them). A server keeps each source's last offset in a system table, `_sources`, in the same transaction as the rows: committed with them, or not at all. An operation whose offset its source has reached already is a replay's, and is skipped (and counted in `skipped`). So a consumer that resumes from `GET /v1/sources/` plus one, or from anywhere before it, applies each event once, every operation it makes included: an `add` to a counter counts once, and an `insert` does not fail as a duplicate. The same holds for `/v1/write`, whose operations may carry sources too. Name a source per partition (`clicks/0`, `clicks/1`), since offsets are per partition. The Python package's [Kafka consumer](python.md#streams-and-kafka) works this way, and so does the server's own [Kafka connector](connectors.md#kafka-topics), which reads topics with no consumer of yours. So does `chloedb-server follow-postgres`, which follows a Postgres database's tables by logical replication, each transaction's operations carrying where it ends in Postgres's log ([Following Postgres](postgres.md)), and `chloedb-server follow-mysql`, which follows a MySQL database's by its binary log ([Following MySQL](mysql.md)); the `postgres` and `mysql` [connectors](connectors.md#databases-followed-by-their-logs) run either inside the server. ```sh printf '%s\n' \ '{"source": {"name": "clicks/0", "offset": 0, "ts": 1761804001250}, "ops": [{"op": "insert", "table": "events", "doc": {"id": 1, "usr": "u3", "item": "p1"}}, {"op": "add", "table": "users", "key": "u3", "field": "n_events", "value": 1}]}' \ '{"source": {"name": "clicks/0", "offset": 1, "ts": 1761804001300}, "op": "insert", "table": "events", "doc": {"id": 2, "usr": "u4", "item": "p2"}}' | curl -s localhost:7700/v1/stream -H 'content-type: application/x-ndjson' --data-binary @- # {"batch":1,"ops":3,"written":3,"skipped":0,"lines":2,"offsets":{"clicks/0":1}} # {"done":true,"batches":1,"lines":2,"written":3,"skipped":0} curl -s localhost:7700/v1/sources/clicks/0 # {"name":"clicks/0","offset":1,"updated":"2026-10-30T06:00:01.412Z"} ``` A line is an operation, or one event's operations as `{"ops": [...], "source": {...}}` (the source going to each operation that names none), which a batch never splits: since an offset reached marks a replay, an event's operations must commit together. Along a stream a source's offsets increase from line to line; a line whose offset does not pass the one before it ends the stream (400), as it would otherwise be skipped. An `{"op": "source", "source": {...}}` operation moves a source's offset without writing a row (for events a consumer filters out). Through a coordinator, each batch goes to the shards its rows are on, and every shard keeps the batch's offsets, whether or not the batch gave it rows. `GET /v1/sources` there answers the least offset over the shards, where a stream resumes: each shard skips the events it applied already. A source some shard does not have is not listed (its first batch never reached that shard), so a stream of it starts over. Offsets move with their slots ([moving slots](#moving-slots), from protocol 16). A shard's offset says which events its own slots hold, and slots that arrive from another shard come with that shard's events of them, which can stop at another offset: a batch that a move's flip catches in flight has committed on the shard the slots go to, for its own rows, and is held on the one they leave, for the moving ones, which the coordinator then sends to their new shard; and a shard added after a stream's last batch has no offset of it at all. So the flip carries each source's offset of the moving slots on the shard they leave, read while their writes are held, and the shard they go to checks the events of those slots against it, until a batch of the source routed by the new map passes it, whatever parts of batches routed by the old map reach it after the flip (it keeps them in `_sources` as `_strata/arrived` rows). A shard that held no slot takes them as its own offsets. Each event is then applied once across a move: the moved part of a batch caught in flight is applied when it comes again, and a replay from the start applies nothing twice. A shard answers each source's least offset over its slots, so `GET /v1/sources` stays where a stream resumes. Moves flipped while a server spoke a protocol before 16 carry no offsets, and the slots take their new shard's. Shards must speak protocol 6 ([gRPC](#grpc)) for writes with sources; an older one is refused by name. Replicas keep their primary's offsets ([replication](#replication-a-primary-and-its-replicas)), and a replica promoted to primary resumes the stream where the old primary stopped. A stream does not wait in the writer's queue: while the database is behind on flushing its memtable to disk (past twice `memtable_max_docs`, while the flusher flushes), or the queue is full, it reads nothing more from its client until it catches up, so TCP or HTTP/2 flow control slows the producer. A plain write then waits up to a second, and is refused with 429 and `Retry-After: 1`, before any of it is applied; the [Python](python.md#a-server-from-python) and [JavaScript](javascript.md#a-server-from-javascript) clients send it again after that, for up to 10 seconds. A coordinator sends a shard its part of a write or of a statement again when the shard refused it with 429 (behind on its flushes, as a shard is while its first flushes build its indexes, its write queue full, or every core embedding), every 200 ms for up to 10 seconds, so its client is answered 429 only when a shard stays busy that long; a stream's batch then goes again a second later. `chloedb_stream_lag_seconds` is a histogram of the time from each event's `ts` to the moment its rows were visible. ### OpenTelemetry logs A server takes logs as [OpenTelemetry](https://opentelemetry.io/docs/specs/otlp/)'s exporters send them, so a Collector, or an application's SDK, writes its logs into ChloeDB with no plugin. `POST /v1/logs` is OTLP/HTTP: an `ExportLogsServiceRequest` in protobuf (`application/x-protobuf`) or in OTLP's JSON (`application/json`), gzip-compressed (`Content-Encoding: gzip`) or not, answered in the request's encoding. The gRPC port serves OTLP/gRPC, `opentelemetry.proto.collector.logs.v1.LogsService/Export`, beside ChloeDB's own service, gzip-compressed or not. Either takes a key that may write (`Authorization: Bearer ...`, as an exporter's `headers` set it), or one limited to tables with a grant of `append` on the logs' table, which sends lines and reads none back ([a key that only appends](#security)): the key in a Collector's config is on every host it runs on. A Collector's exporters: ```yaml exporters: otlphttp/chloedb: logs_endpoint: http://chloedb.example:7700/v1/logs headers: {authorization: "Bearer sk_..."} otlp/chloedb: # or over gRPC endpoint: chloedb.example:7701 tls: {insecure: true} headers: {authorization: "Bearer sk_..."} service: pipelines: logs: {receivers: [otlp], exporters: [otlphttp/chloedb]} ``` The records become rows of table `otel_logs` (or another, named by `?table=` or the header `x-chloedb-table`, over gRPC its metadata), which the first request creates if it is not there: ```sql CREATE TABLE otel_logs (ts TIMESTAMP NOT NULL, observed_ts TIMESTAMP, severity KEYWORD, severity_number INT, service KEYWORD, host KEYWORD, body TEXT, trace_id KEYWORD, span_id KEYWORD, scope KEYWORD, attributes JSON, resource JSON, batch INT NOT NULL) OPTIONS(shard_by = 'batch', compression = 'zstd') ``` - `ts` is the record's time, or when it was observed if it has none (`observed_ts`), or when the server took it if it has neither. - `severity` is its severity text in one spelling (`warning` and `warn` are `WARN`, `err` is `ERROR`, `critical` is `FATAL`, in any case; a text the server does not know stays as written), or the name of its number if it has no text; `severity_number` is the record's, or the first of its text's range (`TRACE` 1, `DEBUG` 5, `INFO` 9, `WARN` 13, `ERROR` 17, `FATAL` 21), so `severity_number >= 17` finds the errors of every source. - `service` and `host` are the resource's `service.name` and `host.name`, or, when it has none, the record's `appname` and `hostname` attributes, which a Collector's syslog receiver sets; `resource` holds its other attributes. - `body` is a string body as it is, another kind of body as its JSON text. - `trace_id` and `span_id` are hex; `scope` is the instrumentation scope's name. - `attributes` holds the record's attributes, its event name as `event_name`, and bytes as base64, in a [JSON field](query-language.md#json-fields-keys-no-schema-names) whose paths filters read from its index. - `batch` is a number made from the request's content (random for a request with records that carry no time): through a [coordinator](#sharding-one-coordinator-many-shards) it places the table's rows (`shard_by`), so that a request's rows go to one shard and requests spread over all of them. A log has no key, and the table has none. `--otlp-retain PERIOD` (`'30 days'`, `'12h'`) makes the table with that retention (`retain = '30 days'`), so its rows older than that are dropped, a window of segments at a time ([tables](query-language.md#tables)); without it they are kept. A table made beforehand takes the columns of these that it has, by name, so make it first for another retention, more columns indexed or fewer kept. Its doc store is compressed with [zstd](query-language.md#tables): on four of Loghub's logs sent this way, `otel_logs` took 30 to 43 bytes a line (it has no key, and its positions are packed), and OpenSearch with its best compression 55 to 83 ([results](https://github.com/chloetech-ai/chloedb/tree/main/chloedb/results/log-bytes)). The rows are searched as any are: ```sql SELECT ts, service, severity, body FROM otel_logs WHERE severity IN ('ERROR', 'FATAL') AND MATCH(body, 'timeout OR refused') AND ts > '2026-11-08T06:00:00Z' ORDER BY ts DESC LIMIT 100; SELECT service, COUNT(*) FROM otel_logs WHERE attributes['http.status_code'] >= 500 GROUP BY service; SELECT * FROM otel_logs WHERE trace_id = '5b8efff798038103d269b633813fc60c'; ``` The answer is OTLP's: an empty `ExportLogsServiceResponse` when every record was written, and `partial_success` with `rejected_log_records` and the first one's reason when the table refused some (attributes nested more than 16 levels, say), the others written. A body that is not OTLP is answered 400, another content type 415, and a server behind on its writes 429 or 503 with `Retry-After`, which exporters wait out and send again. Sending again writes nothing twice: `batch` and an idempotency key for each part of a request (1,000 rows) are made from its content, so a part already written, whose answer the exporter never got, is not written again (for the idempotency window, an hour by default; a request whose records have no time, which the server stamps, has no key); a failure is OTLP's `Status` in the request's encoding (over gRPC, the call's status). A call is counted in the metrics, and audited when refused, as `LogsExport`. ### Connectors A connector keeps another system's data coming into a table: it pulls Prometheus rollups, Jira issues, ServiceNow records, Oxidized configs or any REST API that answers JSON on a schedule, or takes what a system pushes (an email, Alertmanager's webhook, any JSON), or reads Kafka topics while it is on (each event written once, its offset kept with its row), maps each record to a row and upserts it. Connectors are rows of `chloedb_connectors`, each writes with a key limited to its target table, their secrets stay in `.connectors.json` (`--connector-secrets`), and the command center's **Data > Connectors** page shows their health. A server of its own or a coordinator runs the pulls (`--connectors off` turns them off). `POST /v1/admin/connectors`, `GET /v1/admin/connectors`, `POST /v1/connectors/NAME/push`: [Connectors](connectors.md). ### Backups [Back up, restore and upgrade](../guide/backup.md) runs each step on one server, from the first checkpoint to a rollback. Copying the database's files while the server runs is not a backup: a commit reuses pages an older version freed, and the directory layout deletes files a version stops naming, so a copy (`cp`, rsync, a disk snapshot, Time Machine) can pair one version's manifest with another's pages. A checkpoint is the safe copy. `POST /v1/admin/checkpoint` flushes the memtable, pins the version that holds every committed write and copies it into `--backup-dir/` while queries and writes go on (they wait only for the flush). The checkpoint is itself a database, checked against its checksums before it gets its name. Beside it the server writes what a restore needs besides the rows, under the names a server serving the checkpoint with `--db` reads: the cluster map a shard holds, `.slots`, and the API keys, `.keys.json` (the keys' names, scopes and the SHA-256 of their secrets, readable by the server's user only). A checkpoint written while the cluster map changed (a slot move's flip) is not kept, and the answer says to write it again. Restore with [`chloedb-server restore`](#restoring-a-checkpoint). ```sh chloedb-server --db shop.chloedb --backup-dir /backups curl -s localhost:7700/v1/admin/checkpoint -H 'content-type: application/json' -d '{"name": "shop-2026-10-28.chloedb"}' # Directory checkpoints; the second hard-links the segments it shares with the first: curl -s localhost:7700/v1/admin/checkpoint -H 'content-type: application/json' -d '{"name": "shop-2026-10-28", "layout": "dir"}' curl -s localhost:7700/v1/admin/checkpoint -H 'content-type: application/json' \ -d '{"name": "shop-2026-10-29", "layout": "dir", "link_from": "shop-2026-10-28"}' ``` The answer, `{"checkpoint": {...}}`, counts what was copied: `txn`, `tables`, `segments`, `segments_linked`, `live_docs`, `bytes_written` and `seconds`; `name` and the `files` written; and on a shard of a cluster `slots` (its `shard`, the map's `epoch` and `shards`), and `keys`, how many, when it has keys. `GET /v1/admin/checkpoints` lists the checkpoints in `--backup-dir`, the newest first: `{backup_dir, bytes, checkpoints: [{name, layout, bytes, modified_ms, shard?, slot_epoch?, keys}]}`, the shard and map epoch read from the map beside each one, and `keys` whether the keys are beside it. On a coordinator it asks every copy at once and answers each copy's list (`copies`, with an `error` for a copy that did not answer or is of an older version), each shard's newest checkpoint (`newest`), and the names written on every shard under one cluster map, the newest first (`complete`): the sets a [restore of the cluster](runbooks.md#restore-from-checkpoints) can go back to. The command center shows them in **Settings > Upkeep > Backups**. `layout` is `file` (default: one file) or `dir` (a directory of segment files, as `--directory` creates). Segments are immutable and keep their ids in a checkpoint, and its manifest and delete sets are named by the commit it holds, so two directory checkpoints' files share a name only when they hold the same bytes. That makes them incremental off-site backups: sync each one into the same place, `CURRENT` last so that the place always names a complete version, and only the files new since the last sync travel: ```sh aws s3 sync --size-only --exclude CURRENT /backups/shop-2026-10-29 s3://bucket/shop/ aws s3 cp /backups/shop-2026-10-29/CURRENT s3://bucket/shop/CURRENT ``` A database opened from a copy of that place deletes the files its version does not name. A database restored from a checkpoint numbers its next commits as the original did after that checkpoint, so sync its own checkpoints into a new place. A name is letters, digits, `.`, `_` and `-`; an existing name is not overwritten. A coordinator has no database of its own: `POST /v1/admin/checkpoint` there has the copy taking each shard's writes (its primary) write the checkpoint into its own `--backup-dir`, every shard at once, and answers each shard's checkpoint with its copy and backup folder, or an error naming the shards that did not write it (those that did keep theirs: write the next under another name). Its checkpoints are of one cluster map, which the answer's `slot_epoch` names; each shard's is of its own moment, within the time the calls take. To have one copy write one, ask the coordinator `POST /v1/admin/copies/checkpoint {"url": "", "name": "..."}`, which answers the checkpoint and the `node` that wrote it. A checkpoint does not carry a copy's part in replication (`DB.replication`): a copy restored from one starts in the part its flags give it ([restoring a checkpoint](#restoring-a-checkpoint)). The command center's **Settings > Upkeep** writes one of every shard (**Write a checkpoint of every shard**), and a copy's menu on **Cluster** writes one of that copy; [operate a cluster](../guide/operate-cluster.md#checkpoints) writes them on one machine. The `chloedb` shell does the same offline with `.checkpoint DEST [file|dir] [EARLIER]`, `.check` and `.vacuum`. Not yet: point-in-time recovery between checkpoints, which needs the write-ahead log archived instead of truncated at each flush. #### Restoring a checkpoint `chloedb-server restore --from BACKUPS/NAME --db PATH` puts a checkpoint in place of a stopped server's database, with the cluster map and keys kept beside it. It copies the checkpoint beside the database, opens the copy and checks every checksum, and only then changes anything: the database's own files (the database, its `-wal`, `-readers` and `-merging`, the logs a crash left sealed beside a database of one file (`PATH-wal.`) and the copies of damaged logs (`PATH-wal.damaged`, `PATH-wal..damaged`), which the restored database would take for another database's and refuse to open on, its part in replication, `PATH.replication`, and its map, `PATH.slots`) move into `PATH.before-restore-
    `), written with the rows they cover, the slot marks passed, the changes of each table applied and the tables made from the source (`/made/
    `). A follow process killed and started again goes on from there, and a write that failed partway is written again whole: as the follower takes no other writes, rows written twice in order are the rows written once. One killed in its copy copies again, from where that copy began. A copy made again names its marks afresh (`copy_ms`). - **Catching up.** A source shard's ship log (`--ship-log-mb`) holds its latest transactions only. A follower that fell further behind (its follow process stopped a while, or slower than the source's writes) finds a shard's feed `gone`, and catches up on every shard at once (protocol 15): a copy of the rows each shard changed after what the follower applied (`since`), but every row of a table that is not as the source has it now (one altered, dropped and made again, or new: the follower drops its own and makes it again), and drops the tables it made from the source that the source dropped meanwhile. Then the sweep: it compares the digests of its keys by slot with the source's at the copy's version, and in the slots whose differ (256 at a time) deletes the keys the source no longer holds, which no transaction after the copy deletes; a key of a table placed by `shard_by` counts with its value, so a row the follower holds under an old value is deleted there. Then it follows on from the copy. What a catch-up began from is kept first (`//since`, `/whole/
    `), so one cut short begins again from the same. `--copy` copies every row again whatever the follower kept, and sweeps too: after a failover of the source lost transactions the follower had applied (`diverged`), which stops it with that advice. - **Only its writes.** Its first write marks the follower as following `name` (`_strata/follows ` in each shard's `_sources`). From then on the follower's shards refuse every other write (409: "this cluster follows east"), from clients, SQL, imports and the command center alike; the follow process's carry `x-strata-follow: ` with the cluster's token, which a key may not send (403). `POST /v1/admin/follow/stop {"name": "east"}` (an admin key) stops following: the follower takes its clients' writes again and refuses the follow process's, which stops. Started again, a follow process marks the follower as following once more and goes on from where it was. - **Status.** Every 2 s the follow process tells the coordinator it writes through how it stands (`POST /v1/admin/follow/status`): `copying`, `catching up`, `following`, `held` with the error (a write the follower refused, which it tries again every second; a source shard's feed that stopped, read again from its next transaction), or `stopped`. Per source shard: `applied`, the last transaction its feed reaches (`last`), how far behind (`behind`), how many it holds read (`queued`); in all, `behind`, its lag (`lag_ms`: since the source first reached a transaction it has not applied, as the feeds' lines of every second say; while it copies, since the copy began or, catching up, since it fell behind), `rows_copied` and the keys its last copy deleted (`keys_deleted`). `GET /v1/admin/follow` shows it beside the marks. The coordinator it writes through has its lag in `chloedb_follow_lag_seconds`, `chloedb_follow_behind_transactions` and `chloedb_follow_up` (by `name`, and `kind`: `cluster`), and its series in `follow_lag_s` and `follow_behind`: a follow process silent for over 10 s counts as behind for as long as it was silent too. A [Postgres follower](postgres.md#how-far-behind-it-is) tells it the same way, with `kind: postgres`, and counts in `follow_lag_s` and `chloedb_follow_lag_seconds` too. The default alert `follow-behind` fires when the lag stays over 60 s for a minute. Its limits, as it is now: - every table needs a primary key (a copy refuses one without); - a delete or `set` in a table placed by `shard_by` names only the key: the follower deletes or sets the key under each `shard_by` value it holds it, so a key held under two values is deleted from both; - a change of a table while slots move on the source may leave the shards' feeds without one order: the follower then holds, and says so in its status; - the source's shards are not removed while it follows (a shard's feed that ends for good stops it); - a source server keeps the schemas of the tables it dropped in memory: one restarted after a `DROP TABLE` the follower had not yet applied gives the table's rows and its drop as `unknown`, so the follower keeps the table, and a table made again by that name stops it, with both `CREATE TABLE` statements (stop following, drop the table on the follower, and start again with `--copy`); - a shard the follower adds takes its clients' writes until the follow process next writes its marks, within 2 s. ### Switching over A follower takes over from its source by hand: a planned switch-over (a move to another cloud, a region drill) loses no write; one that is not planned (the source is gone) loses the writes the follower had not applied. `chloedb-server switch-over` runs the planned one: ```sh CHLOEDB_SOURCE_KEY=sk_admin_of_east CHLOEDB_CLUSTER_TOKEN=... chloedb-server switch-over \ --target http://127.0.0.1:7700 --name east # {"promoted":"east","at_ms":1762490000000,"planned":true,"lost":0,"seqs":[90412,88213,90377], # "applied":[{"shard":0,"seq":5120,"term":2,"held":true},{"shard":1,"seq":4980,"term":1,"held":true}]} ``` 1. **It holds the source's writes**: `POST /v1/admin/hold-writes` on the source (an admin key, `--source-key`; `--source` names its URL, by default the one the follow process says). Each source shard writes a mark (`_strata/hold`) once the writes under way have committed, and refuses every client's write after it, a change of tables included, with 503 and `Retry-After` ("this cluster holds its writes"): each client's write commits before the mark or is refused. A slot move's own writes go on. The hold is kept with the rows, so a new primary of a shard holds too, until `POST /v1/admin/hold-writes {"hold": false}` ends it; `GET /v1/admin/hold-writes` says whether every shard holds. 2. **It waits** (`--wait-s`, 120) until the follower applied every source shard's transactions up to its hold: the feed marks the hold's transaction (`"hold": true`), the follower keeps it with what it applied (`//held`), and `GET /v1/admin/follow` says `source_holds` and, per source shard, `held`. 3. **It promotes the follower**: `POST /v1/admin/follow/promote {"name": "east"}` there (an admin key, or the cluster's token, `--target-token`). The follower stops following, which ends the follow process, and takes its own clients' writes from then on. Its promotion is kept on every shard (`_strata/promoted east`): a follow process of `east` started again is refused, as is its write ("this cluster was promoted from east"), and only one that copies afresh (`--copy`) follows `east` again. In two writes: the first stops following and holds the follower's own writes once the follow process's under way have committed, so each shard's transaction of it is the last of the source's (`seqs`); the second keeps those numbers and ends the hold. A promotion cut short between them is finished by the next call. The promotion answers what the follower applied of each source shard (`applied`), and `lost`: 0 when planned. 4. Clients write to the follower (those refused with 503 by the source, try the new primary). 5. **The old source follows it back**, if wanted, without a copy: `chloedb-server follow --reverse --source --target --name west`. The process reads the promotion (`GET /v1/feed/promoted`, `feed` scope) and checks that each of the old source's shards holds no transaction with rows after what the new primary applied of it (its own feed from there); then it follows the new primary from the promotion's numbers, and its first write ends the old source's hold (as it follows, the follower guard refuses its clients). Refused when the old source took writes since, as after a promotion that was not planned. Started again, with `--reverse` or without, it resumes; so a switch-over and back (a drill) works the same way the second time, the first cluster following the one promoted from it. **Not planned.** When the source cannot be held, `switch-over` stops and says why; `--unplanned` promotes all the same, losing the writes the follower had not applied, as many as its follow process last said (`behind`, in `lost`). `POST /v1/admin/follow/promote` without `"unplanned": true` refuses (409) while the source does not hold its writes as far as the follower applied. If the old source comes back, it may hold writes the new primary never saw: it rejoins as a new follower, `chloedb-server follow --copy --source --target --name west`, which writes the new primary's rows over its own and deletes, in the sweep, the keys the new primary lacks; its status says how many (`keys_deleted`). Nothing stops the old source from taking writes if clients still reach it after a promotion that was not planned: a hold is the only fence, so promotion stays a person's call. ### Following on Kubernetes, and from the hub On a cluster the [operator](#on-kubernetes) runs, `spec.follow` sets it to follow another; the operator runs the follow process as a Deployment of one pod (`-follow`, strategy `Recreate`), and changing `spec.follow` restarts no server: ```yaml spec: follow: source: https://east.example:7700 # the source's coordinators, as the follower's pods reach them name: east # what the follower calls it keySecret: west-follow-east # a Secret whose key `key` is a feed key of the source caSecret: east-ca # optional: a Secret whose key `ca.crt` is the source's CA (PEM) start: follow # follow (default), copy (afresh) or reverse (back, no copy) askedMs: 1762490000000 # when following was asked for paused: false resources: {requests: {cpu: 100m, memory: 128Mi}, limits: {memory: 1Gi}} ``` The pod runs `chloedb-server follow --source --target http://:7700 --name --once ` (with `--copy` or `--reverse` for those starts, and `--source-ca` from `caSecret`), with the source's key from `keySecret` and the cluster's token from its Secret. Its place is kept in the follower's own `_sources`, so a pod started again resumes. `--once MS` is for a process something starts again by itself: a copy afresh is made once, not again on a restart, and once the cluster stopped following the source or was promoted from it at or after `MS`, the process waits (status `stopped`, "waiting to be stopped") instead of following again. Stopping and promoting (`POST /v1/admin/follow/stop`, `/promote`) remove `spec.follow` as well. `POST /v1/admin/follow/pause {"name": "east", "paused": true}` (an admin key) sets `paused`, which keeps the Deployment at no pod; the follower still refuses its clients' writes, and `{"paused": false}` starts it again from where it was. A follower whose follow process runs elsewhere answers 409 there. A hub ([many clusters from one command center](#many-clusters-from-one-command-center)) sets one connection of its book to follow another: `POST /v1/admin/hub/follow {"follower": "west", "source": "east"}` (an admin key of the hub). The hub makes a key of the `feed` scope on the source ("follow west"), keeps it in a Secret of the follower's namespace through the follower's Kubernetes API, and sets the follower's `spec.follow`; the hub is not on the data path after that. Optional: `name` (by default the source's connection name), `start` (`follow`, `copy`, `reverse`), `source_url` (by default the public URL the source says it has, else its address in the book), `key_secret` (a Secret made already, for a follower the hub reaches at its address rather than through its Kubernetes API) and `ca_secret`. With `"plan": true` nothing is made: the answer lists the steps and why it is refused, if it is: a follower the operator does not run, one that follows another cluster already, a source with no address the follower's pods reach (a cluster made from Cloud setup has none until its coordinators are exposed), a self-signed source without `ca_secret`, or a follower the hub cannot write a Secret on without `key_secret`. In the command center, **All clusters** draws an arrow from each source to its follower with how far behind it is (amber past 60 s, red when its follow process is silent or held), and **Follow…** on it, or on a cluster's tile, opens that plan, then starts it. **Follow** (under Change) is the follower's own page: the source, the lag, what each source shard applied, and **Pause**, **Resume**, **Stop following** and **Promote**. Promote runs the switch-over: it holds the source's writes through the hub when the source is in the book, waits for `source_holds`, and promotes, after which it offers to make the old source follow back. When it cannot hold the source, promoting loses what the follower had not applied, and the count, as the follow process last said it, is typed to confirm. The page also holds and releases the cluster's own writes. The SQL workbench and Import say when a cluster follows another, and a write it refuses for that links to the source. ## Deadlines, admission and metrics Every query runs under a deadline (`timeout_ms` up to `--max-timeout-ms`, or the server's default) and gets its share of the cores: a query arriving when *r* are running searches its segments on about *cores / r* threads, its own and threads it borrows from one pool the whole server shares, as many as the cores (`chloedb_query_pool_threads`). A query starts no threads of its own, and when the pool is busy it goes on with the threads it has instead of waiting for more. At most `--max-concurrent` run at once; the rest wait for a slot, and one still waiting at its deadline is refused with 429 (`ResourceExhausted` over gRPC) and counted in `chloedb_rejected_total`. With `--admission-wait-ms`, a client's query waits for a slot that long at most, not until its deadline, and is then refused the same way, with `Retry-After`. Past its capacity a server otherwise queues every query until its deadline. On a cluster of two 2-core nodes (a coordinator, 2 shards of 2 copies) at 1,000 clients that sent their next query as soon as they had an answer, the queries waited a median of 1.6 s and a p99 of 2 s; with `--admission-wait-ms 100`, and clients that waited out `Retry-After`, the queries it took ran in a median of 0.26 s and a p99 of 0.53 s, while it answered 22% fewer of them: a refused query is cheap, not free, and the coordinator refused about 1,500 a second. Clients that send a refused query again at once, without waiting, keep the coordinator busy refusing and few queries run, so enable it only where clients wait out `Retry-After` (the [Python client](python.md#a-server-from-python) does). A coordinator's calls to its shards always wait until their deadline, since the coordinator's own slots bound them; set the flag on the coordinators (the operator's `coordinatorArgs`) or on a single server. A query still running at its deadline stops and returns an error. So does a query whose caller stopped waiting (a client that hung up, a coordinator's hedge that lost), and it holds its slot and counts as running until it has stopped. A query checks between segments and, inside a segment, every 1,024 rows it groups, orders by a column or lists, every 1,024 rows a graph walk expands (16 when each hop is a vector search), and every 1,024 rows a join hashes or compares, so it stops within milliseconds even in one large segment. A coordinator does not retry a query that a replica refused with 429 on that replica's sibling, which would only take on both loads: the query fails, or a partial answer leaves the shard out. A read every replica of a shard failed is asked again every 100 ms, for up to 3 s within its deadline, only while one of them is up and refused it for now (a primary outside its lease, as when one of two copies restarts, or one another primary replaced); a shard none of whose replicas answers fails it at once, or a partial answer leaves it out. Hedges (asking another replica when one has not answered after `--hedge-ms`) are budgeted at 5% of the calls to shards, with up to 10 saved for a burst, so that a slow cluster is not sent twice its load. A replica outrun after it had `--hedge-ms` to answer is put in its cool-off, asked last for 5 s; one outrun sooner, as a replica a hedge asked is when the replica asked before it answers moments later, was not given its time and is not. Which replica of a shard a read asks first is `--route`'s choice. `least-cost` (the default) asks each in turn, unless another replica, drawn at random, costs clearly less (by more than a quarter, and by a millisecond at least): a replica's cost is the round trip of its recent queries as this coordinator saw them (at least 1 ms), times one more than its calls in flight, raised for its recent errors and refusals for load (429) and for the load it reported in the coordinator's last survey (its query slots or query memory, whichever is fuller). A replica whose round trip this coordinator has not seen in the last 10 s, or has not seen past its first query, counts as the median of the others, so a new replica or one passed over is asked again in its turn; and one passed over in 8 of its turns running is asked in the next whatever it costs, so that one slow round trip on a busy moment does not keep a replica like the others from being asked through a burst of reads. Coordinators share nothing of this, and the draw keeps them from all sending their reads to the replica that looks cheapest at once. `round-robin` asks each in turn whatever its cost, those in their cool-off (failed, or outrun after `--hedge-ms`, in the last 5 s) last. Under `least-cost` those go last too, unless every replica of the shard is in its cool-off: then they are ordered by cost as if none were. Under heavy overload each replica is outrun in its turn, and `least-cost` asked them all in turn before these two rules (0.3.4) and did worse than `round-robin`: on DigitalOcean (the machines below) with copy 0's node also running 24 CPU-bound threads, at 64 clients it served 2,557 queries a second (p99 230 ms) where `round-robin` served 2,775 (p99 61 ms), and with the two rules 4,252 (p99 32 ms); with 48 such threads, 3,164 and 3,228 against 4,220 (p99 33 ms). Measured with `chloedb-route-bench --external` on DigitalOcean (one shard of 1M rows, its 3 copies each on a c-2 node of its own with 2 dedicated vCPUs, the coordinator and clients on a c-32 node, the servers' answer cache off), `least-cost` cut p99 against `round-robin` from 10.0 to 7.3 ms at 16 clients and from 36 to 24 ms at 64 on copies alike, where its median at 64 clients was 16% higher (9.7 against 8.4 ms); with one copy given a third of its node's CPU it served 5,575 queries a second at 64 clients where `round-robin` served 3,523. A read that must ask one replica (the one holding its lease, or the kept statistics it scores by) asks it first either way, and writes go to the primary; under `least-cost` a read takes kept statistics only of the replica the route asks first (without them it asks that replica for its statistics, which are then kept), so that a replica asked less while it was slow is asked in turn again once it is not. Each coordinator shows what it observed of each replica in `/v1/cluster` (`observed`) and in the `chloedb_replica_*` metrics, whichever route it takes. `--hedge-adaptive` hedges a query after the replica asked has taken longer than it usually does rather than after `--hedge-ms`: its tail, the average of its recent plain query round trips (the last 30 s or 200) plus six times their average deviation, at least 2 ms and at most `--hedge-ms`, which it takes until the replica answered 20 queries. Other calls (statistics, fetches, reads by key) keep `--hedge-ms`, and hedges stay within the same budget (5% of calls). A replica outrun by such a hedge before `--hedge-ms` was slower than usual, not failing, so it is not put in its cool-off either. Measured with `chloedb-route-bench` on one machine (Apple M1 Pro, 10 cores, 32 GB, macOS 27.0.1, shards, coordinator and clients in one process over loopback; `chloedb-server/results/route-mac-phase2/`), it brings the 99.9th percentile of a replica that stalls now and then down by more than half under `least-cost` (55 to 19 ms at 16 clients); hedges there compete for the same cores, so p99 rises by about 5% when the machine is saturated. With each replica on cores of its own (`chloedb-server/results/route-containers/`, three containers on 2 vCPUs each in a Docker VM on the same Mac), it costs nothing measurable at p99 or p99.9 on replicas alike, and cuts that 99.9th percentile from 59 to 10 ms. On DigitalOcean (the machines above), it cut the 99.9th percentile of one copy that stalls for 60 ms a second from 61 to 15 ms at 16 clients under `least-cost`, but with 3 shards of copies alike, where a query waits for all three, it raised `least-cost`'s 99.9th percentile from 15 to 21 ms at 16 clients and from 39 to 60 ms at 64; it is off by default for that. `--prefer-caught-up` (on by default, with `--route least-cost`; `--prefer-caught-up=false` turns it off) routes a read that must see a write (`min_seq_nos`) by each replica's round trips of such reads, which include its wait for the write, unless the replica is known to hold the write (it answered a read after it, or a later one); other reads go by its plain queries' round trips. A replica that applies writes late is then asked few reads after a write and its share of plain reads as before, and is not put in its cool-off when such a read outruns it. One found behind is asked such a read again a minute later to see whether it caught up. A read still waits on the replica it is sent to for the write it must see, so this changes where reads go, not what they see. On DigitalOcean (the machines above, one shard whose primary acknowledges writes alone and ships them to one of its two replicas 50 ms late), it raised the queries a second of a mix of writes and reads after them from 1,640 to 2,156 at 16 clients and from 1,961 to 2,851 at 64, against `least-cost` without it. `/v1/cluster` shows the averages apart (`plain_rtt_ms`, `after_write_rtt_ms`), the newest write each replica is known to hold (`held`) and its tail (`tail_ms`), and the coordinator's `route`, `hedge_adaptive` and `prefer_caught_up`. ### Limits A query may reach at most `--max-result-window` rows (10,000), as Elasticsearch's `max_result_window`: one whose LIMIT plus OFFSET is larger fails with 400, and so does one without a LIMIT that matches more rows. A ranked query without a LIMIT returns its best 100. Counts and groups are not rows, but a GROUP BY may make at most `--max-groups` groups (65,536, as Elasticsearch's `search.max_buckets`) and fails with 400 at the next one, before its LIMIT is applied. A cross-encoder's rerank phase may score at most `--max-rerank` rows (20: `ms-marco-MiniLM-L-6-v2` scores twenty abstracts of SciFact, NFCorpus or ArguAna in about 1 s at the median and at most 1.3 s at p99 on four cores in `f32`, a quarter of the default 5 s deadline, where a hundred take 4.4 to 4.8 s at the median, so that many would miss it; its int8 export takes 0.4 s for twenty and 1.8 to 2.0 s for a hundred, which a larger `--max-rerank` can allow): one whose count is larger fails with 400 before any work. Queries that need a model not yet open wait for one of them to open it, and share that copy. A compound query's single-table queries, `WITH` results and join sides may hold up to 1,000,000 rows each, as before; its answer is held to the window. A coordinator checks LIMIT and OFFSET before it asks its shards, and a shard lets a coordinator's single-table query reach 1,000,001 rows. To read more rows than the window, [scroll](#reading-past-the-window-scrolls). #### Reading past the window: scrolls A scroll reads a query's answer a page at a time, every page from the version of the database the first read, as Elasticsearch's scroll does; the window then caps each page, not the whole answer. `POST /v1/query` with `page_size` answers the first page, at most `page_size` rows and at most `--max-result-window`, and, while rows are left, a `cursor`. The cursor alone asks for the next page, `{"cursor": "..."}` (with `format`, `objects`, `keep_alive_ms` or `timeout_ms`, and nothing of the query's), until the last page, which answers no cursor. With `"format": "arrow"` each page is an Arrow stream and the cursor comes in the `x-chloedb-cursor` header. ```bash curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"sql": "SELECT id, price FROM products WHERE stock > 0", "page_size": 10000}' # {"columns": ["id", "price"], "rows": [...10,000 rows...], "cursor": "6f1c...", ...} curl -s localhost:7700/v1/query -H 'content-type: application/json' -d '{"cursor": "6f1c..."}' # the next 10,000; the last page has no "cursor" ``` The answer is the query's own, in its order: the rows a query with no window answers. Rows written, changed or deleted after the first page are not in it. What a scroll keeps between pages depends on the query: - A plain scan (no `ORDER BY`, groups, counts or rerank phases) resumes after its last row, segment by segment, and holds nothing but its place: it can read a table of any size. - An ordered or ranked query runs once, at the first page, and holds its rows' places in order (24 bytes a row), at most what `--max-scroll-rows` leaves; a ranked query without a LIMIT answers its best 100, as it does at once. - Groups, counts and compound queries (joins, `WITH`, `UNION`, `DISTINCT`) run once and hold their rows. A coordinator scrolls too. Each shard it asks starts a scroll of its own (protocol 18, [gRPC](#grpc)), on the copy that answers, which keeps it on a lease of its snapshot; the coordinator merges the shards' pages as they come. Rows in no order come one shard's after another's (the order a coordinator answers them in at once); rows ordered by a column, a path or one score (BM25, a similarity, a ranking expression) come in their order, the coordinator asking each shard for more rows whenever its rows run out before the page is full, so it holds at most two pages of the shards' rows between pages. A shard's scroll is kept open while the coordinator's is: one that a page did not ask is asked for a page of no rows every 30 seconds, and it is kept a minute past the coordinator's keep-alive. Groups, counts, fused scores, rerank phases, guarded queries and compound queries run once on the coordinator, which holds their rows, at most `--max-scroll-rows`, as one server does. Each shard reads one version, the one it had when the scroll started; the shards' versions are their own, as a coordinator's queries' are. A scroll whose shard fails (its copy went down, say) ends, saying so: a scroll of the shard's rows from another copy would read another version, so start the scroll again. A scroll ended early, by `DELETE`, its keep-alive or its LIMIT, ends its shards' scrolls too. The open scrolls hold at most `--max-scroll-rows` rows, or rows' places, between them (1,000,000). A scroll whose query would hold more than all of it fails with 400; one that would hold more than the others leave is refused with 429 until some end. `chloedb_scrolls_open` and `chloedb_scroll_rows_held` show them. Each scroll keeps a lease on the version it reads, so the files of that version stay until it ends, as a [snapshot lease](#http-api) does. A cursor is random and is read only by the key that started it (another key's is answered 404). It ends with its last page, with `DELETE /v1/query/cursors/ID`, or when no page is asked for over its keep-alive: `keep_alive_ms`, given with `page_size` or with any page (60 s by default, the lease TTL; at most an hour). A page that fails, at its deadline say, leaves the cursor where it was, so asking again reads the same page; a page that answered and was lost on the way is not served again. Asking for a cursor's next page while its last is being read is refused with 409. The running queries share a memory budget, `--query-memory-mb` (a third of the cgroup memory limit, or of RAM; merges have their own, a half). As Elasticsearch's request circuit breaker, a query counts what it builds up against it as it goes: its groups, `COUNT(DISTINCT)` values and percentiles' values, the rows it orders or lists before its LIMIT, the rows it returns with their stored text, the nodes and neighbour lists of a graph walk, and a compound query's single-table answers, join tables and joined rows. A query that would go past the budget stops and is refused with 429 (`ResourceExhausted` over gRPC, which a coordinator passes on), and it gives back what it held, as every query does when it ends. `chloedb_query_memory_bytes` shows what the running queries hold and `chloedb_query_memory_trips_total` how many were refused. The counts are estimates of the structures a query grows, not of every allocation; index data is mapped from the file and not counted. An `ORDER BY` with a LIMIT keeps about twice LIMIT plus OFFSET rows as it goes, not every match. Filters are kept between queries, as Elasticsearch's node query cache and Solr's filter cache keep theirs: the second time a segment sees a filter, in a second query, the documents it keeps there are kept, and later queries test a bit for each candidate instead of reading the filter's columns again (a fixed filter beside one that changes with every query is kept on its own). They take up to `--filter-cache-mb` (64 MiB), least recently used out first; a filter larger than a quarter of that is not kept, nor made again while the cache remembers it (up to 1,024 such filters). It counts up to 4,096 filters seen once; past that it forgets the older half. Only filters that read the segment's own rows are kept: not a field with values written in place, a typo or synonym expansion, a graph, a subquery or a JSON path, nor a segment still in memory. Nor a list of the table's keys (`id NOT IN (...)`, the items a user has seen): it is a request's own, its set would hold nearly every row of the segment, and a few hundred requests going round would push each other out before any came back; what is fixed beside it is kept. Deletes are checked apart, and a segment's filters go with it when it is merged away, so answers do not change. A query's plan says `from the cache` for a filter it found there, and `chloedb_filter_cache_total{outcome="hit"|"miss"}`, `chloedb_filter_cache_evictions_total` and `chloedb_filter_cache_bytes` show how it does. The log store's database keeps none. Answers are kept too, up to `--answer-cache-mb` (64 MiB, least recently used out first): the same query (its SQL, parameters and options, and over gRPC its plan) on the same version of the table is answered from memory, without a slot or the executor. A write moves the version, so a kept answer is never stale; it is simply not found again. A query that reads the clock (`now()`, `'now'` as a time), random numbers, `uuid()` or a model (`llm(`) is not kept, whether its own text does or a stored function or rank profile it names (a function made with `CREATE FUNCTION f(b TEXT) AS llm(...)`, a recency boost `decay(at, now(), 86400)` in a profile, a function that calls such a function), nor a scroll, a held snapshot, a profile, an Arrow answer, or an answer larger than a 128th of the budget (512 KiB of the default). A coordinator's shards keep their parts of its answers, so a coordinator's repeated query is answered by each shard from memory. A hit answers the kept rows themselves, not a copy; its steps, when asked for, say `answer cache` (and the list of queries shows the step either way). Identical queries that miss at the same time (the same key on the same version) run once: the first runs, and the others wait for it without a query slot and are answered with its rows, also when they are too large to keep; their steps say `answer cache` too. An error is never handed on: when the run fails, its caller goes, or it outlasts a waiting query's own deadline, that query runs itself. `chloedb_answer_cache_total{outcome="hit"|"shared"|"miss"}` (`shared`: answered by an identical query's run; `miss`: run), `chloedb_answer_cache_waiting` (queries waiting for such a run now), `chloedb_answer_cache_answers` and `chloedb_answer_cache_bytes` show how it does. On a coordinator over 2 shards, all on one 4-core machine, with queries drawn from a Zipf law (the 100 commonest were half of them), it answered 3,568 to 3,671 queries a second instead of 2,192 to 2,256 and each query cost the shards 0.4 ms of CPU instead of 1.0; with every query different it was as fast as without it. An idle HTTP connection costs the server about 31 KB, most of it the 8 KiB buffers HTTP/1 reads and writes through, and a file descriptor: 10,000 connections held open on a coordinator took 314 MB and opened in 1.2 s on one 4-core machine. 100,000 clients then need about 3 GB over the coordinators (about 800 MB each on four) and an open-file limit above 100,000 on each: the server raises its soft limit to the hard one when it starts, so raise the hard limit where it is lower (`LimitNOFILE` in a systemd unit, `ulimit -Hn` in a shell; containers usually allow 1,048,576). Over gRPC or HTTP/2 one connection carries many clients' queries at once. Write requests are held in one queue, from embedding (a server embeds on as many writes at once as it has cores) through waiting for the writer to being applied. With `--max-queued-writes` (1,024) in it, a write or a SQL `INSERT`, `UPDATE` or `DELETE` is refused with 429 before any work, and counted in `chloedb_write_errors_total{status="429"}`; `chloedb_write_queue_requests` shows how many it holds. A body larger than its route allows is refused with 413: `--max-body-mb` (256 MiB) for `/v1/write` and `/v1/import`, 16 MiB for every other route. #### Statement budgets The text of a statement is bounded before it is parsed (`--max-statement-bytes`, `--max-statement-elements`, and 1,000 levels of nesting), and its calls of stored functions written out hold at most 250,000 expressions. A budget is less, and is checked on what the statement becomes, not on what it says: `SELECT f(1)` may be a few bytes that write out to thousands of expressions, and `tags @> :tags` fifteen bytes with 100,000 tags. As ClickHouse's `max_expanded_ast_elements`, `max_rows_to_read` and `max_execution_time` and PostgreSQL's `statement_timeout` per role, it has five parts, each left out when not given: | budget | bounds | checked | |---|---|---| | `nodes` | the expressions of the statement written out (its stored functions and rank profiles in place) | before it binds | | `depth` | how deep they nest; a subquery is a level | before it binds | | `list` | the values of one list: `IN (...)`, `ARRAY[...]`, a list parameter | before it binds | | `plan_ms` | the time one plan takes to make | as it plans, where the deadline is checked | | `rows_read` | the rows its scans, filters and groups visit, and the rows its parts answer (a join's sides, a `WITH` result) | as it runs, every 1,024 rows, and as each part answers | A statement's budget is the tightest of three: the server's `--statement-budget`, its key's, and its request's `"budget"` on `/v1/query`, `/v1/sql`, `/v1/explain` and `/v1/sql/check` (`{"budget": {"rows_read": 100000}}`, or `"budget": "rows_read=100000"`). A request may so lower its key's budget, never raise it. A key gets one when it is made, `POST /v1/admin/keys {"name": "dashboards", "scope": "read", "budget": {"nodes": 20000, "rows_read": 5000000}}`, and `POST /v1/admin/keys/ID/budget {"rows_read": 1000000}` lowers it (a budget is lowered, never raised, as an expiry is brought nearer: the servers of a cluster merge a key's two budgets to the tighter, so a raise would not reach them; a key that needs more is a new key). A key another key made has its maker's budget. The key list shows each key's `budget`. A statement past its shape's budget is a 400 `query_invalid` before it runs, one past `rows_read` a 400 as soon as it reads the row past it, and one past `plan_ms` a timeout, each naming the budget. A coordinator holds a statement to `nodes`, `depth`, `list` and `plan_ms` as it plans it; `rows_read` is counted by a single server, not yet across a coordinator's shards. Embedded, `ExecOptions::budget` is the statement's budget, and `Db::query_with`, `Db::sql_with`, `Db::query_leaf_with` (Python's `query_arrow`), `Db::pack_with`, `Db::explain_with` and `Db::prepare_write_with` plan under it, with the deadline, on a thread with the stack a deep statement needs. A short statement plans on the thread that serves the request, a longer one on a blocking thread, where it holds none of the threads that serve the others and stops at its deadline: a statement is short by its text and its parameters both, so a short text that binds a long list plans on the blocking thread too. Planning, `EXPLAIN` (`/v1/explain`) and `/v1/sql/check` included, stops at the request's deadline, and checks it as it writes out each call of a stored function, as it binds each query, and every thousand values of a list. ### Health `GET /v1/health` reports `status`, and `docs` and `segments`, the rows and segments of the default table (the first table, or on a database made with no tables the first one people made; a coordinator sums its shards'), with `tables` the rows of each. **Changed:** on a database made with no tables, `docs` counted the placeholder, so 0, and so did the clients' `count()`. - `ok`. - `degraded`: on a database, its flushes fail (a full disk), and `error` says why. Writes still commit, to the write-ahead log, until the memtable holds twice its limit; then they are refused until a flush succeeds. On a coordinator, a replica does not answer, or is not `ok`, but every shard has one that answers. - `failing`: the database cannot write until the server restarts. A write failed partway (a full disk, an I/O error) and the database refuses writes until it is reopened, or the writer thread stopped. Reads still work; merges stop. On a shard's primary, hand the primary over to a replica in sync first (with `--failover-after-ms` it does so itself), then fix the cause and restart it: restarted alone, it fails again while its disk is full. - `down`: a coordinator has a shard with no replica answering. It answers 503 for `down` and `failing`. `/livez` and `/readyz` answer 503 only for `failing`, so that an orchestrator restarts the server (the [Kubernetes manifests](https://github.com/chloetech-ai/chloedb/tree/main/chloedb-server/deploy) use them as probes), and `/readyz` also while the server drains: with `--drain-ms N` (`CHLOEDB_DRAIN_MS`; 0 by default, 5,000 under the operator), a server sent SIGTERM answers `/readyz` 503 (`"status": "draining"`) and closes each HTTP connection after its answer for N ms while it goes on serving, so that a load balancer stops sending it requests before it stops; then it stops as it does without the flag, finishing the requests it holds (over TLS too), for up to `--stop-grace-ms` (20 s), and ending the feeds followers read. Neither asks a coordinator's shards, so one slow shard cannot take every coordinator out of service at once; `/v1/health` shows the shards. The writer thread survives a panic while applying a write: the requests in that batch get 500, the panic is counted in `chloedb_writer_panics_total`, and the next batch goes on. `GET /metrics` serves, in Prometheus text format, with `# HELP` and `# TYPE` lines for every family and durations in seconds. Its families are named `chloedb_*`; servers from before the rename name the same families `strata_*` (a dashboard over both versions matches `{__name__=~"(chloedb|strata)_.*"}`). A scrape config, alerting rules mirroring the [built-in alerts](#alerts) and a Grafana dashboard are in [`chloedb-server/deploy/monitoring`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb-server/deploy/monitoring) ([how to use them](../guide/operate-cluster.md#check-its-health)): | metric | labels | what | |---|---|---| | `chloedb_build_info` | `version`, `commit`, `simd` | always 1: the server's version, the commit it was built from (empty for a build outside a git checkout) and the SIMD kernels it runs | | `process_start_time_seconds`, `process_cpu_seconds_total` | | when the process started, and the CPU time it used | | `process_resident_memory_bytes`, `process_open_fds` | | memory in RAM (mapped database pages included) and open file descriptors (Linux) | | `chloedb_http_requests_total`, `chloedb_http_request_duration_seconds` | `route`, `status` | HTTP requests by route pattern (`other` for none) and status, and their duration by route | | `chloedb_grpc_requests_total`, `chloedb_grpc_request_duration_seconds` | `method`, `code` | gRPC calls by method and status code, and their duration by method | | `chloedb_queries_total` | `kind`, `outcome` | queries by kind (`bm25`, `vector`, `sparse`, `hybrid`, `boosted`, `expression`, `reranked`, `decay`, `graph`, `column`, `facet`, `aggregate`, `count`, `filter`, `compound`, `invalid`) and outcome (`ok`, `partial`, `error`, `timeout`, `rejected` for no slot or no memory, `cancelled` by an operator) | | `chloedb_query_duration_seconds` | `kind` | time to answer a query, waiting for a slot included | | `chloedb_query_admission_wait_seconds` | | time a query waited for a slot (`--max-concurrent`) | | `chloedb_queries_running` | | queries running now | | `chloedb_rejected_total` | | queries refused because no slot came free before their deadline | | `chloedb_query_memory_bytes`, `chloedb_query_memory_limit_bytes` | | memory the running queries hold, as counted, and their budget (`--query-memory-mb`; absent with no limit) | | `chloedb_query_memory_trips_total` | | queries refused because the budget was spent | | `chloedb_query_pool_threads`, `chloedb_query_pool_queued` | | threads in the pool queries borrow from to search segments in parallel, and the threads queries asked for that none was free to give yet | | `chloedb_filter_cache_total` | `outcome` | filters queries asked of a segment by whether the [filter cache](#limits) kept them: `hit` (read from it), `miss` (made, also to be kept) | | `chloedb_filter_cache_evictions_total` | `reason` | filters the filter cache dropped: `full` (the least recently used, for room), `segment_gone` (their segment merged away or opened again) | | `chloedb_filter_cache_resets_total` | | times the cache's count of filters seen once (4,096 at most) was full and forgot its older half: many filters asked once each | | `chloedb_filter_cache_filters`, `chloedb_filter_cache_bytes`, `chloedb_filter_cache_limit_bytes` | | filters the cache keeps, about their bytes, and its limit (`--filter-cache-mb`) | | `chloedb_writes_total`, `chloedb_written_docs_total` | | write requests that succeeded, and rows they wrote | | `chloedb_write_errors_total` | `status` | write requests that failed, by HTTP status | | `chloedb_write_duration_seconds` | | time from a write request to its commit, embedding and waiting for the writer included | | `chloedb_write_queue_requests`, `chloedb_write_batches_total` | | write requests held ([limits](#limits)): embedding, waiting for the writer or being applied; and the groups the writer applied in one transaction each | | `chloedb_write_batch_requests` | | write requests per group the writer applied in one transaction (group commit), a histogram with buckets from 1 to 4,096: its `_sum` is the requests applied, its `_count` equals `chloedb_write_batches_total` | | `chloedb_idempotent_replays_total` | | writes answered from their idempotency key instead of being applied again | | `chloedb_slow_requests_total` | `what` | queries and writes the slow log wrote down | | `chloedb_embedded_texts_total`, `chloedb_embed_duration_seconds` | `for` | texts the server's models embedded for writes (`write`), for query parameters (`query`) and for rows stored without vectors (`backfill`), and how long each took | | `chloedb_embed_requests_total`, `chloedb_embed_retries_total`, `chloedb_embed_failures_total`, `chloedb_embed_tokens_total` | `table`, `field`, `model` | requests a [hosted model](#hosted-models) sent, sent again after a rate limit or failure, and failed for good, and the tokens its provider counted | | `chloedb_agent_runs_total` | | questions the agent was asked | | `chloedb_docs`, `chloedb_segments`, `chloedb_deleted_docs`, `chloedb_memtable_docs` | | a database's rows and segments over every table (its rows are `/v1/health`'s `rows`; its `docs` and `segments` are the default table's), deleted rows merges have not dropped yet, and rows not yet flushed | | `chloedb_table_docs`, `chloedb_table_segments` | `table` | each table's rows (`/v1/health`'s `tables`) and segments | | `chloedb_copy_info` | `shard`, `node`, `role` | on a copy of a cluster: always 1, the shard it serves, its `--node-name` and its role (`primary`, `replica`), to join its other series on | | `chloedb_file_bytes`, `chloedb_free_bytes`, `chloedb_wal_bytes` | | its size on disk, the free space in its file, and its write-ahead log (the active file and the sealed ones together) | | `chloedb_wal_active_bytes`, `chloedb_wal_sealed_bytes`, `chloedb_wal_sealed_files` | | the write-ahead log's active file, which commits are appended to, and the sealed files a background flush has not installed yet: sealed files that stay mean flushes fall behind | | `chloedb_wal_sync_duration_seconds` | `path` | time to make writes durable in the write-ahead log, from 50 µs to 0.25 s: `commit` is a commit's append, its write and its fsync together; `replica` is a replica's fsync of a batch shipped to it. Its `_count` is the number of fsyncs | | `chloedb_snapshot_leases` | | snapshot leases held | | `chloedb_failing`, `chloedb_flush_failing` | | 1 when the database is `failing`, or its flushes fail ([health](#health)) | | `chloedb_writer_panics_total` | | write batches whose application panicked | | `chloedb_merges_running`, `chloedb_merge_memory_bytes` | | merges running now and their estimated memory ([merges](#merges)) | | `chloedb_merges_total`, `chloedb_merges_limited_total` | | merges finished, and merges cut (or put off) to fit the memory budget or an interrupted merge's | | `chloedb_merges_interrupted`, `chloedb_merge_failing` | | groups of segments whose merge a crash interrupted; 1 while merges fail | | `chloedb_damaged_segments` | | segments the last [scrub](#replication-a-primary-and-its-replicas) found failing their checksums | | `chloedb_shard_calls_total` | `shard`, `outcome` | a coordinator's calls to each shard (replicas, retries and hedges together) by outcome: `ok`, `error`, `timeout` | | `chloedb_shard_retries_total`, `chloedb_shard_hedges_total` | | calls a coordinator asked of another replica after one failed, or after the first had not answered within `--hedge-ms` | | `chloedb_replica_inflight` | `shard`, `replica` | a coordinator's calls to a replica not answered yet | | `chloedb_replica_query_rtt_ms` | `shard`, `replica` | the round trip of a coordinator's queries to a replica over the last 2 s or 20 queries, which `--route least-cost` compares replicas by | | `chloedb_replica_overhead_ms` | `shard`, `replica` | that round trip less the time the replica counted (its admission wait and run): the network and decoding | | `chloedb_replica_err_rate` | `shard`, `replica` | the share of a coordinator's recent calls to a replica that failed by the replica's fault | | `chloedb_shard_protocol` | | the protocol a coordinator speaks to its shards: the oldest a replica speaks | | `chloedb_fetch_queries_total`, `chloedb_fetch_lost_rows_total` | | a coordinator's queries answered by query then fetch, and rows of their pages no fetch found | | `chloedb_stats_cache_total` | `outcome` | a coordinator's BM25 queries by where their statistics came from: `hit` (kept, no statistics round), `miss` (a round), `stale` (a replica had moved on: sent again with a round) ([kept statistics](#sharding-one-coordinator-many-shards)) | | `chloedb_stats_cache_terms` | | terms whose statistics a coordinator keeps, over every replica | | `chloedb_stale_stats_total` | | queries a shard answered stale, sent kept statistics of an older version | | `chloedb_slot_epoch` | | the epoch of the [slot map](#slots) a coordinator routes writes by; 0 while it routes by the hash before slots | | `chloedb_shard_keyed_ops_per_second` | `shard`, `kind`, `window` | reads (`kind="read"`) and writes a coordinator routed to a shard by key, a second, over the last `1m`, `5m` or `15m`, by the slots it holds now ([hot slots](#hot-shards-and-hot-slots)); a gauge, since a shard's count falls when its slots move | | `chloedb_fanout_queries_per_second` | `window` | requests a coordinator sent to every shard, a second | | `chloedb_slot_ops_total` | `kind` | reads, writes and fan-outs (`kind="fanout"`) a coordinator routed, over every slot | | `chloedb_slot_heat_skew` | | the busiest shard's keyed load over the last 5 minutes, as a multiple of the shards' mean (0: none counted) | | `chloedb_replicas_avoided` | | replicas a coordinator asks last for now, after they failed or were outrun | | `chloedb_replication_role` | | 1 on a [primary](#replication-a-primary-and-its-replicas), 2 on a replica | | `chloedb_global_checkpoint` | | the highest sequence number every in-sync replica holds (on a replica, as its primary last said) | | `chloedb_replica_in_sync`, `chloedb_replica_behind` | `replica` | on a primary: 1 while a replica is in sync, and the transactions it does not hold yet | | `chloedb_replica_shipped_total`, `chloedb_replica_failures_total`, `chloedb_replica_copies_total` | `replica` | on a primary: transactions a replica applied from it, calls to it that failed or that it refused, and copies of the primary it installed | | `chloedb_replica_verifications_total`, `chloedb_replica_divergences_total`, `chloedb_replica_verify_failures_total` | `replica` | on a primary: times a replica's rows were [compared](#replication-a-primary-and-its-replicas) with the primary's, times they differed, and rounds that could not compare | | `chloedb_replica_applied_total`, `chloedb_replica_restores_total` | | on a replica: transactions it applied from its primary, and copies of the primary it installed | | `chloedb_replica_apply_batches_total`, `chloedb_replica_apply_seconds_total` | | on a replica: calls of its primary it applied, and the seconds they took (the wait for a free writer included); with `chloedb_replica_applied_total`, the transactions per call and the time per transaction | | `chloedb_replica_serves_reads` | | on a replica: 1 while it [serves reads](#replication-a-primary-and-its-replicas) | | `chloedb_replica_read_waits_total`, `chloedb_replica_reads_refused_total` | | on a replica: reads that waited for a [write they must see](#reads-that-see-a-write), and reads refused, while it caught up or because it had not applied such a write in time | | `chloedb_replica_digests_total` | | on a replica: digests of its rows it computed for its primary to compare | | `chloedb_follow_lag_seconds`, `chloedb_follow_up`, `chloedb_follow_behind_transactions`, `chloedb_follow_behind_bytes` | `name`, `kind` | on the server or coordinator a [follow process](#following-another-cluster) (`kind="cluster"`) or a [Postgres follower](postgres.md#how-far-behind-it-is) (`kind="postgres"`) writes through: how far behind its source it is, in seconds and in transactions (a cluster) or bytes of WAL (Postgres), and 1 while it follows and told within 10 s | | `chloedb_connector_up`, `chloedb_connector_failures`, `chloedb_connector_last_ok_timestamp_seconds`, `chloedb_connector_lag_events`, `chloedb_connector_behind_seconds` | `connector`, `kind` | on the server that runs the [connectors](connectors.md#health): each one that is on, 1 while it is well (the built-in alert `connector-failing`), its failures in a row, when it last went well, and a Kafka connector's events not written and how long they waited (`connector-behind`) | | `chloedb_connector_partition_lag_events` | `connector`, `topic`, `partition` | the same: a Kafka connector's events not written, by partition | | `chloedb_cluster_copies`, `chloedb_cluster_copies_up`, `chloedb_cluster_copies_down`, `chloedb_cluster_copies_in_sync` | `shard` | on a coordinator, as it last checked its cluster (every 5 s): a shard's copies, those that answer, those that do not (the built-in alert `copy-down`), and those that answer, serve reads and are in sync with its primary (`under-replicated` when fewer than its copies) | | `chloedb_cluster_shard_majority`, `chloedb_cluster_shard_primary`, `chloedb_cluster_shard_term` | `shard` | on a coordinator: 1 while a majority of a shard's copies answer (`shard-no-majority`), 1 while it has a primary that takes writes, and the newest term its copies answer with | | `chloedb_cluster_primary_changes_total` | `shard` | on a coordinator: the changes of a shard's primary it saw since it started, failovers and handovers (`primary-changed`) | | `chloedb_cluster_copy_up` | `shard`, `copy`, `url`, `role` | on a coordinator: 1 while a copy answers it, with its `--node-name` and its role (`primary`, `replica`, or `down`) | | `chloedb_cluster_checked_seconds` | | on a coordinator: seconds since it last checked its cluster | A coordinator's `/metrics` does not ask its shards: each shard serves its own, and the coordinator shows how its calls to them went, and the cluster's state as it sees it (`chloedb_cluster_*`). `strata_query_ms` (milliseconds) became `chloedb_query_duration_seconds`. A server's health gives `rows` (every table) and `tables` (rows per table). A copy's `detail` gives its `limits` (`slow_ms`, `max_concurrent`, `max_rows`, `timeout_ms`) and `system.memory_limit_bytes` (the cgroup's limit, else the machine's memory). A failed change keeps its error in the audit entry's `after.error`, and its event says it in the title. ### Fleet health `GET /v1/health/fleet` answers whether the cluster serves, judged over its copies rather than the coordinator's own process, in one answer the command center's **Home** shows: `status` (`ok`, `warning`, `critical`), a one-sentence `headline`, `since_ms` (since when that status holds), `checks` (shards serving, the share of queries failing and their p99 against the SLO over the last 5 minutes, copies answering, replication lag, disk, the disks' speed, Kubernetes' eviction line ([the disks](#the-disks)), statements that time out, alerts firing; the `error_ratio` check also has `writes`, the share of writes that failed on the server's side against the same SLO, and takes the worse of the two as its status, with `searches_status` then, and writes failing while every shard serves are a problem of their own, `write_error_ratio`), each `ok`, `warning` or `critical` with its value, and `problems`, worst first, each with `where` (a shard or a copy, by its short name such as `s1-0`), `since_ms`, `impact` (what clients feel), `why` for some (the lines that point at a cause), `next` (what to do, with the command center's view that does it) and `actions` for some (what the command center can do about it, [the disks](#the-disks)). The headline holds while nothing changes: it says what crossed a line ("s0-0's disk is over 85% full", "Searches are failing: more than the SLO's 1% fail"), and the problem's `title` and the checks carry the numbers now. Each coordinator judges with what the others see: they tell each other, every 5 seconds, which copies their last survey did not reach (`GET /v1/coordinators?window=1`'s `unreached`). A copy that does not answer this coordinator, but answered another's survey begun since, and then still does not answer a survey of this coordinator begun after that (a copy coming back answers one coordinator a few seconds before the other), is cut off from this one, not down: Home says "This coordinator cannot reach s0-1, which coord-b reaches" (a warning, `shard-0-cut-off`, with the network to look at), or, when this coordinator's clients fail for it, that searches or writes through this coordinator fail while the others' clients are served; and every coordinator's Home names a copy another coordinator cannot reach (`coordinator--cut-off`), from that coordinator's surveys begun since this one last found the copy down. The `copies` check lists the copies down here that another coordinator reaches (`unreached_here`) and those another cannot reach (`unreached_elsewhere`), which make it a warning. `--slo-error-ratio` (0.01) and `--slo-p99-ms` (250) set the SLO. On a shard server the same checks describe that server alone. The headline judges searches over the last minute, and the SLO checks over 5 minutes. A failure that ended is a problem of its own: "Searches failed for 62 s (10% at worst) and answer again" (`error_ratio_recovered`, `p99_recovered`, with `from_ms`, `to_ms`, `worst`); a failure longer than the 5 minutes starts at its first failing point in the hour the coordinator keeps. Each problem has `since_ms` (when it began) and `first_signal_ms` (its earliest signal). The answer's `since_ms` is the headline problem's, and `not_ok_since_ms` is when the status left `ok`. Equal problems are one problem ("4 copies' disks are 97% full"), in the same order on every look. The `alerts` problem counts this coordinator's firing, unsilenced rules once each, "on N copies", and its `impact` names each with its severity and where. `GET /v1/cluster` says what each shard can do: `state` (`ok`, `degraded`, `no_reads`, `no_writes`, `down`), `serves_reads`, `takes_writes`, `majority`, `failover`, `primary` and `why`, a sentence, with `can_lose`, the copies it can lose and still serve reads and take writes (with failover on; 0 for a pair), and `electing`, true during a failover: no primary yet, or a copy just elected that takes writes once the old primary's lease runs out (`failover_window_ms`, the longest `--failover-after-ms` of its copies). Writes sent meanwhile are held and then answered, so the command center says to wait, not to restart that copy. With failover on, a shard of two copies that loses either serves no reads: its primary serves a read only while a majority of its copies answer it. Such a pair is `ok` while both answer, and `warnings` lists it (`survives_no_loss`), as Home's headline does. A copy that does not answer has `role: "unknown"`, with `last_role`, `down_since_ms` and `last_seen_ms`, so a dead primary is no longer the shard's primary. Copies carry a short name (`short`), taken from their address so that a copy keeps it when another copy of its shard leaves or joins, and every coordinator says the same: `s1-0` for a server the operator runs (shard 1, the pod numbered 0), else the host's first label (`a0` for `http://a0.example:7701`) with the port unless it is 7701, and `host:port` for an IP address or `localhost` (`127.0.0.1:8004`); two copies that would share a name are named by their host and port. The command center, `chloedb-server cc`, the fleet's texts and the alerts' messages name a copy by its server's `--node-name` (`name`) when it gave one, with the short name beside it, and a pod the operator runs by its short name. `short` itself does not change: it is the address's in `/v1/cluster` and in an alert's `where`, which carries the name people read in `name` beside it, so match copies by `url` or `short`. Copies also carry `name`, `node`, `zone`, `version` and `backup_dir`, and a copy that answers its position (`seq_no`, the term and number of its last write) and the cluster map's epoch it holds (`slot_epoch`, 0 for none: the coordinator gives the map to a primary or replica that holds an older one, such as a replica rebuilt on an empty disk, and leaves a standalone server at a copy's address without one, since a server added as a replica must hold none); on Kubernetes the operator gives each server its image, pod, node and the cluster's name. One snapshot, taken at most every 2 seconds, answers every caller. `--cluster-name`, `--environment` (`production`, `staging`: the command center treats any environment not named as a lower one, such as `dev`, `test`, `staging`, `qa`, `local`, `sandbox` or `demo`, or none, as production) and `--public-url` (for links in alerts' webhooks) name the cluster in `/v1/cluster` and `/v1/whoami`. `?brief=1` leaves out each copy's `detail`: 3.5 KB against 20 KB for 4 copies. The command center polls it on views that show no copy's numbers. ### The disks Each database server measures the disk under its database itself, every `--disk-probe-s` (a minute): eight random reads of 4 KiB of its database's file and 4 MiB in a row, around the page cache (`O_DIRECT`; `F_NOCACHE` on macOS), two seconds at most, and on Linux how busy the device was since the probe before (`/sys/dev/block`). The readings go into its series (`disk_read_ms`, `disk_mb_s`, `disk_busy`, `disk_await_ms`) and `GET /v1/admin/disk` (`probe`). Fleet health compares the copies' disks (check `disk_speed`): one whose reads take five times the median of its peers' and 2 ms more at least (or 30 ms whatever its peers), or that reads in a row at a fifth of their speed, in two of its last three readings, is a problem (`disk-slow-`) that says how much slower, whether the device was busy (the load) or not (the disk, or the machine under it: a degraded cloud volume or host), and what its searches' p99 is against the shard's other copies; the coordinator's built-in alert `disk-slow` fires after three minutes of it. A reading taken while a scrub ran is left out. Under Kubernetes, a database on the node's own disk (a `hostPath` or an `emptyDir`, told by the device of `/etc/hosts`, which the kubelet writes) shares it with the kubelet, which evicts every pod of the node once that disk has less than its threshold free (`--evict-free-ratio`, 15%). Its series has `disk_on_node`, `disk_evict_headroom_bytes` and `disk_evict_headroom_ratio`; fleet health makes a node whose disk has under 5% of itself left above the line, or reaches it within a day at the last hour's rate, a warning (`evict-`), and under 2%, past the line, or within an hour, critical, saying what of the used bytes is the database and what is not, and which shards have no copy on another node; the alerts `disk-evict` and `disk-evict-now` watch the same. Such a disk is judged by that line, not by the 85% and 95% of a full disk. Fleet health also tells statements of the last 15 minutes that time out (2 calls or more, and a tenth of their calls) or take 2 s a call on average (or ten times `--slo-p99-ms`, if more), the command center's own left out (`slow-statement-`, check `statements`), each with what most likely makes it slow: a WHERE no index serves, that filters on fields the table neither indexes nor is clustered by, so that each call reads every row (`reads.every_row`, with the table's rows when the Tables view counted them), a shard that answers it far slower than the others, and on that shard a copy whose disk reads slowly. `GET /v1/queries/stats/:id` has the same `reads`. Each of these problems carries `actions`, what can be done from the command center: a call (`method`, `path`, `body`) with its `target` and `cost`, made after a person confirms it unless it is free and changes nothing (measuring again); a drawer (`drawer: "disk"`, what fills the disk, from which a person deletes entries that are not the database's after typing the copy's name and a reason; the database and the files named after it, what the server holds open or a flag names, and a folder with another file system mounted in it are never deleted); or `advice`, a remedy that costs money (a volume, a new node) with what it costs, which the command center does not carry out. ### Several coordinators A cluster can run several coordinators over the same shards, for example as a Kubernetes Deployment behind one Service. They find each other through the shards. Each coordinator names itself on its health calls to its shards (gRPC metadata `x-strata-coordinator`, `-name` and `-version`, sent with the cluster token). Each shard keeps who named itself for ten minutes. Every 5 seconds, each coordinator reads the union of what its shards heard. `GET /v1/coordinators` lists them: `{coordinators: [{url, name, this, last_seen_ms, version}], gone, live_ms}`. A coordinator not heard from for a minute is under `gone`. Any server answers it, a shard included. A coordinator names itself by `--peer-url`; on Kubernetes it uses its pod's address (`CHLOEDB_POD_IP`) and port, since `--public-url` is the address they share. When coordinators know each other, what one does it does on all. They call each other with the cluster token and the header `x-strata-peer`, and a call that carries it is not passed on again. - `GET /v1/queries` lists every coordinator's running queries. Another coordinator's ids read `id@name`, with `local_id` and `nodes` (who answered). `DELETE /v1/queries/id@name` cancels the query on that coordinator. - `POST /v1/admin/contain` and its `DELETE` reach every coordinator, and each rule says where it holds (`reach`). A rule is kept in `--contain`'s file with the removals. A coordinator that starts takes up the others' rules and drops those removed while it was down. - `/v1/health/fleet` counts every coordinator's searches. Each coordinator reads the others' last minute and five minutes from `GET /v1/coordinators?window=1`, kept 20 s. `coordinators` lists each one with its own `qps`, `p99_ms`, `recent_error_ratio` and `cpu`, or why it did not answer. - `/v1/index?table=` counts the reads every coordinator made (`reads_from` says who answered), from each one's `GET /v1/index/reads?table=`. `POST /v1/index/reads/reset` starts them all again. - Alerts: one coordinator sends the messages, and acknowledgements, silences and notes reach every coordinator ([Alerts](#alerts)). - Plans: one plan runs at a time in the cluster, and every coordinator's Cluster page shows it ([Changing the cluster](#changing-the-cluster-while-it-serves)). ### Events `GET /v1/events?from=&to=&kind=&limit=` lists what happened, the newest first: copies down and back (`copy_down`, `copy_up`), new primaries (`primary_changed`, with whether failover chose it), shards losing and regaining a majority (`majority_lost`, `majority_back`), shards and copies added or removed, jobs of moves (`moves_started`, `moves_finished`), log level changes (`log_level`), alerts firing and resolving, acknowledged, silenced or noted, Contain rules added, removed and ended, every other audited change (`change`) and notes. One action makes one event. Each has a `severity`, a one-sentence `title`, its `detail`, `where` (`shard`, `copy`, `table`, `rule`) and `who`. A coordinator compares its cluster's snapshots every 5 seconds, so a copy that goes down is an event when it happens, not when someone looks. `POST /v1/events/notes {"text", "ts_ms"?, "where"?}` (admin) adds a note, audited. The latest 20,000 events are in memory, and with a log store each is also written to its table `events`, kept 30 days, which answers ranges older than memory. A coordinator also keeps its latest 5,000 events on every copy of its shards (with its [alert rules](#alerts), in `.coordinator.json`), and a coordinator started again answers those from before its start from there (`source` lists `shards`), so that a coordinator without a log store keeps the Timeline across a restart; where two coordinators recorded the same event within a minute, it is answered once. `record_from_ms` says from when the answer holds every event: the server's start, or earlier when its shards or a log store kept the time before; the Timeline and Home say "since" that time for a window that starts before it. ### Logs The server logs to stderr, as text or, with `--log-format json`, one JSON object per line (`timestamp`, `level`, `target`, `message`, the event's fields, and `span` with the request's `id`, method and route). Every line written while serving a request names its id. At the default level, `info`, it logs what it opened and where it listens, a query or write that took `--slow-ms` or more (`slow query`, with its kind, outcome, rows and SQL, cut to 2,000 bytes; `slow write`, with the rows written and the SQL of an `INSERT`, `UPDATE` or `DELETE`; parameters are not logged), a request that failed on the server's side (status 500 and up, at most ten lines a second, with how many were held back), a merge or background flush that failed, and a database that stopped accepting writes. `debug` adds a line for every request answered (`answered`, with its status and duration), and the engine's flushes and merges. The libraries the server is built on log only warnings unless the filter names them (`--log info,h2=debug`). ### The log store: logs kept in ChloeDB A server also keeps what it logs, the queries it answers, and its load, in a ChloeDB database of their own: its log store, `DB.logs` beside the database it serves (`--log-store PATH`; `off` for none). A coordinator keeps one only when `--log-store` names it. It holds three tables: - `logs`, a line a row: `id`, its time (`ts`, a `TIMESTAMP`, and `minute` and `hour`, whole minutes and hours since 1970, to `GROUP BY`), the server it was logged on (`node`, `--node-name`), `level` (`error`, `warn`, `info`, `debug`, `trace`), `target` (the module), `message`, the event's other fields as JSON text (`fields`), and the request it was logged for (`request_id`, `method`, `route`). A line's `status`, `error` and time (`ms`) are also columns of their own. - `queries`, a query a row: `id`, `ts`, `minute`, `hour`, `node`, `request_id`, `kind`, `outcome`, whether it was a shard's part of a coordinator's query (`shard`), its `sql`, its statement's shape (`fingerprint`, as `/v1/queries/stats` groups them), `ms`, `n_rows`, `error`, and the rest of what the query log keeps of it, its trace, plan and [profile](#what-the-server-is-doing-now) (`steps`) among it, as a JSON object (`detail`). Every slow or failed query is kept, and of the others at most `--log-queries` a second. - `load`, a minute a row: `id`, `ts`, `minute`, `hour`, `step` (whole ten minutes since 1970), `node`, `role` (`coordinator`, `primary`, `replica` or `standalone`), `shard`, and over the minute the mean `qps` and `cpu` (cores busy), `cores`, `busy` (`cpu` over `cores`), the slowest `p99_ms` and the volume's `disk_used_ratio`. [Autoscaling](#autoscaling) replays its rules on it. They are searched with SQL like any table, `POST /v1/logs/query {"sql": "...", "params": {...}}` (or the gRPC call `Logs`, with an admin key), with `MATCH` and `bm25` over the text, `GROUP BY` over the levels, nodes and minutes, and joins between the two: ```sql SELECT ts, node, level, message FROM logs WHERE level IN ('warn', 'error') AND MATCH(message, 'replica OR shard') AND ts > '2026-10-31T06:00:00Z' ORDER BY ts DESC LIMIT 100; SELECT minute, level, COUNT(*) FROM logs WHERE ts > '2026-10-31' GROUP BY minute, level; SELECT fingerprint, COUNT(*) AS n, SUM(ms), MAX(ms) FROM queries WHERE shard = false GROUP BY fingerprint ORDER BY 3 DESC LIMIT 20; SELECT ts, route, status, ms FROM logs WHERE request_id = '9f2c41d07a3e88b1'; ``` A coordinator answers for the whole cluster: it asks every replica of every shard (the `Logs` call, as a shard's part), the other coordinators' stores (`POST /v1/logs/query` with `"scope": "local", "partial": true`, so the queries their clients sent and their own lines are in it too) and its own store, and merges their answers as it merges its shards', so `COUNT(*)` and `GROUP BY` count every server and `ORDER BY ts` interleaves their lines. The answer's `nodes` gives each server's rows and time, or its error: a server that does not answer is named there, and the answer goes on without it (an older server, without a store, answers 501). Such a search reads one table with conditions each store's index answers, so that each store's answer can be merged: a join, a subquery, or a `LIKE` or `ILIKE` on a text column such as `message` (which a store checks row by row after reading every line) is refused, with an error that names it. Find words with `MATCH` instead (`MATCH(message, '"alert firing"')` for a phrase, `MATCH(message, 'alert firing')` for both words); `LIKE 'abc%'` on a `KEYWORD` column (`level`, `node`, `target`, `route`) is merged. Any query runs on one server's own lines, sent to that server with `"scope": "local"` (to a coordinator, its own lines and its clients' queries, when it keeps a store). `GET /v1/logs/store` gives the store (its path, rows, size, retention, what it wrote, dropped and deleted), its tables, and on a coordinator every server's store; `/v1/cluster` shows each replica's under `detail.log_store`. A writer thread writes what waits every second, or as soon as 4,096 lines wait, in one transaction it does not sync: a crash of the process loses nothing written, a power cut the latest lines. Up to 100,000 lines wait in memory; past that the newest are dropped and counted. Every 30 seconds the store deletes the rows older than `--log-retain` and, while it takes more than `--log-store-mb`, the oldest quarter of what is left, then merges, which frees their pages. Reading the logs writes none: what the store's own threads log (its writes, flushes and merges) stays out of it, its searches are not queries of the server's, and the log viewer's requests are not logged as answered. The store is a database like any other, so it can be opened on its own, by a server (`--db app.chloedb.logs --log-store off`), from Python or with `chloedb-server export` while no server holds it. The metrics name it `chloedb_log_store_*`: `rows{table}`, `written_total{table}`, `bytes`, `waiting_lines`, `dropped_total{reason}` (`lines` past the waiting limit, `queries` past it, `failed` writes, `sampled` queries over `--log-queries`) and `deleted_total{reason}` (`expired`, `size`). ### What the server is doing now Beside `/metrics`, a server keeps what an operator (and the [UI](#the-ui)) needs to see what it is doing, in memory, without a Prometheus to scrape it: - `GET /v1/queries` lists the queries running now, the longest running first: the SQL (cut to 4,000 bytes), kind, how long it has run, the request's id, whether a coordinator asked it of this shard, and its trace so far. `DELETE /v1/queries/ID` cancels one: it stops at its next check (within milliseconds, as at a deadline) and answers 499, counted as `outcome="cancelled"` in `chloedb_queries_total`. Cancelling a coordinator's query drops its calls to the shards, which stop theirs. - `GET /v1/queries/recent?since=MS&limit=N&outcome=O` gives the latest 500 queries that ended, the newest first, each with its number (`id`), SQL, statement shape, kind, outcome, rows, time, trace, and its profile's number of steps (`steps_n`) and CPU time (`cpu_ms`, when measured); `GET /v1/queries/slow` the latest 200 that took `--slow-ms` or more (or the threshold set since, below); `outcome` keeps, in either, the queries of the outcomes it names, comma-separated (`ok`, `partial`, `error`, `timeout`, `client_error`, `client_deadline`, `refused`, `cancelled`, and `failed` for every one but `ok` and `partial`), and an outcome it does not know is a 400; `GET /v1/queries/finished/ID` one of them with its profile's steps and the executor's plan lines (`?full=true` gives them in the lists too); `GET /v1/queries/request/ID` those a request ran (its `x-request-id`, which a coordinator passes to its shards, so each shard shows its part of a coordinator's query under the same id). - A trace is the timed spans of one request, from its start: understanding a search's words (`understand`) and expanding them from the first rows (`expand`), parsing and binding its SQL (`plan`, with each text embedded inside it, `embed`), waiting for a write it must see, waiting for a query slot (`admission`), executing, a blend's sources and fill (`blend`), and on a coordinator every call to a shard's replica (`TermStats`, `Query`, `Fetch` and so on) with the shard, the replica, and how it ended (`ok`, `error`, or `outrun` for a call another replica answered first); a hedge or a retry is marked `again`. `POST /v1/query` with `"trace": true` answers with its own. - A query's profile is the timed steps of its execution, an `EXPLAIN ANALYZE` of every query, which the list of queries keeps (`/v1/queries/finished/:id`) and its answer has in `stats.steps` when the request asks, with `"steps": true` or `"profile": true` (in `/v1/query`, `/v1/sql` and `/v1/plan`; `/v1/explain` always answers them). Without, an answer leaves them out: they were most of its bytes, and a coordinator spent a sixth of its CPU reading its shards' steps and writing them out again. A coordinator asks its shards to leave theirs out too (`QueryRequest.skip_steps`), so its own list keeps its calls to the shards and its merge, and each shard's list its own steps. The profile is a tree in pre-order (each step's `depth`), each step with what ran (`op`: `rank`, `bm25`, `vector`, `segment`, `filter`, `aggregate`, `project`, a compound query's `leaf`, `join` or `distinct`, a coordinator's `shard` and `merge`, and the server's own `wait for a thread`, `finish` and `hand back` around the run), what it ran on (`detail`), when it began and how long it took (`start_us` and `us`, from the request's start as the trace's spans are), the rows it ended with, and for a segment's step the segment (`seg`) and the thread that searched it (`thread`: 0 the query's own, 1 and up the helpers that joined it). With `"profile": true` each step has its CPU time too (`cpu_us`, of every thread that worked for it, at a system call a step, about 0.3 µs) and the bytes it allocated and its allocations (`alloc_bytes`, `allocs`, of every thread that worked for it, as the server's allocator counts them, below), and the answer has the request's trace. A coordinator's profile holds each call to a shard (`shard`) with the shard's own steps inside it (`on the shard`), on the coordinator's clock with the network's time split evenly each way; with `"profile": true` they have their CPU time and allocations too: the coordinator asks each shard for them (`QueryRequest.profile`), and a shard measures them for every query with `cpu_all` (below). A query keeps at most 4,000 steps (`stats.steps_dropped` counts the rest). `GET /v1/profile/settings` and `PUT /v1/profile/settings {"slow_ms": 50, "cpu_all": true}` (admin) set, while the server runs, the time from which a query is kept among the slow ones (`null`: none) and whether every query's CPU time is measured. On a coordinator, `GET /v1/profile/settings?node=` and `PUT /v1/profile/settings?node= {...}` read and set a copy's (its URL or short name), over the same gRPC call a profile takes; the change is audited on the coordinator ("profiling on s0-0: slow_ms 25") and on the copy. `?coordinator=` (its URL or name) reads and sets another coordinator's, through this one. Both last until the server restarts: `--slow-ms` sets the threshold it starts with, and measuring every query's CPU time has no flag. - A query's funnel is everything it does between its text and its rows, on thirteen stages in the order a query meets them: **Wait** (a query slot, a thread, the writes it must see), **Understand** (words that name values become conditions), **Expand terms** (the words become the terms searched: typos, synonyms, prefixes, the terms of the first rows), **Embed** (texts where vectors go), **Plan**, **Match** (the rows each input of the ranking reaches: BM25's rows that hold a term, the nearest vectors, a column), **Select** (`WHERE`, and each input's top rows, the candidates), **Rank**, **Rerank** (rerank phases, cross-encoders), **Blend**, **Shards** (a coordinator's calls: the network and a shard's work around its query), **Fetch** (the answer's columns, counts and groups) and **Other**. Each microsecond of a query's time counts once: a step's time is its stage's less the steps inside it, steps that ran side by side share the time they ran together, and a shard's steps count for their own stages. `GET /v1/queries/funnel?since=MS&table=T&fingerprint=F&kind=K` (admin) lays the latest queries' time on the stages: `stages` (each stage's mean over every query, its p50, p95 and max over those that ran it, its `share`), `stage_rows` (the rows each stage's steps held, on average, and the rows `answered`), `statements` (by statement shape, each with its own `rows` by stage, a funnel of one shape) and the `slowest` 50, each with its stages; a query the answer cache answered says `cached` (it ran no stage of its own), and `cached` counts them; `?id=ID` one of them. `POST /v1/funnel` (above) runs one query, a stored function's call written out first as a query of it runs (a saved template of the Query designer, [below](#the-ui), whose body reads a blend or understands its words), and follows its rows too: probes that are queries of the bound statement (counts of what each input matches and what each condition of `WHERE` leaves in turn, each input's top rows with `WHERE` and without, the ranking past the page, and which of the rows seen pass each condition), so a row says where it left: on the page (`shown`), ranked before or past it (`offset`, `cut`), reranked off it (`reranked`), below every input's top (`not_candidate`) or dropped by a condition it names (`filtered`). A coordinator runs the probes over its shards as any query, so its funnel is one database's. A query of several tables, or of groups, shows its time alone. `Db::funnel(sql, params)` is the rows' funnel in Rust. - `POST /v1/profile/cpu {"seconds": 5, "hz": 99}` (admin) samples every thread of the server for `seconds` (at most 60), `hz` times a second of each thread's CPU time (at most 1000, from SIGPROF on Linux and macOS; 501 elsewhere; macOS does not interrupt the thread that spent the CPU time, so a profile there shows little of where it goes: a query run in a loop on one thread got none of 534 samples on a macOS CI runner, where Linux gives it more than half), and answers what they were running: the threads by pool (`threads`, each with its `count` and `samples`), each distinct stack with its frames from the root by place in `names` and its `samples` (`stacks`, at most 50,000; `dropped` counts the samples of the rest), `samples`, `seconds` the process's CPU time (`cpu_seconds`) and the cores it kept busy (`cores`). With `sql` (and `params`) it profiles that query, run again and again for that long by `clients` callers at once (1 to 64): it runs once first, so a query that fails answers at once, its runs are not kept among the latest queries, and the answer has their times (`runs: {count, clients, min_ms, median_ms, p99_ms, max_ms, error}`). `?format=folded` answers folded lines (`thread;root;...;leaf samples`) for flamegraph.pl, inferno or speedscope. A sample stands for its share of the process's CPU time, measured while the profile is taken (`cpu_seconds`): the system's timer gives the whole process at most one sample a tick (250 a second on many Linux kernels), so a busy server gets fewer than `hz` a CPU second (`rate`). With glibc 2.35 or later the samples include the C library (malloc, memcpy, system calls; 40% of the samples of a query run in a loop on the demo data); before it, and on other systems, samples there are not taken (`blocked`), since unwinding from them could deadlock. One profile is taken at a time (409 while another is). Sampling slows the threads it interrupts: in the cloud container (4 cores), a BM25 query run in a loop by one caller ran 6% fewer times a second at 99 Hz and 11% fewer at 997 Hz, and by four callers within the noise (about 4%). The frames are named from the binary's symbol table after the timer stops. The sampler's table of stacks takes about 70 MB of memory the first time a profile is taken, which the server keeps from then on (each later profile replaces it and gives the old one back to the system). The debug information read to name the frames, of a CPU or an allocation profile, is given back once they are named. One profile of each kind at a time: a second answers 409 with who takes the first and for how many seconds more ("a CPU profile of this server is being taken, by ops-key, for 4 s more: one at a time"). Each is audited with its `object` ("CPU profile of NODE"), the server (`node`), `seconds`, `hz` or `every_bytes`, and the `sql` and `clients` of a query run in a loop. - `GET /v1/profile/memory` (admin) answers the heap as the server's allocator counts it (`heap`: the bytes in use, `in_use_bytes`, and their peak, `peak_bytes`, kept every 100 ms; the bytes allocated, allocations and frees since the server started), the resident memory and its peak, the bytes the running queries hold against `--query-memory-mb` and the number of threads; the series has `heap_bytes`, `heap_peak_bytes`, `alloc_bytes_s` and `allocs_s`, and each of the latest queries profiled its bytes allocated (`alloc_bytes`). The server's allocator is the system's, counting: each allocation and free adds to a counter of the bytes in use (one of 64, picked by thread), and each thread counts what it allocated, which a query's steps read. `POST /v1/profile/heap {"seconds": 5, "every": 2097152}` (admin) takes an allocation profile: about one allocation in every `every` bytes a thread allocates (4 KiB to 64 MiB, default 2 MiB; the gaps are random, so each byte is as likely as any other to be sampled) records its stack and the bytes it stands for (its size over the chance it had to be sampled), and is watched until it is freed. The answer is shaped as a CPU profile's, each stack with the bytes allocated (`bytes`), the allocations (`allocs`) and the bytes still in use when the profile ended (`in_use`), with the bytes allocated and allocations counted while it was taken (`allocated_bytes`, `allocs`), the heap in use at its start and end, `samples`, and `untracked` (samples past the 65,536 whose frees are watched, which count as freed). With `sql` it profiles a query run in a loop as a CPU profile does; `?format=folded` answers folded lines of the bytes allocated (`&value=in_use`: of those still in use). One is taken at a time (409 while another is), and a program that uses the crate without the server's allocator answers 501. `GET /v1/profile/threads` (admin) lists every thread of the process with its name, state, CPU time and context switches (Linux; empty elsewhere). - On a coordinator, each of the four (`cpu`, `heap`, `memory`, `threads`) with `?node=URL`, a replica's URL as `GET /v1/cluster` lists it, is that server's: the coordinator asks it over gRPC (`Profile`) and answers what it answered, with `node` in its JSON. The server takes the profile itself, a query of it run on its own rows. A URL not in the cluster answers 404, a server that is not a coordinator 400, and a node whose server is older than the call 501. What it costs, measured on a BM25 query run in a loop on the demo data in the cloud container (4 cores), against the same binary with the system's allocator: counting every allocation, the median of 14 paired rounds of 5 s was 5% fewer runs a second with one caller (the rounds ranged from 30% fewer to 27% more: that container is noisy) and within 1% with four callers. Taking an allocation profile walks a thread's stack for each sample: the loop ran 3 to 6% fewer times a second sampled every 2 MiB, 6 to 29% at 512 KiB and 20 to 46% at 64 KiB (medians over runs of the benchmark, one and four callers). - `GET /v1/queries/stats` gives statistics per statement shape, as PostgreSQL's `pg_stat_statements`: the SQL with every literal replaced by `?` (a list of values by `?...`), so that queries differing only in their values count as one, with calls, errors, total, mean, minimum, maximum and percentile times, rows per call and its share of the time spent, the most time first. It keeps 2,000 shapes, dropping the least called for a new one; `POST /v1/queries/stats/reset` starts over. - `GET /v1/timeseries?since=MS` gives a point every 2 seconds for the last hour (`?from=MS&to=MS` reaches further back: from memory while it holds `from`, else a point a minute from the log store's `load` table, an hour a point past 10,000 minutes, with `source` and `interval_ms` saying which): queries per second (by kind too), query latency percentiles and the histogram of the interval, errors, refusals, partial answers, HTTP requests and their 4xx and 5xx, writes and rows written per second, the writes that ended and those that failed on the server's side (`writes`, `write_failures`, and their `write_error_ratio` when a write ended), slow requests, CPU (cores busy), resident memory, queries running and slots free, query memory, and on a database its rows, segments, deleted rows, memtable rows, file, log and reusable bytes, merges, the write queue, leases, the disk's free and total bytes, the `failing` flags, and replication (a primary's replicas in sync and the most transactions one is behind; a replica's sequence number and whether it serves reads). - `GET /v1/logs?after=SEQ&level=warn&request=ID&q=TEXT&limit=N` gives the latest 5,000 log lines, as the log writes them (with each line's request id, method and route), from line `after` on; `PUT /v1/logs/filter {"filter": "debug", "expires_s": 1800}` changes what is logged while the server runs, as `--log` names it, for 30 minutes by default (`0`: until set again), then goes back on its own; a word that is not a level (`warnn`) is refused, at start as in a change, since to the log library it names a module and turns every other line off (a module's level is written `chloedb_server::http=debug`), and so is a field other than `filter` and `expires_s`; both answers say the filter, when it expires (`expires_ms`) and who set it (`set_by`), and each change is an event. On a coordinator, `?node=` (a copy's URL or short name) sets that copy's filter. A coordinator's `GET /v1/logs` has its own lines only, and says so in `note`: a copy's are in the [log store](#the-log-store-logs-kept-in-chloedb), which `POST /v1/logs/query` searches on every server at once (`WHERE node = 's1a'` for one copy). A client's 4xx answers are logged at INFO, and a query that ran out of its client's own deadline at WARN, counted as `client_deadline` rather than the copy's failure. A coordinator tells a shard, in the call's metadata (`x-strata-deadline: client`), that its part runs to the client's own deadline; a shard whose part passes it counts `client_deadline` and logs a warning rather than an error. - `GET /v1/load?from=&to=` on a coordinator reads each copy's own minutes from its log store (16 at a time, 10 s each): `copies` (`shard`, `url`, `short`, `name`, `points` of `t`, `qps`, `cpu`, `cores`, `busy`, `p99_ms`, `disk_used_ratio`) and `missing` (the copies that did not answer, and why). The log store's `load` rows hold, besides the rate and CPU, `error_ratio`, `errors_s`, `client_errors_s`, `timeouts_s`, `rejected_s`, `p50_ms`, `writes_s` and `mem_bytes`. - `GET /v1/system` gives the process (version, uptime, cores, SIMD, resident memory, CPU time, the memory limit), the database's path and the space left on its disk, and the server's limits; `GET /v1/routes` requests by route and queries by kind, with their mean and 99th percentile times; `GET /v1/cluster` where the server stands: its role and health, or on a coordinator every replica of every shard with its role, health, latest point of the series, version and how long it took to answer, and the slots each shard holds. `GET /v1/routes?from=MS&to=MS` answers over that window from minute snapshots (an hour a snapshot past a day), with `from_ms`, `to_ms` and `held_from_ms` when the server holds less than the window; without `from`, since the server started. ### Alerts The server checks alert rules against each new point of the series ([above](#what-the-server-is-doing-now)) and, on a coordinator, against the cluster's state. A rule names one of the point's values (`p99_ms`, `error_ratio`, `disk_used_ratio`, `replica_behind_max` and so on); some are made of others: `http_5xx_ratio` (5xx answers over all HTTP requests, weighted by each point's requests, leaving out the 504s of queries whose client's own deadline passed, which are the client's; like `error_ratio` and `availability` with `eval: mean`, it is judged over a window of 100 requests or more, or 10 failures or more, and counts as none failed below both), `replica_behind_s` (how long the replica furthest behind has lacked a transaction the primary committed, read from the primary's `seq_no` over the series; a replica being sent a whole copy, or not heard from since the primary started, is left out; a point alone, without the series, gives transactions behind over the write rate, and no value when nothing is written), `disk_hours_to_full` (the window's least-squares slope of `disk_used_ratio`, 87,600 when it does not fill) and `key_error_ratio` (the worst key's failed calls over its calls in the window, keys with 30 calls or more, a call being a query or a write, so a client whose INSERTs all fail with a duplicate key fails its calls as one whose queries fail; the alert's `where` names the keys, their calls and owners, and its message goes to the route named after the worst key's owner when there is one) and `key_busy_ratio` (the queries the busiest key ran at once on average, its calls' time over the window, per core of the server, counted only for a key with over half of the window's query time while another key made 30 calls or more, and 0 otherwise; the default rule `key-flood`, "A client crowds out the others", fires over 1 for a minute, resolves under 0.5, names the key with its share, the queries it ran at once and its owner, and links to its queries in Queries, Running now), how the points of a window (`window_s`) make one value (`eval`: their `mean`, `max`, `min`, the `rate` of a count, or `all`, a value every point must pass), a comparison (`>`, `>=`, `<`, `<=`) and a threshold, how long the condition must hold before the alert fires (`for_s`), the threshold that resolves it (`resolve`, by default the threshold itself), or, with `vs: "before"`, the window's value as a multiple of the same window just before it (`p99_ms` mean over 5 min `> 2` with `vs: "before"` fires when the p99 doubled; a latency, a metric ending in `_ms`, under 20 ms in the window counts as unchanged, so a p99 going from 1 ms to 2 ms does not fire, and `p99_ms` under half the p99 objective too, `--slo-p99-ms`, so with the default 250 ms a p99 going from 26 ms to 54 ms does not either), a severity (`critical`, `warning`, `info`), and who it is for (`owner`, `runbook`, `route`). An alert goes `pending` when its condition holds, `firing` once it has held `for_s` seconds, and back to `ok` (resolved) when the window's value passes `resolve`. A window without any value of the metric is no data: it keeps the alert as it was (a firing alert stays firing, with `no_data_since_ms`) and never resolves it. **A rule on the data** watches a query instead of a value of the server's: its `sql` is one `SELECT` (at most 4,096 bytes) whose answer's first number is the value, run every 30 seconds with the parameters `:since` (the start of the rule's `window_s`, as a time) and `:now`, with a deadline of 10 seconds, on the server that holds the rule (`scope` `self`): `{"id": "payments-errors", "name": "payments errors (from its logs)", "sql": "SELECT COUNT(*) FROM logs_app WHERE service = 'payments' AND severity = 'ERROR' AND ts > :since", "op": ">", "threshold": 50, "resolve": 10, "eval": "max", "window_s": 60, "severity": "critical"}`. Its metric is `sql_`, set for it, which the series' points carry like any other, so `op`, `threshold`, `resolve`, `eval`, `for_s`, its routes and its messages work as they do for the rest. A query that fails or answers no number gives the rule no data; `GET /v1/alerts` gives each such rule's last run (`sql_run`: when, how long it took, the value or the error). On the **Alerts** page, **Or a query** writes one. Since the value is read every 30 seconds, an alert on it fires within about a minute of the rows that cross its threshold. A rule's `scope` is `self` (this server's points) or `each_copy`: every copy of every shard evaluates it on its own points and reports its states in its health detail (`detail.alerts`), and a coordinator gathers them into one alert per rule whose `where` lists the copies that are not ok (`copy`, `short`, `state`, `value`, `since_ms`; `unheard_since_ms` for a copy that stopped reporting, `rule_differs` for one that runs another version of the rule). A coordinator gives its each_copy rules to its copies: `PUT /v1/alerts/rules` on a coordinator answers `pushed: {copies, took, failed: [{copy, short, error}]}`, and a copy that did not take them (down, or an older chloedb-server) gets them again within 30 seconds of answering. A copy keeps its own `self` rules, and a copy whose rules were edited after the coordinator's is left alone. Until a copy runs the rule as edited, the coordinator judges that copy's value by the rule as it is now, so no FIRING names a value that passes its rule; the alert says `copies.rule_differs` (and `copies.push_failed`), and its message says how many copies run the old rule. A copy not heard from for a minute has no data for its each_copy rules: what it said before it went down no longer keeps an alert firing, and "A copy is down" says why. A copy whose points never carry the rule's metric (a primary for a replica's lag) is left out and counted in `copies.not_reported`; the rule has no data only when no copy has the metric. A window the series does not cover yet, after a restart, is judged on the points there are once they span 30 seconds (or half the window), at once for a rule that fires on any one point (`max` over `>`), and the rule's state says `window_partial` and `window_covered_s`. A coordinator also has built-in rules over the cluster: a shard without a majority (`shard-no-majority`), a copy down, a shard with fewer copies than asked (`under-replicated`), a primary that changed, partial answers, a copy that stopped reporting (`copy-silent`), and the availability of searches. A server starts with rules for a database that refuses writes, failing flushes or merges, data a scrub found damaged on disk (`damaged`), a disk over 90% full (warning) and over 97% (critical), a disk that fills within 12 hours at the last 30 minutes' rate, query p99 over the SLO (`--slo-p99-ms`, 250 ms), a p99 that doubled against the 5 minutes before, more queries failing than the SLO allows (`--slo-error-ratio`, 1%; the built-in rule over searches that fail takes it too, and both follow a changed SLO unless someone changed their threshold), one key's calls failing over 20%, refused queries (429), server errors over 1% of requests, a replica over 30 seconds behind, out of sync or not serving reads, query memory over 90% spent, and a write queue over 512; each has a resolve threshold, so a value at the threshold does not page on and off. The built-in partial answers rule is a mean over 2 minutes (over 0.1/s, resolved under 0.02/s). `PUT /v1/alerts/rules {"rules": [...]}` (admin) replaces them, audited with the rules before and after, and the UI's **Alerts** page edits them; rules and routes are kept in `--alerts FILE`, by default `.alerts.json` beside the database of a server that is not a coordinator, so a restart keeps them. A coordinator also keeps them, with each alert's state, acknowledgement, silence, notes and what it paged, and the latest 2,000 entries of its [audit log](#security), on every copy of its shards (`.coordinator.json` beside each copy's database), and takes them back before it serves, the newest of each part winning: a coordinator started again without `--alerts` keeps them, as it keeps the keys, and only a server with no database file to keep them beside (an in-memory demo) keeps them in memory alone. `GET /v1/alerts` says where under `kept` (`file`; `shards`, how many copies hold them, which failed, when they were last given them and what the coordinator took back when it started; `memory_only`), and `PUT /v1/alerts/rules` and `/routes` answer it. Next to that file, `alerts.state.json` keeps each alert's state, acknowledgement, silence, notes and when and by whom its FIRING message was sent: a restarted server keeps them, and does not page again what it already paged. An edit of a rule that stays on keeps its alert, judged by the new condition at the next check (it resolves then if the value passes, with "the rule was edited by X"); turning a rule off or deleting it resolves it at once. `GET /v1/alerts` lists the rules with their states (`firing` is how many fire); `GET /v1/alerts/:rule` one rule with its changes over 7 days. `POST /v1/alerts/:rule/ack`, `POST /v1/alerts/:rule/silence {"minutes", "reason"}` (`DELETE` ends it) and `POST /v1/alerts/:rule/notes {"text"}` (write scope) are audited and become events (`alert_acked`, `alert_silenced`, `alert_note`), as are firing and resolving (`alert_fired`, `alert_resolved`). Each change of an alert is kept in memory and in the log store's `alerts` table for 7 days. `POST /v1/alerts/backtest {"rule": {...}, "from"?, "to"?}` replays a rule (as it would be saved, or a saved rule by its id, `"rule": "p99-jump"`) over memory's points or up to 7 days of the `load` table, the last day by default, and says when it would have fired and resolved; it changes nothing. `from` and `to` are milliseconds or seconds since 1970, as numbers or digits, or ISO 8601 text (`2026-11-12T08:00:00Z`); anything else is a 400. A server without a log store backtests over the points memory holds: the window is cut to them, and the answer's `note` says what it covers rather than what was asked. On a coordinator a rule over the cluster's state is replayed from its events (copies down and up, majorities lost and back), and an each_copy rule is backtested by every copy over its own points, answering each copy's spans and the points of the six that fired most or came closest (`source: "copies"`). Every answer says `covered_from`, the first time it had points for; `key_error_ratio` and `key_busy_ratio` cannot be replayed. A coordinator's events start when it does: what was already down then counts from its start, as its alert did. `GET /v1/alerts?brief=1` answers each rule's state and, of those not ok, their since, value, acknowledgement, silence, cause (`held_by`) and copies, without events, routes or `where`: what the bell needs, about a fifth of the whole (5 KB of 27 KB on a 2x2 cluster in a storm). With several coordinators of one cluster, one sends the messages: the one with the lowest URL among those heard from in the last 45 seconds (`GET /v1/alerts` says `pager: {this, sends, coordinators}`). It tells the others what it paged, and they show "paged by X"; one that is not told within a minute of an alert becoming sendable (firing, and neither held nor silenced) sends it itself, saying why. A rule over a coordinator's own traffic (its searches' errors, p99, a key's failing calls) can fire on one coordinator alone: every coordinator shows it as firing, with `here` (its own state) and `elsewhere` (the coordinators where it fires or waits, from what they last told it, at most 45 s old), counts it in `firing_shown` and `firing_elsewhere`, and takes an acknowledgement of it, which goes to the one where it fires. That one sends the message at once once the one that sends the messages said, 15 s or more after it fired, that it does not see it, and sends its resolution too. Coordinators telling each other their alerts are not audited: the person's change is, on the coordinator where it was made. A coordinator restarted with its state file sends no FIRING message for its first 20 seconds: by then it has taken what the others paged, and pages nothing twice. Rules, routes, acknowledgements, silences and notes made on one coordinator reach the others (`POST /v1/alerts/peer`, `GET /v1/alerts/peer`, admin, with the header `x-strata-peer`), the newest edit of the rules winning. In a storm a cause holds back what it explains: a shard without its majority or a copy down holds its shard's replica rules (out of sync, behind, not serving reads, under-replicated), a shard without its majority holds its copies down, and either holds the coordinator's traffic rules (searches fail, errors, p99) that are no more severe. A key's failing calls are held the same way. A held alert shows `held_by` and `held_why` and sends no message of its own. Once its cause resolved it stays held for its own window and wait (at most 10 minutes, `held_until_ms`), which still include the outage, and pages only if it still fires then. `firing_shown` counts what fires neither silenced nor held. Firing and resolved alerts go to the routes that take their severity, unless the alert is silenced. A route added while an alert fires, or one a rule is newly routed to, is sent its FIRING within seconds (saying since when it fires, with the same `dedup_key`), once; a RESOLVED goes only to the routes that were sent the FIRING, which the alert lists (`paged.routes`). An alert says what each route was sent of it and whether it was delivered (`notified`: per route, `state`, `ok`, `error`, `at_ms`, for the episode that fires now or the last one, since this server started). Routes: `GET` and `PUT /v1/alerts/routes` (admin) list and set them (`name`, `kind`: `webhook`, `pagerduty` or `opsgenie`, its `url`, a `key` for PagerDuty's Events API v2 routing key or Opsgenie's API key, kept and never shown, the `severities` it takes, all when empty, `repeat_min`, after which a critical alert nobody acknowledged is sent again, and `allow_internal`, true for a webhook inside this network: a route reaches the public internet only, and is refused a private or loopback address unless it says so and a link-local one always; a redirect to another origin is not followed, which fails the send), each with how its last delivery went, and `POST /v1/alerts/routes/:name/test` sends a test message. A message says the cluster, the rule, where it fires (a copy by its `--node-name`, when it gave one), the value against its threshold (with the digits it takes to differ from it; a 0/1 metric "is on" or "is off"), the rule's owner, the rule's runbook when it has one, else a built-in rule's [runbook](runbooks.md) by its title and link (as `runbook_docs` in `GET /v1/alerts`), and a link to the alert's page when `--public-url` says where the command center is, as `{"text": "[chloedb FIRING warning] Disk almost full on prod/search/s1-0: disk_used_ratio = 0.934 (> 0.9, mean over 5 min). ... Runbook: ... https://cc.example/#/alert/disk-full", "alert": {...}}`, which a Slack incoming webhook takes as it is, with `dedup_key` (`strata///`, in the old name still, the same in its RESOLVED; a test message's is `strata//test/`; PagerDuty and Opsgenie routes open and close one incident with it), each try of a message carrying the same `Idempotency-Key`, and `[chloedb RESOLVED warning] ... after firing for 17 s` when it resolves (how long the alert fired, which starts once its rule's window has held, not how long its cause lasted). `--alert-webhook URL` is a route of every severity, which may be inside the network. Firings are logged and counted in `chloedb_alerts_firing{severity}`. ### Who sends the queries, and containing them Every query is kept with who sent it: the key's name and id (`key`, `key_id`), the client's address (`addr`, from `X-Forwarded-For` only behind `--trust-proxy`), its application (`x-chloedb-app`), its client (`x-chloedb-client`, `command-center` for the UI), its parameters (`params`: only their types, such as `{"q": "text", "n": "int"}`, unless the server was started with `--keep-params`, which keeps their values; the statement's text with its placeholders is kept either way) and its deadline (`deadline_ms`), in the running and finished queries, the statements and the log store's `queries` table. A query ends `ok`, `partial`, `error`, `timeout`, `client_error` (the client's mistake, such as a misspelt column), `client_deadline` (the client's own deadline, shorter than the server's), `refused` (429) or `cancelled`, and the series counts the client's failures apart from the server's (`client_errors_s`, `client_deadlines_s`); `error_ratio` is the server's failures over the queries that ended, and absent when none ended. `GET /v1/queries/stats?from=&to=` gives each statement shape over a window, counted a minute at a time for the last day: calls, errors, times, its `share` of the time, the keys and clients that sent it, whether it is `new` (`first_seen_ms`) and the window before (`prev`) to compare. `GET /v1/queries/stats/:fingerprint` is one statement: its trend, its time by key and by shard, its slowest and latest calls with their parameters, and its errors. On a coordinator both are every coordinator's: the counts of each shape are added up over the coordinators that answer (`coordinators` says which), each statement saying how many calls went through each, and a statement's slowest and latest calls name their coordinator (`local=1` for this coordinator's alone). `GET /v1/queries?group=shape` groups the running queries by shape and key, and `DELETE /v1/queries?fingerprint=&key=` (admin) cancels a group at once, audited with the reason. `POST /v1/admin/contain {"match": {"fingerprint"?, "key"?}, "action": "limit" | "refuse", "concurrency"?, "expires_s"?, "reason"}` (admin) limits a statement shape or a key to `concurrency` queries at once, or refuses it, at admission, for `expires_s` (15 minutes by default): a refused query is answered 429 naming the rule. `GET /v1/admin/contain` lists the rules and `DELETE /v1/admin/contain/:id` ends one; each is audited and an event, and so is a rule that expires (who `system`, reason `expired`). Contain rules are each server's own, in memory. ### Merges A local database merges its segments on merger threads as writes add them ([how merges work](index.md#merges)). `--merge-threads` sets how many merges may run at once (default: half the cores, 1 to 4), `--merge-memory-mb` the memory they may use together (default: half of the cgroup memory limit, or of RAM), and `--merge-write-mb-per-sec` how fast they may write (default: no limit). `GET /v1/stats` shows them under `merges`, and the server logs a merge that fails. A server killed for running out of memory during a merge restarts into smaller merges of the same segments. ## The UI `GET /` serves the command center, a console for one server or a whole cluster. It reads the same API as any client (the cluster's shards, fleet health, the series, alerts, events, running and recent queries, the logs, keys and the audit log), so what it shows is what the server reports, and every change it makes is an API call a key's scope allows. Its requests carry `x-chloedb-client: command-center`, and a change it makes carries the reason it asked for in `x-chloedb-reason`, which the [audit log](#security) keeps with it. A button that changes something says, when the key lacks the scope, which scope it takes. The navigation has five groups: **Build**, for the data and the queries (Start here, Tables, saved searches, team views, the query builder, the SQL workbench, import and export, connectors, models, the schema, slices), **Watch** and **Run the cluster**, for running a server or a fleet (a coordinator lists those two first), **Apps**, the programs the server shows as views of their own ([below](#apps)), and **Labs**, the tools for search engineers, collapsed (pin one to keep it in the sidebar). ![Start here, on a server with the demo catalogue: the first steps (put your data in, search it by words and by meaning, save a search, give an agent the tools), each done or one click away](../assets/img/cc-start.webp) ![Tables: the server's tables, one card each, with its rows, size and fields](../assets/img/cc-table.webp) **Watch** - **Home** answers one question first, whether the fleet is serving, from [`GET /v1/health/fleet`](#fleet-health): the numbers behind the answer (shards serving reads and taking writes, p99 and the share of searches and of writes failing against the SLO, copies answering, the replica furthest behind, the fullest disk), where the trouble is on a map of every shard, what would restore service, since when, and what changed just before. A problem says why when its figures point at a cause, and offers what can be done about it ([the disks](#the-disks)): measure a slow disk again, hand a shard's primary to a copy on a fast disk (after a confirm that says what it does), open what fills a disk and delete what is not the database's (after typing the copy's name and a reason), or read a remedy that costs money and what it costs, which it does not carry out. - **Alerts** lists what is firing first, grouped by rule, with where each rule fires (which copies, which shard) and whether someone acknowledged or silenced it. In a storm what a cause explains is listed under it, held back, with Acknowledge all. Rules show fires and flaps over the range, and a noisy filter; a rule some copies have not taken yet says so. Rules follow, with their scope, owner, runbook and how often they fired over the range. A rule with no data says so plainly. An alert's page (`#/alert/`, the link in every notification) is where an incident is worked: the metric around the alert with failovers, rollouts and changes marked, the blast radius, what changed just before it fired, the failing statements, the affected copies with links to their logs, the profiler and Cluster, the log lines grouped by pattern, and a shared timeline of acknowledgements, silences and notes. The rule editor evaluates over a window (mean, max, min or rate), resolves at its own threshold, or judges a query's first number instead (in the query's own unit: it runs the query once, shows what it answers, and warns of a threshold far from that, such as 20 for a share that runs from 0 to 1), and backtests a change over the last 7 days before you save it (saying the span it had points for, each copy's line for an each_copy rule), saves with how many copies took it, and compares with the window before for a relative rule. Routes send messages by severity, as webhooks, PagerDuty or Opsgenie, can send an unacknowledged critical again, and show whether their last delivery worked. - **Timeline** shows what changed in the fleet on one time axis, from [`GET /v1/events`](#events): alerts, copies going down and coming back, primaries changing, rollouts, moves, people's changes and notes, with a summary of the night. Add a note from it. - **Logs** searches the [log store](#the-log-store-logs-kept-in-chloedb), every server's lines at once, over the range, from one search bar (`level>=warn server:s1-0 "no answer"`), kept in the link. A line opens a pane with its fields and where to go next: its request on every server, its queries, the copy in Cluster, the lines around it. **Patterns** groups similar messages, **Live** adds new lines at the top, and **Log levels** changes what a server logs until an expiry, with a reason (`PUT /v1/logs/filter`). Servers that did not answer are named on one line. - **Log explorer** searches the log lines in the database's own tables (any table with a `TIMESTAMP`: syslog, [OpenTelemetry logs](#opentelemetry-logs), an app's JSON lines, and any other table's rows by their time), with a key limited to tables too (the `oncall` preset's): a search box (words, `"phrases"`, `host:core-rtr-02`, `level>=warn`, `-term`, or `WHERE ...`), the last 15 minutes to a week (`ts > now() - INTERVAL '15 minutes'`) or a window, lines per minute (`time_bucket`), the newest lines followed live, the lines around one on the same host, the lines grouped by pattern, and the SQL it ran. A line is its text (the column most of the newest lines fill, or one picked under the search box, as its time column is), with the row's other fields beside it when the table is not a log (it has no level or host), when the text is empty, or when asked; a table with no text column shows its fields, and a word in its search is a field's exact value. Without a log table it shows how to send logs: the table, the key, an OpenTelemetry Collector's settings and a JSON lines import ([Search your logs](../guide/logs.md)). - **Queries** shows what runs now, grouped by statement shape and API key. A group can be cancelled at once, with a reason for the audit log, or contained: its shape or key refused for a while. **Statements** cover the range, compared with the window before, with cards for errors by statement and key, new shapes and those that grew most. **History** reads 7 days of queries from the log store. Each statement has its own page (`#/statement/`) with its trend and the events around it, why it is slow or failing, its time by shard, copy and key, and its slowest calls with their parameters. A query's trace sums up the fan-out (the rounds, the critical path, the copy it waited for) and draws every call on request. - **Query funnel** (`#/funnel`) shows what a query does between its text and its rows ([its funnel](#a-querys-funnel)). **All queries** lays the latest queries' time on the stages, as one bar and a table of each stage's mean and percentiles, the rows each stage held on average, by statement and the slowest one by one. **One query** runs a query you write (or one opened from Queries, whose time as it ran it shows first) and lists its stages in order with what each did: the words understood, the terms its words became with the rows that hold each, their typos, prefixes and synonyms, "did you mean", the texts embedded, each input's matches, `WHERE` a condition at a time, the ranking and its candidates; then the rows left after each stage, every row the probes saw with where it left and why, a blend's sources and receipts, every step and the answer. A query's drawer in Queries opens it with **Its funnel**. - **Performance** covers the fleet over the range: findings that each say which rule fired on which numbers, and never report that all is well without data; failures a second by cause, with the clients' errors and deadlines apart from the server's; and, on a coordinator, every copy's p99, CPU, disk and lag. Drag across a chart to zoom every chart to that span. - **Feedback** (`#/feedback`) holds what people asked of the command center itself ([below](#feedback)): each item with the screenshot its sender marked up, the view it is about, and its status and priority, to read, put in order and hand to someone, or to an agent. **Run the cluster** - **Cluster** (a coordinator) is one canvas for the whole cluster. In **Live**, every shard is a tile and every copy a pip in it, coloured by one lens at a time (health, CPU, disk, p99, version, replication lag, and load: the reads and writes the coordinator routed to the shard by key over 5 minutes, against the mean of the shards) on the SLO's scale, grouped by shard, node or zone, with the problems named first; 192 shards of 3 copies fit on one screen. Click a shard for its copies (role, term, lag, version, why the coordinator avoids one), its diagram, its logs, profile and statements, and each copy's operations: make it the primary, compare its replicas, write a checkpoint, remove it. Each operation says why when it is not offered (a primary is never removed from here, a copy that is down, being copied or behind is not made the primary, and nothing changes while a rollout runs). Fail a node or a zone in a what-if to see which shards would keep serving. Under the map, **Key slots** draws the 4,096 slots as a 64 × 64 grid, each coloured by the reads and writes routed to it over 1, 5 or 15 minutes, with a line between shards, the coordinator's verdict (a hot range or a hot slot, [hot shards and hot slots](#hot-shards-and-hot-slots)) and the slots most counted; a slot opens its shard. What needs attention names a shard the verdict calls hot. **Even out by load…** (on a hot range in Key slots and What needs attention, and in Capacity) shows the [rebalance by load](#rebalancing-by-load) it would run, each shard's keyed load now and after and the disks of the copies sent rows, before it runs it as a plan's step; on counts that cover too little of the window, or a disk without room, it shows the plan and does not offer to run it. **Even out the slots…** shows its plan the same way, with the disks of the copies sent rows. - In **Draft**, drag a copy to another shard or node, drag a shard onto another to move slots, or drag the end handle to add shards; on a phone each drag is also a button. Nothing applies until the plan does: its steps in order (repairs first), the rows each copies and how long that takes at the rate the last move ran, what it touches, what is checked first ([`POST /v1/admin/plan`](#changing-the-cluster-while-it-serves)), and what it removes, which is only what was asked. One **Apply**, typed when anything is removed, runs the admin calls one at a time on machines of your own, or patches the StrataCluster once on Kubernetes; then its progress shows, with **Stop**. **Capacity** says the autoscaler's suggestion in words and the headroom left, and **Changes** lists the cluster's events and audited changes. `#/topology`, `#/fleet` and `#/control`, the views this canvas replaced, open it. - **Profiler** is the diagnostics of one server: the coordinator, or a copy found by its short name (`s1-0`), node or shard. It asks first above the safe sampling rates and says what they cost. Profile a query (once, 5 or 20 times, with each run's time and the median run's profile), or open one that ran among the slow or the latest, and set the slow threshold and CPU time for every query while the server runs. A profile has its time, CPU time and how parallel it ran; a flame chart of every step beside the request's trace, segments that ran at once on their threads and a coordinator's shard calls side by side, clicked to zoom; the operator tree with each step's total and self time, CPU time and rows (an `EXPLAIN ANALYZE`); the segments by the thread that searched them; the time by operator; and on a coordinator each shard's call split into the network and the shard's own time. **CPU** samples every thread of the server for 1 to 30 seconds, whatever its clients send or a query run in a loop by 1, 4 or 16 callers at once, and draws a flame graph of what they ran: every frame as wide as its CPU time, coloured by whose code it is (ChloeDB, the server, the async runtime, the standard library), split by thread pool or merged, with a thread filter, a search that shows a function's share and click to zoom; the functions by self and total CPU time; and downloads as folded stacks or JSON. **Memory** charts the heap in use, its peak and the resident memory with the bytes allocated a second, and takes an allocation profile of the whole server or of a query in a loop: a flame graph of the bytes allocated, of those still in use when it ended or of the allocations, and the functions by them. Below it, every thread of the process, by pool or each, with its state, its CPU now and its waits and preemptions a second. A Profile link (from a statement, History or Running now) fills the Profiler's query and its parameters and never runs it on open; Profile asks first when the statement is slow or contained. - **Query path** (a coordinator) runs a query, with its parameters, 10 to 100 times, one after the other, says first how many shard calls that makes, and takes each run's steps apart: a radar with the coordinator in the middle and a spoke per shard as long as its call (the shard's own time thickened inside it), each shard's call times over the runs against the coordinator's hedge (`--hedge-ms`), and which shard was the last to answer how often, which tells a slow shard from chance. From the same runs it estimates the p99 if the coordinator asked another copy sooner, and how many calls that would send twice. - **Tables and storage** (`#/tables`) answers four questions for every table at once: which is growing, which shard is skewed, which shard is hot, which copy is stale. Above them, every table added up: the bytes of all tables on all copies (on a cluster, as each copy says them), on one copy, their rows and the largest table; the list has a column of each table's bytes on all copies and a row of the totals under it. Sizes come from [`GET /v1/index/tables`](#the-index-inspector); a row opens its shards against the mean and its copies' lag, and the table's name opens **Table details** (`#/inspector?table=`): how many documents and fields it has, how its bytes split between each field's index, the doc store and the rest (a treemap), the size of its documents and of each field's values (histograms and percentiles), each field's fill, tokens, distinct terms and range, how fresh each copy is, how the shards compare, and how often its documents are retrieved and its keys asked for. Click the cluster, a shard or a replica in the map at its top and every number follows ([below](#the-index-inspector)). - **Rollouts** (a coordinator the operator runs) shows where a change is: how many copies run the new version, at what pace, and when it ends. When a health gate holds the change (the search p99 and failed searches the coordinator's clients see, the replica furthest behind, the fullest volume, each a live chart with its limit a dashed line to drag), it says which gate, which copy is slow, and that staying held is safe, with **Resume** and **Raise the limit**. Every action gives its cost first; a rollback counts only the copies that differ, and a resume asks for a reason. **Versions** lists the published images by tag, commit and build date, newest first ([`GET /v1/admin/kube/versions`](#upgrades)), with the ones the copies run marked. Pick one and the operator's plan shows (the copies it restarts, how long that takes, how to go back) before anything restarts. On machines of your own it shows the chloedb-server version each server runs. - **Autoscaling** writes the [rules](#autoscaling) as sentences, each setting an underlined word to click for its choices, each rule with its switch, and replays the servers' last week of load on them at once: how busy the busiest shard's copies would have been, beside a fixed size to pick, with the time over 85% and the frozen hours hatched, each change marked, the copies of each shard and the fullest volume below, the copy-hours of both, and what happened on a day to click. **Act**, **Ask a person** and **Off** set what a rule that fires does; **Undo** and **Save rules** appear once the rules differ from what was loaded, and saving shows the operator's plan first. On a cluster the operator runs it also shows a change the rules suggest, in words (the servers it adds or removes, the room they need, the rows copied and the time), with **Apply** (removing servers asks for the cluster's name) and **Dismiss**. On machines of your own it says that nothing runs the rules, replays them only, and links to Cluster's Capacity. - **Simulator** sets up a [test run](#the-simulator-a-test-run-and-a-model-of-the-cluster): a workload (a profile, or weights by kind), the test documents, a rising or steady rate, the SLO and a target, and asks before it runs, more firmly on a production cluster. While it runs it shows each phase and the rate against the p99 step by step. Its report leads with a grade and a sentence, then what the cluster holds, its p99 at the target, what fills first and what it costs, the checks behind the grade, the steps measured beside the model's curve, where the work went (the coordinator and each copy), a **What if** of shards, copies a shard, machines, rows and rate (with a grid of what each shape holds, the cheapest that holds the target ringed), the advice with its gains and costs, each kind's numbers, and what the model assumes. Its **Choosing a copy** test compares the coordinator's ways of choosing a shard's copy: a tick a setting, the clients, the reads right after a write; **Preview** answers at once by the model, with a what-if of a slow, busy, stalling or late copy, a table of the settings by clients (p99, p99.9, p50, throughput or reads after a write, the best of each count marked, each against this coordinator's), and how shard 0's reads spread; **Measure** runs the settings on the cluster in turns, and its report shows the medians measured with the model's under each, and every turn. - **Access and audit** opens on **Changes**: who changed what, from where, the value before and after, and why. Refusals and every audited request have their own tabs. Keys show their owner, last use and expiry; revoked keys stay listed, and a key can be rotated with a grace period, its new secret shown once. It also says who you are and checks the server's posture (a token, keys, loopback, TLS). - **Settings** edits, on Kubernetes, every fleet-wide setting of the StrataCluster's spec, each saying what it does at its value, when it makes the cluster less safe, where its value comes from and what applying it takes (a restart of every server, one at a time, of the coordinators, or nothing). The coordinator plans the change, and one **Apply**, with a reason, hands it to the operator, whose progress then shows. On machines of your own it shows the flags the cluster reports and how to change one, a server at a time. **Upkeep** says how the replicas compare (copies that differ, copies never compared), runs **Compare every shard now** and **Write a checkpoint of every shard** ([backups](#backups)), lists the checkpoints each copy keeps (**Backups**: each shard's newest, and the newest name on every shard), and shows the fullest disks against 80% and 90%. **This coordinator** shows its process, limits, configuration and the `/metrics` text. A server that is not in a cluster keeps its operations (check, vacuum, checkpoint, compare the replicas, a snapshot lease, reset statistics), each answering in words. - **Cloud setup** plans a cluster on [Amazon EKS](#on-aws), [DigitalOcean Kubernetes](#on-digitalocean) or [Google Kubernetes Engine](#on-google-cloud), picked at its top (and in the address, `#/cloud?provider=digitalocean` or `?provider=gcp`), starting from the running cluster's size. Save an AWS access key or a DigitalOcean token (checked with the cloud, then shown only masked), or, for Google Cloud, which takes no key, the project (the page shows the gcloud sign-in it calls with, or says how to sign in); when the keys come from the server's environment it asks the cloud nothing on open and says what using them would call. The view reads the region's machines with their prices and the account's limit: AWS's vCPU quotas, DigitalOcean's droplet limit, or the project's vCPU and address quotas. The machines are a chart of memory against price an hour (coloured by what each is for; on AWS, on demand or spot, Graviton filled and x86-64 hollow; on DigitalOcean, shared CPUs hollow; the suggested ones ringed) and a table to sort and filter; pick one, then the nodes (1 to 1,000), shards, copies of each, coordinators and each copy's volume (on DigitalOcean also the control plane and the Kubernetes version; on Google Cloud the autoscaler's most nodes, Spot, one zone or three, and GKE's version), and see where every copy goes, each copy's share of a node's memory and CPU, the cost an hour, a day and a month line by line, and whether the account's limit allows it. **Check with AWS** has CloudFormation check the template, **Check with DigitalOcean** asks DigitalOcean again for the account, the region, the size, the version and the droplet limit, and **Check with Google Cloud** asks Google again for the region, the machine type, the version, the quotas, the network and which permissions the credentials hold. **Create it** makes the cluster after its name is typed again (and not while the account's limit is too small). **Clusters made here** follows each one: where it is (the stack or cluster, ChloeDB, the copies, ready), the cost so far, its last step and what happened before it, the StrataCluster's status, why it failed, the commands that open its command center, on GKE **Nodes…** (how many, and GKE's autoscaler), and **Delete**, also after typing its name. The files that make the cluster yourself (the template, DOKS's request or GKE's) and the operator's and the cluster's manifests also download, with the commands that make the cluster and delete it. - **Follow** shows the cluster this one follows: the source, how far behind it is and what each source shard applied, with **Pause** and **Resume** (where the operator runs the follow process), **Stop following** and **Promote**, a switch-over that holds the source first ([following on Kubernetes, and from the hub](#following-on-kubernetes-and-from-the-hub)). It also holds and releases the cluster's own writes. **Build** - **Query designer** designs a search stage by stage, as a template whose one input is the text a person types (`:q`). A step for each stage, in the order a query meets them: *Understanding* (words that name a value of a `KEYWORD` field or a range of a number become a boost or a filter, [`understand =>`](query-language.md#understanding-a-querys-words-understand)), *Retrieval* (words over one or more text fields, all or any of them, with typos, synonyms and terms from the first rows, [`expand =>`](query-language.md#query-expansion-expand); meaning by a vector field the server embeds the text for; fixed filters; fused by rank or by weights; cut to the top N candidates), *Ranking* (boosts of the retrieval's score by a number, by recency, by closeness to a value or by a condition, each weight a parameter; then heads over its top N in a [second phase](query-language.md#rerank-phases), each a prediction with a weight: words in a field, meaning by any vector field, a number, recency, a [ranking model](query-language.md#ranking-models-gbdtmodel-features) over features of your choice (its probability with `sigmoid`), a [cross-encoder](query-language.md#cross-encoders-cross_encodermodel-fields-query); fused by weights over `minmax` or `zscore`, or by rank) and *Blending* (a page made of several queries run with the same text: the template's own rows, other saved templates', words in another table, or any query, each with a boost; diversity, a cap per value, near duplicates dropped, a share for a kind, as a [blend](query-language.md#blends-create-blend-and-blend)), then *Save and use*. Each step shows what its stage does to a sample query: "did you mean" and the values the words name, the rows each input of the retrieval matched and the terms its words became, the rows the ranking moved, coloured by how far each one went (or, with **Lists**, the steps side by side as plain lists), and each head's own top rows, the page the blend made and why each row is on it; under it, the [funnel](#a-querys-funnel)'s rows, stage by stage. The preview runs queries and stores nothing. Saving runs four `CREATE` statements: a [rank profile](query-language.md#rank-profiles-a-ranking-kept-with-its-table) of the template's name (so the relevance autopilot can tune its boosts), a blend `_blend` when blending is on, the function apps call (`CREATE FUNCTION (q TEXT, k INT DEFAULT 10) RETURNS TABLE`: `SELECT * FROM ('red shoes')`, and the MCP tool `fn_`), and `_template()`, which keeps the design so the page opens it again. Each is versioned as functions, profiles and blends are. Saved searches marks a template's function and opens it here. - **Tables** lists the tables, and a table's page searches it from one box, by words, by meaning or both, shows its rows, how full each field is, and what uses it. A search says how many rows match (a `COUNT(*)` of the rows that have one of the words, and of them how many have the words as typed, the others matched within a typo), pages through them 20 at a time, and opens a row in a pane with every field (click it, or Enter). By words and meaning, the rows with every word come first (`rrf(...) + CASE WHEN MATCH(f, :q, min => '100%') THEN 1 ELSE 0 END`), so a row that says the words is not ranked under rows only close in meaning. **Data** pages through the rows a condition keeps, and its CSV and JSON Lines hold every one of them, read by a scroll, not the page on screen. - **Team views** (`#/views`) are queries kept on the server for the team: built in the query builder or written in the SQL workbench and saved with a name, what they show and how their chart is drawn, as rows of the table `cc_views`, which the first save makes (with an admin key; a write key saves and removes views after that, and a read key lists and opens them). A view's link (`#/views/`) opens its answer, as a chart and a table with its count and export, on a phone too; **Open in the builder** (or the workbench) changes it, and saving under the same name replaces it for everyone. - **SQL workbench** is an editor in tabs that completes tables, fields (after an alias too), a `JSON` field's keys at each level (`attrs.`, then `attrs.dims.`, each key with its share of rows and its type), functions and parameters as you type. On production (an environment starting with `prod`, or none set) it is read-only until someone allows writes for 15 minutes with a reason. Every write first shows how many rows it changes, on which shards, and asks for a reason, kept in the audit log; an `UPDATE` or `DELETE` without `WHERE`, and a `DROP`, need the table's name typed. A statement that fails shows what kind of error it is, the server's whole message, its line with the place marked (in the editor too) and buttons that write the name it may have meant (a column, table, function or keyword) into the editor; a fix for a write never runs by itself. `SHOW TABLES`, `DESCRIBE t` (`SHOW COLUMNS FROM t`) and `SHOW CREATE TABLE t` are answered from the catalog, with which fields are indexed and stored and what searches each, and `EXPLAIN SELECT ...` opens the plan. Parameters get a form, where a vector parameter can be a text the server embeds: text given for `similarity(f, :q)` of an embedded field is embedded by its model. The answer is a grid with each row's score as a bar, a chart of any numeric columns, the plan as a tree with what ran on each segment, the query's profile (with the trace and each step's CPU time when *profile* is ticked), and the JSON; it exports as TSV, CSV or JSON Lines. An answer larger than a query returns (`--max-result-window`, 10,000 rows) shows its first 10,000 rows, read as a scroll, under a banner that says how many the query matches, with **Export all**: every row as a CSV, written a page at a time (to the file chosen, where the browser can stream one), or a table read whole (`SELECT * FROM t`) as Parquet from `GET /v1/export` when the key may export. **Health** profiles the answer's columns by SQL over every row it matches: values, NULLs, distinct values, the least and the most, and a number's spread; it flags a column that is always NULL, one with a single value, and a sum that a few rows make (the top 1% of rows holding half of it). Numbers read the same in the grid, a chart (whose axis has round ticks: 0, 500M, 1B) and Sheets: grouped digits, two decimals from 1,000 up and six below. The sidebar lists the tables and fields to drag into the editor, with snippets written for the table's own fields; history and saved queries stay in the browser, **Save as a view** keeps a query for the team as a team view (with its chart, when the Chart tab shows), and a link opens a query (`#/sql?q=...`). A link with `store=logs` (Logs' **As SQL**) opens a tab that runs `SELECT` on every server's log store instead. A write that changes every row of a table, or over 1,000 rows, runs only once the table's name is typed, whatever its WHERE or LIMIT. - **Schema** draws every table as a card with its fields, linked by references (crow's feet), edge tables and `EDGES` fields, and inside each card the vectors embedded from text, generated and derived text and semantic IDs. Drag the cards, hover one to see its links, click it for its fields, links, models, rank profiles and `CREATE TABLE`, and for each `JSON` field the tree of [its paths](query-language.md#which-paths-a-field-holds-json_paths) (the share of rows holding each, its types, its range or values; click one to facet it or query its rows), and query, template or drop it. **Design a table** builds a new one by dragging types into it, with each type's options, table options (`shard_by`, `cluster_by`, `retain`, `edges`) and templates; the server checks it as you go and shows the statement that creates it. - **Import and export** loads a CSV, TSV, JSON Lines or JSON file into a table or a new table made for it: the first rows show with the type each column reads as and the field it goes to, before anything is written, and the upload shows its progress. A column whose values list several things (Zendesk's tags, `billing refund web_form`) is found and split into a multi-valued `KEYWORD[]`, the separator it was split at (spaces, commas, semicolons or `|`) shown beside it with a value and its items, to change or turn off; the file is rewritten with `|` between the items before it is sent. A SQLite file shows its import plan first, table by table. The database (or some tables) downloads as a SQLite file (not from a coordinator), as Parquet, and a table as CSV or JSON Lines from `GET /v1/export`, which a read key may ask, and the stream sources show each one's last offset, with a box that sends operations to `/v1/stream`. ![Logs: the server's own lines, kept in ChloeDB, by level and server, with the search bar above](../assets/img/cc-logs.webp) ![The SQL workbench: a count by category over a search, its answer, and the table's fields and the snippets beside it](../assets/img/cc-sql.webp) ![The schema: a table's fields and the vector embedded from its text](../assets/img/cc-schema.webp) **Labs** - **Query builder** builds a query as a flow of stages: drag blocks and fields onto *Find* (words, typos allowed, and meaning, fused by rank or by weights), *Keep rows where* (conditions by type, with a keyword's most common values to pick from), *Boost* (recency, closeness to a value, a number), *Group and measure*, *Order* and *Show*. The SQL is written as you build and runs as you build, and the links between stages count the rows each kept: the table's, those that pass the filters (counted with a `COUNT(*)` of the same `WHERE`, which the answer's header shows as "N match"), those scored and those shown. *Group and measure* groups a time by day, week (Monday weeks, `date_trunc('week', t)`) or month, in time order, and measures counts, distinct counts, sums, averages, the median (`MEDIAN`), minimums and maximums, of a number or of the hours from one time to another (`date_diff('minute', a, b) / 60.0`), and each group's share of the rows (`COUNT(*)` over a window's `SUM`), of all of them or within each group of another field (each priority's share of its week). A keyword's condition is *is one of*, *is none of* (`NOT IN`) or *is* and *is not* one value; turning *is one of* with several picks into *is not* gives *is none of* of the same picks. The answer is a table or a chart, its series split by a column (a line for each priority), and **Save as a view** keeps the query, its chart and the builder's state as a team view, which opens in the builder again (`#/builder?view=`). **Changed:** the count of rows that passed the filters, here, on a table's Search tab and in the workbench, was the executor's `filter_docs`, the rows of the segments it read before a `LIMIT` stopped it, so it was below the rows that match; the header no longer shows it, and the workbench's plan calls it rows in materialised filters. "Edit as SQL" opens it in the workbench. A `JSON` field's paths are listed under it as fields of their own (`attrs.dims.w`), each with the share of rows that hold it, to drop on any stage. - **Relevance lab** runs two rankings of a query side by side (BM25, typos allowed, vectors, rank fusion, a weighted hybrid, a boost, a rank profile, or any expression), with lines showing where each row moved. Grade rows 0 to 3 (kept in the browser), and each ranking gets its nDCG (with exponential gain, 2^g − 1, as the autopilot measures, or linear, g, as trec_eval and BEIR do), its share of good rows and its first good row; over every graded query, their means (the first good row as MRR@k) and the share of queries with a good row in the top k (trec_eval's success), and a bar per query shows which ranking won, with a paired randomization test of the difference, and a weighted hybrid's weight (or rank fusion's k) is tuned by trying each on half of the queries and measuring the best on the other half, with the same test. **Import · export** brings grades in from a TREC qrels file and its queries file (TREC's `qid 0 key grade` or BEIR's `query-id corpus-id score`, with `qidtext` lines or BEIR's `queries.jsonl`) or from a judgments table (`relevance_judgments`, as the [autopilot](query-language.md#the-relevance-autopilot) reads it), and takes them out as qrels and queries files; a qrels file whose grades are only 0 and 1 (BEIR's) is read as binary, its 1 becoming good (2), so the good rows, the first good row and the queries with one count the relevant ones as trec_eval does (nDCG is the same either way). A vector field is offered only when a model embeds it, which the lab needs to embed the query. A ranking can be kept with its table as a rank profile. **Grade with Claude** grades the rows of both rankings not graded yet through [`/v1/judge`](#relevance-judgments); the measures then read your grades, Claude's or yours where you gave one, and the evaluation says how well your grades and Claude's agree (Cohen's linear-weighted kappa). - **Blending** keeps the [blends](query-language.md#blends-create-blend-and-blend) of the server: each a card with its sources' share of the slate, its rules and its note, and a draft started from two queries. A blend opens on a canvas of its stack, the blend at the top and the blends stacked under it, each a card with its sources' share of the rows it places and its rules as chips, wired to its sources below, the wires as wide as each source's share. Pieces are dragged from the palette onto a card: a Query, a Blend (stacked under it, or on a query, which it then holds), a copy of another saved blend, a rule (a slot kept, a quota, spacing, a cap, diversity, near copies) or a head; a source dragged onto a card moves there, onto another source stacks a new blend on the two (named for both; a rule above that named either now names it through the new blend, as `via = 'node/source'`), onto the bin removes it, and each card's menu does the same without a mouse. A click on a card selects it: its settings and its slate below are that node's; a source's swatch drags onto a slot, each source has its boost; each head's calibration, weight and what a source without it gets, with the utility written as a sum; the slots, dragged onto to keep one for a source; each quota as a range on a bar of the top rows, with where the slate is now; spacing, caps, diversity and near copies. Every change previews the draft against the server (`POST /v1/blends/preview`), with the query's parameters filled in above: each row's source, its utility as a bar of its heads' parts, how it got its slot and why, each quota's count, what each rule costs the slate, the rows passed over and what barred them, and the plan. **Save as v*n*** writes the next version with a note (an admin's), **Versions** lists them with what changed and opens an old one as a draft, and the SQL drawer shows the `CREATE OR REPLACE BLEND` it writes. **Value on the log** sets the draft against the serving version over the blend's exploring pages in a rank log (`POST /v1/blends/:name/evaluate`; the log, the table of clicks and its columns are picked at the top): each one's verdict and why, its value with its interval beside the logged blend's, SNIPS beside cascade doubly robust over the top slots, and slot by slot the value each slot adds with the searches behind it, paler where the log could not draw the page; **Tune toward clicks** tries blends near the draft on half the searches and shows the best on the other half, which opens in the editor. Without exploring pages it shows how to log them. - **Recsys eval** measures logged rankings against what users did next. It joins the [rank log](query-language.md#the-rank-log-what-each-query-served) to an events table (pick its user, item, time and action columns), grades each served row by the actions within a window, and gives each variant its nDCG, hit rate, MRR and gain at k, with the lift of one over another and whether it is significant (Welch's test over requests). [Interleaved](query-language.md#interleaving-two-rankings) requests count as a variant of their own, and a card says which of their two rankings the users preferred (team-draft credit and a sign test). Charts show the share of good rows by position, how well each logged feature alone tells good rows from the rest (its AUC), the measures over time and by a user segment; open a request for the user's history, the rows it served and their grades, and set a grade by hand. The settings download as training data (`POST /v1/rank_log/export`) or copy as `curl`. - **Semantic IDs** draws a table's codebook as a sunburst: the inner ring is one level of codes, the outer the next, each sized by its rows and coloured by a keyword field's commonest value (paler when mixed). Click a code to zoom into it, and a filter limits it to the rows that pass. The decoding columns are what `/v1/sid/next` answers a generative recommender at each step, and each code lists its rows with their full codes and how many codes each level uses. - **Autocomplete** completes as you type from a table of queries and counts (`PREFIX`, the most used first, then typos allowed with `fuzzy`), with the completion ghosted in the box (`Tab` takes it). A timeline shows each keystroke's time on the server and round trip, and a benchmark measures the latency by prefix length, exact and with typos; a card says whether the table is clustered by its key (`cluster_by`), which lets an `ORDER BY ... LIMIT` read its best blocks first. - **Understanding** is what models make of each row and of each search, as two workflows, and where the understanding components are configured. *Enrich rows* adds fields that a model makes of a row's text when it is written. You pick the field the models read, then add steps: a language (`builtin:lang`), main phrases, near duplicates, the names it mentions (`dict:
    .`), a classifier's class, a language model's text by a prompt, a vector for meaning, or a caption or transcript of a file. Each step is tried on sample rows before anything is added (`/v1/derive/preview`, `llm()`, `embed()`). The fields are added in one `ALTER TABLE ... ADD COLUMN`. Rows written before them are then filled in, 200 rows a write, by an `UPDATE` that writes each row's source again so the writer makes the values (the server fills in vectors itself). A table of the fields made so far shows how many rows have each, their commonest values, and fills in the rest. *Enrich queries* reads a search in steps and adds what it reads to the request. Spelling (`/v1/correct`) changes the words, and a classifier's class, the language and the names it mentions become filters; the values the words name, synonyms, typo tolerance, expansion and a vector's similarity become options of `bm25` and `rrf` that the query runs itself. Context the caller knows (`country = CL`) adds filters too. The page shows the request as SQL with its parameters, runs it beside the words alone with the rows only it finds marked, and saves it as a search whose filters are parameters (`NULL` leaves one out). *Inspect a row* shows a row's text, its derived fields and classes, what each built-in model makes of it, and its chunks (`chunks_of`). *Configure* trains and drops classifiers (`CREATE CLASSIFIER`), edits the table's synonym list (`CREATE SYNONYMS`), and mines proposals for it (`/v1/synonyms/mine`). - **Media search** finds images (or sounds) by a description, by a file dropped on the page, or by a row (more like this), over a vector embedded from a `MEDIA` field, with the caption's words mixed in by a slider, a keyword field's values and the colours a model named as filters. Results are a grid of the files (`GET /v1/media/`) with their rank and score; the map lays every row out by its vector's two main directions, the hits and the query among them. - **Graph explorer** draws rows as nodes and their links as edges (an edge table, an `EDGES` field, or a vector field's nearest rows), laid out by forces: drag a node to pin it, scroll to zoom. Search to add nodes, open one to add its neighbours (`REACHABLE`), rank the graph from it with personalized PageRank (`ppr`; *PageRank eps* is how far it walks, auto lowering it as the walk needs, and the ranking says when the walk stayed near the node), and shift-click another, or type its key, for the shortest path (`PATH`); colour and size follow fields, and each walk shows its SQL. - **Query console** is the earlier UI, below (`#/classic`). ![The query builder: the stages to drag blocks onto, the SQL it writes, and the rows it answers](../assets/img/cc-builder.webp) ![The graph explorer: products linked to their nearest vectors, coloured by brand](../assets/img/cc-graph.webp) One time range applies to every view and is kept in the link: 15 minutes to 7 days, or a fixed window (past the last hour the series come from the log store's minutes). Views without a time axis (the SQL workbench, Schema, Labs) hide it. **Share** copies a link that opens the same view and window, paused; it never holds a key. When the API does not answer, the top bar says so and since when, and every panel says how old its data is. `Ctrl K` (`⌘K`) finds a shard, a copy (`s9-2`), a node, a table, a statement, an alert, a key or a view, and what to do about it; `g` then a letter goes to a view, and `?` lists the shortcuts. On a phone the navigation is behind the menu button and panels open full screen. The page follows the system's light or dark theme unless you choose one. The page and its modules (`chloedb-server/ui/`) are compiled into the binary. The page names them under `/ui/v-/`, which the browser keeps for good, so a reload asks the server for the page alone; a new build's page names new paths. To work on them without rebuilding, start the server with `CHLOEDB_UI_DIR=chloedb-server/ui`: it then reads them from there on each request, and the page names them under `/ui/` alone. ### Feedback Any view sends feedback about itself: press `f` (or the speech bubble in the top bar, or "Send feedback" in the palette), and the view as it is becomes a picture to draw on, with boxes, arrows, a pen and text, each numbered, and black boxes over what must not be kept (a key, a customer's data). A note says what is wrong or what should change, and the item is a bug, a change, an idea or a question. It is sent with `POST /v1/feedback` (a write key) and kept as a row of the table `cc_feedback`, which the server makes the first time. The picture is made in the browser, and nothing is sent anywhere but the server: **From the page** copies the page, puts its stylesheet beside it and draws the copy as an SVG image onto a canvas (no prompt; an app's frame shows as a box), and **From the screen** takes the tab with the browser's screen capture, which asks first and takes everything pixel for pixel. What is sent is one picture with the marks drawn on it, so a blacked-out part is not in what the server keeps. The marks go too: each with its number, tool, place on the picture in CSS pixels, what it says, and what was under it on the page (a CSS selector, its text, the card and the view's heading), which is what lets an agent find the code. So do the view and its address, the window's size and theme, the server's version, the sender's key name, and, if the sender agrees, the last errors of the page. **Feedback** (`#/feedback`, `g` then `f`) lists the items, open ones first by priority (P0 now to P3 some day) or newest first, filtered by status, kind and words; each has its thumbnail, and opens with its screenshot, note, marks, the page's context and its triage: status (`new`, `triaged`, `planned`, `doing`, `done`, `wontfix`), priority, assignee and resolution. **Copy for an agent** copies a prompt that says what to change and how to mark it done. | route | body | answer | |---|---|---| | `POST /v1/feedback` | `{note, kind?, title?, page?, route?, url?, shot?, thumb?, shot_w?, shot_h?, marks?, context?}`; `shot` and `thumb` are `data:` URLs of a PNG, JPEG or WebP image (6 MB and 256 KB at most); `route` is a route of the command center (`#/` and a path), `url` an http or https address | `{id, ts}`: write scope | | `GET /v1/feedback?status=open&kind=&q=&assignee=&limit=100&thumbs=1` | | `{feedback, counts, statuses, kinds, exists}`, newest first, without the pictures (`thumbs=1`: with each thumbnail); `status` is `open` (new, triaged, planned, doing), `all`, or a list | | `GET /v1/feedback/:id?shot=1` | | the item, its marks and context as JSON, `shot_url`; `shot=1` adds the screenshot as a `data:` URL | | `GET /v1/feedback/:id/shot`, `/thumb` | | the picture, served inert as [media files](#media-fields) are | | `PATCH /v1/feedback/:id` | `{status?, priority?, assignee?, resolution?, kind?, title?, if_status?}` | the item: write scope; `if_status` refuses with 409 when the status is another, so that two agents do not take one item (a server or coordinator triages one item at a time, so of two takers at once the second gets 409; two coordinators do not wait for each other) | | `DELETE /v1/feedback/:id` | | `{deleted}`: admin scope | Agents read the same rows. With SQL, `SELECT id, kind, priority, title, note, page, marks_text FROM cc_feedback WHERE status IN ('new', 'triaged', 'planned') ORDER BY priority, ts`, where `marks_text` is the marks one a line (`1. box "too small" on "Shards" (button.btn: Add shard)`) and `MATCH` finds words of the note, the title and the marks. Over [MCP](#agents-over-mcp), `list_feedback`, `get_feedback` (which answers the screenshot as an image the model sees) and `update_feedback`. An agent takes an item with `{"status": "doing", "assignee": "", "if_status": "new"}` and closes it with `{"status": "done", "resolution": ""}`. A key limited to tables reaches these routes with a grant on `cc_feedback`: `read` to read, `write` to send and triage. A mark names what it points at by its label (a button's words, a field's label, a cell's column), never by a field's value or a cell's content, and names nothing that meets a blacked-out area: what is there stays in the picture, where the sender can black it out. ### The index inspector `GET /v1/index?table=T` (admin scope) answers what the command center's **Index inspector** shows, for one table. On a server it is that server's (`cluster`, with `shards` empty); on a coordinator it asks every replica of every shard for its own, over the `Profile` call of gRPC with kind `index` (no change to the shard protocol: a server older than the coordinator answers that it has no such profile, and its replica shows that), and answers each replica's, each shard's and the whole cluster's: ```json {"role": "coordinator", "table": "products", "reads_on": true, "sample": 2000, "took_ms": 41.2, "cluster": {"stats": {...}, "freshness": {...}, "reads": {"docs": {...}, "keys": {...}}, "copies_bytes": 7340032}, "shards": [{"shard": 0, "url": "...", "scope": {...}, "replicas": [{"url": "...", "takes_writes": true, "behind": 0, "scope": {...}}, {"url": "...", "error": "..."}]}]} ``` A shard's statistics are its primary's (the first copy that answered, without one), and its reads its copies' added up; the cluster's are its shards' added up, with `copies_bytes` the bytes of every copy. `behind` is how many writes a copy is behind its shard's primary. - `stats`: documents live, deleted and in memory; bytes on disk and in memory, split into each field's index (by section), the doc store (compressed, and `store_raw` before compression), the primary key and other sections, and segment overhead; each segment's documents and bytes; and per field its kind, how many documents have a value (`present`), the size of its values (`size`: a histogram of buckets `[lo, hi, documents]`, four to an octave, with `mean`, `p50`, `p90`, `p99`), the items of a list, tokens per document of a text field, its share of the doc store, its distinct terms (`terms`: `low` and `high` bounds over the segments and an `estimate`), and the range of a number or a timestamp. `doc_bytes` is the same histogram for whole stored documents. - `freshness`: when the table was last written (`last_write_ms`) and how many writes it took since the server started, and when the database's file last changed. - `reads`: of documents retrieved (rows returned in query answers) and of keys asked for (`GET /v1/kv`, `POST /v1/kv/get`, `Get` over gRPC): the total, the distinct keys read, the share of the table read at least once (`coverage`), how often each was read (`per_key`), the concentration curve (`curve`: the share of reads taken by the most read fraction of the keys read, with `top1` and `top10`), the most read keys (`top`, each with its count, the most it may be too high, `err`, and its share), and, for keys, those no row has (`missing`). `GET /v1/index/tables` lists every table at once: its documents, bytes and segments by shard (`bytes` are one copy's, each shard's primary), on a coordinator its bytes on every copy (`copies_bytes`, the sum of what each copy of each shard says it holds, with `copies_measured` and `copies_missing`, the copies that did not answer and are left out; also per shard), `skew` (the shard furthest over the mean, and by how much), writes and reads a minute, `last_write_ms`, the copies behind (`stale`), and its `growth` over a day and a week from the log store's hourly `tables` rows; `totals` adds the tables up (`tables`, `failed`, `docs`, `bytes`, `segments`, and on a coordinator `copies_bytes` and `incomplete`, the tables a copy did not answer for). It samples no document and is kept 30 s; the command center's **Tables and storage** reads it. Writes and reads a minute are measured against a look the server keeps every minute, so they are there on a first look once the server is 30 s old: over the last 5 minutes at most (`rate_window_s`), and for each shard (`shards[i].writes_per_min`, `reads_per_min`). The drill-down (`GET /v1/index`) measures over the same window (`rates`). What is exact and what is estimated: documents, bytes, segments and index sizes are read from every segment; distinct terms too, but those of a large field are estimated with a HyperLogLog sketch, which also merges across shards. Value sizes, fill and document sizes come from `sample` documents (2,000 by default, at most 100,000) drawn at random from each server with `seed`, weighted to its whole table; the fill of a field that is not stored, and tokens per document, come from every document's length norm instead (exact below 24 tokens, rounded down by at most 12.5% above). `terms=false` skips the term sketches. Reads are counted in memory, since the server started or since `POST /v1/index/reads/reset`, and are approximate: each table keeps its 256 most read keys (Space-Saving: a count is at most its `err` too high), and a hash sample of the keys read that halves itself to stay under 4,096 entries gives the distinct keys, the coverage and the frequencies (`exact` while it holds every key). The first 10,000 rows of an answer are counted by key and the rest in the totals (`skipped`). A coordinator counts what each replica served through it (by the shard and replica each row came from), and every server counts what it answers its own clients; a shard does not count the coordinator's questions, so nothing is counted twice. Profiling runs and the parts of a compound query are not counted. `--no-read-stats` turns counting off. ### The query console `GET /classic`, and the command center's **Query console**, serve the query console, a single page with six tabs. ![The query builder: search text, similar to a description, weighted fusion, a filter, the SQL it writes, and the results](../assets/img/strata-server-builder.png) - **Build** writes SQL from a form: search text (ranked, or only matching rows, with typo tolerance and synonyms), "similar to" a stored row or a description, rank fusion or a weighted sum with a slider, conditions, a boost by closeness (`decay`), a facet, the columns and the row count. Conditions nest in groups of *all of* (`AND`), *any of* (`OR`) and *none of* (`NOT`), and a condition can be "is among the *field* of the rows where …", an `IN (SELECT ...)` subquery. **Join related rows** pairs each row with the rows it links to, the rows linking to it (for each `EDGES` field) or the rows sharing a value, with conditions and columns for the related rows; **Summarize** groups by any fields of either side and computes counts, distinct counts, sums, averages, minimums and maximums, with `HAVING` and an order. The SQL updates as you type; "Edit as SQL" takes it to the editor. Clicking a keyword field in the sidebar shows its most common values, and clicking a value adds a condition. Each result row has a "similar" link that searches for rows like it, and a "links" link that opens its neighbourhood in the Graph tab. A search that finds nothing offers to search again allowing typos, or with synonyms. - **Graph** (for a table with an `EDGES` or `VECTOR` field) starts from keys, the top rows of a search or the rows matching a condition, follows links (out, in or both ways, optionally one label) or similarity (each row's *k* nearest), and finds the rows within some hops, the shortest path to other rows, or the rows ranked by personalized PageRank, with conditions on the rows found. The answer is a table and a picture: rings by hop distance, a path left to right, or PageRank as node size. Clicking a node shows its row, expands its links or starts a new walk from it. - **SQL** is an editor with parameters, results and the plan the executor recorded, segment by segment, with example queries one click away. It only reads (it sends `POST /v1/query`, which takes only a `SELECT`): a write or a schema change opens in the SQL workbench, which checks it first. - **Ask an agent** takes a question in plain language. - **Schema and import** uploads a JSON Lines, JSON, CSV or TSV file (or pasted rows) into the table, showing the upload's progress and the columns it skipped. It shows the table's schema in the short form, and designs new ones: fields by type with their options, vector fields embedding chosen text fields by a named model, a first draft guessed from a file's first rows (numbers, lists, vectors, short values as keywords and longer ones as text, a unique `id`-like column as the key), JSON that edits both ways, a check against the server, a download, and the commands that create and fill a database with it. - **Query language** is a guide to the SQL with examples written against the table's own fields and words from its rows: boolean, phrase, prefix, typo and synonym searches, conditions, aggregates and `HAVING`, subqueries and `WITH`, joins, graph queries, hybrid ranking and boosts, and what is not supported. "Try it" runs an example in the SQL tab. It also edits the server's synonym list. ![The SQL editor with a plan](../assets/img/strata-server-sql.png) ### In a terminal `chloedb-server cc [URL]` is the command center in a terminal, for an SSH session or a machine without a browser. It reads the routes the command center reads (`/v1/cluster`, `/v1/health/fleet`, `/v1/alerts`, `/v1/queries/stats`, `/v1/queries`, `/v1/logs`, `/v1/index/tables`, `/v1/events`), every 2 seconds (`--every`), and sends its changes to the same routes with the same key, so a key may do there what it may do in the browser, and the audit log keeps each change with its reason and `x-chloedb-app: chloedb-cc`. Nothing new runs on the server. ```bash CHLOEDB_KEY=sk_… chloedb-server cc https://db.example.com:7700 chloedb-server cc # http://127.0.0.1:7700; it asks for the key chloedb-server cc https://hub.local:7700/c/prod # a cluster in a hub's book, with the hub's key ``` The key comes from `CHLOEDB_KEY` (or `CHLOEDB_TOKEN`), else from a prompt that does not show it; there is no flag for it, so it is never in the shell's history or the list of processes. `--ca FILE` trusts a CA for an https URL. The screens need 80 columns by 24 rows, and `NO_COLOR` draws them without colour. Without a terminal it exits, naming `chloedb-server admin` for scripts. | key | screen | what it shows | |---|---|---| | `1`, `g h` | Home | the fleet's health: its headline, the copies that answer, p99 against the SLO, errors, replication lag, the fullest disk, the alerts firing, and each problem with what to do next | | `2`, `g c` | Cluster | a map of the shards, or of the nodes (`G`), each tile coloured by the lens `L` picks (health, p99, CPU, disk, errors, lag, version); beside it the shard picked, each copy's role, node, lag, p99 and CPU, and why the shard is in its state | | `3`, `g a` | Alerts | every rule, firing first; `a` acknowledges one, `s` silences it for the minutes typed with a reason, `u` lifts the silence | | `4`, `g q` | Queries | the queries running now (`x` cancels one) and the statements of the last 15 minutes, by their share of the time, p99, calls or errors (`o`) | | `5`, `g l` | Logs | the server's own newest lines, followed as they come; `f` sets the level and `/` the text they hold. They are an admin's (or an `ops` or `propose` key's): for another key, the screen says so and lists the log tables the key reads (those with a `TIMESTAMP`), and `Enter` shows one's newest lines in SQL | | `6`, `g o` | Tables | each table's rows, size, segments, reads and writes a minute, skew and last write, and the one picked shard by shard | | `7`, `g w` | SQL | a statement run as the key, its rows as a grid, `↑` `↓` its history | | `8`, `g t` | Timeline | the events, newest first: changes, alerts, primaries and failures | The `g` letters are the browser's. Space pauses the reading, `r` reads at once, `:` takes a command (a screen's name, `lens p99`, `ctx`, `writes`, `sql SELECT …`, `q`), and `?` lists the keys. **Changes** ask first, in a dialog that says what the change does, and on production (an environment that names no test or sandbox, or none on a server that is not this machine's or is reached through a hub, as the browser decides) for a reason the audit log keeps; Enter does nothing until it is given. On **Cluster**, `p` makes the copy picked its shard's primary, by its copies' votes (`POST /v1/admin/shards/{i}/promote`), refused for what the browser refuses it: it is the primary, does not answer, is being copied or is behind, or the shard has one copy, or the key is not admin. While a plan runs on the coordinator, a band names its step and `S` stops it after that step; it goes on when the terminal closes. On **SQL**, as in the SQL workbench, production is read-only until `W` allows writes for 15 minutes with a reason, which goes with each write; each write asks first, and an `UPDATE` or `DELETE` without `WHERE`, a `DROP` or a `TRUNCATE` needs its table's name typed. Draft and its plans (copies and shards added, moved and removed), the schema, the query builder, keys and the audit log, the profiler, rollouts, the cloud views and the apps stay in the browser. **Through a hub**, the URL is the connection's, `https://hub:7700/c/`, and the key is the hub's (an admin key of the hub): each call goes through the hub, which adds that cluster's key, so the terminal never holds it ([many clusters from one command center](#many-clusters-from-one-command-center)). `:ctx` lists the hub's book and opens another of its clusters, and `:ctx -` the hub itself. A hub on another machine that listens on its loopback is reached through a tunnel: `ssh -L 7700:127.0.0.1:7700 host`, then `chloedb-server cc http://127.0.0.1:7700/c/`. ### Apps An app is a program of its own that the command center shows as a view: the [crawler](crawler.md), the [spreadsheets](sheets.md), [network operations](netops.md), [ChloeCtx](../chloectx/app.md) and the [app engine](apps.md) are four. `--app name=url` (repeatable, or `CHLOEDB_APPS=a=url,b=url`) names each, and the server reaches it there; browsers never do, so the app needs no address of theirs and no keys (the app engine's studio is the exception: it runs code a model wrote, so it keeps an address of its own and signs browsers in with a link its view hands out). On Kubernetes, `spec.crawler`, `spec.sheets`, `spec.chloectx` and `spec.apps` of a `StrataCluster` have the operator run them beside the cluster and set this on its coordinators, and give each app a key [limited to its tables](#security) and a token of its own (below) ([the crawler on Kubernetes](crawler.md#on-kubernetes), [the spreadsheets on Kubernetes](sheets.md#on-kubernetes), [ChloeCtx on Kubernetes](../chloectx/app.md#on-kubernetes), [the app engine on a cluster](apps.md#on-a-cluster)): - `GET /v1/apps` lists the apps (read scope), each with its manifest, the app's `GET /app.json`: `title`, `description`, `icon_svg` (the shapes of a 24-unit outline icon; only shapes and their geometry are drawn), `version`, and `view`, the path of its view module, as `/v1/apps//`. An app that does not answer is listed with `up: false` and why. Manifests are read again after 15 seconds. - `/v1/apps//` is sent on to the app's ``, with its query, body, `content-type`, `accept`, `if-none-match` and `if-modified-since`, and the app's token as `Authorization: Bearer` in place of the caller's key: its own, from the file of its name in `--app-token-dir` (`CHLOEDB_APP_TOKEN_DIR`, read as it is sent) or from `CHLOEDB_APP_TOKEN_` (its name in capitals, `-` as `_`), else the server's `CHLOEDB_APP_TOKEN`. Give each app a token of its own, so that one app cannot call another as the server. The caller's key is checked first, read scope for `GET` and `HEAD` and admin scope for the rest; a key [limited to tables](#security) only reaches an app whose `app.json` says `"limited_keys": true` (it holds such keys to their grants itself), with any grant that reads. The app is told who it was in headers the server sets (a caller's own of those names are not passed on): `x-chloedb-principal` (the key's name, `token` or `open`), `x-chloedb-key` (its id), `x-chloedb-scope`, and `x-chloedb-tables` for a key [limited to tables](#security) (`crawl_*=admin,*=read`). An app may trust them because they come with its token. The answer comes back with its `content-type`, `content-disposition`, `etag`, `last-modified` and `x-app-*` headers, and `cache-control: no-cache`: a browser asks again each time, and an app that tags its answers (its view, say) answers `304` with no body to one that holds it . A request's body may be as large as an import's (`--max-body-mb`, 256 MiB), an answer is at most 32 MB, in at most 120 s, and an app that does not answer is a 502. On Kubernetes no app holds the cluster's admin token once its coordinators make keys limited to tables (`/v1/whoami`'s `auth.app_keys`): the operator keeps a Secret per app, `--credentials`, with `key`, a key of the cluster limited to the app's tables (named `-app`, made through the coordinators and made again when the tables change), and `token`, random, which the app's own API requires and the coordinators send it (their `STRATA_APP_TOKEN_DIR`, the Secrets mounted as a folder of files, so no restart is needed when one is made). `spec..tables` names the tables (`table=scope`, as above); by default network operations get `netops_*=admin`, the spreadsheets get `sheets_*=admin, *=read` (the cluster's tables open in them as sheets, read only), ChloeCtx `ctx_*=admin, chloectx_memory=read, chloectx_mem_*=read` (each project `chloectx sync` copies has a table of its own, `chloectx_mem_`; its Seen before asks the on-call agent, which is the server's admin, and goes without), the app engine `sa_*=admin, app_*=admin` (from which it makes each of its apps a key of its own, `apps-app/app-`, limited to `app__*`), and the crawler `*=admin` (a crawl fills the table it names). The crawler that grows the cluster (`crawler.grow`, the default) keeps the admin token as its key, since adding shards is the server's admin; its token is its own. Until an app's Secret is made, and with coordinators from before such keys, the app runs with the admin token, as it did before. An app taken out of the spec loses its key and its Secret. When an app's key is made again (its tables changed, or its Secret lost the key), the new key is made before the old one is revoked, and the key's id is on the app's pod template (`strata.chloetech.ai/key-id`), so its pod restarts with the new key rather than calling with a revoked one. When making the new key fails (a timeout, an error of the coordinators, coordinators rolling), the Secret keeps the key it has, with its id and tables, so the pod neither restarts nor gets the admin token, and the next reconcile tries again; an app with no key yet then gets no key at all (the Secret is marked `strata.chloetech.ai/key-pending`) until one is made. Only coordinators from before keys limited to tables give an app the admin token. The operator writes these Secrets only where the ClusterRole `strata-operator-secrets` is bound: `operator.yaml` (and the cloud view's install) binds it in the namespace `strata`; for clusters in another namespace, bind it there (`kubectl -n NS create rolebinding strata-operator-secrets --clusterrole=strata-operator-secrets --serviceaccount=strata-system:strata-operator`), or that cluster's apps keep the admin token. Its ClusterRole, bound everywhere, only reads Secrets (each cluster's `tokenSecret`). #### Apps the server starts A server of its own, or a coordinator, starts the crawler (`chloedb-crawl serve`), Sheets (`chloedb-sheets serve`) and ChloeCtx (`chloectx app`) itself when their programs are installed in its own directory, as an install puts them (a build's `target/` has none of them, so tests and `cargo run` start nothing). Each is a child process that listens on a loopback port of its own and is listed under its name, as if it had been given with `--app`: - the server binds that port itself and holds it while it runs, and hands the listening socket to the app as file descriptor 3 (`CHLOEDB_LISTEN_FD=3`) at each start, so no other process can take the port while the app starts or restarts; - it takes requests only with a token the server makes for it at each start, which no one else holds; - it calls the server back with a key of its own, scoped to the tables it keeps (the crawler `crawl_*`, Sheets `sheets_*` and reads of the rest, ChloeCtx `ctx_*` and reads of `chloectx_memory`), made at each start, held in memory only and never in the keys file; it is never given the server's token, cluster token or keys: its environment is the server's with every credential taken out (the `PATH`, the home, the locale, proxies, CA files, `ANTHROPIC_API_KEY` and the crawler's `CHLOEDB_CRAWL_CONTACT` and `CHLOEDB_CRAWL_ALLOW_PRIVATE` stay); - it runs in a process group of its own and, on Linux, ends when the server ends; when it exits it is started again after a second, then up to a minute between tries; when the server stops it gets SIGTERM, and SIGKILL 10 s later; - its output goes to the server's log, each line under `app=`, and `GET /v1/apps` lists its `process`: `program`, `pid`, `running`, `restarts`, `last_exit` and its last 40 lines, which the command center shows when the app does not answer. The crawler a server starts does not grow the cluster (`--grow off`), and names the tables it fills `crawl_`. A replica, a shard (a server with a cluster token and no `--shards` or `--replicas`), a shard with its coordinator beside it, a pod the Kubernetes operator runs (which runs the apps as Deployments of their own) and a server over TLS start none; `--start-apps off` turns it off anywhere, and an `--app` of the same name takes the app's place. The servers `chloedb-crawl --local` and `chloedb-sheets serve --local` start are given `CHLOEDB_START_APPS=off`, since those programs are their apps. The navigation lists the apps under **Apps**, each at `#/app/`. Its view module is JavaScript the command center loads through the server (with the signed-in key) and runs with its own helpers: the module's default export's `render(el, ctx)` draws into `el` and may return a function that stops it, and `ctx` holds `core`, `charts` and `data` (the command center's modules), `app` (its listing), `api(path, opts)` (the app's API through the server), `path()`, `href(...)` and `onPath(f)` for the view's own paths under `#/app//`. An app's view is trusted as the server's own pages are: an admin names the app on the server's command line. ## The agent `POST /v1/agent`, and the query console's **Ask an agent** tab, give a Claude model one tool, `run_sql`, which runs a read-only `SELECT` on the table. The model sees the schema and a description of ChloeDB's SQL (it runs facet queries to learn a field's values), then searches, filters, ranks, counts and facets until it can answer, for at most `max_steps` model calls (8 by default, 20 at most). The answer lists every query it ran, with its row count and time, so you can check its work or open a query in the editor. Writes are refused. The model is a setting: `--model` sets the server's default (`claude-haiku-5-5`), and a request or the UI can name any other model id and an effort level. The API key comes from `ANTHROPIC_API_KEY` on the server, or from the request (`api_key`, never stored by the server; the UI keeps it in the browser only if you tick "remember"). On Kubernetes, a `StrataCluster`'s `secretEnv` gives it to every server and coordinator from a Secret ([model keys](https://github.com/chloetech-ai/chloedb/blob/main/chloedb-server/deploy/README.md#model-keys)). ### Relevance judgments `POST /v1/judge` grades rows of a table against a query, 0 to 3, the scale of TREC's judgments and of the relevance lab's grades, with UMBRELA's prompt (Upadhyay et al., 2024: the open reproduction of the prompt with which Thomas et al., SIGIR 2024, found an LLM agreeing with Bing's searchers as well as its human labellers did, and the one TREC 2024's RAG track judged with). Each row is its own request, so a grade does not depend on the other rows or their order; the passage is the row's stored `TEXT` fields (or the `fields` named), each on a line after its name and cut at 4,000 characters. Up to 200 rows a request, eight at a time; an answer without a grade is asked once more for one, and a row still without one, or not in the table, gets `grade: null` and an `error`. The model and key are the agent's. ```sh curl -s localhost:7700/v1/judge -H 'content-type: application/json' -d '{"query": "mrna vaccine side effects", "keys": ["d17", "d3", "d240"]}' # {"grades": [{"key": "d17", "grade": 3}, {"key": "d3", "grade": 1}, {"key": "d240", "grade": 0}], # "model": "claude-haiku-5-5", "prompt": "umbrela", "fields": ["title", "body"], "usage": {"input_tokens": 2310, "output_tokens": 21}, "took_ms": 1840.2} ``` On 25 TREC-COVID queries, pooling the top 10 of BM25 and of dense retrieval (464 rows), `claude-haiku-5-5`'s grades agreed with TREC's on "relevant" for 84% of the rows TREC judged (Cohen's kappa 0.57), were the more lenient (27% of the rows TREC judged not relevant got 2 or 3), and named the same winner of the two rankings on 21 of the 24 queries TREC's judgments decide; they reproduce the size of a gap less well (Kendall's tau 0.32 between the per-query differences). They are a good stand-in for telling which ranking is better on queries nobody has judged, and a weaker one for absolute nDCG. The study (`chloedb-server/results/judge/`) sent the prompts through Claude Code, where the model thinks before most answers; the endpoint asks without thinking. ## The on-call agent > **Experimental.** The on-call agent (`/v1/admin/oncall/*`) has no compatibility promise yet: its routes, settings and what it stores may change in any release, with no upgrade path promised. Its answers carry `x-chloedb-experimental`, and `GET /v1/catalog` marks its routes ([compatibility](../compatibility.md#experimental-features)). `POST /v1/admin/oncall` (admin) has a Claude model look into a firing alert (`{"alert": ""}`) or a question about the cluster (`{"question": "why did p99 double at 14:05?"}`) the way an operator would, and report what it found and what it would do. It has the read-only views of this page as tools: health (`fleet` for every coordinator's), the cluster's shards and copies, each copy's load, the host, the alerts and one rule's events, the events timeline, the running, slow and recent queries and the statistics by statement, this server's log lines, the metrics series and the contain rules. Each tool call is a request to the server's own route with the caller's key, through the same checks and audit as any other, named `oncall` in the query log (`x-chloedb-app`), and the model sees at most 12,000 characters of each answer. It changes nothing. What it would do is a proposal: a contain rule (limit or refuse a statement or a key for a while), removing one, cancelling a running query, or silencing an alert. Each is kept for an admin to approve or reject, and can be approved for an hour; after that it is `expired`, so an action seen fit then is not applied to a cluster that has moved on. Approving one makes its request with the approver's key and the proposal's reason (`x-chloedb-reason: on-call proposal p3: `), so the audit log and the contain rule name the admin who approved it. ```sh curl -s localhost:7700/v1/admin/oncall -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' -d '{"alert": "p99_high", "note": true}' # {"run": "oc1762557300112", "answer": "Summary: one statement holds every core ...\nProposed actions: p1 ...", # "proposals": [{"id": "p1", "action": "contain", "what": "limit statement 9f3c... to 2 at once for 15 min", "why": "...", "state": "pending", ...}], # "steps": [{"tool": "alerts", "input": {"rule": "p99_high"}, "ok": true, "took_ms": 1.9}, ...], "usage": {...}} curl -s localhost:7700/v1/admin/oncall/proposals?state=pending -H "authorization: Bearer $ADMIN_KEY" curl -s -X POST localhost:7700/v1/admin/oncall/proposals/p1/approve -H "authorization: Bearer $ADMIN_KEY" curl -s -X POST localhost:7700/v1/admin/oncall/proposals/p1/reject -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' -d '{"reason": "a deploy is rolling back"}' ``` The report comes as a summary, the evidence (what each tool showed), the likely cause and how sure the model is, the proposals, and what to watch. `note: true` also writes it as a note on the events timeline. A run takes at most `max_steps` model calls (12 by default, 30 at most); the model, effort and key are the agent's. Approval is a person's, with an admin key: an approval by an agent is refused ([agents and administration](#agents-and-administration)). A run goes on in the server whether or not its caller waits: `"wait": false` answers `{"run": "oc...", "state": "running"}` at once, and `GET /v1/admin/oncall/runs/` shows it as it goes, with each tool call (what it asked, how long it took, and the first 4,000 characters of what the route answered), what the model wrote between them, and then its report and proposals. `POST /v1/admin/oncall/runs//stop` stops it before its next model call. `{"question": "...", "follows": ""}` asks a follow-up in the same conversation, so the model remembers what it looked at. `GET /v1/admin/oncall` says whether the server has a Claude key and lists the runs kept, newest first. The server keeps the latest 50 runs and 200 proposals beside its audit log (`.oncall.json`, or the file `CHLOEDB_ONCALL_STATE` names), so a restart loses neither; a run under way when it stopped is marked failed. ### In the command center **On-call agent** (under Operate, `g n`, an admin's) is the agent's page. Pick a firing alert and click **Investigate**, or ask a question (a few common ones are one click away); the options set the model, the effort, the model calls at most and whether the report goes on the timeline, and take a Claude key for the tab when the server has none (sent with each run, never kept). Each step shows as the agent takes it, with what it read in words, and a click opens what the route answered and a link to the view that shows the same. The report comes in its sections, each proposal as a card with what it does, why, the exact request it makes, and how long it can still be approved: **Approve** shows all that again before it applies it with your key, **Reject** takes a reason. Ask a follow-up under the report. The side lists the proposals waiting for an admin (the navigation counts them) and the investigations kept, with their follow-ups; **Copy** gives a conversation as Markdown, and the download as JSON. An alert's page has an **Investigate** button that starts a run on it. ![The on-call agent's page in the command center](../assets/img/strata-command-center-oncall.png) ## Agents over MCP An agent such as Claude Code, Claude Desktop or any client of the [Model Context Protocol](https://modelcontextprotocol.io) drives ChloeDB through tools: it lists the tables, reads their `CREATE TABLE` statements, checks a statement before it runs it, queries, writes, and looks up the syntax it needs in this documentation, which the server carries. `POST /v1/mcp` speaks the protocol's Streamable HTTP transport (versions 2025-06-18, 2025-03-26 and 2024-11-05), answering each message with JSON; `chloedb-server mcp` speaks it over stdin and stdout, for a client that starts its servers as commands, and sends each message to a server's `/v1/mcp`. ```sh # Claude Code, over HTTP: claude mcp add --transport http chloedb http://127.0.0.1:7700/v1/mcp --header "Authorization: Bearer $CHLOEDB_KEY" # or over stdio (the key from the environment, never on the command line): claude mcp add chloedb --env CHLOEDB_KEY=$CHLOEDB_KEY -- chloedb-server mcp --url http://127.0.0.1:7700 ``` | tool | does | route | |---|---|---| | `list_tables` | every table's `CREATE TABLE`, primary and shard keys, rank profiles, models | `GET /v1/tables` | | `describe_table` | one table's schema in full | `GET /v1/schema` | | `query` | one `SELECT`: its columns and at most `max_rows` rows (100 by default, 2,000 at most), saying when it cut them | `POST /v1/query` | | `explain` | how a `SELECT` runs, and with `hits` the top rows' scores and features | `POST /v1/explain` | | `check_sql` | binds a statement against the tables without running it: what it would do, or why it is refused | none: bound in the server | | `execute` | `INSERT`, `UPDATE`, `DELETE`, `CREATE`, `ALTER`, `DROP`, rank profiles | `POST /v1/sql` | | `write` | rows as JSON operations, in one transaction | `POST /v1/write` | | `import` | many rows at once into a table: CSV, TSV or JSON lines as text (`data`), or objects (`rows`); `create: true` makes the table from the rows first (admin key); answers how many it wrote and the columns it skipped | `POST /v1/import` | | `get_rows` | rows by primary key | `POST /v1/kv/get` | | `json_paths` | the keys a `JSON` field holds, with counts, types and common values | `GET /v1/tables//paths` | | `list_models` | the embedding models a `VECTOR` field may name | `GET /v1/models` | | `judge` | grades rows 0 to 3 for a query, by a Claude model ([relevance judgments](#relevance-judgments)) | `POST /v1/judge` | | `search_docs` | sections of the [query language](query-language.md) and [Build an app](build-an-app.md) that match some words | none: the documents are compiled in | | `list_feedback` | what people asked of the command center, with each item's marks as text ([feedback](#feedback)) | `GET /v1/feedback` | | `get_feedback` | one feedback item in full, and its screenshot as an image | `GET /v1/feedback/?shot=1` | | `update_feedback` | an item's status, priority, assignee or resolution; `if_status` takes it only if no one did first | `PATCH /v1/feedback/` | | `whoami` | the key's name and scope | `GET /v1/whoami` | A tool's call is a request to the route in its last column, made inside the server with the caller's `Authorization` header, so it passes every check that route makes: the key's scope decides what an agent may change (a read key's `execute` of an `INSERT` answers the 403 that `/v1/sql` does, as the tool's error, which the model reads), contain rules apply, the audit log names the key, and the latest queries name the client's app as `mcp` (or `mcp-stdio`). Give an agent a read key to explore, a write key to load rows, and an admin key only to make tables. A failed call answers its route's status and error (`403: ...`), so a model can fix its statement and try again; an argument a tool does not take is the protocol's error (-32602). An answer longer than 200,000 characters is cut, saying so. The server also offers the query language reference and the Build an app guide as resources (`strata://docs/query-language`, `strata://docs/build-an-app`) and, at `initialize`, a few lines of instructions on ChloeDB's SQL. It keeps no session (any coordinator answers any message), sends no requests of its own, and has no stream to open (`GET /v1/mcp` answers 405). A request from a browser page of another origin is refused, as on every route. ## Agents and administration An agent administers ChloeDB the way a person does, through the same routes, with three things a person does not need: a key that says what it may do, a way to ask before it changes what it may not change alone, and answers it can act on without reading their sentences. **What a route risks: its tier.** Every route has one, which `GET /v1/catalog` lists: | tier | what | who may, alone | |---|---|---| | 0 | reads: views, plans, dry runs | a key of the route's scope; an `ops` or `propose` key the server's views too | | 1 | bounded, and undone by itself: a contain rule (it expires), a query cancelled, an alert acknowledged or silenced (for a while), a note, a log filter, a profile, a scrub or verify | an `ops` or admin key, with a reason | | 2 | changes the cluster or its data, and can be undone: a plan applied, a spec, an upgrade, rank profiles, synonyms, alert rules, keys, rows | an admin key (an agent's says why, in `x-chloedb-reason`); an `ops` or `propose` key files a change request | | 3 | loses data or costs money: a shard removed, a promotion, a follow stopped, writes held, a key revoked, a tenant deleted, a cloud cluster made or deleted, vacuum, a `DROP TABLE`, a `DELETE` or `UPDATE` of every row | as tier 2, and an agent never does it alone, even with an admin key: the server refuses it `change_request_required` | **Keys for agents.** `POST /v1/admin/keys {"name": "oncall-bot", "scope": "ops", "expires_minutes": 60, "on_behalf_of": "dana"}` makes a key for an agent. Two scopes are for agents: `propose` reads what a read key reads and the server's views (health, the cluster, load, alerts, events, queries, logs, the audit log, plans and dry runs), and files change requests; `ops` does that, and the tier 1 actions alone. Neither writes a row nor calls a tier 2 or 3 route, nor the routes that copy every row out or carry other clusters' credentials (`/v1/export`, the hub, a tenant's SQL, a cloud's credentials). `"agent": true` marks a key of another scope as an agent's (a role key is one already), `expires_minutes` (5 at least) makes it last as long as one task, and `on_behalf_of` names the key the person it acts for, which the audit log keeps. A key an agent makes (with its admin key, or a person's key sent with an agent's headers) is an agent's too, for the person its maker acts for, expiring no later than its maker and within its maker's statement budget; an agent asking for `"agent": false` or for another person is refused (`change_request_required`), and it rotates agents' keys alone, since the new secret of a person's key would be a key outside its fence. A role key is kept as a read key with its role beside it, so a server from before roles admits it as a read key. `GET /v1/whoami` answers `may`: the tier a key may act at alone (`act_alone_up_to_tier`), whether it may file and approve change requests, and whether it must give a reason. **Who is an agent.** A request is an agent's when its key is an agent's (`agent`, or a role), when it comes through MCP (`/v1/mcp`, `chloedb-server mcp`) or the on-call agent, or when it says so in `x-chloedb-agent-model`, `x-chloedb-agent-session` or `x-chloedb-agent-run` (each at most 120 characters, kept in the audit log's `agent`). An agent with a person's admin key and none of these looks like a person: give agents agent keys. **Reasons and caps.** An agent's tier 1 request and up says why in `x-chloedb-reason` (or is refused `reason_required`), and an agent's contain rule lasts an hour at most, its silence two hours (`limit_exceeded`). The audit log names an agent's entries `actor: "agent"`, with its model, session, run and app (`agent`), and the person it acts for (`on_behalf_of`). **Error codes.** Every error answer carries, beside its sentence (`error`), a stable `error_code`, whether the same request may succeed later (`retryable`), a `hint` and the section of this page that explains it (`docs`): ```json {"error": "no such table: orders", "error_code": "table_not_found", "retryable": false, "hint": "list the tables the key may read (GET /v1/tables, or the list_tables tool)", "docs": "https://chloetech-ai.github.io/chloedb/site/docs/server.html#schemas"} ``` The codes are `unauthenticated`, `scope_refused`, `table_refused`, `reason_required`, `limit_exceeded`, `change_request_required`, `approval_refused`, `change_not_pending`, `plan_stale`, `table_not_found`, `column_not_found`, `query_invalid`, `schema_invalid` (the schema is refused), `value_invalid` (a row's value does not fit its field: a NaN in a vector, a word in an INT field), `table_altered` (an `ALTER TABLE` of the table committed while the statement ran, again until its deadline, and nothing was written: retryable), `idempotency_conflict`, `contained`, `overloaded`, `query_too_large` (422: the query alone needs half or more of `--query-memory-mb`, so sending it again fails the same way, where a query refused for what others hold is a 429 `overloaded`), `deadline_exceeded`, `cancelled`, `unavailable`, `write_in_doubt` (a write through a coordinator that may or may not be applied: send it again with the answer's `idempotency_key`; [Failover](#failover)), and a general one for each status (`not_found`, `conflict`, `too_large`, `unsupported_media_type`, `unprocessable`, `rate_limited`, `not_implemented`, `bad_request`, `internal`, `upstream`). The field is `error_code`, not `code`, which the Python and JavaScript clients read as their own class of error. A code is never renamed or reused, only added; `GET /v1/catalog` lists them with their hints. Errors answered before a route's handler runs have the same shape: a body that is not JSON (400), a missing or wrong content type (415), a body over its limit (413, naming the limits), a path no route matches (404), a method the route does not take (405), a connection past `--max-connections` (503 `overloaded`), and a write that failed partway through a coordinator, which also says `partial` and each shard's part (`shards`). Over gRPC the code travels in the metadata `chloedb-error-code`. A statement sent to `POST /v1/sql` or `POST /v1/query` that names a table, column or function that is not there, close to one that is, is answered with `fixes` too: `[{"label": "title for titel", "sql": "SELECT title FROM movies"}]`, the statement with the name replaced where it stands as a name, for each name the error suggests; nothing is run. The MCP tools end such an error with the first one (`Corrected statement: ...`). **Dry runs.** `POST /v1/admin/changes/preview {"method": "POST", "path": "/v1/admin/plan/apply", "body": {...}}` answers, for a change of any route, without changing anything: its `tier`, what it `would` do, whether it is `reversible` and its `undo`, its `blast` (what clients feel meanwhile), what it `affects` (for SQL, the rows a `DELETE` or `UPDATE` matches and a `DROP` loses, counted by the statement's own `WHERE`), the route's own `plan` where it has one (a plan of the cluster's shape, a Kubernetes spec, an upgrade, a statement bound against the tables), a `plan_id` and a `fingerprint`. **Change requests.** `POST /v1/admin/changes {"method", "path", "body"?, "reason", "what"?}` files a change for a person to approve: its dry run is kept with it, and it waits `pending` for an hour (`GET /v1/admin/changes?state=`, `GET /v1/admin/changes/`). A person with an admin key approves it (`POST /v1/admin/changes//approve`) or rejects it (`.../reject {"reason"}`), and whoever filed it may withdraw it (`.../withdraw`). An approval by an agent is refused (`approval_refused`), whatever its key: an agent never approves its own change or another agent's. Approving dry runs the change again, and when its plan differs from the one it was filed with (other steps, another table, twice the rows or half of them; a few rows more or less, up to 10, do not count), it is not applied but fails `plan_stale`, and the agent files it again. Applied, it is the approver's request, with the request's reason, audited as theirs and naming the change request (`change_request`). Every role key reads the change list, and the desk it is kept in (`.oncall.json`, readable by the server's user alone), so a change request carries no credential: the routes that make or show a key's secret (`/v1/admin/keys`, a key's rotation, `/v1/keys/own`, a connector's config, test and key), take another cluster's (the hub's connections) or a cloud's (its credentials and their checks), and those no role key calls, are refused as targets (`scope_refused`), and so is a body with a field named as a credential holds (a secret, token, password, `Authorization`, an API or private key). What it was answered is kept with any such field `(hidden)`. Change requests live beside the on-call agent's proposals, in the same list (`GET /v1/admin/oncall/proposals`), and the command center's **On-call agent** page lists both under **Waiting for an admin**, with each change's tier, what it touches, its undo and who filed it. **An agent's SQL.** An agent's `DROP TABLE`, `DROP` of a rank profile or function, `ALTER TABLE ... DROP`, and `DELETE` or `UPDATE` without a `WHERE` are refused `change_request_required`, even with an admin key: it dry runs the statement and files it. **The catalog.** `GET /v1/catalog?q=` lists every route of the server (read from the router itself, so it lists exactly the routes there are) with its methods, scope, tier, whether a role key may call it, its dry run and its MCP tool, and every error code. **Jobs, and waiting.** `GET /v1/admin/jobs?kind=` lists what runs in the background in one shape (`{kind, id, state, running, started_ms, done, of, eta_s, url}`): a plan being applied, slot moves, on-call runs, change requests waiting. `GET /v1/events?after=&wait_s=30` answers as soon as an event after that one comes, 30 seconds at most, so an agent waits on a job instead of polling. **Runbooks.** The [runbooks](runbooks.md) say what to do for each alert and fleet problem; the server compiles them in, `GET /v1/runbooks?for=` (or `q=`) finds one, and each fleet problem's `next` names its `runbook` and the read it makes (`api`). **Over MCP.** A role key or an admin key sees the operations tools beside the data tools: the reads (`health`, `cluster`, `load`, `system`, `alerts`, `events`, `queries`, `logs`, `timeseries`, `contain_rules`, `audit`, `catalog`, `jobs`, `runbook`), the plans (`plan_reshape`, `plan_kube`, `plan_upgrade`), change requests (`dry_run`, `propose_change`, `list_changes`, `get_change`) and the tier 1 actions, each with a reason (`contain`, `remove_contain`, `cancel_query`, `silence_alert`, `ack_alert`, `note`). A tool's error says its code and hint after the route's sentence (`403: ... [code scope_refused: ...]`). `chloedb-server mcp` names its session in `x-chloedb-agent-session`, and the model from `CHLOEDB_AGENT_MODEL`. **From a shell.** `chloedb-server admin` makes one request and prints its JSON (`--json` on one line), for a script or an agent without MCP, with `--url`, `--key` (or `CHLOEDB_URL`, `CHLOEDB_KEY`) and `--reason` (`CHLOEDB_REASON`): ```sh chloedb-server admin whoami chloedb-server admin health chloedb-server admin catalog contain chloedb-server admin preview POST /v1/sql '{"sql": "DELETE FROM logs WHERE ts < 1700000000000"}' chloedb-server admin --reason "old logs fill the disk" propose POST /v1/sql '{"sql": "DELETE FROM logs WHERE ts < 1700000000000"}' chloedb-server admin changes --state pending chloedb-server admin runbook disk-full chloedb-server admin call GET /v1/admin/jobs ``` It exits 0 when answered 2xx, 1 when refused or failed otherwise, 2 when refused for who the key is (`unauthenticated`, `scope_refused`, `reason_required`, `change_request_required`, `approval_refused`, ...), 3 when stale (`plan_stale`, `change_not_pending`: look again), 4 to retry later (a `retryable` code), and 5 when the server was not reached. --- # Operate a cluster This page runs ChloeDB as a production-shaped cluster on machines of your own, without Kubernetes: two shards, each held by three copies that elect their primary among themselves, a coordinator in front of them, a token that the servers send each other and API keys for clients. It then checks the cluster's health, loads and searches rows, kills a primary and watches the failover, writes checkpoints, and upgrades the cluster one server at a time while it serves. To make a database you already serve into shards on one machine, one command does it: `chloedb-server grow --db shop.chloedb --shards 3` ([grow](../chloedb/server.md#sharding-one-coordinator-many-shards)). This page builds a cluster with copies of each shard, which a production cluster needs. Everything starts on one machine, on loopback, so that each command runs as written. On virtual machines each copy is a machine of its own (or a systemd unit), and the addresses are theirs. On Kubernetes the operator does all of this for you ([on Kubernetes](../chloedb/server.md#on-kubernetes)). You need `chloedb-server` on your `PATH` ([install](../quickstart.md)), and `curl` and `python3`. ## The layout | server | what it holds | HTTP | gRPC | |---|---|---|---| | `s0a` | shard 0: its first primary | 7711 | 7721 | | `s0b`, `s0c` | shard 0: replicas | 7712, 7713 | 7722, 7723 | | `s1a` | shard 1: its first primary | 7714 | 7724 | | `s1b`, `s1c` | shard 1: replicas | 7715, 7716 | 7725, 7726 | | `coord` | no data: it routes each write to the shard that holds its row, and asks every shard for a search | 7700 | off | The copies of a shard talk to each other, and to the coordinator, over gRPC. Clients talk to the coordinator over HTTP. A shard elects a primary only while a majority of its copies answer, so three copies keep a shard working through the loss of any one of them. With two and failover on, losing either copy stops the shard's reads and writes for as long as that copy is down, not for a few seconds: its primary serves a read only while a majority of its copies answer it, and a write waits for a majority. Give a shard that must stay up a third copy ([failover](../chloedb/server.md#failover)). ## Tokens ```sh export CHLOEDB_CLUSTER_TOKEN=$(python3 -c 'import secrets; print(secrets.token_hex(32))') export ADMIN_TOKEN=$(python3 -c 'import secrets; print(secrets.token_hex(32))') ``` The cluster token is what the servers send each other: a primary to its replicas, the coordinator to the copies. Every server of the cluster gets the same one, and only it may make the calls between servers (shipping writes, changing the cluster map, sharing keys); clients never hold it. You use it yourself for one thing: adding a server to the cluster (a copy that replaces a dead one, a new shard), since the coordinator sends the server it adds this token, and so takes it, not the admin token, for that call ([a copy that does not come back](#kill-a-primary)). Every server reads it from `CHLOEDB_CLUSTER_TOKEN`. The admin token is the coordinator's `--token`, for you, the operator. Clients get API keys, made below. On virtual machines, keep both in each unit's environment file (`EnvironmentFile=`, mode 0600) rather than on the command line, where `ps` shows them. ## Start the copies Each copy is the same command with its own name, ports and, on its first start only, its part in replication: ```sh copy() { # copy NAME HTTP_PORT GRPC_PORT [ROLE FLAGS...] name=$1 http=$2 grpc=$3; shift 3 mkdir -p "$name/backups" && echo "$http $grpc" > "$name/ports" chloedb-server --db "$name/db.chloedb" --seq-no --failover-after-ms 2000 \ --listen 127.0.0.1:$http --grpc 127.0.0.1:$grpc --node-name "$name" \ --backup-dir "$name/backups" --start-apps off "$@" >> "$name/server.log" 2>&1 & echo $! > "$name/pid"; disown # the shell then says nothing when the copy is stopped } G=http://127.0.0.1 copy s0a 7711 7721 --replicas $G:7722,$G:7723 copy s0b 7712 7722 --replica --replicas $G:7721,$G:7723 copy s0c 7713 7723 --replica --replicas $G:7721,$G:7722 copy s1a 7714 7724 --replicas $G:7725,$G:7726 copy s1b 7715 7725 --replica --replicas $G:7724,$G:7726 copy s1c 7716 7726 --replica --replicas $G:7724,$G:7725 ``` - `--seq-no` numbers the database's writes, which is how a primary ships them to its replicas. It cannot be undone. - `--failover-after-ms 2000`: a replica that hears nothing from its primary for two seconds asks its shard's copies to elect it, and a primary that cannot reach a majority of its copies stops serving reads. Without it (the default, 0) a shard whose primary dies takes no writes until you promote a replica by hand. - `--replicas` makes a copy a primary that ships to the copies it names. `--replica --replicas` makes a replica, which takes only what its primary ships and refuses clients' writes, and names its shard's other copies, which it ships to once it is elected. - The role flags are for a copy's first start. A copy keeps its part (primary or replica, its term, the primary it follows) beside its database, in `db.chloedb.replication`, and a copy started again without `--replicas` or `--replica` takes it up again: that is how every restart on this page starts one, and a systemd unit's command leaves them out once the copy has started once. A replica started again with `--replicas` refuses to start, and says to use `--replica`. - `--node-name` names the copy in the coordinator's views and the log stores' rows; `--backup-dir` is where its checkpoints go. - `--start-apps off` keeps each server from starting the apps installed beside `chloedb-server` (the crawler, Sheets, ChloeCtx), which a cluster runs beside its coordinator, if at all ([apps on a cluster](apps.md)). On machines of their own, each copy listens on its machine's address (`--listen 10.0.0.11:7700 --grpc 10.0.0.11:7701`) and names the others by theirs. A server with a cluster token, a `--token` or an API key may listen beyond loopback; one with none of them refuses to. Between machines, serve every server over TLS (`--tls-cert FILE --tls-key FILE`), list the copies as `https://`, and give the servers that call them `--shard-ca FILE` when your certificates are not signed by a public authority ([security](../chloedb/server.md#security)). ## Start the coordinator ```sh CHLOEDB_TOKEN=$ADMIN_TOKEN chloedb-server --listen 127.0.0.1:7700 --grpc off --node-name coord --start-apps off \ --shards "$G:7721|$G:7722|$G:7723,$G:7724|$G:7725|$G:7726" >> coord.log 2>&1 & echo $! > coord.pid ``` `--shards` lists the copies' gRPC addresses: a comma between shards, and `|` between the copies of one shard. Which copy is the primary is not in the list: the coordinator asks each copy its part, and sends a shard's writes to the copy that answers as its primary. The first time, the coordinator gives every server the cluster map (each shard's copies, and its slots: 2,048 of the 4,096 each here), and every server keeps it beside its database. From then on the coordinator routes by the newest map its servers hold, so a coordinator started again on this same list, or on one copy of each shard, serves the cluster as it is now, after any changes ([changing the cluster while it serves](../chloedb/server.md#changing-the-cluster-while-it-serves)): a copy on the list that was replaced since, and does not answer, is left out, and its log says so. The coordinator holds no data and needs no `--db`: run two or more of them behind a load balancer, each with the same flags and `--peer-url` naming the address the others reach it at (`http://10.0.0.21:7700`), so that they find each other through the shards ([several coordinators](../chloedb/server.md#several-coordinators)). What you change on the coordinator lives on the shards too. Its alert rules and routes, the alerts' acknowledgements, silences and notes, the latest 2,000 entries of its audit log and its latest 5,000 events (the Timeline: copies down and back, new primaries, changes, notes) are kept on every copy (in `db.chloedb.coordinator.json`, beside the keys), and a coordinator started again takes them back before it serves, as it takes the keys: a restart, or a new coordinator on the same `--shards`, keeps them without a file of its own, and the Timeline after a rolling upgrade still shows the upgrade. `--alerts FILE` keeps the rules and routes in a file as well, and `--audit-log FILE` keeps every entry of the audit log rather than the latest 2,000; **Alerts** says where its rules are kept. Name the cluster for the people who change it: `--cluster-name` and `--environment production` (or `staging`, `dev`) on each coordinator, which the command center shows in its header; on production it asks for a reason before each change, which the audit log keeps. A cluster with no environment is shown as a sandbox when it is reached on this machine, as this one is, and changes ask for no reason. ## Check its health `GET /v1/cluster` is the coordinator's view of every shard and copy. This script prints the part an operator reads first, and is used for the rest of the page: ```python file=cluster.py """The cluster as its coordinator sees it: a line a shard, a line a copy. python3 cluster.py print it python3 cluster.py --ok exit 1 unless every shard and copy is ok and every copy serves reads python3 cluster.py --primary N the name of shard N's primary python3 cluster.py --replicas N the names of shard N's replicas python3 cluster.py --versions which servers run which version """ import json, os, sys, urllib.request req = urllib.request.Request("http://127.0.0.1:7700/v1/cluster", headers={"authorization": "Bearer " + os.environ["ADMIN_TOKEN"]}) cluster = json.load(urllib.request.urlopen(req, timeout=10)) shards = cluster["shards"] name = lambda c: c.get("name") or c["short"] arg = sys.argv[1:] if arg[:1] == ["--ok"]: good = all(s["state"] == "ok" for s in shards) and all( c["status"] == "ok" and c["serves_reads"] for s in shards for c in s["replicas"]) sys.exit(0 if good else 1) if arg[:1] == ["--primary"]: print(*[name(c) for c in shards[int(arg[1])]["replicas"] if c["role"] == "primary" and c["status"] == "ok"]) elif arg[:1] == ["--replicas"]: print(*[name(c) for c in shards[int(arg[1])]["replicas"] if c["role"] == "replica"]) elif arg[:1] == ["--versions"]: by = {} by.setdefault(cluster["coordinator"]["version"]["version"], []).append(cluster["coordinator"]["name"] or "coordinator") for s in shards: for c in s["replicas"]: by.setdefault((c.get("version") or {}).get("version", "?"), []).append(name(c)) for version, names in sorted(by.items()): print(" ".join(names) + ":", version) else: for s in shards: primary = [name(c) for c in s["replicas"] if c["url"] == s["primary"]] print(f"shard {s['shard']}: {s['state']}, {s['why']}; primary {primary[0] if primary else 'none'}") for c in s["replicas"]: print(f" {name(c)} {c['role'] if c['status'] != 'down' else ''} {c['status']}" + (" serves reads" if c["serves_reads"] and c["status"] != "down" else "")) ``` The cluster is ready once every copy answers and every replica has caught up with its primary: ```sh until python3 cluster.py --ok 2> /dev/null; do sleep 0.5; done python3 cluster.py ``` ```text output shard 0: ok, 3 of 3 copies answer; primary s0a s0a primary ok serves reads s0b replica ok serves reads s0c replica ok serves reads shard 1: ok, 3 of 3 copies answer; primary s1a s1a primary ok serves reads s1b replica ok serves reads s1c replica ok serves reads ``` A shard's `state` is `ok`, `degraded` (a copy down, the shard still serving), `no_writes`, `no_reads` or `down`, and `why` says it in a sentence. `GET /v1/health/fleet` sums up the whole cluster in one headline, with each problem's impact, what to do next and the [runbook](../chloedb/runbooks.md) for it; it is what the command center's Home page shows: ```sh curl -s localhost:7700/v1/health/fleet -H "authorization: Bearer $ADMIN_TOKEN" \ | python3 -c 'import json, sys; f = json.load(sys.stdin); print(f["status"], "|", f["headline"])' ``` ```text output ok | All 2 shards serve reads and take writes; 6 of 6 copies are up... ``` For a load balancer or a process supervisor, every server answers `GET /livez` (the process runs) and `GET /readyz` (it serves) without a credential. The command center is the coordinator's address in a browser, `http://127.0.0.1:7700`, which asks for the admin token or a key; `chloedb-server cc http://127.0.0.1:7700` is the same in a terminal, with the key in `CHLOEDB_KEY` or typed at its prompt. ## Keys for clients Give each client a key of its own, with the least scope it needs: here a write key for an application and a read key for Prometheus. Keys are made on the coordinator, and reach every copy of every shard within a few seconds: ```sh key() { # key JSON: make an API key, print its secret (shown this once) curl -s -X POST localhost:7700/v1/admin/keys -H "authorization: Bearer $ADMIN_TOKEN" \ -H 'content-type: application/json' -d "$1" | python3 -c 'import json, sys; print(json.load(sys.stdin)["secret"])' } export APP_KEY=$(key '{"name": "shop-app", "scope": "write", "expires_days": 90}') export MONITOR_KEY=$(key '{"name": "prometheus", "scope": "read"}') ``` Each copy keeps the keys, as SHA-256 digests and never the secrets, in `db.chloedb.keys.json` beside its database, so a coordinator started again takes them from its shards. The read key scrapes every server's `/metrics`, the copies' included. On a shard's primary, its replicas' state is there, by replica: ```sh until curl -sf localhost:7711/metrics -H "authorization: Bearer $MONITOR_KEY" -o s0a.metrics; do sleep 0.5; done grep -E '^chloedb_replica_(in_sync|behind)' s0a.metrics ``` ```text output chloedb_replica_in_sync{replica="http://127.0.0.1:7722"} 1 chloedb_replica_in_sync{replica="http://127.0.0.1:7723"} 1 chloedb_replica_behind{replica="http://127.0.0.1:7722"} 0 chloedb_replica_behind{replica="http://127.0.0.1:7723"} 0 ``` Scrape the coordinator and each copy as targets of their own, with the key in Prometheus's `authorization.credentials_file`. The coordinator's `/metrics` has its view of the cluster, a series a shard, the state its built-in alerts judge: `chloedb_cluster_copies`, `chloedb_cluster_copies_up` and `chloedb_cluster_copies_down`, `chloedb_cluster_copies_in_sync`, `chloedb_cluster_shard_majority` and `chloedb_cluster_shard_primary` (1 or 0), `chloedb_cluster_shard_term`, `chloedb_cluster_primary_changes_total` (its failovers and handovers), and `chloedb_cluster_copy_up{shard, copy, url, role}` a copy. A copy's own series carry no shard label: its `chloedb_copy_info{shard, node, role} 1` says which shard it serves, to join on, or add the label in the scrape config. `chloedb_docs` and `chloedb_segments` count every table of a copy's database (`chloedb_docs` is `/v1/health`'s `rows`), and `chloedb_table_docs{table}` each one. The coordinator's alerts go to a webhook, PagerDuty or Opsgenie ([alerts](../chloedb/server.md#alerts)); `--alert-webhook URL` sends them all to one URL. To page from Prometheus instead, or as well, start from the kit in [`chloedb-server/deploy/monitoring`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb-server/deploy/monitoring): `prometheus.yml` scrapes this page's coordinator and six copies with the key in a file, `chloedb-rules.yml` holds an alerting rule for each of the servers' built-in alerts (the same conditions and defaults, each with its runbook as `runbook_url` and the copy's `--node-name` in the copy-down alert), plus one for a target Prometheus cannot scrape, which sees a coordinator that is down, and `grafana-dashboard.json` is a dashboard to import (Dashboards, New, Import), its data source asked for on import. Check the rules with `promtool check rules chloedb-rules.yml` after changing a threshold or the disk rules' mount point. ## Load and search Making a table takes the admin token, and runs on every shard: ```sh curl -s localhost:7700/v1/sql -H "authorization: Bearer $ADMIN_TOKEN" -H 'content-type: application/json' \ -d '{"sql": "CREATE TABLE products (id KEYWORD PRIMARY KEY, title TEXT, category KEYWORD, price FLOAT)"}' \ | python3 -c 'import json, sys; print(json.load(sys.stdin).get("error", "made"))' ``` ```text output made ``` The application writes with its key. Each row goes to the shard whose slots hold its key, and the answer counts what each shard took. Give every write an idempotency key: when an answer is lost, or a shard's primary changes under it, the same request sent again with the same key is applied once ([when a write fails](../chloedb/server.md#when-a-write-fails)). ```sh python3 - > rows.json <<'EOF' import json titles = ["red wool sofa", "blue linen sofa bed", "oak dining table", "walnut coffee table", "green velvet armchair", "steel desk lamp", "rattan garden chair", "pine bookshelf"] ops = [{"op": "upsert", "table": "products", "doc": {"id": f"p{i}", "title": t, "category": t.split()[-1], "price": 100.0 + 10 * i}} for i, t in enumerate(titles)] print(json.dumps({"ops": ops, "idempotency_key": "load-2026-11-17"})) EOF curl -s localhost:7700/v1/write -H "authorization: Bearer $APP_KEY" -H 'content-type: application/json' -d @rows.json \ | python3 -c 'import json, sys; r = json.load(sys.stdin); print(r["written"], "rows:", ", ".join("shard %d %d" % (s["shard"], s["rows"]) for s in r["receipt"]["per_shard"]))' ``` ```text output 8 rows: shard 0 3, shard 1 5 ``` A search asks every shard, with the whole collection's BM25 statistics, so it ranks as one database would: ```sh curl -s localhost:7700/v1/sql -H "authorization: Bearer $APP_KEY" -H 'content-type: application/json' \ -d "{\"sql\": \"SELECT id, title FROM products WHERE MATCH(title, 'sofa') ORDER BY bm25(title, 'sofa') DESC LIMIT 5\"}" \ | python3 -c 'import json, sys; [print(*row, sep=" | ") for row in json.load(sys.stdin)["rows"]]' ``` ```text output p0 | red wool sofa p1 | blue linen sofa bed ``` [What a cluster does differently](../chloedb/cluster-limits.md) lists the few statements a coordinator refuses or runs another way. ## Kill a primary `s0a` is shard 0's primary. Kill it without warning, as a crashed machine would, and send a write for shard 0 straight away: ```sh kill -9 $(cat s0a/pid) row='{"ops": [{"op": "upsert", "table": "products", "doc": {"id": "p20", "title": "cherry side table", "category": "table", "price": 80.0}}], "idempotency_key": "order-p20"}' until curl -sf localhost:7700/v1/write -H "authorization: Bearer $APP_KEY" -H 'content-type: application/json' -d "$row" -o answer.json; do sleep 0.5; done python3 -c 'import json; r = json.load(open("answer.json")); print(r["written"], "row on shard", [s["shard"] for s in r["receipt"]["per_shard"]][0])' ``` ```text output 1 row on shard 0 ``` Until shard 0 has a new primary, about two seconds here, its writes are refused with 503 and an answer that says what happened and that the write is safe to send again: ```json norun {"error": "127.0.0.1:7721 (shard 0): tcp connect error", "error_code": "unavailable", "retryable": true, "hint": "a copy, a shard or a hosted model did not answer: send it again after Retry-After seconds", "docs": "https://chloetech-ai.github.io/chloedb/site/docs/server.html#failover"} ``` The loop above sends it again, with the same idempotency key, until a new primary takes it. A primary that freezes rather than dies (a stopped process, a long pause, a disk that hangs) stalls a write longer than a kill does. Its copies elect another one within about two seconds as before, but the elected copy takes writes only once the old primary's lease has run out (about two seconds more with `--failover-after-ms 2000`), and a write sent meanwhile is held rather than refused: in a drill on this page's cluster, with the primary stopped by `kill -STOP` under a steady writer, one write was held 6.8 s and then answered 200, and none failed. For those few seconds the coordinator shows the new primary as taking no writes. Leave it alone: it is waiting out the lease, and restarting it while the old primary is still frozen leaves the shard one copy of three, with no majority and no writes until a second copy answers. Shard 1's writes, and the searches of both shards, went on all along: a replica serves reads while its primary's last call found it caught up. Every write answered before the kill is on a majority of shard 0's copies (`--write-acks all`, the default, waits for every replica in sync and never fewer than a majority), and the elected copy holds all of them. The coordinator now sees `s0a` down and another copy as shard 0's primary: ```sh python3 cluster.py ``` ```text output shard 0: degraded, 2 of 3 copies answer (s0a down); the shard serves reads and takes writes; one more copy down stops its reads and writes; primary s0... s0a down ... shard 1: ok, 3 of 3 copies answer; primary s1a s1a primary ok serves reads s1b replica ok serves reads s1c replica ok serves reads ``` Bring `s0a` back with the command that started it, without its role flags. A copy that was its shard's primary starts again as a replica ("was its shard's primary: starts as a replica, until its shard's copies elect one", its log says), finds the primary its shard elected meanwhile, and follows it: it is sent what it missed, and serves reads once it has caught up. Started again with `--replicas`, as at its first start, it would start as the primary of its old term and log errors until the newer primary fenced it; so give the role flags on a copy's first start alone. ```sh copy s0a 7711 7721 until python3 cluster.py --ok 2> /dev/null; do sleep 0.5; done python3 cluster.py ``` ```text output shard 0: ok, 3 of 3 copies answer; primary s0... s0a replica ok serves reads ... ``` A shard of three copies with two of them down has no majority: it takes no writes and elects no primary until a second copy answers. Its reads go on only from a replica that still serves them. When a copy will not come back, replace it. Start an empty copy as its shard's copies were started (with `--replica --replicas` naming the others), then plan the repair: `POST /v1/admin/plan {"shards": [{"shard": 1, "copies": [the gRPC URLs the shard keeps, the new one among them]}]}` adds the copies it names that are new and removes those it leaves out, and changes nothing until it is applied. Adding a server takes the cluster token, which the coordinator sends to it: apply the plan with that token rather than the admin token, `CHLOEDB_URL=http://localhost:7700 chloedb-server admin --key "$CHLOEDB_CLUSTER_TOKEN" call POST /v1/admin/plan/apply @plan.json`, with the same body in `plan.json`. The command center's **Cluster** page plans it too ("Plan the repair"); there, Apply needs a sign-in with the cluster token. The [runbooks](../chloedb/runbooks.md#a-copy-is-down) say what to read and do for each alert. ## Checkpoints Copying a database's files while its server runs is not a backup: a copy can pair one version's manifest with another version's pages. A checkpoint is: the copy writes a consistent copy of its database into its `--backup-dir` while it goes on serving. Through the coordinator, ask one copy of each shard (any copy will do; a replica keeps the work off the primary): ```sh for c in s0b s1b; do curl -s -X POST localhost:7700/v1/admin/copies/checkpoint -H "authorization: Bearer $ADMIN_TOKEN" \ -H 'content-type: application/json' -d "{\"url\": \"$G:$(cut -d' ' -f2 $c/ports)\", \"name\": \"$c-before-upgrade\"}" \ | python3 -c 'import json, sys; r = json.load(sys.stdin); print(r.get("error") or "written by " + r["node"])' done ls s0b/backups s1b/backups ``` ```text output written by http://127.0.0.1:7722 written by http://127.0.0.1:7725 s0b/backups: s0b-before-upgrade s0b-before-upgrade.keys.json s0b-before-upgrade.slots s1b/backups: s1b-before-upgrade s1b-before-upgrade.keys.json s1b-before-upgrade.slots ``` Beside each checkpoint the copy writes its shard's cluster map (`NAME.slots`) and the cluster's API keys (`NAME.keys.json`: names, scopes and the hashes of their secrets), under the names a server serving the checkpoint reads. `POST /v1/admin/checkpoint {"name": "..."}` on the coordinator writes one on every shard's primary at once, all of one cluster map. A name is letters, digits, `.`, `_` and `-`, and an existing one is never overwritten. The command center writes one from a copy's menu on its **Cluster** page, and one of every shard from **Settings > Upkeep**. `GET /v1/admin/checkpoints` on the coordinator lists the checkpoints of every copy (name, size, when it was written, the shard and map epoch it is of), each shard's newest, and the names written on every shard under one cluster map, which are the sets a restore can go back to; **Settings > Upkeep > Backups** shows them. Copy the three files of each checkpoint off the machines: with `"layout": "dir"` a checkpoint is a directory of segment files, which a sync to object storage sends only the new ones of ([backups](../chloedb/server.md#backups)). To restore, stop the server and put the checkpoint in place of its database with `chloedb-server restore --from s0b/backups/s0b-before-upgrade --db s0b/db.chloedb`: it checks the checkpoint before it changes anything, moves the database's own files aside, puts the map beside it and merges the keys in. A copy's part in replication (`db.chloedb.replication`) is not in a checkpoint: start a restored copy with the role flags it had. The runbook [Restore from checkpoints](../chloedb/runbooks.md#restore-from-checkpoints) restores a whole cluster, a shard or one copy this way, and [restoring a checkpoint](../chloedb/server.md#restoring-a-checkpoint) says what the command does. There is no point-in-time recovery between checkpoints. ## Upgrade one server at a time A rolling upgrade keeps the cluster answering searches and taking writes, one server at a time: 1. In each shard, the replicas first, one at a time: stop it, start it again on the new binary, and wait until it has caught up and serves reads. A replica must not be older than its primary, which may write what an older version cannot read. 2. Then hand the shard's primary over to an upgraded replica (`POST /v1/admin/shards//promote`), and upgrade the old primary, now a replica, as the others. 3. The coordinators last, one at a time. While versions are mixed, the cluster serves what the oldest server involved speaks, and [versions and compatibility](../compatibility.md#a-cluster-of-mixed-versions) says, release by release, what has an order of its own. Read the [changelog](../../CHANGELOG.md) of every release you skip. On each machine, the new binary is the release's archive, checked against its `.sha256`: ```sh # install v=0.3.11 p=linux-x86_64 curl -fLO https://github.com/chloetech-ai/chloedb-releases/releases/download/chloedb-server-v$v/chloedb-server-$p.tar.gz curl -fLO https://github.com/chloetech-ai/chloedb-releases/releases/download/chloedb-server-v$v/chloedb-server-$p.tar.gz.sha256 sha256sum -c chloedb-server-$p.tar.gz.sha256 && tar xzf chloedb-server-$p.tar.gz sudo install chloedb-server-$p/chloedb-server /usr/local/bin/chloedb-server # where the unit runs it from ``` From 0.3.8, `gh attestation verify` checks that the release workflow built the archive, before you install it on every machine: [checking what you download](../../SECURITY.md#checking-what-you-download). Here the new binary is the one on your `PATH` already, so the upgrade is a rolling restart in the same order, which is how you rehearse one. `restart` stops a copy with SIGTERM (it ends the requests under way first), starts it again without role flags, waits until the copy's own `/v1/health` says it serves reads (a replica does once it holds its primary's last transaction), and then until the coordinator sees the whole cluster well. Wait for both before the next copy: two copies of a shard down at once leave it without a majority. `handover` makes a copy its shard's primary: ```sh restart() { # restart NAME kill $(cat $1/pid); while kill -0 $(cat $1/pid) 2> /dev/null; do sleep 0.2; done copy $1 $(cat $1/ports) until curl -sf localhost:$(cut -d' ' -f1 $1/ports)/v1/health -H "authorization: Bearer $MONITOR_KEY" \ | python3 -c 'import json, sys; sys.exit(0 if json.load(sys.stdin)["replication"]["serves_reads"] else 1)' 2> /dev/null; do sleep 0.5; done until python3 cluster.py --ok 2> /dev/null; do sleep 0.5; done } handover() { # handover SHARD NAME curl -sf -X POST localhost:7700/v1/admin/shards/$1/promote -H "authorization: Bearer $ADMIN_TOKEN" \ -H 'content-type: application/json' -d "{\"url\": \"$G:$(cut -d' ' -f2 $2/ports)\"}" > /dev/null until [ "$(python3 cluster.py --primary $1)" = "$2" ]; do sleep 0.5; done } for shard in 0 1; do primary=$(python3 cluster.py --primary $shard) replicas=$(python3 cluster.py --replicas $shard) for r in $replicas; do restart $r; done handover $shard ${replicas%% *} restart $primary done python3 cluster.py --versions ``` `--versions` lists which servers run which version: halfway through a real upgrade it shows two. The coordinator goes last. With one coordinator, its clients are refused for the second it takes to start again; with several behind a load balancer, restart them one at a time, each with `--drain-ms 5000`, so that `/readyz` answers 503 for five seconds after SIGTERM and the load balancer sends it nothing more before it stops: ```sh kill $(cat coord.pid); while kill -0 $(cat coord.pid) 2> /dev/null; do sleep 0.2; done CHLOEDB_TOKEN=$ADMIN_TOKEN chloedb-server --listen 127.0.0.1:7700 --grpc off --node-name coord --start-apps off \ --shards "$G:7721|$G:7722|$G:7723,$G:7724|$G:7725|$G:7726" >> coord.log 2>&1 & echo $! > coord.pid until python3 cluster.py --ok 2> /dev/null; do sleep 0.5; done curl -s localhost:7700/v1/sql -H "authorization: Bearer $APP_KEY" -H 'content-type: application/json' \ -d '{"sql": "SELECT COUNT(*) FROM products"}' | python3 -c 'import json, sys; print(json.load(sys.stdin)["rows"][0][0], "rows")' ``` ```text output 9 rows ``` Every row is there. Under writes, a replica's restart costs the clients nothing: its shard's writes wait for the copies in sync, and reads go to the other copies. A handover holds the shard's writes for a moment, a second at most, while the new primary catches up: the coordinator sends a write that meets it on to the new primary, and a write that was in flight as the primary changed may be answered 409, in doubt, which the same request with the same idempotency key settles. ## Next - [Runbooks](../chloedb/runbooks.md): what to read and do for each alert and each problem the fleet view names. - [chloedb-server](../chloedb/server.md): every flag; [replication](../chloedb/server.md#replication-a-primary-and-its-replicas), [failover](../chloedb/server.md#failover) and [slots](../chloedb/server.md#slots) in depth; adding shards and copies while the cluster serves. - [Security model](../chloedb/security.md): what the tokens and keys protect, and what to set before a cluster holds data that matters. - [Versions and compatibility](../compatibility.md): what mixes in a cluster during an upgrade. --- # What a cluster does differently A coordinator over shards ([sharding](server.md#sharding-one-coordinator-many-shards)) answers most requests as one server does: the tests run every query kind against three shards and one database and compare the answers. This page lists what it refuses, and what it does in another way, so that nobody finds out in production. A table placed by a column (`OPTIONS(shard_by = '...')`, [tables on shards](server.md#tables-on-shards)) has a few differences of its own, listed after. `POST /v1/sql/check` with `{"sql": ..., "params": ...}` says whether a statement will run on the deployment it is sent to, without running it: `{"runs": true, "deployment": "cluster", "kind": "write", "notes": [...]}`, or `runs: false` with the `error` it would get. A pipeline's CI can send its statements to the cluster it deploys to, with a key of every table, a read key included (a key limited to tables is refused). ## Refused on a cluster | what | on one server | on a cluster | instead | |---|---|---|---| | Graph walks over a `VECTOR` column (`REACHABLE(emb, ...)`, `ppr(emb, ...)` over the nearest-neighbour graph) | run | refused: the graph is each shard's own index | walk an `EDGES` column or an edge table, or run it on a server that holds the whole table | | `ALTER TABLE ... DROP COLUMN` | runs | refused: the coordinator's plans name columns by place | add a column and stop reading the old one | | `INSERT ... ON CONFLICT DO UPDATE` whose rows go to several shards | runs | refused (400) | one statement per row or per shard, or `INSERT OR REPLACE` | | The relevance autopilot (`POST /v1/relevance/autopilot`) | runs | refused: it replays queries on one snapshot | run it on a server with a copy of the tables | | `/v1/export` of the database as SQLite (`format=sqlite`) | the admin's | refused: a coordinator holds no files | `format=parquet`, `jsonl`, `csv` or `arrow` export one table's rows from a cluster | | `EXPLAIN` through `/v1/sql` | refused on both | | `POST /v1/explain` | | `CREATE RECOMMENDER` over an events table that is not placed by its user column, on a coordinator of several shards | runs | refused: each user's events are counted in order, on one shard | create the events table with `OPTIONS(shard_by = '')` and load its events again ([below](#graphs-and-recommenders)) | ## Different on a cluster - **`FULL JOIN`** runs on the coordinator over every row of both sides, which it reads whole from the shards (a `JOIN` or `LEFT JOIN` reads the second side's rows by the first side's join values only); it answers as one database does. - **A write across shards is one transaction a shard, not one over all.** The coordinator checks each shard's part first and writes nothing when one refuses; what can still fail partway, and how to finish it with the idempotency key, is in [when a write fails](server.md#when-a-write-fails). - **`UPDATE ... LIMIT n` and `DELETE ... [ORDER BY ...] LIMIT n`** are two steps: the coordinator reads the keys of the rows the statement's `WHERE`, `ORDER BY` and `LIMIT` pick (over every shard), then runs the statement without its `LIMIT` over those keys alone (`WHERE (...) AND key IN (...)`). A row changed in between so that it no longer matches is left alone, so fewer than n rows may change. The table needs a primary key, and the `LIMIT` is at most 10,000. - **An `UPDATE` or `DELETE` whose `WHERE` has a subquery** (`WHERE id IN (SELECT ...)`, `NOT EXISTS (...)`), which reads rows of other shards, is two steps the same way: the coordinator reads the keys of the rows its `WHERE` picks over every shard, then runs it over those keys alone (`WHERE key IN (...)`, the subquery read once, in the first step). Without a `LIMIT` it writes at most 10,000 rows, and one that picks more is refused, with nothing written: narrow its `WHERE`, or run it in parts. One whose `WHERE` reads only its own row (a `TEXT` column compared with `=`, `LIKE`) runs on each shard, as any write does. - **`INSERT ... ON CONFLICT DO NOTHING`** goes as an `insert_if_absent` operation (protocol 21: a shard of an older version refuses it as an unknown operation). **`ON CONFLICT DO UPDATE`** runs as written on the one shard its rows go to. - **`INSERT ... SELECT` and `CREATE TABLE ... AS SELECT`** run their `SELECT` over every shard (one that does not answer fails the statement), then make the table on every shard as `CREATE TABLE` does, then write the rows as `INSERT`s of 500 rows each through the coordinator, one row each for `ON CONFLICT ... DO UPDATE`: each `INSERT` is a write of its own, so a failure part way leaves the rows written before it, and a table made for rows that failed is dropped. When every shard speaks protocol 22 and the `SELECT` reads one table's rows each by itself (columns and a `WHERE`, with no `GROUP BY`, aggregate, `ORDER BY`, `LIMIT`, ranking or join), into a table placed by its key, the rows skip the coordinator: each shard's primary runs the `SELECT` over its own rows and writes each row to the shard its slot is on, in writes of 1,000 rows (`RunTask`), and only the counts come back. A `GROUP BY` of one KEYWORD or INT column, with counts and aggregates (and `HAVING`, but no `ORDER BY` or `LIMIT`), into a table whose key is that column runs so too, in two stages when every shard speaks protocol 23: each shard sums its own rows into partial groups and sends each to the shard of its group's key (`Exchange`), then each shard merges the groups it was sent and writes them, so neither the rows nor the groups pass through the coordinator. The rows written are the same, and so is what a failure leaves; a `CREATE TABLE ... AS SELECT` goes this way only when its columns' types are known before its rows are (each a column of a table it reads, a `CAST`, a count or another expression of a number, BOOL or TIMESTAMP, or defined by the statement), as the table is made first. `CHLOEDB_TASKS=off` on the coordinator sends every such statement through it as before ([query language](query-language.md#rows-from-a-select-insert--select-and-ctas)). The table a `CREATE TABLE ... AS SELECT` makes needs a primary key the statement names (`CREATE TABLE t (PRIMARY KEY (id)) AS SELECT ...`) or `OPTIONS(shard_by = ...)`, since the coordinator places each row on a shard by it: one without is refused before its `SELECT` runs, and `POST /v1/sql/check` says so. On one server the rows are one transaction, and a table needs no key. - **DDL** (`CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`, rank profiles, functions) runs on every shard, one change a shard: a shard that fails leaves the others changed, and the statement is sent again with `IF NOT EXISTS`, `IF EXISTS` or `OR REPLACE`. `ALTER TABLE ... ADD COLUMN c ... NOT NULL` without a default is refused by each shard that has rows, and the error counts every such shard's rows. - **A SQLite or Parquet import that creates its table** creates it on every shard by `CREATE TABLE` through the coordinator, as its plan (`plan=true`) says. - **Exports**: `GET /v1/export?format=jsonl|csv|arrow|parquet&tables=T` reads the table by a scroll over every shard, with read on the table. Each page is read from the shards as they are then, not one snapshot of all of them: a write during the export may or may not be in it. Arrow is one batch built in memory (at most 1,000,000 rows); Parquet is written a page at a time and keeps the table's schema. - **Rank-log export and interleaving credit** (`/v1/rank_log/export`, `/v1/rank_log/interleaving`) run their queries over every shard, each read whole by a scroll, rather than from one snapshot: a request logged during the export may be left out or come with part of its events. - **Conditional writes** (`if_seq_no`, `seq_no()`) need every shard to number its writes alike (one replica, or a primary its replicas follow), and answers carry each shard's number (`seq_nos`), not one. - **Write receipts** count per shard (`receipt.per_shard`); a shard from before protocol 21 does not count, and its counts are `null`. A strict write goes only to shards of protocol 21. ## Graphs and recommenders - **Graph walks** (`REACHABLE`, `PATH`, `hops()`, `ppr()`) over an `EDGES` column or an [edge table](query-language.md#edge-tables) run on the coordinator: it runs the same walk one database runs, over what it has read so far, and reads what the walk is missing in one round of reads by key over every shard (keys in batches of 2,000, four reads at a time), then walks again, until nothing is missing. `ppr()` over an edge table whose ends both `REFERENCES` the table walked counts a row's edges first and reads them only to push it ([graphs](graphs.md#on-a-cluster)). `REACHABLE` and `hops()` take about one round per hop, `PATH` one per hop from either end, `ppr()` one each time its pushes reach rows it has not read. Each shard is then given the walk's answer (hops, place on the path, score) for its own rows, and the rest of the query (filters, `bm25`, `GROUP BY`, joins) runs as for any query. The plan says `walked by the coordinator in N rounds`, and the answer is one database's, but for two things: `PATH` may pick another path of the same length, and `ppr()` scores may differ in the last digits, since it pushes rows in the order it met them (more when it adapts its own `eps`). A walk is refused past `max_nodes` rows, as on one database, and after 256 rounds. - **A coordinator of one shard** that holds every slot (no move in progress) sends graph queries to that shard, which walks them itself. - **Joins along links** (`JOIN items b ON b.cooc = a.id`, rows that point at a key) run on a cluster too: each shard answers one hop in by key from its own rows' edges, whatever shard the key's row is on. - **Recommenders** run when the events table is placed by its user column (`OPTIONS(shard_by = 'usr')`). `CREATE RECOMMENDER` runs on every shard, and each shard counts the events it holds, as they are written, in its own rows of the counts table (keys that end with its slot map's epoch and shard). `recommend(...)` reads the counts summed over the shards (`sum(next)`, `sum(co)` and `sum(n)` grouped by item, and every row of the user's), ranks as one database does, and runs the query with each call as `ranked(...)` of the keys; the plan says `counts summed over the shards`. So a counts table read directly on a cluster holds each shard's part, not the totals. After a move of slots, the shards that take a user's events count them in new rows of their own, and a user's recent events are those of all their rows; `CREATE OR REPLACE RECOMMENDER` counts everything again. - **Kept whole on every shard:** not yet. An edge table is placed by its key like any table, so a walk over it reads by key each round. Keeping a small edge table whole on every shard would let each shard walk it alone; that is next. ## A table placed by a column (`shard_by`) A row goes to the shard of its `shard_by` value, not of its key. So: - **A primary key is unique across the shards for `INSERT`.** Before it writes, the coordinator asks every shard's primary whether it holds the keys being inserted (one read by key a shard, for the whole request), and refuses a key another shard holds (409, naming the shard and the row's value of the column). Two inserts of one key through one coordinator wait for each other. Two coordinators inserting one key at the same moment with different `shard_by` values are not ordered by this check, and can both succeed: send the inserts of one key through one coordinator, or give the table a `shard_by` equal to the key's own placement. - **`INSERT OR REPLACE` (upsert) replaces a row only on the shard of its `shard_by` value.** An upsert that gives an existing key another value of the column writes a second row there and leaves the old one (as Elasticsearch's custom routing does): change the column by deleting the row first. - **`ON CONFLICT DO NOTHING`** passes over a key that another shard holds; **`DO UPDATE`** of a key that another shard holds under another value of the column is refused (409), since it would insert a second row. - **Writes by key give the column's value as `"routing"`.** A `set`, `add` or `delete` whose routing places it on a shard that has no row with the key is refused (404, naming the routing and the column) rather than answered `written: 0`; `"if_missing": "skip"` passes over it as before. `DELETE /v1/kv/T/K` without `routing` on such a table is refused (400). - **The column cannot change:** `UPDATE` of it, and `set` or `add` on it, are refused. A row that moves is a delete and an insert. - **Queries ask every shard,** as for any table. --- # Back up, restore and upgrade Before ChloeDB holds data someone depends on, whoever runs it will ask three things. How is it backed up? How is a backup put back after a bad write or a lost disk? How is it upgraded, and rolled back if the new version misbehaves? This page answers all three for one server and runs every step. The same page runs in CI on every change, so the commands and what they print are rehearsed. A cluster does the same per copy: see [Operate a cluster](operate-cluster.md#checkpoints) and the [restore runbook](../chloedb/runbooks.md#restore-from-checkpoints). You need `chloedb-server` on your `PATH` ([install](../quickstart.md)), and `curl` and `python3`. ## A server with a backup folder `--backup-dir` names the folder its checkpoints go to. Put it on another disk, or sync it off the machine (below), since a backup on the database's own disk goes with that disk. ```sh mkdir -p backups chloedb-server --db ./shop.chloedb --backup-dir ./backups --listen 127.0.0.1:7700 --grpc off --start-apps off > server.log 2>&1 & echo $! > server.pid until curl -sf http://127.0.0.1:7700/v1/health > /dev/null; do sleep 0.2; done export ADMIN_KEY=$(curl -s -X POST localhost:7700/v1/admin/keys -H 'content-type: application/json' \ -d '{"name": "admin", "scope": "admin"}' | python3 -c 'import json, sys; print(json.load(sys.stdin)["secret"])') ``` A table and a thousand orders to keep safe: ```sh curl -s localhost:7700/v1/sql -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' \ -d '{"sql": "CREATE TABLE orders (id KEYWORD PRIMARY KEY, customer KEYWORD, total FLOAT)"}' > /dev/null python3 - <<'EOF' > orders.json import json ops = [{"op": "upsert", "table": "orders", "doc": {"id": f"o{i}", "customer": f"c{i % 40}", "total": float(i % 97)}} for i in range(1000)] print(json.dumps({"ops": ops})) EOF curl -s localhost:7700/v1/write -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' -d @orders.json \ | python3 -c 'import json, sys; print(json.load(sys.stdin)["written"], "rows written")' ``` ```text output 1000 rows written ``` ## Back up Copying the database's files while the server runs is not a backup: a copy can pair one version's manifest with another's pages ([why](../chloedb/server.md#backups)). A checkpoint is a consistent copy, made while the server serves, and checked against its checksums before it is kept: ```sh curl -s localhost:7700/v1/admin/checkpoint -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' \ -d '{"name": "nightly"}' | python3 -c 'import json, sys; c = json.load(sys.stdin)["checkpoint"]; print(c["name"], c["live_docs"], "rows")' ``` ```text output nightly 1000 rows ``` Run it from cron or a systemd timer with a dated name (`shop-$(date +%F)`), and list what is kept with `GET /v1/admin/checkpoints`. A directory checkpoint (`"layout": "dir"`, `"link_from"` the one before) shares the files that did not change with the one before, so syncing each one to object storage sends only what changed ([how](../chloedb/server.md#backups)). ## Restore after a bad write Someone deletes the wrong rows: ```sh curl -s localhost:7700/v1/sql -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' \ -d "{\"sql\": \"DELETE FROM orders WHERE customer = 'c7'\"}" > /dev/null curl -s localhost:7700/v1/sql -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' \ -d '{"sql": "SELECT COUNT(*) FROM orders"}' | python3 -c 'import json, sys; print(json.load(sys.stdin)["rows"][0][0], "rows")' ``` ```text output 975 rows ``` Stop the server, put the checkpoint in place of its database, and start it again with the flags it had. `restore` copies the checkpoint and checks every checksum before it changes anything, and moves the database it replaces aside rather than deleting it, so a restore can be undone too: ```sh kill $(cat server.pid) && while kill -0 $(cat server.pid) 2> /dev/null; do sleep 0.2; done chloedb-server restore --from ./backups/nightly --db ./shop.chloedb ``` ```text output restored ./shop.chloedb from the checkpoint ./backups/nightly (one file): ... ... ``` ```sh chloedb-server --db ./shop.chloedb --backup-dir ./backups --listen 127.0.0.1:7700 --grpc off --start-apps off >> server.log 2>&1 & echo $! > server.pid until curl -sf http://127.0.0.1:7700/v1/health > /dev/null; do sleep 0.2; done curl -s localhost:7700/v1/sql -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' \ -d '{"sql": "SELECT COUNT(*) FROM orders"}' | python3 -c 'import json, sys; print(json.load(sys.stdin)["rows"][0][0], "rows")' ``` ```text output 1000 rows ``` The admin key still works: the server's keys are kept beside its database, and `restore` merges those kept with the checkpoint into them (a key revoked since stays revoked). What a checkpoint does not carry is listed under [Restoring a checkpoint](../chloedb/server.md#restoring-a-checkpoint): the log store, connectors' settings, and a coordinator's own state. Writes made after the checkpoint are not in it. ChloeDB has no point-in-time recovery yet, so take checkpoints as often as you can afford to lose writes. ## Upgrade, and roll back An upgrade is a stop and a start with the new binary on the same `--db`. [Versions and compatibility](../compatibility.md) says what each version promises about the file format: a newer server opens an older database, and once it has written to it an older one may not. So the order is: checkpoint, stop, start the new version, check. ```sh curl -s localhost:7700/v1/admin/checkpoint -H "authorization: Bearer $ADMIN_KEY" -H 'content-type: application/json' \ -d '{"name": "before-upgrade"}' > /dev/null kill $(cat server.pid) && while kill -0 $(cat server.pid) 2> /dev/null; do sleep 0.2; done # Install the new version here, then start it with the same flags: chloedb-server --db ./shop.chloedb --backup-dir ./backups --listen 127.0.0.1:7700 --grpc off --start-apps off >> server.log 2>&1 & echo $! > server.pid until curl -sf http://127.0.0.1:7700/v1/health > /dev/null; do sleep 0.2; done curl -s localhost:7700/v1/health -H "authorization: Bearer $ADMIN_KEY" | python3 -c 'import json, sys; h = json.load(sys.stdin); print(h["status"], h["docs"], "rows")' ``` ```text output ok 1000 rows ``` To roll back, stop the new version, install the old one, and restore `before-upgrade` with the old version's `chloedb-server restore`, as above. Writes made between the upgrade and the rollback are not in that checkpoint, so decide how long you watch the new version before you let writes depend on it. A cluster upgrades one server at a time while it serves: see [Upgrade one server at a time](operate-cluster.md#upgrade-one-server-at-a-time). ## An embedded database A program that opens the database file itself (Python, JavaScript, Rust, Java) backs it up the same way, without a server: `db.checkpoint("backup.chloedb")` in Python writes a consistent, checked copy while the database is open and in use ([Python](../chloedb/python.md)). Restore by opening the copy in place of the file, with the program stopped. A database closed with `db.close()` is whole in its file, so a copy of a closed file is a backup too. ## ChloeCtx's stores `chloectx backup DEST`, run in a project's directory, copies that project's store while sessions go on ([how](../chloectx/setup.md)). Stores live under `~/.local/share/chloectx/projects/`, and they are transcripts of your sessions: back them up to a place only you can read. --- # Runbooks What to do when an alert fires or the fleet view names a problem, written for an operator and for an agent alike. Each runbook names the alerts (`GET /v1/alerts`) and fleet problems (`GET /v1/health/fleet`, each problem's `id`) it is for, then the steps: what to read first, what an `ops` key may do alone (tier 1), and what needs a person's approval (tier 2 and 3, filed as a change request with `POST /v1/admin/changes`). The tiers are explained in [chloedb-server](server.md#agents-and-administration). The server compiles this page in: `GET /v1/catalog` lists the routes the steps name, the MCP tool `runbook` finds a runbook by an alert's or a problem's id (`runbook {"for": "copy-down"}`), and each fleet problem's `next.runbook` names the one to read. The last section, on upgrading servers outside Kubernetes, is for no alert. ## Queries are slow For: `p99`, `p99-jump`, `p99_recovered` 1. Read where the time goes: `GET /v1/queries/slow` (tool `queries`, `which: slow`) and `GET /v1/queries/stats` group the slowest statements by their fingerprint; `GET /v1/load` shows each server's CPU and queue. 2. Read what changed around the jump: `GET /v1/events?from=` (tool `events`): a plan applied, a primary changed, a copy down, a rollout. 3. One statement or one key holding the cores (tier 1, an `ops` key with a reason): limit it with a contain rule, `POST /v1/admin/contain {"match": {"fingerprint": "..."}, "action": "limit", "concurrency": 2}` (tool `contain`); an agent's rule lasts an hour at most. 4. One query running for minutes (tier 1): cancel it, `DELETE /v1/queries/` (tool `cancel_query`). 5. The cluster is short of CPU for its load (tier 2): plan more copies or shards, `POST /v1/admin/plan` (tool `plan_reshape`), and file the plan as a change request. ## Searches fail For: `errors`, `availability`, `5xx`, `error_ratio`, `error_ratio_recovered`, `partial-answers`, `key-failing` 1. Read which statements fail and where: `GET /v1/queries/recent?outcome=failed` and `GET /v1/logs?level=error` (tools `queries`, `logs`). Each error answer carries an `error_code` (`GET /v1/catalog` lists them): `query_invalid` and `table_not_found` are a client's, `unavailable` and `internal` the cluster's. 2. Errors of one client (`key-failing`): tell the key's owner; nothing to change on the server. 3. Shards that do not answer (`partial-answers`, `unavailable`): follow "A copy is down" below. 4. Errors after a change: read `GET /v1/events` and `GET /v1/admin/audit` for what changed, and file the change that undoes it (each dry run's `undo` says which) as a change request. ## Queries are refused For: `rejected`, `query-memory`, `key-flood`, `contained` 1. Read what is refused and why: `GET /v1/queries` (running now, grouped by key and statement) and `GET /v1/admin/contain` (the contain rules in force; tool `contain_rules`). An answer refused by a contain rule has code `contained`. 2. One key crowds out the others (tier 1): limit the key, `POST /v1/admin/contain {"match": {"key": "..."}, "action": "limit", "concurrency": 4}`, and tell its owner. 3. A contain rule that refuses too much (tier 1): remove it, `DELETE /v1/admin/contain/` (tool `remove_contain`). 4. The load is real and lasting (tier 2): raise `--max-concurrent` or `--query-memory-mb` in the spec (`POST /v1/admin/kube/plan`, then a change request), or add copies. ## A copy is down For: `copy-down`, `copy-silent`, `under-replicated`, `shard-no-majority`, `copies`, `shards`, `coordinators_gone` 1. Read which copy, since when, and what else happened: `GET /v1/health/fleet` (tool `health`), then `GET /v1/events?kind=copy_down,primary_changed` and the copy's own lines from the log stores, `POST /v1/logs/query {"sql": "SELECT ts, level, message FROM logs WHERE node = '' ORDER BY ts DESC LIMIT 200"}` (on a coordinator it searches every copy's store; `GET /v1/logs` has the coordinator's own lines only). 2. A copy that restarts by itself (a pod killed for memory, a rollout): wait for it, `GET /v1/events?after=&wait_s=30` answers as soon as its next event comes. Silence the alert meanwhile (tier 1, two hours at most for an agent): `POST /v1/alerts/copy-down/silence {"minutes": 30, "reason": "s1-0 restarting"}` (tool `silence_alert`; the server refuses a silence without a `reason`). 3. A copy that does not come back (tier 2): replace it. `POST /v1/admin/plan {"shards": [{"shard": , "copies": [...]}]}`, the gRPC URLs the shard keeps with the dead copy left out and its replacement in, plans the repair (Cluster: Plan the repair, in the command center); file the plan as a change request. A plan that adds a server is applied with the cluster's token, which the coordinator sends to it (403 `cluster_token_required` with the admin token or a key): on machines of your own, a person runs `chloedb-server admin --key "$CHLOEDB_CLUSTER_TOKEN" call POST /v1/admin/plan/apply @plan.json` with the same body; on Kubernetes the operator adds copies itself. 4. A shard with no majority takes no writes, and its copies cannot elect a primary. Its searches go on while a replica that is up serves reads (the shard's state is `no_writes`); when the copy left is its primary, it serves no reads either (`no_reads`), since with failover a primary serves reads only while a majority of its copies answer. Bring a copy back, or remove the dead one (tier 2 for a replica, `DELETE /v1/admin/shards//replicas`; promoting by force is tier 3 and a person's alone). ## A replica is behind For: `replica-behind`, `out-of-sync`, `replica-reads`, `lag`, `follow-behind` 1. Read how far behind and why: the primary's `GET /v1/health` (`replication.replicas`: each replica's `seq_no`, how many transactions it is `behind`, and whether it is `in_sync`; on `/metrics`, `chloedb_replica_behind`), and `GET /v1/load` (the primary's write rate, the replica's disk and CPU). `GET /v1/cluster` says each copy's role and whether it serves reads; its `txn` counts the transactions of each process since it started, so it does not compare two copies. `GET /v1/admin/follow` for a follower cluster, Data > Connectors (`followers` in `GET /v1/admin/connectors`) for a Postgres follower. 2. A replica catching up after a restart: wait, with `GET /v1/events?after=&wait_s=30`, and silence the alert for the while (tier 1). 3. A replica out of sync must not become the primary: do not promote it. Replace it (tier 2: a plan and a change request) if it does not catch up. ## A Postgres follower holds a table For: `follow-table-held` A table `chloedb-server follow-postgres` could not write is held: it is not followed (its rows stay as they were), the other tables are, and it is tried again after 30 seconds, then twice as long each time up to 15 minutes ([postgres.md](postgres.md#when-one-table-fails)). 1. Read which and why: Data > Connectors, or `GET /v1/admin/connectors` (the follower's `table_states` with `state` `held`, and its `error`, which names the table, the column and the row's key); on `/metrics`, `chloedb_follow_tables_held` and `chloedb_follow_table_error_info`. 2. Fix the cause where it is: a value ChloeDB refuses, in the row in Postgres; a table without a primary key, by giving it one in Postgres (`ALTER TABLE ... ADD PRIMARY KEY`) or taking it out of the publication; a ChloeDB table someone made with a type that cannot read Postgres's values, by fixing it in ChloeDB. Changing data in Postgres is the owner's (tier 2: a change request). 3. Then wait for the next try (`retry_in_s`), or start the follower again with `--copy-table
    ` to copy it now (tier 1): its rows stay readable throughout, and the other tables keep following. ## A connector fails or falls behind For: `connector-failing`, `connector-behind` A connector that fails writes no new rows into its table, so what reads the table (a dashboard, an alert rule on it) goes quiet rather than wrong. 1. Read which and why: Data > Connectors, or `GET /v1/admin/connectors` (each connector's `health`, `state.last_error` and `state.failures`; a Kafka connector's `stream`, with `last_error`, `lag` and each partition's `lag`); on `/metrics`, `chloedb_connector_up`, `chloedb_connector_failures`, `chloedb_connector_behind_seconds` and `chloedb_connector_partition_lag_events`. 2. A source that is down or refuses the connector's credentials: fix it there, or the connector's secret (tier 2: a change request, since it changes what the server reaches). A pull runs again on its schedule, or now with `POST /v1/admin/connectors//run` (tier 1); a Kafka connector tries its brokers again by itself. 3. A Kafka connector behind but streaming: the server writes slower than the topics grow. Read the writes (`GET /v1/load`, the alerts `write-queue` and `write-p99`); a bigger `batch` writes more a time. Stopping it (`POST /v1/admin/connectors//stop`) loses nothing: it goes on from the offsets ChloeDB keeps, while Kafka still holds them. ## The disk is filling For: `disk-full`, `disk-critical`, `disk-filling`, `disk` 1. Read which tables grow: `GET /v1/tables` and `GET /v1/load` (each copy's disk). 2. Old rows a table keeps for a set time: a table made with a retention (`retain`) drops them on its own. A table's retention is set when it is made and cannot be changed (`ALTER TABLE ... SET (retain = ...)` is refused): for a table made without one, or with too long a one, make a new table with the retention, move the writers to it, and drop the old one once its rows are no longer needed (tier 2 and 3, change requests). 3. More room (tier 2): add disk in the spec (`POST /v1/admin/kube/plan`), or add a shard and move slots to it (`POST /v1/admin/plan`), each filed as a change request. 4. Deleted or expired rows still on disk: a server that takes writes gives the free space of its file back by itself, every 5 minutes, once 64 MB and a sixteenth of the file are free (it moves segments from the end of the file into free space below them and truncates the file; it needs no room and loses nothing; not on a replica). **Tables and storage** shows the file (`totals.file_bytes` of `GET /v1/index/tables`) beside the tables' live data. When the free space is in pieces too small for the segments above them, `POST /v1/admin/vacuum` frees them for good (tier 3: it loses old versions, and is a person's alone). It needs room first: the file grows while it runs, by what lies above its first free gap, which is written twice (in a persona study, a 1.4 GB file reached 2.5 GB before it shrank to 1.1 GB, and the process's memory 3 GB), so on a disk that is nearly full, free room another way first. Pages a statement freed become reusable two commits later: a vacuum straight after a `DROP TABLE` can free nothing, and the next one frees them. ## A disk reads slowly For: `disk-slow`, `disk_speed` 1. Read what each copy's disk probe measured: `GET /v1/admin/disk?copy=` on a coordinator (`probe.kept`: the last hour's readings) and the problem's `why`. A disk far slower than its peers' that is not busy (`disk_busy` low) is the disk's fault, or the machine's under it (a degraded cloud volume or host), not the load's. 2. Measure again (tier 1, an `ops` key with a reason): `POST /v1/admin/disk/probe {"copy": ""}`. 3. The copy is its shard's primary, and another copy is in sync on a fast disk: hand the primary over (tier 3, a person's), `POST /v1/admin/shards//promote {"url": ""}`, so that writes go to a fast disk. 4. Replace the copy (tier 2, and it costs money: a node or a volume): add a copy of the shard on another node or a volume, wait until it is in sync, then remove the slow one; plan it and file it as a change request. ## A node's disk nears Kubernetes' eviction line For: `disk-evict`, `disk-evict-now`, `evict` The database is on the node's own disk (a `hostPath` or an `emptyDir`), which the kubelet shares: once that disk has less than its eviction threshold free (15% on DigitalOcean, `--evict-free-ratio`), Kubernetes evicts every pod of the node, the database's among them. 1. Read what fills the disk: `GET /v1/admin/disk?copy=` lists the database's own files and every other entry beside them, the largest first, with when each last changed (a build's output, a copy left behind). 2. Delete what is not needed (tier 3, a person's: it loses data): `POST /v1/admin/disk/clean {"copy": "", "paths": [{"path", "modified_ms"}]}` with entries as the listing gave them. The server refuses its own files, anything changed since it was listed, and anything it did not list. Files outside the database's folder (images, other pods' files) are the node's: clean them on the node. 3. Move the database to a volume of its own (tier 2, and it costs money): a copy of each shard on a volume, in sync, then remove the copies on the node's disk. ## A statement times out For: `slow-statement`, `statements` 1. Read the statement: `GET /v1/queries/stats/` (its slowest calls, where it waits by shard, who sends it) and the problem's `why` and `reads`: a filter on a field the table neither indexes nor is clustered by reads every row of the table (`reads.every_row`). 2. One client sending it (tier 1, an `ops` key with a reason): limit it with a contain rule, `POST /v1/admin/contain {"match": {"fingerprint": "..."}, "action": "limit", "concurrency": 2}`, while it is fixed. 3. A filter no index serves: the application reads a summary table kept by that field, or the table is made again indexed or clustered by it (tier 2, a change of the schema). 4. A shard that holds it up, on a copy whose disk reads slowly: follow "A disk reads slowly". ## Writes fail or queue For: `failing`, `flush-failing`, `merge-failing`, `write-queue`, `write-p99`, `write_error_ratio` 1. Read the server's lines: `GET /v1/logs?level=error` on the server itself (a full disk, an I/O error), or through a coordinator, every copy's: `POST /v1/logs/query {"sql": "SELECT ts, node, message FROM logs WHERE level = 'error' ORDER BY ts DESC LIMIT 100"}`. 2. A database that refuses writes (`failing`) on a primary: with `--failover-after-ms` it hands its shard over to a replica in sync by itself; without it, hand the primary over first (tier 3, `POST /v1/admin/shards//promote`, a person's). Then fix the cause and restart the server. 3. Slow writes with `--write-acks all`: a replica or its link is slow; follow "A replica is behind". ## Data damaged on disk For: `damaged` 1. Read which copy and which segments: `GET /v1/health/fleet` and `GET /v1/events?kind=damaged`. 2. Verify again (tier 1): `POST /v1/admin/verify`, which on a coordinator has every shard's primary compare its replicas (one shard: `POST /v1/admin/copies/verify {"url": ""}`). 3. Replace the copy (tier 2): plan the repair and file it as a change request; never make the damaged copy the primary. ## A shard's primary changed For: `primary-changed` 1. Read why: `GET /v1/events?kind=primary_changed,copy_down` and the old primary's lines (`POST /v1/logs/query {"sql": "SELECT ts, level, message FROM logs WHERE node = '' ORDER BY ts DESC LIMIT 200"}`). 2. Nothing to do when the old primary is back as a replica in sync; it resolves ten minutes after the last change. A handover asked by hand fires it too. Otherwise follow "A copy is down". ## A rollout is held For: `rollout`, `held` 1. Read what the gate saw: `GET /v1/kube` (the operator's status and the gate's reason) and `GET /v1/events`. 2. When the reason is understood and the change is wanted (tier 2): `POST /v1/admin/kube/resume`, filed as a change request; otherwise roll back (`POST /v1/admin/kube {"rollback": }`), also a change request. ## Restore from checkpoints For: `restore`, `lost-data`, `bad-write` Rows were deleted or overwritten by mistake, or a shard's copies all lost their disks, and the cluster has to go back to its checkpoints. Restoring is a person's alone (tier 3): it stops the cluster and takes back every write since the checkpoint. These steps are for servers you start yourself (by hand, from systemd, in a container); on Kubernetes the operator keeps its pods running and has no restore step yet. 1. Have checkpoints of every shard from one cluster map: `POST /v1/admin/checkpoint {"name": "nightly"}` on the coordinator writes one on each shard's primary, into its `--backup-dir`, with the shard's cluster map (`nightly.slots`) and the cluster's API keys (`nightly.keys.json`) beside it, and answers the `slot_epoch` they are of. Copy the three files of each shard off the machine. A checkpoint of one copy is `POST /v1/admin/copies/checkpoint {"url": "...", "name": "..."}`. `GET /v1/admin/checkpoints` lists every copy's, each shard's newest, and under `complete` the names on every shard under one cluster map: the sets you can go back to. 2. Read what you are going back to: each shard's checkpoint names its shard and epoch (`nightly.slots`), and `GET /v1/cluster` gives the epoch now (`slot_epoch`). Slots moved since the checkpoint when the two differ: then restore every shard, never one alone, or rows would be in two shards or in none. 3. Stop the coordinator and every copy of the shards you restore. 4. On each copy, put its shard's checkpoint in place of its database: `chloedb-server restore --from /backups/nightly --db /data/shop.chloedb` (with `--keys FILE` when the server has `--keys FILE`). It checks the checkpoint before it changes anything, moves the database's own files aside into `/data/shop.chloedb.before-restore-
    __idx`, and on a `MEDIA` field's `json_extract(field, '$.sha256')`, as ChloeDB indexes it (`--no-indexes` leaves them out). - **An FTS5 index** over each table's `TEXT` fields, `
    _fts`, with its text in the table itself (`content=`) and triggers that keep it in step with inserts, updates and deletes (`--no-fts` leaves it out). Search it as FTS5 is searched: `SELECT t.* FROM t_fts JOIN t ON t.rowid = t_fts.rowid WHERE t_fts MATCH 'wizard' ORDER BY rank`. - **The ChloeDB schemas** in a table `_strata_tables` (`name`, `position`, `schema` in the short JSON form), which an import of the file reads to restore them (`--no-schemas` leaves it out; an import then makes schemas from the SQLite tables). A table of that name without the `name` and `schema` columns is the file's own, and imported as the others are. ### What SQLite does not hold The data round-trips; ChloeDB's indexes and search do not, since SQLite has no counterpart: - **Vector indexes.** HNSW and IVF indexes and the compressed codes stay behind; the vectors are exported. SQLite searches them with an extension (sqlite-vec, libSQL's vector index) or by a scan. An embedded field's model is recorded in the kept schema only. - **Text analysis and ranking.** FTS5 tokenizes on its own: `porter unicode61` stands in for the `english` analyzer (ChloeDB stems with Snowball English and drops stopwords; Porter stems a little differently and keeps them), `unicode61` for `simple`, and a table has one tokenizer for all its text fields. FTS5's `bm25()` is not ChloeDB's BM25, and fused, decayed and boosted scores, typo tolerance and synonyms have no SQLite form. - **Graphs.** `EDGES` are JSON arrays of keys; walks and PageRank over them are queries SQLite cannot run without recursive SQL of your own. - **Generated fields** export their text as a plain column, not as a SQLite generated column; an import with the kept schema recomputes it. - **Fields that are not stored** hold what the indexes give back, often NULL. - **ChloeDB's file features**: segments, snapshots, the write-ahead log, replication and sequence numbers. --- # Parquet and S3 ChloeDB reads Parquet files, and directories of them as Spark, DuckDB, polars and pandas write them, into a table, making the table's schema from the columns' types and values when it does not exist, and writes a table to a Parquet file that any of those tools reads. An export keeps the table's ChloeDB schema in the file, so importing it back gives the same schema and rows. Wherever a file is read or written, an `s3://` URL works too: an object, or every object under a prefix, on AWS S3 or any store that speaks its API. ## Import From the command line, into a database no server has open: ```sh chloedb-server import --db lake.chloedb events.parquet # a new database, its table named events chloedb-server import --db lake.chloedb --table clicks out/clicks/ # a directory: every part file, one table chloedb-server import --db lake.chloedb s3://lake/raw/events/ # every object under the prefix chloedb-server import --db lake.chloedb --key event_id events.parquet # the key of a table it creates chloedb-server import --db lake.chloedb --plan events.parquet > plan.json # what it would do; writes nothing chloedb-server import --db lake.chloedb --schema plan.json events.parquet # with the plan, edited ``` A Parquet file is recognised by its name (`.parquet`), its first bytes or `--format parquet`, and a directory by the Parquet files in it, at any depth; names starting with `_` or `.`, such as Spark's `_SUCCESS` and its `.crc` checksums, are passed over. The files of a directory make one table, read in the order of their paths, and may differ in columns: each file's columns fill the fields of their names. Parquet and SQLite files, and JSON and CSV files, can be mixed in one command. The rows go into the table `--table` names, else the one an [export](#export) kept in the file, else a table named for the file or directory (`events.snappy.parquet` and `events/` make `events`): - **A table ChloeDB has** keeps its schema: each column fills the field of its name (in any case), the others are left out and listed. The rows are upserted by key (inserted, in a table without one), 10,000 a transaction, or bulk-loaded when the table is empty. - **A table ChloeDB lacks** is created, with the schema `--schema` gives, or the one an export kept in the file, or else one made from the columns, and its rows are bulk-loaded in one commit: a value that does not fit is reported with its file and row, and nothing is written. A database that does not exist is created with the first Parquet file's table. In Python, `chloedb.from_parquet("events.parquet", "lake.chloedb")` creates a database, `db.import_parquet("out/clicks/", table="clicks")` imports into an open one, and `chloedb.plan_parquet("events.parquet")` returns the plan ([Python](python.md)). From Rust it is `chloedb::parquet` (feature `parquet`): `import_new`, `import`, `plan` and `Source` for each step. ### How Parquet columns become fields Parquet columns have types, so a table made from a file takes them, and reads the first 100,000 rows only to choose between a few: | Parquet / Arrow column | ChloeDB field | |---|---| | integers of any width, decimals with no scale | `INT` | | floats, other decimals | `FLOAT` (a decimal as a double: the plan notes it) | | booleans | `BOOL` | | dates, timestamps of any unit or time zone | `TIMESTAMP` (a date at midnight UTC) | | text that is the key, dictionary-encoded, or labels rather than prose | `KEYWORD` | | other text | `TEXT` | | fixed-size lists of numbers, or lists of numbers all of one length | `VECTOR(n)` | | lists of text or of integers | multi-valued `KEYWORD` or `INT` | | lists of vectors | multi-vector `VECTOR(n)[]` | | structs, maps, other lists | `JSON` | | binary | left out (ChloeDB has no binary type), or base64 text in a stored `KEYWORD` with `--blobs-base64` | | times of day, durations, intervals, columns of NULLs only | left out | Text reads as labels when no value is over 256 bytes and the values have 2.5 words or fewer on average, or each value repeats ten times on average (as the [SQLite import](sqlite.md#how-sqlite-columns-become-fields) judges). Column names that are not ChloeDB identifiers are respelled (`City Name` becomes `City_Name`; the plan lists each). A column named `id` (in any case) of integers or text without NULLs in the sample is the key; `--key` names another, and `--key ""` makes a table without one. A NaN or infinite float is read as NULL, and the import says how many were. A column fills only the field of its own name, and nothing renames one on the way in. A key column named otherwise, such as `_id` in BEIR's corpora and in MongoDB's documents, therefore does not fill a table keyed `id`: an import into one fails with `bad value for field id: NULL does not fit a KEYWORD field`, and a table made from the file has no key unless `--key` names one, since only a column named `id` becomes the key by itself. The plan's `columns` says which field each column fills, but it is read, not followed: a plan given back as `--schema` (or `schema=`) gives the table's schema, and a `columns` edited to `{"_id": "id"}` fails the same way. Two ways through: - **Keep the column's name as the key.** `--key _id` (`key="_id"` in Python, `?key=_id` over HTTP) makes `_id` the key of the table the import creates, and SQL reads it as any column (`WHERE _id = 'd1'`). To choose the fields' types, analyzers or an embedded vector field, create the table first with a key named `_id` and import into it with `--table`. - **Rename the column before the import**, in Arrow from Python, and write the rows with [`import_arrow`](#arrow-from-python) into the table you made: ```python import pyarrow.parquet as pq t = pq.read_table("corpus.parquet") t = t.rename_columns(["id" if c == "_id" else c for c in t.column_names]) db.import_arrow(t, table="docs") ``` A table made from a file without `--table` is named for the file, so Hugging Face's `corpus-00000-of-00001.parquet` makes `corpus_00000_of_00001`: give `--table corpus` (`table="corpus"`). Into a table that exists, a column fills its field when its values do: any integer, float or decimal for a number, dates, timestamps and ISO 8601 text for a `TIMESTAMP`, a list of `n` numbers (or `4n` little-endian float32 bytes) for a `VECTOR(n)`, a list for a multi-valued field, structs, maps and lists for a `JSON` field. Integers that are Unix times (seconds, milliseconds or microseconds, by their size) fill a `TIMESTAMP` too. ### Directories and Hive partitions A directory Spark writes with `partitionBy` holds its files under `key=value` directories (`year=2026/month=11/part-00000-….snappy.parquet`). Each key becomes a field, `INT` when every value is an integer and `KEYWORD` otherwise, and each row takes its file's values; `__HIVE_DEFAULT_PARTITION__` is NULL. Into a table that exists, a key fills the field of its name. A directory whose files keep different ChloeDB tables (an export of several, below) is refused: import its files one at a time. ## Export ```sh chloedb-server export --db lake.chloedb --tables events events.parquet # one table, one file chloedb-server export --db lake.chloedb out/ # every table: out/
    .parquet chloedb-server export --db lake.chloedb --format parquet --tables events s3://lake/exports/events.parquet chloedb-server export --db lake.chloedb --no-schemas events.parquet # without the kept schema ``` An export reads the rows of one snapshot. It writes a `.parquet` file when the name says so (one table), and otherwise a new directory with a `
    .parquet` file a table (`--format parquet`, or a name ending in `/`; without either, the export is a [SQLite file](sqlite.md#export)). The files are compressed with Zstandard, in row groups of about 128 MB, and written under another name and renamed into place when complete; an existing file or directory is an error, but for an empty directory. In Python it is `db.export_parquet("events.parquet", tables="events")`, from Rust `chloedb::parquet::export`. | ChloeDB field | Parquet / Arrow column | |---|---| | `INT` | `INT64` | | `FLOAT` | `DOUBLE` | | `BOOL` | `BOOLEAN` | | `TIMESTAMP` | `TIMESTAMP(MICROS, UTC)` | | `TEXT`, `KEYWORD` | `STRING` | | `VECTOR(n)` | a list of `n` floats (Arrow `FixedSizeList(Float32, n)`, which NumPy, PyTorch and Spark's `array` take) | | `VECTOR(n)[]` | a list of those | | multi-valued `KEYWORD`, `INT` | a list of `STRING`, of `INT64` | | `JSON`, `SPARSE`, `EDGES`, `MEDIA` | `STRING`, the value's JSON text | Only the key's column is not nullable. Each file keeps its table's ChloeDB schema as JSON in its key-value metadata (`strata.schema`), which other tools ignore and an import restores: analyzers, vector indexes and their kinds, embedding models, references, defaults and generated fields' definitions, which Parquet has no place for. A field neither stored nor recoverable from an index is NULL, and a generated field holds its text; the export's notes list what does not carry over. ## S3 and S3-compatible stores `s3://bucket/key` (or `s3a://`, as Spark writes) works wherever a file does: `chloedb-server import` and `export`, and in Python, on a database in your process (`chloedb.open`), `from_parquet`, `import_parquet`, `export_parquet`, `from_sqlite`, `import_sqlite`, `export_sqlite` and `import_file`. A `Client` of a server (`chloedb.connect`) reads and writes local paths only: its `import_parquet` and `export_parquet` send the file over HTTP, so copy an object down first, or write the export to a local file and upload it (with boto3 or `aws s3 cp`). `chloedb-server export` to S3 needs the database closed: a server that has it open for writing keeps it. A URL names one object, or every object under a prefix: one that ends in `/`, or that names no object (`s3://lake/raw/events` reads `raw/events/year=2026/part-0.parquet` and the rest). The objects are read into a temporary directory, keeping their paths under the prefix, eight at once, and imported from there; an export is written to a temporary file or directory and then sent, in parts of 16 MB for large files. An object already at the URL of an export, or under its prefix, is an error, checked before anything is sent. The store is configured as the AWS tools are, by environment variables: | variable | what | |---|---| | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` | the credentials; without them, a web identity (`AWS_WEB_IDENTITY_TOKEN_FILE` and `AWS_ROLE_ARN`, as EKS gives pods), ECS task credentials, or EC2 instance metadata | | `AWS_REGION` (or `AWS_DEFAULT_REGION`) | the bucket's region | | `AWS_ENDPOINT_URL` | a store other than AWS S3: `https://nyc3.digitaloceanspaces.com` for DigitalOcean Spaces, `https://.r2.cloudflarestorage.com` for Cloudflare R2, MinIO's or Ceph's address | | `AWS_ALLOW_HTTP=true` | for an endpoint over plain `http://`, such as a local MinIO | | `AWS_VIRTUAL_HOSTED_STYLE_REQUEST=true` | `bucket.host` addresses instead of `host/bucket` | Profiles in `~/.aws` are not read. The S3 client is [object_store](https://docs.rs/object_store)'s, in ChloeDB's feature `s3` (on by default in chloedb-server and the Python package). ## Over HTTP and in the UI `POST /v1/import` takes a Parquet file in the body (`application/vnd.apache.parquet`, or recognised by its first bytes; up to the server's `--max-body-mb`), into the table `?table=` names or the one an export kept in the file, with `?key=`, `?blobs_base64=true` and `?plan=true` as on the command line. The rows are checked before any is written and then written through the writer, so a value that does not fit writes nothing; an import that creates the table needs an admin key, and a coordinator imports into tables its shards have. `GET /v1/export?format=parquet&tables=events` answers one table as a Parquet file (a database of one table may leave out `tables`), and `?schemas=false` leaves out the kept schema. From Python's client: `client.import_parquet(path, table=None, key=None)`, `client.plan_parquet(path)` and `client.export_parquet(path, table=None)`. The command center's Import view reads a dropped Parquet file's plan from the server: the table it goes to (named in a box, which re-plans), each column's field and type, the key and what is left out, then imports it with its progress. Its Export card writes SQLite or Parquet, a Parquet file a table chosen. ## Arrow from Python `db.import_arrow(data, table=None)` writes the rows of anything that gives an Arrow stream (`__arrow_c_stream__`): a pyarrow Table, RecordBatch or RecordBatchReader, a polars DataFrame, a DuckDB relation, an answer of `query_arrow`, and a pandas DataFrame through pyarrow. Each column fills the field of its name, read as an import reads a Parquet column; the others are left out and listed. Into an empty table the rows are bulk-loaded in one commit, otherwise upserted by key. With `query_arrow` going the other way, a table moves between ChloeDB and dataframe libraries without JSON in between. ## With Spark Spark reads an export as it reads any Parquet (`spark.read.parquet("s3a://lake/exports/events.parquet")`): vectors as `array`, timestamps as `timestamp`, lists as arrays, JSON as strings to `from_json`. What Spark writes (`df.write.partitionBy("year").parquet("s3a://lake/raw/events")`) imports as a directory, partitions and all. A data source that lets Spark read from and write to a running server is a later step. ## What it does not do - **Read Parquet in place.** An import copies the rows into ChloeDB's own files, which hold the indexes Parquet has none of; a query never reads a Parquet file. - **Several tables from one directory.** A directory is one table, as Spark, DuckDB and polars read one; an export of several tables is a directory of files, imported a file at a time. - **Partitioned exports.** An export writes one file a table, in row groups; it does not split a table by a column into `key=value` directories. - **Stream from S3.** An import reads all the objects to local disk before it reads them, and an export writes the file locally before it sends it, so both need the space. --- # Following Postgres `chloedb-server follow-postgres` keeps ChloeDB in step with a Postgres database by logical replication: it copies the tables of a publication, then applies every insert, update, delete, `TRUNCATE` and new column a moment after Postgres commits it, so ChloeDB serves search over the rows Postgres holds without a nightly job or a Debezium and Kafka pipeline in between. It speaks Postgres's own protocol (`pgoutput`, the plugin Postgres ships, from version 10), and keeps what it applied in ChloeDB's `_sources`, in the same transactions as the rows, so a follower stopped and started again goes on from there and applies each change once. The same follower runs inside the server as a [`postgres` connector](connectors.md#databases-followed-by-their-logs), started and stopped on Data > Connectors, with its password kept as the connector's secret; [`follow-mysql`](mysql.md) follows MySQL by its binary log the same way. This is ChloeDB reading from Postgres, not ChloeDB speaking to Postgres clients: ChloeDB serves no Postgres protocol of its own, so `psql`, DBeaver, Metabase and dbt's Postgres adapter cannot connect to it. [Running SQL](query-language.md#running-sql) lists the ways in. ## Set up Postgres Postgres writes what logical replication needs once `wal_level` is `logical` (a restart takes it): ```sql ALTER SYSTEM SET wal_level = logical; -- then restart Postgres CREATE PUBLICATION strata FOR TABLE products, reviews; -- or FOR ALL TABLES CREATE ROLE chloedb LOGIN REPLICATION PASSWORD '...'; GRANT SELECT ON products, reviews TO chloedb; ``` The role signs in by SCRAM-SHA-256 (Postgres's default), MD5 or a password, and needs `REPLICATION` and `SELECT` on the tables. On managed Postgres, logical replication is a setting (`rds.logical_replication` on RDS and Aurora, `cloudsql.logical_decoding` on Cloud SQL; Supabase and Neon have it on). Since Postgres 15 a publication can leave columns out (`FOR TABLE users (id, name, bio)`) and rows (`WHERE (published)`); the follower copies and follows what it publishes. Each table needs a key: its primary key, or a unique index named as its replica identity (`ALTER TABLE t REPLICA IDENTITY USING INDEX t_code_key`). A key of several columns becomes one `KEYWORD` column `_key` in ChloeDB, their values joined by `:` (`42:en`), beside the columns themselves. ## Run it ```sh chloedb-server follow-postgres \ --source 'postgres://chloedb:...@db.example:5432/shop?sslmode=verify-full' \ --target http://localhost:7700 --name shop ``` | option | | |---|---| | `--source` | the database's URL (or `CHLOEDB_POSTGRES_URL`); `PGPASSWORD` gives a password it leaves out; `sslmode` is `disable`, `prefer`, `require`, `verify-ca` or `verify-full`; without one, `require` for a database on another machine (a connection that could fall back to plain text would send the password's proof and every row in the clear) and `prefer` for one on `localhost` or a loopback address, and `sslrootcert` (or `--source-ca`) a CA certificate to check the server's by; with `verify-*` and no CA given, the public CAs are trusted | | `--target` | ChloeDB's HTTP URL: a server, or a cluster's coordinator (`--target-token` or `CHLOEDB_CLUSTER_TOKEN`, `--target-ca`) | | `--name` | the name ChloeDB knows the database by, which its marks in `_sources` name | | `--publication` | the publication (`strata`) | | `--slot` | the replication slot it makes and reads (`strata_`) | | `--batch` | the most rows of one write while copying, and of the transactions written together (1,000) | | `--copy-workers` | how many tables are copied at once (4) | | `--copy` | copy everything again, with a new slot. Each followed table is emptied first and filled again as the copy goes, so its searches and counts answer partly, or nothing, until its copy ends ([copying again](#run-it)) | | `--copy-table` | copy these tables again once following (`orders`, `sales.orders`, or ChloeDB's name; repeat it or separate the names by commas), over the rows ChloeDB holds, which stay readable until the new copy is in; the rows Postgres no longer has are deleted after it, and the other tables follow meanwhile ([one table](#when-one-table-fails)) | | `--drop-slot` | drop the slot, release the tables it followed (they take other writes again) and exit | The first run makes the replication slot, which holds a snapshot of the database, and copies each table as of that snapshot while Postgres goes on taking writes; it then streams the slot's changes from the snapshot's position, so no change between the two is missed or applied twice. A ChloeDB table it lacks is made from the Postgres table; one that exists keeps its schema (see [below](#choosing-chloedb-types)). It tells ChloeDB how it stands every 2 seconds ([below](#how-far-behind-it-is)) and logs it every 30 (`applied`, `confirmed`, `postgres`, `behind_bytes`, `lag_s`), and `GET /v1/sources` on ChloeDB shows the last position it applied (`postgres//`, with its `lsn` as Postgres writes it), with when. Stop it whenever: started again it resumes from what ChloeDB applied. While it is stopped, **Postgres keeps the WAL the slot has not consumed**, which can fill its disk over days; when you stop following for good, drop the slot (`--drop-slot`, or `SELECT pg_drop_replication_slot('strata_shop')`). Postgres 13 and later can cap what a slot keeps (`max_slot_wal_keep_size`); a slot that lost WAL it needed is copied afresh on the next start. A copy afresh, this one or `--copy`, empties each followed table before it fills it again: until a table's copy ends, its searches and counts see only the rows copied so far (in a persona study, 50,000 products read 0 rows for 2 s and were partial for 10 s, and 318,514 orders for 16 s). Copy again when the site can do without those tables' answers for as long as the copy takes; to copy one table again, `--copy-table` keeps its rows readable throughout and the others following. ## How far behind it is Every 2 seconds the follower tells ChloeDB how it stands (`POST /v1/admin/follow/status`, which takes the cluster's token or an admin key: where the server asks for keys, give `--target-token` one, or the follower logs once that its reports are refused and goes on following). ChloeDB shows it on Data > Connectors (`followers` in `GET /v1/admin/connectors`), in `/metrics` and to the built-in alert "A follower is behind its source" (`follow-behind`): | | | |---|---| | `state` | `copying`, `following`, `retrying` (ChloeDB refused a write, which it tries again; `error` says why), `failed` (it exited; `error`) or `stopped` (its slot was dropped) | | `applied_lsn` | where the last transaction it wrote to ChloeDB ended | | `confirmed_lsn` | the position it told Postgres it holds, before which Postgres may free the WAL: `applied_lsn` or later, since Postgres's WAL also holds what the publication does not send | | `postgres_lsn` | Postgres's own position, `pg_current_wal_lsn()` (on a standby, `pg_last_wal_replay_lsn()`), read every 2 seconds on a connection of its own | | `behind_bytes` | `postgres_lsn` less `confirmed_lsn`: the WAL Postgres keeps for it | | `lag_ms` | since Postgres's WAL first reached a position the follower has not confirmed (within 8 KB), so 0 once it has confirmed what Postgres had | Positions are written as Postgres writes them (`0/16B3748`), to compare with `pg_current_wal_lsn()` and `confirmed_flush_lsn` in `pg_replication_slots`. A transaction still open in Postgres is not behind: Postgres sends it when it commits. A follower that stops telling (killed, or cut off from ChloeDB) is *silent* after 10 seconds, and from then on its lag grows by the time since it last told, so `follow-behind` (over 60 seconds behind, for a minute) fires within about two minutes of it stopping. `/metrics` has `chloedb_follow_lag_seconds`, `chloedb_follow_behind_bytes` and `chloedb_follow_up` (1 while it follows, copies or catches up and told within 10 seconds; 0 while it retries, failed or is silent), labelled with its `name` and `kind="postgres"`, and per table the series of [a table held](#when-one-table-fails). ChloeDB holds what followers told it in memory: after ChloeDB restarts, Data > Connectors lists a follower that has not told it since from its marks, as not reporting, and the alert waits for it to tell again. ## What it applies - **Inserts and updates** are upserts of the whole row by key; an update that changes the key deletes the old row. A large value an update leaves unchanged, which Postgres does not send (TOAST), is kept: taken from the old row with `REPLICA IDENTITY FULL`, or else read from ChloeDB's row. - **Deletes** are by key. **`TRUNCATE`** deletes every row of the table. - **Columns added** in Postgres are added to the ChloeDB table (`ALTER TABLE ... ADD COLUMN`), and a column renamed while the follower runs is renamed. A column renamed while the follower is stopped is not: started again, it sees a column it does not know and adds it, so the old column keeps the values from before and the new one has only those written since. Rename such a column in ChloeDB too (`ALTER TABLE products RENAME COLUMN color TO colour`) before you start the follower again, or keep it running through the migration. The rows from before the column read what they read in Postgres: a constant default (`ADD COLUMN vip boolean DEFAULT false`), which Postgres keeps beside the table rather than writing into its rows, so the stream never sends it, becomes the ChloeDB column's `DEFAULT`; a default Postgres writes into each row (a volatile one, as `random()` or `gen_random_uuid()`, or a type ChloeDB's `DEFAULT` cannot hold, as `jsonb`) has the table copied again, as of then, with the changes since applied over it. A column dropped in Postgres stays in ChloeDB, `NULL` (or its default) in rows written since. A changed type that maps to another ChloeDB type (`ALTER COLUMN qty TYPE numeric(6,2)` on an `integer`: `INT` to `FLOAT`), in a column of the type the follower made, has that table alone copied again with the column made anew: its rows stay readable, and the column reads `NULL` in each until the copy writes it again (seconds for a few hundred thousand rows); the other tables follow meanwhile. ChloeDB cannot change a column's type in place, and a coordinator does not drop columns yet, so on a cluster such a table is held ([below](#when-one-table-fails)) until you copy it again with `--copy`. A key column whose type changed holds its table too. Any other changed type keeps the ChloeDB column's, and the values are read as it reads them. - **Tables joining the publication** (`ALTER PUBLICATION ... ADD TABLE`, or a table created under `FOR ALL TABLES`) are copied when the follower sees them, within 30 seconds, then followed. A table leaving it is no longer followed; its ChloeDB rows stay. A table renamed in Postgres goes on into the ChloeDB table of its old name. - ChloeDB's tables the follower writes take no other writes: an `INSERT`, `UPDATE` or `DELETE` of one, or a `POST /v1/write`, is refused (409, `followed_table`), since a row written in ChloeDB would answer what Postgres does not until Postgres changed it and the follower wrote over it, and a transaction applied again after a restart must write what it wrote before. Write the change in Postgres. The follower names itself on its requests (`x-chloedb-postgres-follower`), and a server reads which tables are followed from the follower's marks within seconds of a copy. Nor can the table be dropped in ChloeDB, or a column the follower writes dropped or renamed there (`DROP TABLE`, `ALTER TABLE ... DROP COLUMN`, `RENAME COLUMN`: 409, `followed_table`): the follower would stop on the table, or write the column again without the values it held. Change the table in Postgres. Columns may still be added in ChloeDB (an embedded vector, say), and a column ChloeDB derives may be dropped or renamed. A table that leaves the publication, or whose follower's slot is dropped (`--drop-slot`), takes writes again. Transactions are applied whole, each in one write (several at once while Postgres sends faster than they are written), but one of more than 1,000 changes, more than 16 MB of values, or with a `TRUNCATE`, is written in steps: a reader can see part of it, as it can see part of any write across a cluster's shards. **Changed:** a follower of 0.3.7 or earlier adds a new column with its type only, so the rows from before read `NULL` in it until Postgres next changes each of them (add the column in ChloeDB first, with the same default, or copy again with `--copy`), and its server takes other writes to the followed tables, whose rows then differ from Postgres's, with no warning, until Postgres changes them. ### How Postgres columns become fields | Postgres | ChloeDB | |---|---| | `boolean` | `BOOL` | | `smallint`, `integer`, `bigint`, `oid` | `INT` | | `real`, `double precision`, `numeric` | `FLOAT` | | `text`, `varchar`, `name`, `citext`, `xml` | `TEXT` (`KEYWORD` as the key) | | `char(n)`, `uuid`, enums, and other types (`inet`, `interval`, ...) | `KEYWORD`, their text | | `date`, `timestamp`, `timestamptz` | `TIMESTAMP` (UTC; `infinity` is `NULL`) | | `json`, `jsonb` | `JSON` (a value that is not an object becomes `{"value": ...}`; an empty key, which ChloeDB's JSON refuses, becomes `_empty`, at any depth, with `_` added while the object holds that key too) | | arrays of text types, `uuid` or enums | `KEYWORD[]` | | arrays of integers | `INT[]` | | pgvector's `vector(n)`, `halfvec(n)` | `VECTOR(n)` | | pgvector's `sparsevec` | `SPARSE` | | `bytea`, `tsvector`, other arrays, `vector` without a dimension | left out | ### Choosing ChloeDB types A `text` or `varchar` column becomes `TEXT`, which is searched by its words. It groups (`GROUP BY country`, `SELECT DISTINCT country`) and compares with `=` by its stored text, read row by row, where a `KEYWORD`'s index answers both ([differences from PostgreSQL](query-language.md#differences-from-postgresql)). A join compares `KEYWORD`, `INT` and `FLOAT` columns, not `TEXT`: `ON a.borough = b.borough` of two followed `varchar` columns is refused, and the message says so. A column of names, codes or statuses that you join, group and filter by its whole value (`brand` below) belongs in a `KEYWORD`; for a table followed already, `CREATE TABLE zones_k AS SELECT *, CAST(borough AS KEYWORD) AS borough_k FROM zones` makes a copy to join ([CREATE TABLE ... AS SELECT](query-language.md#rows-from-a-select-insert--select-and-ctas)). To choose the types, analyzers, an embedded vector or fields of ChloeDB's own, make the table in ChloeDB before the first run, with the Postgres key as its key and the columns of the names Postgres has: ```sql CREATE TABLE products ( id INT PRIMARY KEY, title TEXT, sku KEYWORD, brand KEYWORD, description TEXT OPTIONS(analyzer = 'english'), price FLOAT, emb VECTOR OPTIONS(embed = 'title, description', model = 'potion-retrieval-32M') ); ``` The follower writes each Postgres column into the field of its name as that field reads it (an `integer` into a `KEYWORD`, a `real[]` into a `VECTOR(n)`), adds the published columns the table lacks, and leaves the other fields to ChloeDB: here `emb` is embedded from each row as it arrives. A value a field cannot read (text in an `INT`, a JSON value nested more than 16 levels) holds its table, with the table, column, value and the row's key ([below](#when-one-table-fails)); fix the row in Postgres, or the ChloeDB table, and the follower copies the table again at its next try. ## When one table fails A table the follower cannot write (a value ChloeDB refuses, a table without a primary key joining the publication, two Postgres tables that become one ChloeDB table, a ChloeDB table dropped from under it) is *held*: the follower stops following that table and goes on with the others, and the process stays up. A held table keeps its ChloeDB rows (and still takes no other writes), and its changes in the stream are not applied: when it is tried again, at first after 30 seconds and then after twice as long each time, up to 15 minutes, it is copied again as of then, over its rows, which stay readable, the rows Postgres no longer has are deleted, and it is followed again. A follower started again copies the tables it held when it stopped (`.../again/`, [below](#how-a-restart-resumes)). Data > Connectors shows each held table with its error and when it is tried next; `GET /v1/admin/connectors` has them in the follower's `table_states` (`state` `held`, `error`, `since_ms`, `attempts`, `retry_in_s`) and counts them in `held_tables`, and its `last_error` is the latest. `/metrics` has, per table, `chloedb_follow_table_up` (0 while held), `chloedb_follow_table_lag_seconds` (since it was held, while held) and `chloedb_follow_table_error_info` (1, with the error in its `error` label), and per follower `chloedb_follow_tables_held` and `chloedb_follow_last_error_timestamp_seconds`. The built-in alert `follow-table-held` ("A Postgres follower holds a table") fires when one stays held for a minute; the runbook is [A Postgres follower holds a table](runbooks.md#a-postgres-follower-holds-a-table). At the start, a publication none of whose tables can be followed stops the follower, saying why for each. The follower exits too when ChloeDB refuses it as a whole (a wrong `--target-token`) or on an error it cannot place on a table; it connects again by itself when Postgres or ChloeDB does not answer. Run it under a supervisor that starts it again, which resumes it where it stopped: ```ini # /etc/systemd/system/chloedb-follow-shop.service [Unit] Description=ChloeDB follows Postgres database shop After=network-online.target Wants=network-online.target [Service] # CHLOEDB_POSTGRES_URL=postgres://... and, for a cluster, CHLOEDB_CLUSTER_TOKEN=... EnvironmentFile=/etc/chloedb/follow-shop.env ExecStart=/usr/local/bin/chloedb-server follow-postgres --target http://localhost:7700 --name shop Restart=always RestartSec=10 [Install] WantedBy=multi-user.target ``` `systemctl enable --now chloedb-follow-shop`, and `journalctl -u chloedb-follow-shop` for its log. In a container, `docker run -d --restart unless-stopped --env-file follow-shop.env ghcr.io/chloetech-ai/chloedb-server:latest follow-postgres --target http://chloedb:7700 --name shop` (on Kubernetes, a Deployment of one replica restarts it). Run one follower per `--name`: two would read the same slot, and Postgres gives it to one at a time. ## How a restart resumes What the follower applied is in ChloeDB's `_sources`, written in the same transaction as the rows it covers: - `postgres//copy` is when the copy it follows from began; a copy made again names every other mark afresh, under `postgres///`. - `postgres//` is the LSN where the last applied Postgres transaction ends. Every operation of a transaction carries it as its stream offset, so a shard that applied the transaction skips it when it comes again, and a follower started again streams from the least over the shards ([streams](server.md#streams)). - A transaction written in steps numbers them (`.../step`, carried by each step's operations), and its last step writes how many steps such transactions took so far (`.../base`): replayed, it numbers its steps as before, each shard skips the steps it applied, and a `TRUNCATE` already done is not done again. - `.../copied` says the copy finished, and `.../t//
    ` which Postgres table each ChloeDB table follows. - `.../again/` is odd while a table's copy is owed (a table held, or a column Postgres wrote values into) and even once it is made again: a follower started again copies the tables owed. The follower tells Postgres how far it applied, so that the slot lets go of the WAL before it. A copy cut short is made again, from a new slot. --- # Following MySQL `chloedb-server follow-mysql` keeps ChloeDB in step with a MySQL database by its binary log, as a replica reads it: it copies the tables it follows as of one snapshot, then applies every insert, update, delete, `TRUNCATE` and new column a moment after MySQL commits it, so ChloeDB serves search over the rows MySQL holds without a Debezium and Kafka pipeline in between. It speaks MySQL's replication protocol itself (MySQL 8.0 and later), and keeps what it applied in ChloeDB's `_sources`, in the same writes as the rows, so a follower stopped and started again goes on from there. The same follower runs inside the server as a [`mysql` connector](connectors.md#databases-followed-by-their-logs), started and stopped on Data > Connectors, with its password kept as the connector's secret. ## Set up MySQL The follower reads row events of whole rows, which are MySQL's defaults since 8.0 (`log_bin` on, `binlog_format = ROW`, `binlog_row_image = FULL`); it says which is off when one is. It signs in as a user that may read the binlog and the tables: ```sql CREATE USER 'chloedb'@'%' IDENTIFIED BY '...'; GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'chloedb'@'%'; GRANT SELECT ON shop.* TO 'chloedb'@'%'; ``` `caching_sha2_password` (MySQL's default) and `mysql_native_password` sign-ins both work, over TLS or, on a plain connection, with the server's RSA key. On managed MySQL the binlog is a setting: RDS and Aurora keep it while backups are on (set `binlog_format` to `ROW` in the parameter group, and `CALL mysql.rds_set_configuration('binlog retention hours', 24)` so a stopped follower finds its position); Cloud SQL writes it with point-in-time recovery on. Each followed table needs a primary key, by which the follower updates and deletes its rows; a table without one is refused with the statement that adds one. A key of several columns becomes one `KEYWORD` column `_key` in ChloeDB, their values joined by `:` (`42:en`), beside the columns themselves. ## Run it ```sh MYSQL_PWD=... chloedb-server follow-mysql \ --source 'mysql://chloedb@db.example:3306/shop?ssl-mode=verify_identity' \ --target http://localhost:7700 --name shop ``` | option | | |---|---| | `--source` | the database's URL (or `CHLOEDB_MYSQL_URL`), naming the database whose tables it follows; `MYSQL_PWD` gives the password (a password in the URL works too, but stays in the process list); `ssl-mode` is `disabled`, `required`, `verify_ca` or `verify_identity`; without one, `required` for a database on another machine and `disabled` on a loopback address, and `--source-ca` a CA certificate (PEM) to check the server's by | | `--tables` | the tables it follows, joined by commas: `orders`, `shop.orders` or `shop.*` (default every table of the URL's database). A table of another database is named `_
    ` in ChloeDB | | `--target` | ChloeDB's HTTP URL: a server, or a cluster's coordinator (`--target-token` or `CHLOEDB_CLUSTER_TOKEN`, `--target-ca`) | | `--name` | the name ChloeDB knows the database by, which its marks in `_sources` name | | `--server-id` | the server id it reads the binlog as, which must differ from every replica's of that MySQL (default a number made from `--name`) | | `--batch` | the most rows of one write (1,000) | | `--copy` | copy everything again, as of a new snapshot | | `--release` | release the tables it followed (they take other writes again) and exit | The first run notes the binlog's position (`SHOW BINARY LOG STATUS`, or `SHOW MASTER STATUS` before 8.4), opens a consistent snapshot and copies each table as of it while MySQL goes on taking writes, then reads the binlog from the position noted. A ChloeDB table it lacks is made from the MySQL table; one that exists keeps its schema, so make it first to choose the types, analyzers or an embedded vector, as for [Postgres](postgres.md#choosing-chloedb-types). Stop it whenever: started again it reads on from the last transaction ChloeDB holds. Unlike a Postgres slot, MySQL keeps nothing for a stopped follower: it purges its binlog files on its own schedule (`binlog_expire_logs_seconds`, 30 days by default), and a follower whose position is in a file purged since copies its tables again, as of a new snapshot, and says so in its log. A copy made again (that one, or `--copy`) writes over the rows ChloeDB holds, which stay readable, and then deletes those whose keys MySQL no longer has. ## What it applies - **Each change at least once, in order.** The changes between the position noted and the snapshot are applied again over the copy, and after a restart those since the last transaction ChloeDB holds; since an insert or update is an upsert of the whole row and a delete is by key, the rows end as MySQL has them, a moment behind while it catches up. Changes are written in batches of up to `--batch` rows, each batch that ends a transaction with the position after it, so a reader can see part of a large transaction, as it can see part of any write across a cluster's shards. - **Inserts and updates** are upserts of the whole row by key; an update that changes the key deletes the old row. **Deletes** are by key. **`TRUNCATE`** deletes every row of the table. - **Columns added** in MySQL (`ALTER TABLE ... ADD COLUMN`) are added to the ChloeDB table. A column dropped stays in ChloeDB, `NULL` in rows written since. - **Tables created** that `--tables` matches are followed from their first row; a table dropped is no longer followed and its ChloeDB rows stay. - ChloeDB's tables the follower writes take no other writes, as a Postgres follower's ([what it applies](postgres.md#what-it-applies)): an `INSERT`, `UPDATE`, `DELETE`, `POST /v1/write`, `DROP TABLE` or a column dropped or renamed is refused (409, `followed_table`). Write the change in MySQL. `--release`, or deleting the connector, lets them take writes again. ### How MySQL columns become fields | MySQL | ChloeDB | |---|---| | `tinyint(1)`, `boolean` | `BOOL` | | `tinyint`, `smallint`, `mediumint`, `int`, `bigint`, `year`, `bit(n)` | `INT` | | `decimal`, `float`, `double` | `FLOAT` | | `char`, `varchar`, `text` types | `TEXT` (`KEYWORD` as the key) | | `enum` | `KEYWORD`, the member's name | | `set` | `KEYWORD[]`, the members' names | | `date`, `datetime`, `timestamp` | `TIMESTAMP` (UTC; a zero date is `NULL`) | | `time` | `KEYWORD`, as `HH:MM:SS` | | `json` | `JSON` (a value that is not an object becomes `{"value": ...}`) | | `binary`, `varbinary`, `blob` types, spatial types | left out | The follower's session is in UTC (`time_zone = '+00:00'`), so a `timestamp` is read as the instant MySQL holds; a `datetime`, which has no zone, is taken as UTC. ## How far behind it is Every 2 seconds the follower tells ChloeDB how it stands, as a Postgres follower does ([how far behind](postgres.md#how-far-behind-it-is)): Data > Connectors lists it among the followers, `/metrics` has `chloedb_follow_lag_seconds`, `chloedb_follow_behind_bytes` and `chloedb_follow_up` with `kind="mysql"`, and the built-in alert `follow-behind` reads them. Its status has `state` (`copying`, `following`, `retrying`, `failed`, `stopped`), `applied_position` (the binlog file and position of the last transaction written), `mysql_position` (MySQL's own), `behind_bytes` (the binlog between the two, across files) and `lag_ms` (while it is behind, since MySQL wrote the last change it applied). ## How a restart resumes What the follower applied is in ChloeDB's `_sources`: - `mysql//copy` is when the copy it follows from began; a copy made again names the other marks afresh, under `mysql///`. - `mysql//` is the end of the last MySQL transaction applied, as the binlog file's number times 2³² plus the position (`binlog.000042` at 1234 is `42 << 32 | 1234`). - `.../copied` says the copy finished, and `.../t//
    ` which MySQL table each ChloeDB table follows (odd while it follows, even once released). Run one follower per `--name` and one per `--server-id` on a MySQL: MySQL drops a replica's connection when another signs in with its id. Under systemd or in a container, run it as the [Postgres follower](postgres.md#when-one-table-fails) is run, with `MYSQL_PWD` in its environment file. --- # Connectors A connector brings another system's data into a table of `chloedb-server`, and keeps it coming: it reads the system on a schedule (a pull), takes what the system sends (a push), or, for Kafka, keeps reading its topics while it is on (a stream); it turns each record into a row by a map, and upserts the rows by the table's key, so a record read twice is the same row (a stream writes each event once, by its offset). Connectors are configured as rows of a table, each writes with a key limited to its own target, and the command center's **Data > Connectors** page shows each one's health. | kind | pull or push | what it brings in | default table | |---|---|---|---| | `prometheus` | pull | PromQL queries over each new step (`query_range`), joined by labels into one row per subject and minute: the rollups an incident needs, the full series staying in Prometheus (or Thanos, Mimir, VictoriaMetrics) | `prometheus_rollups` | | `jira` | pull | issues matching a JQL query updated since the last run (Jira Cloud's `/rest/api/3/search/jql`, or Data Center's `/rest/api/2/search`) | `jira_issues` | | `servicenow` | pull | records of a table (`change_request`, `incident`, `problem`, ...) updated since the last run, through the Table API | `servicenow_records` | | `oxidized` | pull, and push from its hook | device configurations from oxidized-web: each node whose backup changed is fetched and kept as a version | `device_configs` | | `mail` | push | emails handed over raw: headers, text, and the maintenance fields carriers attach (the BCOP `X-MAINTNOTE` iCalendar properties: provider, maintenance id, circuits, window, impact, status) | `mail_messages` | | `webhook` | push | any system that posts JSON; preset `alertmanager` for Alertmanager's webhook | `webhook_events`, `alertmanager_alerts` | | `http_json` | pull | any REST API that answers JSON: records at a path, the next page at another, a cursor kept from the records | `http_records` | | `kafka` | stream | Kafka (or Redpanda, MSK, Confluent Cloud) topics, read by the server itself while the connector is on, each event written once: its partition's offset is kept with its row ([Kafka topics](#kafka-topics)) | `kafka_events` | | `postgres` | stream | a Postgres database's tables by logical replication, followed by the server itself while the connector is on: copied, then every change applied a moment after Postgres commits it ([databases](#databases-followed-by-their-logs)) | the source's own tables | | `mysql` | stream | a MySQL database's tables by its binary log, the same way ([databases](#databases-followed-by-their-logs)) | the source's own tables | | `mcp` | pull | any MCP server's tool, called on a schedule over the Streamable HTTP transport (or a resource, read): its result's records become rows ([MCP servers](#mcp-servers)) | `mcp_records` | | `s3` | pull | a prefix of S3, Cloud Storage (`gs://`), R2, Spaces or MinIO watched for new Parquet or JSON-lines files, each read once it appears and again when it is written over ([Files and warehouses](#files-and-warehouses)) | made from the files' columns | | `snowflake` | pull | a Snowflake table or query through the SQL API: all of it the first time, then the rows whose cursor column (`updated_at`) grew | made from the table's columns | | `bigquery` | pull | a BigQuery table or query through the jobs API, read as Snowflake's is | made from the table's columns | | `stripe` | pull | a list of Stripe's API (customers, charges, invoices, subscriptions, ...): every object the first time, then the objects of its events, so that changes and deletes come too ([Apps](#apps)) | `stripe_records` | | `shopify` | pull | a store's orders, products or customers (the Admin API's REST resources) updated since the last run | `shopify_records` | | `odoo` | pull | an Odoo model's records (`res.partner`, `sale.order`, `crm.lead`, ...) written since the last run, through its JSON-RPC API | made from the model's fields | | `hubspot` | pull | a HubSpot CRM object's records (contacts, companies, deals, tickets, a custom object) modified since the last run, with a private app's token or a [sign-in](#sign-in-with-hubspot-shopify-or-stripe) | `hubspot_records` | | `google_drive` | pull | the files of a folder (and its subfolders), a shared drive or a list modified since the last run, with the text of Docs, Slides, Sheets, Word, PowerPoint, Excel and text files, to search: paste a link, sign in with Google ([Google Drive and Sheets](#google-drive-and-sheets)) | `drive_files` | | `google_sheets` | pull | a tab of a Google Sheet (or an Excel or CSV file in Drive) as a table, its columns from the header row and typed from the values, kept in step when the file changes | made from the tab's header | Other ways rows come in stay as they are, and the Connectors page lists their sources beside the connectors: OpenTelemetry logs (`POST /v1/logs`, [server.md](server.md#opentelemetry-logs)), streams with offsets applied once (`POST /v1/stream`, which a consumer of your own can write), Postgres and MySQL followed by a process of their own ([`follow-postgres`](postgres.md), [`follow-mysql`](mysql.md)), and files ([SQLite](sqlite.md), [Parquet and S3](parquet.md)). ## Connect by pasting The Connectors page's **Connect** box takes what you have, a link, an address or a key, and makes the connectors it needs: it works out the system, asks only for the fields still missing (each with where to find its value), tries every connector before making it, and runs each once, linking its table. Each keeps in step from then on. | pasted | what it makes | |---|---| | a Google Drive or Sheets link | the connectors of [Google Drive and Sheets](#google-drive-and-sheets) | | a Stripe key, `sk_live_...`, `sk_test_...` or a restricted `rk_...` | `stripe-customers`, `stripe-charges`, `stripe-invoices` and `stripe-subscriptions`, a table each (`stripe_customers`, ...); a list the key may not read is left out, and said so | | a HubSpot private app's token, `pat-...` | `hubspot-contacts`, `-companies`, `-deals` and `-tickets` | | a Shopify Admin API token, `shpat_...` (asks for the store), or a store's address, `https://my-store.myshopify.com` (asks for the token) | the store's orders, products and customers | | `postgres://user@host:5432/db` or `mysql://...` (asks for the password unless the address has it) | a follower of the database ([databases](#databases-followed-by-their-logs)); the password is taken out of the address and kept as a secret | | `s3://bucket/prefix/` or `gs://bucket/prefix/` | an `s3` connector of the prefix (asks for the keys when the bucket is not public) | | `kafka://broker:9092/topic` (`kafka+ssl://` for TLS) | a `kafka` connector of the topics, on from then on | | `https://mycompany.odoo.com` | Odoo's partners, sales orders and leads (asks for the database, the login and an API key) | | any other `https://` address | an MCP server's: asks for its token if it wants one, then for the tool to call, from its own list | Pasting the same thing again finds the connectors it made and runs them again, with the secret given, rather than making them twice; another account's key makes connectors of its own (`stripe-customers-2`, into `stripe_customers_2`), each connector keeping which account it reads as its setting `account` (a key's, a few bytes of its SHA-256). A key refused by its system is asked for again, with why. The key or password is never answered nor kept in the connector's note. ```bash curl -X POST localhost:7700/v1/admin/connect -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"text": "postgres://ana@db.example.com:5432/shop"}' # {"title": "Postgres", "need": [{"field": "password", "label": "Password", "secret": true, "help": "…"}]} curl -X POST localhost:7700/v1/admin/connect -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"text": "postgres://ana@db.example.com:5432/shop", "fields": {"password": "…"}}' # {"title": "Postgres", "connectors": [{"name": "pg-shop", "kind": "postgres", "ok": true, "following": true}], "notes": []} ``` The body: `text`, `fields` (the values of the fields asked for, and `objects` or `resources` to choose Stripe's, HubSpot's or Shopify's lists, comma separated), `grant` (a Google sign-in's), `oauth` (a sign-in's below), `every_s`. Something it does not know is a 400 that lists what it reads; for those, **Add a connector** makes any kind with its settings. ### Sign in with HubSpot, Shopify or Stripe Beside the box, **Sign in with HubSpot**, **Shopify** (paste the store's address first) and **Stripe** connect with nothing to copy: the system's page opens, you allow ChloeDB to read, read-only, and the connectors are made with what it granted. Each button is greyed out until the server has an app at that system: register one, once, and give the server its client id and secret. | system | register the app | redirect | read access asked for | flags | |---|---|---|---|---| | HubSpot | a HubSpot developer account (developers.hubspot.com): **Apps → Create app** (a public app), its **Auth** tab | `https:///v1/oauth/hubspot/callback` | `crm.objects.contacts.read`, `crm.objects.companies.read`, `crm.objects.deals.read`, `tickets` | `--hubspot-client-id`, `--hubspot-client-secret` | | Shopify | the Partner Dashboard (partners.shopify.com) or the Dev Dashboard: **Apps → Create app**, its configuration's **Allowed redirection URL(s)**; for orders and customers, request **Protected customer data access** in its API access settings | `https:///v1/oauth/shopify/callback` | `read_orders`, `read_products`, `read_customers` | `--shopify-client-id`, `--shopify-client-secret` | | Stripe | the platform's Stripe account: **Settings → Connect → Onboarding options → OAuth**, turn OAuth on; the client id (`ca_...`) is there | `https:///v1/oauth/stripe/callback` | `read_only` (Stripe Connect's OAuth) | `--stripe-client-id ca_...`, `--stripe-client-secret` (the platform's secret key, `sk_...`) | Each flag can be the environment's instead, `CHLOEDB_HUBSPOT_CLIENT_ID` and `CHLOEDB_HUBSPOT_CLIENT_SECRET` and so on (on Kubernetes, the secrets from a Secret: the StrataCluster's `spec.secretEnv`). The redirect is `--public-url`'s address when it is set, else the address the page was opened at, so register the address people open the command center at (`http://localhost:7700/v1/oauth//callback` to try one on a laptop, where the system allows `http://localhost`). The flow is OAuth's authorization code: `POST /v1/admin/oauth//start` (`{"shop": "my-store.myshopify.com"}` for Shopify) answers the system's address to open and a `state`; the system sends the browser back to `/v1/oauth//callback` with a code, which the server trades at once (for Shopify, after checking the answer's HMAC with the app's secret, and that it is for that store); `GET /v1/admin/oauth/grant?state=` then answers `{"state": "done", "grant": "…", "account": "…"}`, and `POST /v1/admin/connect {"oauth": ""}` makes the connectors. A sign-in has 10 minutes, its state is used once, and a grant waits 30 minutes. What each keeps, as the connectors' secrets (in the secrets file, never in a table or an answer): - **HubSpot**: the refresh token, with the app's client id and secret (`refresh_token`, `client_id`, `client_secret`); each run trades them for an access token of 30 minutes. Uninstalling the app in HubSpot ends it, and the next run says to sign in again. - **Shopify**: the store's offline access token (`access_token`), as a pasted one. - **Stripe**: the connected account's read-only key (`api_key`), as a pasted one; the account is named by its id (`acct_...`). ## Make one `POST /v1/admin/connectors` with an admin key: ```json { "name": "jira-changes", "kind": "jira", "target": "netops_changes", "every_s": 300, "config": {"url": "https://example.atlassian.net", "jql": "project = NET AND issuetype = Change", "username": "bot@example.com", "fields": {"window_start": "customfield_10050", "window_end": "customfield_10051"}}, "secrets": {"token": ""} } ``` - `name`: 1 to 48 lowercase letters, digits, `-` and `_`. - `target`: the table it writes. Left out, the kind's own table, which is made then (its columns are in the table above's [defaults](#default-tables-and-presets)). A table that does not exist and is not the kind's own is refused, unless `config.create_target` is `true`, which makes it with the columns of the connector's own `map` when it has one (each typed by its `as`: `int` an `INT`, `float` a `FLOAT`, `bool` a `BOOL`, `time` or `{"now": true}` a `TIMESTAMP`, `list` a `KEYWORD[]`, `json` a `JSON`, `hash` a `KEYWORD`, any other `TEXT`, or the type a spec says: `{"path": "$.action", "type": "KEYWORD"}` for a value kept whole, to group or filter by, rather than searched as words; `id` its primary key, or none without an `id`), else with the kind's columns. - `every_s`: seconds between pulls (at least 10; 0 runs only when asked). The defaults: 60 for Prometheus, 300 for Jira, ServiceNow and HTTP pulls, 900 for Oxidized. A failed pull waits twice as long after each failure in a row, up to 32 times its interval and never more than an hour; one that stopped at its limit (20,000 records a run) runs again at once. - `config`: the kind's settings (below) and an optional `map`. - `secrets`: passwords and tokens, by name. They are never written to a table nor answered: the server keeps them in `.connectors.json` beside the database, readable by its user only (`--connector-secrets FILE`; a coordinator without one keeps them in memory, so give it one, or name each secret as `"env:VARIABLE"`, which the server reads from its environment at each run, as a Kubernetes Secret gives it). An `env:` secret names a variable whose name starts with `CHLOEDB_CONNECTOR_SECRET_` (`--connector-env-prefix` chooses another prefix), so that no connector reads the server's own tokens, model keys or cloud credentials; another name is refused with a 400. - `enabled` (default `true`) and `note`. The answer has the connector, `made_target`, and for a push connector its key's secret, `push_secret`, shown this once. | | | |---|---| | `GET /v1/admin/connectors` | every connector with its `health`, `state` (cursor, last run, last ok, failures in a row, runs, rows written) and last 12 runs; the kinds and their settings; whether pulls run on this server (`scheduler`); the stream sources | | `GET /v1/admin/connectors/NAME` | one, with its last 50 runs and the map it writes with | | `POST /v1/admin/connectors/NAME` | changes the settings the body gives (`secrets` are merged, a `null` taking one out) | | `DELETE /v1/admin/connectors/NAME` | its config, state, secrets and push key; the rows it wrote stay, and its runs for their 30 days | | `POST /v1/admin/connectors/NAME/run` | a pull now; answers what it did | | `POST /v1/admin/connectors/NAME/key` | a new push key in place of the old one, which stops working now | | `POST /v1/admin/connectors/test` | a dry run: what a connector would read and the first ten rows it would write, nothing written. The body is a connector's (`kind`, `target`, `config`, `secrets`, given as values: an `env:` one is refused; or `name` alone for a saved one), with `sample`, the body of a push, for a pushed kind | | `POST /v1/connectors/NAME/push` | a system's push: any body (JSON, or a raw email), written with the sender's key. A body with no records at the connector's `records` path (Alertmanager's: `$.alerts`), or with no message for a mail connector, is refused with 422, which says what the body has instead (its top-level keys), so that a sender set up wrong finds out; an empty list there is a push of no records, answered 200 | ### Health | health | | |---|---| | `ok` | the last run went well (and, for a pull, within three times its interval, or 15 minutes when that is longer) | | `warning` | the last run went well but found something wrong: `state.last_warning` (and the run's `warning`) says what. An `http_json` pull whose `records` path matched nothing in an answer that had a body (no key of that name, as against an empty list) reads 0 records and says so: "the records path $.items matched nothing; the top-level keys are data, next". A dry run answers it as `warning` too | | `invalid` | its row fails the API's checks (`invalid` says why): it does not run | | `failing` | the last run failed: `state.last_error` says why, `state.failures` how many in a row (a request that failed says why, from its causes: the connection refused, a name that does not resolve, TLS, a timeout; an error names a URL without its query, and a secret's value nowhere: it reads `***`, since a read key reads these tables) | | `stale` | a pull whose last good run is older than that | | `pending`, `waiting` | a pull not run yet (one run by hand, `every_s` 0, too); a push connector nothing was pushed to yet | | `running`, `disabled` | | On `/metrics`, the server that runs the connectors has each one that is on as `chloedb_connector_up` (0 while it is `failing`, `stale` or `invalid`), `chloedb_connector_failures` and `chloedb_connector_last_ok_timestamp_seconds`, by `connector` and `kind`; a Kafka connector also has `chloedb_connector_lag_events`, `chloedb_connector_behind_seconds` (while a partition has events waiting, since the last it wrote of it happened) and `chloedb_connector_partition_lag_events` by `topic` and `partition`. The built-in alerts `connector-failing` (one failing for two minutes) and `connector-behind` (a Kafka connector over 5 minutes behind for 5 minutes) read them ([runbook](runbooks.md#a-connector-fails-or-falls-behind)). ## Configured as rows Each connector is a row of `chloedb_connectors` (`id` its name, `kind`, `target`, `enabled`, `every_s`, `config` as JSON text, `push_key` its key's id, `note`, `created`, `updated`), each run a row of `chloedb_connector_runs` (trigger, started, took, ok, records read, rows written, records that made no row, columns left out, error, cursor after, `warning`; kept 30 days), and each connector's cursor and counts a row of `chloedb_connector_state` (its `rows_total` counts every row each run wrote, an upsert of a row already there too, so it can be more than the target's rows; the Connectors page's column says "rows written"). The tables are made with the first connector, with `updated_by`, who changed the config last, and the runs' `warning` and the state's `last_warning` (a server adds the columns it lacks to older tables). SQL reads them, and only the server writes them: a statement or a write that changes one of them (`INSERT`, `UPDATE`, `DELETE`, `CREATE`, `ALTER`, `DROP`, `/v1/write`, `/v1/kv`) answers 403 `server_owned` for every key, an admin's too, since a row would choose the URL a connector sends its credentials to and the table its run's key writes. Change a connector through the API (`POST /v1/admin/connectors/NAME {"enabled": false}` turns one off), which checks it and writes the change in the audit log. The schedule reads `chloedb_connectors` again every 10 seconds and checks each row as the API does: a row that fails (one written with the server's own token, say, or by an older server) is shown with health `invalid` and why, and is neither pulled nor pushed to until an admin changes or deletes it. ```sql SELECT connector, COUNT(*) AS runs, SUM(rows_) AS rows, AVG(took_ms) AS ms FROM chloedb_connector_runs WHERE ok = false AND started > '2026-11-13' GROUP BY connector; ``` ## What a connector reaches A connector asks its system from inside the database's network, so by default it reaches the public internet only: an address on the server's own machine, a private network (10/8, 172.16/12, 192.168/16, 100.64/10, fc00::/7) or another reserved range is refused, checked on each URL and again on each address a name resolves to. A system inside the network is reached when the connector's config says so, `"allow_internal": true` (a Prometheus at `http://prometheus:9090`, oxidized-web on the management network). Link-local addresses, where clouds answer instance metadata (169.254.169.254, fe80::/10), are refused even then. The hosts of `HTTP_PROXY` and `HTTPS_PROXY` are reachable, as the proxy is the operator's. A connector's credentials (its basic or bearer auth, and its `headers`, where `{secret:NAME}` is expanded) go to the origin of its `url` (`instance` for ServiceNow) only. It follows a redirect within that origin, five at most; a redirect to another origin fails the run with where it led. An `http_json` next page on another origin is asked without them, and a `{secret:NAME}` in a URL read from an answer is expanded only when the configured `url` names that secret and the page is on its origin. An answer is read up to 32 MiB (`"max_body_mb"`, 1 to 1024), and a run that gets more fails saying so. ## Keys A connector writes with a key of its own, never with the server's: - **A pull** runs inside the server and writes its rows through the server's own API, with a key the server makes for the run (named `connector-run:`, kept in memory only) that may write the target and nothing else; the connectors' own tables are written with another (`connectors`), which may touch only those. So a pull's rows are checked as any client's are, and a map cannot write another table. - **A push connector** gets a key of the keys file when it is made, named `connector:` and limited to writing its target (a [key limited to tables](server.md#security)). The sending system holds it, and a push is written with the key it came with: one leaked lets its holder write that table, nothing else, and read nothing: the server refuses such a key (by its name, `connector:`) every route but the push, `POST /v1/write` and `GET /v1/health` and `/v1/whoami`, so it cannot query or list even its own table. It is listed in Access and audit, rotated with `POST /v1/admin/connectors/NAME/key`, and revoked when the connector is deleted. On an open server (no token, no key) a push needs no key, and none is made. - **A follower** (`postgres`, `mysql`) writes the source's tables and its marks in `_sources`, and tells the server how it stands, which a key limited to tables may not: it calls the server's own routes in the process with the server's credential ([below](#databases-followed-by-their-logs)). What it may write is still checked: the tables it creates and writes are the source's, and its config names no table of ChloeDB's. ## Who runs the pulls A server of its own, or a coordinator; with several coordinators, the one that sends the alerts' messages (the lowest URL among those that answer), so each pull runs once. A replica or a shard runs none, and `--connectors off` (`CHLOEDB_CONNECTORS=off`) turns them off on any server. A push may go to any coordinator. A pull that runs twice anyway (a coordinator taking over) writes the same rows again, as upserts. ## Maps A record is the JSON a connector read: a Jira issue, a point of a series, an alert, an email. `config.map` names each column of the row and how to fill it: | spec | value | |---|---| | `"$.fields.summary"` | a path into the record: `$` the record, `.name` or `["name"]` a key, `[0]` an element, `[*]` every element | | `"{key}-{fields.status.name}"` | a template, each `{path}` replaced by its value as text | | any other value | itself | | `{"path" \| "template" \| "const" \| "now": true, "split": ",", "values": {...}, "as": "...", "default": ...}` | the value, then in this order: text split into a list; a value replaced by another, by its text (`"*"` for any other); a conversion (`text`, `int`, `float`, `bool`, `time`, `list`, `first`, `json`, `lower`, `upper`, `hash`, `text_of`); a default when it came out empty | A column the map does not name is left out; with no map at all (and no preset), the record is the row. The row is then fitted to the target's columns: a column the table does not have is left out and named in the run (`dropped`), a time in any of the forms systems write (ISO 8601 with any offset, ServiceNow's `2026-11-13 03:00:00`, an email's date, iCalendar's `20261113T030000Z`, seconds or milliseconds since 1970) becomes ISO 8601 text for a `TIMESTAMP`, a number in text a number, one value a list for a `KEYWORD[]` or `INT[]`, and an object or list text for a `TEXT` or `KEYWORD`. A row without the table's primary key makes no row, and the run counts it (`skipped`) with the first reason. ```json "map": { "id": "$.number", "title": "$.short_description", "status": {"path": "$.state", "as": "lower", "values": {"scheduled": "approved", "implement": "running", "*": "planned"}}, "window_start": "$.start_date", "devices": {"path": "$.cmdb_ci", "as": "list"} } ``` ### Default tables and presets Each kind writes its own table with a map of its own. Some targets of the network operations app have presets, used when the connector writes that table and gives no map: | kind | target | | |---|---|---| | `servicenow` | `netops_changes`, `netops_tickets` | a change's number, window, state as the app's status, CI as its devices; an incident's fields as a ticket | | `jira` | `netops_changes`, `netops_tickets` | an issue as a change (custom fields named in `config.fields`: `window_start`, `window_end`, `devices`, `risk`, `approver`, `rollback_plan`) or a ticket | | `oxidized` | `netops_configs` | a version of a device's configuration | | `mail` | `netops_maintenance` | a carrier's notice: provider, maintenance id as the reference, its first circuit, window, impact and status, the text as `raw` | A Prometheus connector writes any table whose columns are its query names and key labels: `{"queries": {"cpu": "...", "mem": "..."}, "key": ["device"]}` writes rows `{id, ts, device, cpu, mem}` (`id` the key labels' values and the time), so `netops_device_metrics` takes them as they are (`rename` renames a label: `{"instance": "device"}`). ## The kinds' settings **prometheus**: `url` (the base URL); `queries` (`{"column": "PromQL"}`); `key` (the labels that name a row's subject; default every label but `__name__`); `rename`; `step_s` (default 60); `lag_s` (how far behind now to stay, default 60, so a step is complete); `backfill_s` (how far back the first run reads, default 3600); `auth` (`basic` with `username` and secret `password`, or `bearer` with secret `token`). A run asks for the steps after the last one it wrote, up to 10,000 steps, and keeps 20,000 records at most: when its series make more, it ends at an earlier step and the next run goes on from there; when one step's series alone are more, the run fails and says so (aggregate them with `sum by` or `topk`). **jira**: `url`; `jql`; `username` (the account's email: Cloud signs in with it and the secret `token`, an API token; without `username`, `token` is sent as a bearer token, as a Data Center personal access token is); `api` (`cloud` or `server`; default `cloud` for `*.atlassian.net`); `fields` (`{"name": "customfield_10050"}`, read into the record's `custom`); `backfill_days` (default 30). The record: `key`, `url`, `project`, `issuetype`, `summary`, `description` (text, from Atlassian's document format too), `status`, `priority`, `assignee`, `reporter`, `labels`, `components`, `created`, `updated`, `resolution`, `resolved`, `due`, `custom`. Since a date in JQL is read in the account's time zone, a run asks for `updated >= "-Nm"` (minutes on Jira's own clock) with a minute or two of overlap. **servicenow**: `instance`; `table`; `query` (an encoded query that narrows them); `fields`; `username` and the secret `password` (or the secret `token` as a bearer token); `backfill_days` (default 30). A record is read with `sysparm_display_value=all` and kept flat: each field's display value (a choice's label, a reference's name) and, where it differs, its value as `_value`; a date-time field's value, which is UTC (its display is in the user's zone). A run asks for `sys_updated_on>=javascript:gs.minutesAgoStart(N)`, on the instance's own clock. **oxidized**: `url` (oxidized-web's); `username` and secret `password` if it is behind basic auth; `max_nodes` (per run, default 200). A pull reads `/nodes.json` and fetches `/node/fetch//` for each node whose last backup is newer than the one it fetched. The record: `id` (`@`), `device`, `ip`, `model`, `group`, `ts`, `version` (the backup's time in seconds, rising per device), `lines`, `sha256`, `body`. Oxidized's exec hook pushes a node as soon as it is stored: ```yaml hooks: chloedb: type: exec events: [post_store] cmd: 'curl -sS -X POST https://chloedb.example.com/v1/connectors/oxidized/push -H "Authorization: Bearer $CHLOEDB_PUSH_KEY" -H "Content-Type: application/json" -d "{\"node\":\"$OX_NODE_NAME\",\"group\":\"$OX_NODE_GROUP\"}"' ``` **mail**: no settings. The body is the raw message (any content type but JSON), or JSON `{"raw": "..."}` (or a list of those). Postfix hands a mailbox's mail over with a pipe (`notices: "|curl -sS -X POST https://.../v1/connectors/carriers/push -H 'Authorization: Bearer sk_...' --data-binary @-"` in `/etc/aliases`), fetchmail with `--mda`, and providers' inbound routes post it. The record: `id` (the Message-ID), `from`, `sender`, `sender_domain`, `to`, `subject`, `date`, `received`, `body` (the first text part, else the HTML part's text), and from a BCOP calendar part `provider`, `account`, `maint_id`, `circuits`, `start`, `end`, `impact`, `status`, `calendar`; without one, `provider` is the sender's domain's name. A notice in another format keeps its text in `body` for a parser that reads it. **webhook**: `records` (the path to the list of records in a request; default the body, or its list); `preset: "alertmanager"` (records `$.alerts`, each alert a row keyed by its fingerprint and start, its labels and annotations as searchable text). In Alertmanager: ```yaml receivers: - name: chloedb webhook_configs: - url: https://chloedb.example.com/v1/connectors/alertmanager/push http_config: authorization: credentials: sk_... ``` **http_json**: `url` (`{cursor}` is replaced by the cursor, URL-encoded); `records`; `next` (the path to the next page's URL, or a path on the same host); `cursor` (the path in a record whose highest value is the next cursor) and `start` (the first one); `headers` (`{secret:NAME}` is replaced by a secret); `auth`, `username`. ## Kafka topics A `kafka` connector reads topics into a table while it is on, and writes each event once. Its section on **Data > Connectors** lists the Kafka connectors with their consumers live: state, events a second, lag (each partition's end less the next offset to write, since there is no consumer group for Kafka's own lag tools to see), events and rows since the server started, replays skipped, events that made no row, and a table of partitions; **Start** and **Stop** turn one on and off (kept in its row, so it stays so across restarts), and **Add a Kafka connector** has a form with a dry run that connects and shows the rows a few events would make. ```bash curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "orders", "kind": "kafka", "target": "orders", "config": { "brokers": "kafka-1:9092,kafka-2:9092", "topics": "orders", "allow_internal": true, "create_target": true, "map": {"id": "$.value.order_id", "customer": {"path": "$.key", "type": "KEYWORD"}, "total": {"path": "$.value.total", "as": "float"}, "at": {"path": "$.ts", "as": "time"}} } }' curl -X POST localhost:7700/v1/admin/connectors/orders/stop -H "Authorization: Bearer $KEY" curl -X POST localhost:7700/v1/admin/connectors/orders/start -H "Authorization: Bearer $KEY" ``` - **Each event once.** Each partition is a [stream source](server.md#streams) named `/` (prefix `kafka//` unless `prefix` says another), whose last offset the server keeps in `_sources` in the same transaction as the rows its events made. A consumer starts each partition after the offset ChloeDB has, not after one committed to Kafka, so a stop, a restart of the server or of a broker, or a coordinator taking over writes no event twice and misses none (a second write of an offset is a replay, and skipped). A partition ChloeDB has no offset of starts at its first event (`"start": "earliest"`, the default) or its end (`"latest"`). Another prefix reads the topics again from the start; two connectors with the same prefix share their offsets. - **Who reads.** The server that runs the pulls ([above](#who-runs-the-pulls)) keeps one consumer per connector: a task per partition fetching, and one writer writing the rows in batches through the stream path, as `POST /v1/stream` does. It commits nothing to Kafka and joins no consumer group. New partitions of its topics are found within 30 seconds and read from their first event. - **Rows.** An event's value is JSON (`"format": "json"`, the default), text (`"text"`), or a Debezium change event (`"debezium"`, [below](#debezium-change-events)). The map reads the event as `{topic, partition, offset, ts, key, value, headers}`: `$.value.x` a field of the value, `$.key`, `$.offset`, `$.ts` (milliseconds since 1970; `"as": "time"` makes it a time). Without a map, a JSON object's fields are the row; the default table, `kafka_events`, keeps each event as a row (`id` `//`, `topic`, `partition_`, `offset_`, `ts`, `msg_key`, `value` as JSON, `text` the value's text, searched, `headers`). A keyed table whose row has no key gets `//`; a keyed table's rows are upserted, another's inserted. An event no row comes of (a value that is not JSON, a map that fails) still moves its partition's offset, and is counted with the first reason. A tombstone (an event without a value) writes nothing, or, with `"tombstones": "delete"`, deletes the row of its key. - **When it fails.** A broker that cannot be reached, a sign-in refused or a write that fails ends the consumer's session, and the next one starts after a wait that doubles up to a minute, from ChloeDB's offsets again; the connector's health is `failing` until it streams. Events that the topic's retention deleted before they were read are counted (`lost`) and said in a warning, and the partition goes on from its first event kept. A partition whose offsets went back (a topic emptied or made again) stops the consumer with an error that says so, since its new offsets would be taken for events written already: give the connector another prefix to read it. The settings, in `config`: `brokers` (bootstrap brokers, `host:port`, joined by commas or a list); `topics` (joined by commas or a list); `start`; `format`; `map`; `prefix`; `tombstones` (`skip` or `delete`); `tls` (`true` to connect with TLS, checked against the public roots, or against `ca_pem`, a PEM certificate); `sasl` (`{"mechanism": "PLAIN" | "SCRAM-SHA-256" | "SCRAM-SHA-512", "username": "..."}`, the password the secret `password`); `allow_internal` (the bootstrap brokers are checked as a pull's URL is: a private address, or this machine, only with `true`); `batch` (events written at a time, 1 to 4,096, default 1,000); `max_wait_ms` (how long a fetch waits for new events, 10 to 10,000, default 500); `fetch_kb` (1 to 65,536, default 1,024). The API answers a Kafka connector with `"streams": true` and its consumer as `stream`; `POST /v1/admin/connectors/NAME/run` is refused for one (it streams while it is on), and its runs table gets a row per session (`trigger` `stream`, every 10 minutes while it lasts). ### Debezium change events With `"format": "debezium"`, each event is a change Debezium (or Redpanda Connect, or Flink CDC in Debezium's format) read from a database's log, with its schema in the envelope or not (`{"schema": ..., "payload": {...}}`, or the payload alone). A create, an update or a snapshot's read (`op` `c`, `u`, `r`) upserts the row after the change; a delete (`d`) deletes the row named by the key of the row before it (the target's primary key read from `before`, or from the event's key); a truncate (`t`) is counted as an event that made no row, and a tombstone (the null Kafka writes after a delete) is skipped. The map reads `$.value` as the row after the change, with the envelope beside it: `$.op`, `$.before`, `$.source` (`$.source.table`, `$.source.lsn`...) and `$.ts`, the change's time in the source (`source.ts_ms`). Without a map, the row's columns are the target's. ```bash curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "shop-items", "kind": "kafka", "target": "items", "config": {"brokers": "kafka-1:9092", "topics": "shop.public.items", "format": "debezium", "allow_internal": true, "map": {"id": "$.value.id", "title": "$.value.title", "changed": {"path": "$.ts", "as": "time"}}} }' ``` Since a partition's offset is kept with its rows, a change is applied once, in the order its partition has it (Debezium writes a row's changes to one partition, by its key). To follow Postgres without Kafka, the server reads its log itself ([`follow-postgres`](postgres.md)). ### The test broker To try a connector without Kafka, the server has a test broker: a broker in its own process that speaks as much of Kafka's protocol as a consumer needs (and producing, so any Kafka client can write to it), keeps topics in memory (the last 200,000 events of each partition), and writes made-up click events (`{event_id, user, item, action, page, at, price}`, keyed by user) into a topic at a rate. On **Data > Connectors** the **Test Kafka broker** card starts and stops it, sets the rate, sends an event typed in, and **Connect a connector to it** fills the form with its address, its topic and a map into `demo_clicks`. By the API: ```bash curl -X POST localhost:7700/v1/admin/kafka/test-broker -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"listen": "127.0.0.1:19092", "topic": "demo.clicks", "partitions": 3, "rate": 5}' # or {"rate": 50} while it runs curl -X POST localhost:7700/v1/admin/kafka/test-broker/produce -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"topic": "orders", "messages": [{"key": "c42", "value": {"order_id": "o1", "total": 19.5}}]}' curl localhost:7700/v1/admin/kafka/test-broker -H "Authorization: Bearer $KEY" # its topics, offsets and counts curl -X DELETE localhost:7700/v1/admin/kafka/test-broker -H "Authorization: Bearer $KEY" ``` The API starts it on a loopback address only, and it stops with the server; `username` and `password` make it ask clients to sign in with SASL PLAIN. For one other machines reach, run it on its own: `chloedb-server kafka-test-broker --listen 0.0.0.0:19092 --advertise test-kafka.internal --topic demo.clicks --rate 20` (`--advertise` is the host its clients are told to connect to after the first; `--username` with `CHLOEDB_KAFKA_TEST_PASSWORD` for a sign-in). Kafka's own tools that need no consumer group read and write it too: `rpk topic consume demo.clicks -X brokers=127.0.0.1:19092`. It is for trying and testing, not a Kafka: one broker, no replication, nothing kept on disk. ## Databases followed by their logs A `postgres` or `mysql` connector runs the follower of [`follow-postgres`](postgres.md) or [`follow-mysql`](mysql.md) inside the server, while the connector is on: it copies the database's tables, then applies each change a moment after the database commits it, and keeps what it applied in `_sources` with the rows, so a stop, a restart of the server or a coordinator taking over goes on from there. Its tables are named after the database's (a table of another MySQL database is `_
    `), so it has no `target`; they take no other writes while it follows them (409, `followed_table`). ```bash curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "shop", "kind": "mysql", "config": {"url": "mysql://chloedb@db.internal:3306/shop?ssl-mode=verify_identity", "tables": "orders,customers", "allow_internal": true}, "secrets": {"password": "env:CHLOEDB_CONNECTOR_SECRET_SHOP_DB"} }' curl -X POST localhost:7700/v1/admin/connectors/shop/test -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{...the same body...}' # a dry run: the tables it would follow ``` - **Settings.** `url` (`postgres://user@host:5432/db` or `mysql://user@host:3306/db`, with `sslmode` or `ssl-mode` as the commands take them, and no password: a URL with one is refused, since the config is a row a read key reads; the password is the secret `password`); `ca_pem` (a CA certificate, PEM, to check the database's by; a path to a file of the server's, `sslrootcert`, is refused); `allow_internal` (the database's host is checked as a pull's URL is); `batch` (rows of one write, default 1,000). Postgres: `publication` (default `strata`), `slot` (default `strata_`), `copy_workers` (default 4). MySQL: `tables` (`orders`, `shop.orders`, `shop.*`, joined by commas; default every table of the URL's database), `server_id` (default a number made from the name). Set the database up as each page says ([Postgres](postgres.md#set-up-postgres), [MySQL](mysql.md#set-up-mysql)). - **Who follows.** The server that runs the pulls ([above](#who-runs-the-pulls)) runs one follower per connector, with its own routes (no HTTP between them) and a credential of the server's: its token, or, on a server with keys and no token, an admin key it makes in memory for the follower (`connector-follower:`, listed in Access, ended when the follower stops). A follower that fails starts again after a wait that doubles up to a minute; the connector's health is `failing` meanwhile, with the error. - **Health.** `streaming` once it follows, `copying` while it copies, `connecting`, `failing`, `stale` (it has not told how it stands for a minute), `pending`, `disabled`. The follower is listed under `followers` too, with its lag, tables and positions, as a follower run by itself is ([Postgres](postgres.md#how-far-behind-it-is), [MySQL](mysql.md#how-far-behind-it-is)), and `follow-behind` alerts on it. - **Stop, start, delete.** `POST .../stop` stops reading: a Postgres slot keeps the WAL meanwhile, which can fill the database's disk over days, and MySQL may purge the binlog files, after which the next start copies again. `.../start` goes on from what ChloeDB applied. Deleting the connector stops it, releases its tables, which take other writes again, and drops a Postgres connector's slot, so that Postgres keeps no WAL for it (the answer's `released` says what it did). When the database cannot be reached then, the answer says so and the tables stay followed: end it with `follow-postgres --drop-slot` or `follow-mysql --release` and the connector's name. To pause without losing the slot's place, stop it instead. `POST .../run` is refused: it follows while it is on. ## MCP servers An `mcp` connector makes ChloeDB a client of an MCP server: each run opens a session over the Streamable HTTP transport (`initialize`, then `notifications/initialized`, with the `Mcp-Session-Id` the server gives on every later message), calls a tool with the connector's arguments, or reads a resource, and ends the session. So any system that has an MCP server (a SaaS product's, a company's own, another ChloeDB's `/v1/mcp`) can fill a table without a connector of its own. ```bash curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "shop-orders", "kind": "mcp", "target": "orders", "every_s": 300, "config": {"url": "https://mcp.shop.example.com/mcp", "tool": "list_orders", "arguments": {"updated_since": "{cursor}", "limit": 100}, "start": "2026-01-01T00:00:00Z", "records": "$.orders", "cursor": "$.updated_at", "next": "$.next_page", "next_argument": "page_token", "create_target": true, "map": {"id": "$.id", "customer": {"path": "$.customer", "type": "KEYWORD"}, "total": {"path": "$.total", "as": "float"}, "updated_at": {"path": "$.updated_at", "as": "time"}}}, "secrets": {"token": "env:CHLOEDB_CONNECTOR_SECRET_SHOP_MCP"} }' ``` - **The result.** A tool's result is its `structuredContent` when it has one; else its text content read as JSON (one text that is JSON is that value, several are a list of them), and texts that are not JSON are records `{"text": ...}`. A resource's contents are read the same way. `records` is a path into it (default: the result, or its list). A result with `isError` fails the run with the tool's own words. - **Incremental reads.** `cursor` is a path in a record whose highest value is kept; an argument written `"{cursor}"` is given that value, a number staying a number (and its text inside a longer string); `start` is the first one (read as JSON when it is: `"0"` is the number 0). - **Pages.** `next` is a path into the result to the next page's token, given as the argument `next_argument` (default `cursor`) of the next call, until there is none. A run that reaches its `batch` stops after that page, and the next run goes on from the next page with the same cursor; the pass that reads the last page keeps the highest value it read. - **Answers** may be JSON or a stream of server-sent events, of which the event that answers the request is read (progress notices before it are passed over). - **Signing in.** The secret `token` is sent as a bearer token; `headers` adds others, `{secret:NAME}` a secret. A server's OAuth sign-in in a browser is not done by the connector: give it a token the server issues. The settings: `url` (the Streamable HTTP endpoint); `tool` and `arguments` (an object), or `resource` (a URI); `records`; `cursor`; `start`; `next`; `next_argument`; `headers`; `batch`; `map`; `allow_internal`; `max_body_mb`. A dry run (`POST /v1/admin/connectors/test`) calls the tool (up to 200 records) and shows the rows it would write, writing none. ## Files and warehouses **s3** watches a prefix of an object store. Each run lists it, and reads the files modified since the last one it read, oldest first (then by name), up to `batch` rows (20,000 at most): a file larger than that is read over several runs, each from the row the last stopped at, and a file written over (a newer modification time) is read again. Its rows are upserted by the table's key, or inserted into a table without one. The requests are signed with SigV4 by the connector itself, with the secrets `access_key_id`, `secret_access_key` and `session_token` (temporary keys), never the server's own `AWS_*`; with neither secret, a bucket is read unsigned, as a public one is. For Cloud Storage, make HMAC keys (Cloud Storage > Settings > Interoperability) for a service account that reads the bucket. ```bash curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "events", "kind": "s3", "target": "events", "every_s": 300, "config": {"url": "s3://my-lake/events/2026/", "region": "eu-west-1", "key": "event_id", "create_target": true}, "secrets": {"access_key_id": "env:CHLOEDB_CONNECTOR_SECRET_LAKE_ID", "secret_access_key": "env:CHLOEDB_CONNECTOR_SECRET_LAKE_KEY"} }' ``` The settings: `url` (`s3://bucket/prefix/` or `gs://bucket/prefix/`); `format` (`parquet`, the default, or `jsonl`); `suffix` (the files read, by how their names end: `.parquet` or `.jsonl` by default, `""` for every object); `region` (default `us-east-1`, `auto` for `gs://`); `endpoint` (another store: `https://.r2.cloudflarestorage.com`, `https://.digitaloceanspaces.com`, MinIO's address; a plain `http://` one needs `allow_internal`); `path_style` (the bucket in the path, not the host: the default for an `endpoint`, and on AWS for a bucket whose name has a dot); `key`; `batch`; `max_body_mb` (the largest file read, default 32 MiB, at most 1,024: a file is read whole). A Parquet file's rows are read with their columns' types (a time as a time, a list of text as a `KEYWORD[]`, a fixed-size list of floats as a vector); each record also has `_file`, its file's name, for a map's `$._file`. A prefix of more than 200,000 objects is refused: name a narrower one. **snowflake** and **bigquery** read a table (`"table"`) or a query (`"query"`, one `SELECT` or `WITH`). With a `cursor` column (`updated_at`), each run asks for the rows past the last value it read, in its order: `SELECT * FROM
    WHERE > ? ORDER BY LIMIT `, the value bound as a parameter, never written into the statement. A batch never ends inside a value: when the row past it shares the last rows' value, those rows are left to the next run, which reads them whole (a value shared by more rows than a batch is a run that fails and says so: choose a finer column). Rows with no value in the cursor column are not read. With no cursor but a `key`, the key orders the reads, and the table is read again from its start once a pass ends; with neither, the whole source each run (20,000 rows at most). A row read again is upserted by the key. Deletes in the warehouse are not seen: follow a log for those (Postgres, MySQL or Debezium), or read the whole table by key. ```bash curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "orders", "kind": "snowflake", "target": "orders", "every_s": 600, "config": {"account": "myorg-myaccount", "user": "CHLOEDB_READER", "table": "SHOP.PUBLIC.ORDERS", "cursor": "updated_at", "key": "id", "warehouse": "XS_WH", "create_target": true}, "secrets": {"private_key": "env:CHLOEDB_CONNECTOR_SECRET_SNOWFLAKE_KEY"} }' curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "signups", "kind": "bigquery", "target": "signups", "every_s": 600, "config": {"project": "my-project", "table": "analytics.signups", "cursor": "created_at", "key": "user_id", "location": "US", "create_target": true}, "secrets": {"service_account": "env:CHLOEDB_CONNECTOR_SECRET_BQ_KEY"} }' ``` Snowflake's settings: `account` (`myorg-myaccount`, or a locator such as `xy12345.us-east-1`); `user`; `table` (`DATABASE.SCHEMA.TABLE`) or `query`; `cursor`; `key`; `warehouse`; `role`; `batch`; `token_type` (`pat`, the default, or `oauth`, for the secret `token`); `base_url` (for a private link: default `https://.snowflakecomputing.com`). It signs in with a key pair, the secret `private_key` (the user's RSA key in PKCS #8 PEM, `BEGIN PRIVATE KEY`, unencrypted, whose public key is the user's `RSA_PUBLIC_KEY`: `ALTER USER CHLOEDB_READER SET RSA_PUBLIC_KEY='MIIB...'`), or a programmatic access token (or OAuth's) as the secret `token`. A statement still running is waited for (5 minutes at most), and an answer in several partitions read whole. Its columns' names are read in lower case (`$.updated_at`), times as UTC, `VARIANT`, `OBJECT` and `ARRAY` as JSON. BigQuery's settings: `project` (where the queries run and are billed); `table` (`dataset.table` or `project.dataset.table`) or `query` (GoogleSQL); `cursor`; `key`; `location`; `batch`; `base_url`. It signs in with a service account's key, the secret `service_account` (its JSON; its signed request for a token goes to `https://oauth2.googleapis.com/token` only, whatever the key names), or an access token as the secret `token`. Give the service account BigQuery Data Viewer on the dataset and BigQuery Job User on the project. Times are read to the microsecond, a `RECORD` as JSON, a `REPEATED` column as a list. A target that does not exist is made, with `"create_target": true` (or as the kind's default table), from the source's columns: the first file's for `s3`, the table's or the query's (`LIMIT 0`) for a warehouse, `key` its primary key. A column of a type it does not keep (binary) or whose name is not one of letters, digits and `_` is left out, and the answer says which (`made_target.columns_left_out`). With a `map`, the map's columns make it instead, as for any kind. ## Apps Four kinds read an app's API (and Google Drive does too, [below](#google-drive-and-sheets)) with the app's own way of finding what changed, so each run after the first reads only that. Each signs in with a secret of its own, keeps its cursor as JSON in `state.cursor`, and goes on from the page it stopped at when a run reaches its `batch`. Each has a default table and map (`GET /v1/admin/connectors` lists them), the record whole in a JSON column (`data`, or `properties`) and its words in `text`, for `MATCH`; give a `map` for other columns. ```bash curl -X POST localhost:7700/v1/admin/connectors -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{ "name": "customers", "kind": "stripe", "every_s": 300, "config": {"object": "customers"}, "secrets": {"api_key": "env:CHLOEDB_CONNECTOR_SECRET_STRIPE"} }' ``` - **stripe** lists `object` (`/v1/customers`, 100 a page) the first time, then reads the events of that object created since the list began (`customer.*` for customers, `customer.subscription.*` for subscriptions; `events` names others), oldest first, each event's object a row, with `deleted` true for a `*.deleted` event and the event as `_event`. A batch ends between two seconds of events, so none is read twice or left out. Secret: `api_key`, a restricted key that can read the list and events (Stripe keeps events 30 days: a connector off longer than that lists again when its cursor is cleared). Settings: `object`, `events`, `api_version` (default `2024-06-20`). - **shopify** reads `resource` (default `orders`; `products`, `customers`, ...) ordered by `updated_at`, from the highest value read before, 250 a page, following the `Link` header's next page on the store's own address only; orders of every `status` unless it says one. Secret: `access_token`, an Admin API token (a custom app's, `shpat_...`) with the resource's read scope. Settings: `shop` (`my-store.myshopify.com`), `resource`, `status`, `api_version` (default `2025-07`). - **odoo** signs in through `/jsonrpc` (`common.authenticate`) and reads `model` with `search_read`, ordered by `write_date` and `id`, each run from the last pair read (so records written in the same second are not lost), narrowed by `domain` when it gives one. The fields read are `fields`, or every field but binaries (pictures, attachments); a many-to-one field is `{"id", "name"}` (JSON), a many-to-many one a list of ids, a date a time, and Odoo's `false` for an empty field no value. Its table is made from the model's fields (`fields_get`), with `"create_target": true` or as the default, `id` its key. Secret: `api_key` (Preferences > Account Security > New API Key) or `password`. Settings: `url`, `db`, `username`, `model`, `fields`, `domain`, `key`. Records deleted in Odoo are not seen. - **hubspot** searches `object` (`/crm/v3/objects//search`) for records whose last change (`lastmodifieddate` for contacts, `hs_lastmodifieddate` for the others) is at or after the highest read before, oldest first, 100 a page; a search that reaches HubSpot's 10,000 results begins again at once from the highest value read. A record's properties are its columns, with `id`, `createdAt`, `updatedAt` and `archived`. Secret: `token`, a private app's access token with the object's read scope, or a [sign-in](#sign-in-with-hubspot-shopify-or-stripe)'s `refresh_token`, `client_id` and `client_secret`, traded at each run for an access token at `/oauth/v1/token`. Settings: `object`, `properties` (default: HubSpot's default properties of the object). Each also takes `batch`, `map`, `base_url` (another address: a test's, a proxy's), `allow_internal` and `max_body_mb`. A dry run (`POST /v1/admin/connectors/test`) reads the first page and shows the rows it would write. ## Google Drive and Sheets Paste a link, and sign in with Google when the file is not shared with anyone who has the link: the Connectors page's **Google Drive** box makes the connectors a link needs, runs each once, and links their tables. Each keeps in step with Drive from then on, every 15 minutes. - **A spreadsheet** (a Google Sheet, or an Excel `.xlsx` or CSV file in Drive): each tab is a table of its own, named after the file and the tab (`budget_2026_q1`). The header row gives the columns, in lower case with `_` for spaces and signs (`Amount ($)` is `amount`), and each column's type is guessed from its values: `INT`, `FLOAT`, `BOOL`, `TIMESTAMP` (a Sheet's date cells, an Excel date, text that reads as a time) or `TEXT`. Each row is keyed by its row number in the sheet, `sheet_row`. When the file changes, the tab is read again whole: changed rows are updated, and rows no longer in it are deleted. A link to one tab (`#gid=`) imports that tab only. - **A folder**: its files and its subfolders' files, into one table (`team_docs_files`), with their text, to search with `MATCH(text, '...')`. Docs and Slides are read as text, Sheets as CSV, Word (`.docx`), PowerPoint (`.pptx`) and Excel files read by the server, and text, JSON and XML files as they are, up to 2 MiB of text a file. PDFs and pictures come with their details only (name, type, owners, link, size, times). The folder's spreadsheets (the ten changed last) are each made tables too, as above. - **A Doc, Slides or another file**: a row of `drive_files`. ```bash # Signed in (the page does this): start, open the url, then ask for the grant. curl -X POST localhost:7700/v1/admin/google/start -H "Authorization: Bearer $KEY" -d '{}' # {"state": "…", "url": "https://accounts.google.com/o/oauth2/v2/auth?…", "redirect_uri": "…/v1/google/callback"} curl "localhost:7700/v1/admin/google/grant?state=…" -H "Authorization: Bearer $KEY" # {"state": "done", "grant": "…", "account": "ana@example.com"} curl -X POST localhost:7700/v1/admin/google/import -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"link": "https://docs.google.com/spreadsheets/d/1AbC…/edit", "grant": "…"}' # {"connectors": [{"name": "budget-2026-q1", "kind": "google_sheets", "target": "budget_2026_q1", "ok": true, "rows": 212}, …], "account": "ana@example.com"} ``` **Picking folders.** After signing in, the box's **Pick folders** opens Drive in a drawer: My Drive, Shared with me and the shared drives, then each folder's subfolders, with how many files are in it and whether a connector already watches it. Tick folders and **Watch the folders ticked** makes a connector for each; unticking a watched one pauses its connector, and ticking it again starts it. A folder inside a watched one is watched already (its files are in that table). Once a folder connector exists the picker browses with its sign-in, so a later visit needs no new one. The page asks the server: ```bash curl -X POST localhost:7700/v1/admin/google/browse -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"folder": "root", "grant": "…"}' # or "connector": "team-docs-files" instead of the grant # {"folder": "root", "folders": [{"id": "1AbC…", "name": "Team Docs", "modified": "…", "owner": "Ana", "watched_by": {"connector": "team-docs-files", "enabled": true}}, …], # "here": {"files": 12, "more": false}, "account": "ana@example.com", "watched_here": null} ``` With no `folder` it answers the top level (`root` is My Drive, `shared` is Shared with me, and each shared drive by its id). `POST /v1/admin/google/import` takes `connector` in place of `grant` the same way, and copies that connector's sign-in to the new one. **Searching them.** The command center's **Documents** page (Build) searches a Drive table's files as Drive does: the words against the text and the name, ranked by BM25 with the name counted twice and typos forgiven, the types and how recent as filters with their counts, each result's best passage marked, and a document read in a drawer with every match marked. It finds every table with the columns `name`, `mime`, `url` and a TEXT column `text`, and shows the SQL it ran: ```sql SELECT id, name, mime, modified, owners, url, size FROM team_docs_files WHERE (MATCH(text, :q, syntax => 'plain', fuzzy => 'auto') OR MATCH(name, :q, syntax => 'plain', fuzzy => 'auto')) AND modified >= now() - INTERVAL '1 month' ORDER BY bm25(text, :q, fuzzy => 'auto') + 2 * bm25(name, :q, fuzzy => 'auto') DESC LIMIT 30 ``` The passages come from `POST /v1/highlight` with `keys` (the rows' ids) in place of `texts`, so the server reads each document's text from its row and the page never fetches a long document whole. **Signing in.** The sign-in asks Google for read-only access to Drive (`drive.readonly`) and the account's address, with the authorization code flow and PKCE: Google sends the browser back to `/v1/google/callback` with a code, which the server trades for a refresh token at once. The refresh token is kept as each connector's secret `refresh_token` (in the secrets file, never in a table or an answer), and each run trades it for an access token of an hour. A grant waits 30 minutes for the connectors made with it (`"secrets": {"google_grant": "…"}` in `POST /v1/admin/connectors` uses one too), and a sign-in has 10 minutes from its start. A run whose sign-in Google no longer honors (taken off at myaccount.google.com/permissions, a password changed, six months unused) fails and says to sign in again. **Without signing in.** A Doc, Slides or Sheet shared "Anyone with the link" is read from Google's export addresses, with no credentials (a Sheet's tab as CSV, its types guessed from the text; it says nothing of when it changed, so the tab is read each run, and written only when it did). A folder needs a sign-in, a service account (the secret `service_account`; share the folder with its address) or, for one shared with anyone, an API key (the secret `api_key`). **Setting it up on a server.** Signing in needs the server's Google OAuth client, the same one the command center's Google sign-in uses (or a new one of type Web application), once: 1. In the Google Cloud console, in the client's project: APIs & Services, Library, turn on the **Google Drive API** and the **Google Sheets API**. 2. Google Auth Platform, Data access: add the scope `.../auth/drive.readonly`. It is a restricted scope: an app in testing works for its test users (up to 100), and an internal app of a Google Workspace organization for its people; an external app for anyone needs Google's verification. 3. Google Auth Platform, Clients, the client: under Authorized redirect URIs add `https:///v1/google/callback` (and `http://localhost:7700/v1/google/callback` to try it on a laptop), and make a client secret. 4. Start the server with `--google-client-id` and `--google-client-secret`, or `CHLOEDB_GOOGLE_CLIENT_ID` and `CHLOEDB_GOOGLE_CLIENT_SECRET` in its environment (on Kubernetes, from a Secret: `env: [{name: CHLOEDB_GOOGLE_CLIENT_SECRET, valueFrom: {secretKeyRef: {name: chloedb-google, key: client-secret}}}]`). The redirect address is `--public-url`'s when it is set, else the address the page was opened at. Without `--google-allow`, the client is used for Drive only, and nobody signs in to the command center with it. The kinds' settings. `google_sheets`: `url` (the spreadsheet's link or id; an Excel or CSV file's in Drive too); `sheet` (the tab's title; default the link's `#gid=` tab, else the first); `gid`; `header_row` (default 1); `key` (a column to key rows by instead of `sheet_row`; rows gone from the tab are then not deleted). `google_drive`: `folder` (a folder's link or id); `recursive` (default true: its subfolders, to 500 folders); `drive` (a shared drive's id); `files` (a list of files' links or ids, read each run they changed); `query` (a Drive search that narrows them: `mimeType = 'application/pdf'`); `text` (false: details only). Both take `batch`, `map`, `base_url`, `allow_internal` and `max_body_mb`, and the secrets `refresh_token` (a sign-in's), `service_account`, `token` or `api_key`. ## Limits - One run reads 20,000 records at most (a push too: one of more answers 413, and a push's body is 32 MiB at most, or `--max-body-mb` when that is smaller), and writes them 500 rows (or about 4 MB) at a time; a run that stopped at the limit runs again at once. An `http_json` pull whose cursor does not move its URL on (no `cursor` path, or no `{cursor}` in the URL) keeps the next page's URL in its cursor instead (`{"next": URL, "cursor": ...}`, a secret in it kept as its `{secret:NAME}`), so the next run goes on from that page, and the run that reads the last page clears it. A run that fails partway keeps the rows it wrote and its cursor, so the next one reads them again, as upserts. - A pull runs for 10 minutes at most; each request to the system waits 60 seconds. - Pulls are not yet spread over coordinators or shards, and a connector's runs are one at a time. - A Kafka connector's writer writes up to `batch` events (default 1,000) at a time, and each partition's fetch asks for up to `fetch_kb` (default 1 MiB); one server reads every partition of its Kafka connectors (no consumer group spreads them over servers). - An `s3` run reads each of its files whole (`max_body_mb`, 32 MiB by default), and a warehouse's run waits 5 minutes at most for its statement. - Not yet connectors: IMAP mailboxes (hand the mail over instead). Of the apps, only `stripe` sees deletes. --- # The OpenSearch API `chloedb-server --opensearch-listen 127.0.0.1:9200` answers OpenSearch's REST API on a port of its own: an application written for OpenSearch or Elasticsearch 7 (Gitea, Mastodon, an OpenSearch client library) indexes into ChloeDB and searches it without a change. An application on one of Elasticsearch 8's clients needs the OpenSearch client of its language instead, as [below](#elasticsearch-8s-clients). Each index is a ChloeDB table; queries in OpenSearch's Query DSL become SQL. What ChloeDB does not answer, it refuses with a 400 that says so, rather than answer another request. ## Run it ```sh chloedb-server --db search.chloedb --opensearch-listen 127.0.0.1:9200 curl -s localhost:9200/ # {"version": {"number": "2.11.0", "distribution": "opensearch"}, ...} curl -s -XPUT localhost:9200/books -H 'content-type: application/json' \ -d '{"mappings": {"properties": {"title": {"type": "text"}, "year": {"type": "long"}}}}' curl -s -XPOST 'localhost:9200/books/_doc/1?refresh=true' -H 'content-type: application/json' -d '{"title": "The quick brown fox", "year": 2026}' curl -s localhost:9200/books/_search -H 'content-type: application/json' -d '{"query": {"match": {"title": "fox"}}}' ``` | flag | environment | what | |---|---|---| | `--opensearch-listen ADDR` | `CHLOEDB_OPENSEARCH_LISTEN` | where the API listens (off when not given) | | `--opensearch-version V` | `CHLOEDB_OPENSEARCH_VERSION` | the version `GET /` reports, `2.11.0` by default; a `7.x` version (`7.10.2`) answers as Elasticsearch 7 does, which clients of Elasticsearch 7 check for (elasticsearch-ruby 7.17, which Mastodon uses, refuses OpenSearch 2.x itself) | It shares the server's TLS (`--tls-cert`), hosts (`--allow-host`) and credentials. With a token or keys, a request carries one as `Authorization: Bearer `, or as the password of Basic authentication (any user name), which is how most OpenSearch clients send one: `http://user:@host:9200`. Reads need a key of scope `read`, writes of documents `write`, and changes to indexes, mappings, aliases and settings `admin`; an index made by its first document needs `admin` too. A key of every table reaches every index; a [key bound to a tenant](#keys-bound-to-a-tenant) reaches one tenant's documents of its indexes, and a key limited to tables is refused here (it calls the HTTP API). On a coordinator, or beside one (`--coordinator-listen`), the indexes are tables of the cluster, split over its shards. ## Tested with | client | how | result | |---|---|---| | [opensearch-py](https://pypi.org/project/opensearch-py/) | 34 checks: indexes, `helpers.bulk`, searches, scroll, aggregations, documents, aliases, errors | 34 of 34 pass, as they do on OpenSearch 2.11 | | [Gitea](https://gitea.com) 1.24.6 | its issue indexer and code indexer set to `elasticsearch` at this port, next to a second Gitea on OpenSearch 2.11, the same repository and issues in both | 42 of 42 searches find the same issues and files | | [Mastodon](https://joinmastodon.org) 4.3 | its four indexes (accounts, tags, statuses, public statuses: analyzers, mappings) and the searches its services make (account autocomplete and full search with follower boosts, hashtag search, status search over two indexes), replayed on 1,500 accounts, 1,200 tags and 4,000 statuses next to OpenSearch 2.11 | 112 of 114 searches return the same hits in the same order; the other two differ in the order of two hits tied at score 0 | | elasticsearch-ruby 7.17 (Mastodon's client, through Chewy) | its product check, index creation, `_bulk`, a search with `script_score` | works with `--opensearch-version 7.10.2` | | [opensearch-go](https://github.com/opensearch-project/opensearch-go) v4.8.1 | a multi-tenant service's loader (`BulkIndexer`, 300,000 documents) and searches (`bool` with filters, `multi_match`, `terms` aggregations, highlights, `search_after`), in a persona study of 0.3.8 | work unchanged | | go-elasticsearch v8.19.7 | the same service on Elasticsearch 8's Go client, at every `--opensearch-version` | refuses the server before its first request: see [Elasticsearch 8's clients](#elasticsearch-8s-clients) | | OpenSearch 2.11 itself | 100 requests sent to both, answers compared field by field | 96 identical; the others are listed under [Differences](#differences) | | OpenSearch 2.11 on [TREC-COVID](#numbers) | 3,000 searches of ten kinds over 171,332 abstracts | every one finds as many hits; see [Numbers](#numbers) for the first pages | Gitea's `app.ini`: ```ini [indexer] ISSUE_INDEXER_TYPE = elasticsearch ISSUE_INDEXER_CONN_STR = http://127.0.0.1:9200 REPO_INDEXER_ENABLED = true REPO_INDEXER_TYPE = elasticsearch REPO_INDEXER_CONN_STR = http://127.0.0.1:9200 ``` Mastodon's `.env.production`: `ES_ENABLED=true`, `ES_HOST=localhost`, `ES_PORT=9200`, `ES_PRESET=single_node_cluster`, and the server started with `--opensearch-version 7.10.2`; then `tootctl search deploy`. ### Elasticsearch 8's clients Elasticsearch 8's official clients (Go's go-elasticsearch v8, Java's elasticsearch-java, Python's elasticsearch 8, JavaScript's @elastic/elasticsearch 8) check that every answer carries Elastic's product header, `X-Elastic-Product: Elasticsearch`, which ChloeDB does not send at any `--opensearch-version`; they stop at the first answer with "the client noticed that the server is not Elasticsearch and we do not support this unknown product". Move such an application to the OpenSearch client of its language: [opensearch-go](https://github.com/opensearch-project/opensearch-go), [opensearch-java](https://github.com/opensearch-project/opensearch-java), [opensearch-py](https://pypi.org/project/opensearch-py/) or [opensearch-js](https://github.com/opensearch-project/opensearch-js), which send the same requests and read the same answers; its queries and index mappings stay as they are. An Elasticsearch 7 client works with `--opensearch-version 7.10.2`. ## What it answers **APIs**: `GET /`, `_cluster/health`, `_cluster/settings`, `_cluster/state`, `_nodes`, `_cat/indices|aliases|health|count` (text with `v`, `h`, `s`, or `format=json`), index `PUT`/`GET`/`HEAD`/`DELETE` (names, patterns with `*`, `_all`, comma lists, aliases; `DELETE` takes names and patterns of names, never an alias, as in OpenSearch), `_mapping` and `_settings` (read and add), `_aliases`/`_alias` (`add` with a `filter` and `is_write_index`, `remove`, `remove_index`, the actions of one request applied at once), `_stats`, `_refresh`, `_flush`, `_forcemerge` (accepted; ChloeDB needs none of them), `_doc`, `_create`, `_update` (`doc`, `upsert`, `doc_as_upsert`, `detect_noop`), `_source`, `_mget`, `_bulk` (`index`, `create`, `update`, `delete`), `_search`, `_msearch`, `_count`, `_search/scroll`, `_delete_by_query`, `_update_by_query` (without a script), `if_seq_no`, `version_type=external`, `refresh`, `filter_path`, `pretty`, `_source` filtering, and gzip request bodies. **Queries**: `bool` (`must`, `filter`, `should` with `minimum_should_match`, `must_not`), `match` (`operator`, `minimum_should_match`, `fuzziness`, `zero_terms_query`), `match_phrase`, `match_phrase_prefix`, `match_bool_prefix` (`operator`, `minimum_should_match`, `fuzziness`), `multi_match` (`best_fields`, `most_fields`, `cross_fields`, `phrase`, `phrase_prefix`, `bool_prefix`, `field^boost`, `field.*`), `query_string` and `simple_query_string` (Lucene's syntax: fields, `AND`/`OR`/`NOT`, `+`/`-`, phrases, `*` and `~`), `term`, `terms`, `ids`, `range` (with date math: `now-7d/d`), `exists`, `prefix`, `wildcard` (a trailing `*`), `fuzzy`, `constant_score`, `dis_max`, `function_score` (`field_value_factor`, `gauss`/`exp`/`linear` on numbers and dates, `script_score`, `weight`, every `score_mode` and `boost_mode`), `script_score`, `nested` (as paths of objects), `knn` (with `filter`), `match_all`, `match_none`, and `term`/`terms` on `_index`. **Scripts**: `script_score` runs the part of Painless that scoring scripts are written in: numbers, `params.x`, `doc['field'].value` of a number or a date, `_score`, `+ - * /`, `Math.log10`, `log`, `log1p`, `exp`, `sqrt`, `pow`, `abs`, `max`, `min`, and Painless's `saturation`, `sigmoid` and `decayNumericGauss|Exp|Linear`, with an optional `return` and `;`. Anything else is refused with a `script_exception` that names what it met. **Searches**: `from`/`size` (to 10,000, or the index's `max_result_window`), `sort` (fields, `_score`, `_doc`, `missing`), `search_after`, `track_total_hits`, `post_filter`, `highlight` (`pre_tags`, `post_tags`, `fragment_size`, `number_of_fragments`, `encoder`), `fields`/`docvalue_fields`, `version`, `seq_no_primary_term`, `collapse` (the first hit of each value), scrolls (past 10,000 hits when in the documents' order), and searches of several indexes at once (`a,b/_search`, a pattern, an alias of several), which merge their hits in the search's order. **Aggregations**: `terms` (`size`, `order`, `min_doc_count`, `missing`, `include`/`exclude` lists), `composite` (`terms` and `date_histogram` sources, `after`), `histogram`, `date_histogram` (`calendar_interval`, `fixed_interval`, `min_doc_count`, `extended_bounds`; in UTC), `range`, `date_range`, `filter`, `filters`, `global`, `missing`, `avg`, `sum`, `min`, `max`, `value_count`, `cardinality` (exact), `stats`, `extended_stats`, `percentiles`, `top_hits`, nested in each other. **Aliases**: a search, `_count`, aggregation (`global` too), `_msearch`, `_delete_by_query`, `_cat/count` and get by id (`_doc`, `_source`, `_mget`) through an alias with a `filter` reach the documents the filter matches alone, so that an alias per tenant over one shared index keeps each tenant's searches to its own documents; a request naming two filtered aliases of an index reaches what either filter matches, and one naming the index too, every document. A filter is compiled when the alias is made: one ChloeDB cannot apply is refused then, with a 400. The actions of one `_aliases` request are written at once (every alias is kept in one row), so a client searching an alias that one request moves from an old index to a new one finds the old index or the new one, never neither or both. Writing through an alias of several indexes goes to its write index (`is_write_index`). A filtered alias is not a boundary between tenants: a key that reads the alias reads the index by its name too, and a write through an alias is not checked against its filter (as in OpenSearch). A [key bound to a tenant](#keys-bound-to-a-tenant) is such a boundary on this API (a key limited to tables is refused here; a table per tenant with keys limited to its tables is the other, on the HTTP API: [security](security.md), "Multi-tenant isolation"). **Requests**: a key that a search body, a query or an `_aliases` action does not read is refused with 400, naming it and the key it is likely a misspelling of (`[bool] query does not support [filtr]; did you mean [filter]?`), as OpenSearch refuses keys it does not know; so is a second field in a query on one field (`match`, `term`), and the parts of a search ChloeDB does not answer, each with what to do instead: `pit`, `rescore`, `suggest`, `runtime_mappings`, `slice`, `script_fields`, `indices_boost`, a top-level `knn` (it is a query here), `min_score`, `explain` and `profile`. `timeout`, `track_scores`, `terminate_after` and `stats` are taken and change no hit (a search is not cut short, and every match is counted). ### Keys bound to a tenant One index shared by tenants, with a field that names each document's tenant, gets a key per tenant (finding KENJI-402), as document-level security in OpenSearch's security plugin gives a role a filter. An admin makes it on the HTTP API: ```bash curl -s -X POST localhost:8080/v1/admin/keys -H "Authorization: Bearer $TOKEN" \ -d '{"name": "tenant-t007", "scope": "write", "tenant": {"index": "tickets", "field": "tenant_id", "value": "t007"}}' ``` `index` names one index (`"indices": [...]` several, by name), `field` a `keyword` field of each, `value` the tenant's value, and `scope` is `read` or `write` (`read` when left out). The answer holds the secret once, and the key's `tenant`, which the key list and `/v1/whoami` show too. With that key, here: - every read is filtered by `tenant_id = t007`: `_search` (its aggregations, `global` included, `top_hits`, `post_filter`, `q=`), `_count`, `_msearch`, scrolls, `_doc`, `_source` and `_mget` by id (another tenant's document is not found, 404), `_delete_by_query` and `_update_by_query`; - every document it writes (`_doc`, `_create`, `_update` and its upsert, `_bulk`) has `tenant_id` exactly `t007`; one of another tenant, of none, in a list or of another case is refused (403, `security_exception`), as is a document whose id another tenant's document has; another tenant's document is not there for a delete or an update by id (404). A field the mapping lacks is refused (`strict_dynamic_mapping_exception`): an admin maps new fields; - it names its indexes by name: `_search` with no index, a pattern (`tick*`), `_all`, another index or an alias (another tenant's filtered alias too) is refused (403) before anything is looked up, and so is a scroll id naming one. `GET /`, `_cluster/health` (which counts its indexes) and `GET /_mapping` answer; `_cat`, `_stats`, `_alias`, `GET `, settings, `_nodes` and every change of an index, mapping, alias or setting are refused. A tenant's field that is not a `keyword` field of the index is refused at the first request (map it first). The key is refused on the HTTP API (but `/v1/health` and `/v1/whoami`), gRPC, MCP, the feed and apps, where its filter is not enforced. What it cannot hide: ids are one namespace over the index, and BM25 scores use the whole index's term statistics, as in OpenSearch. The keys file keeps such a key as limited to no table, so that a server from before these keys admits it nowhere. ## How an index is kept An index `books` is the table `os_books`: its key `_id`, `_version`, `_hash` (a hash of the id, the order scrolls page through), and `_source`, a JSON field holding the document, whose index answers term, range, prefix and exists queries and the aggregations on every keyword, number and boolean, mapped or not. Fields that need more have columns of their own: `text` a TEXT column, `date` a TIMESTAMP, `knn_vector` a VECTOR, and `long`/`double` an INT or FLOAT holding the field's smallest value, which scores read. A `terms` aggregation on a field that documents hold arrays of (`"tags": ["billing", "vpn"]`) counts each document's values from that index, as one on a single keyword does, rather than reading each document. A text field without a keyword sub-field is kept in its column alone, and put back into `_source` when read. The mappings and settings are rows of the table `opensearch_indices`, and every alias is in the one row of `opensearch_aliases` (an older version listed each index's aliases in its row, which is read until an alias is first changed). Dynamic mapping adds fields as OpenSearch does (`text` with a `keyword` sub-field, `long`, `float`, `boolean`, `date`, objects), adding their columns with `ALTER TABLE`; `dynamic: false` and `strict` are kept. Text is read by one of two of ChloeDB's analyzers, chosen from the field's: `english` for OpenSearch's `english` analyzer or a custom one with a stemmer, `simple` (lowercased, folded, nothing dropped) for the rest. Before ChloeDB reads it, the text is cut into words as the field's analyzer would: - the `standard` tokenizer keeps `merge_segments`, `mastodon.social`, `children's`, `3.14`, a word with a soft hyphen in it and a word with combining marks, viramas or tone marks (`हिन्दी`, `ผู้ใหญ่`) whole, makes each emoji (`★`, `👩‍💻`, a flag), each ideograph (Chinese, Japanese) and each hiragana a word, and a run of katakana one, and cuts at `²`, `¼`, `①`, `☆` and `✓`. Each character from U+00A0 to U+1FBFF was compared with OpenSearch 2.11's `_analyze`: they differ only for a combining mark that follows a space; - accents are kept (`sévère` is not `severe`), unless the analyzer has an `asciifolding` filter; - the `english` analyzer, and a `stemmer` filter of `possessive_english`, drop a word's `'s`; - `whitespace` keeps every word between spaces whole, and `keyword` the whole text; - `word_delimiter_graph` cuts where case or digits change (`CatsOfMastodon2026` is `cats of mastodon 2026`); - an `edge_ngram` or `ngram` tokenizer or token filter makes the field's column hold the n-grams themselves, each a word, so that a query's words match them and BM25 counts them as Lucene does (on Mastodon's account search, scores agree with OpenSearch's to five digits); - a field's `search_analyzer` cuts the query's text. ## Differences What a request gets that OpenSearch would answer otherwise: - **Analysis**: only what the list above names. Stop words other than English's, synonyms, other languages' stemmers, `pattern` tokenizers (taken as ChloeDB's words), `path_hierarchy`, `shingle`, phonetic filters and normalizers are not applied. Chinese and Japanese are cut a word per ideograph, as the `standard` tokenizer cuts them, not into the `cjk` analyzer's pairs or a dictionary's words. - **Ranking**: BM25 with OpenSearch's defaults (k1 1.2, b 0.75) over the same words and the same one-byte lengths, so scores agree to about five digits when the words do, and two documents of nearly equal scores can swap places. Hits of equal scores come in the order of their `_id` (OpenSearch's in the order they were written), which ChloeDB keeps the same on one server and over shards. A phrase (`match_phrase`, or one in `query_string`) scores the sum of its words' BM25, where OpenSearch scores how often the phrase itself occurs: phrase searches find the same documents and rank them otherwise. A ranked query lists the rows none of its words scores after the others, with score 0. - **Queries**: `wildcard` takes a trailing `*` alone; `match_phrase`'s `slop` is ignored; `nested` queries read the paths of objects, without matching inside one object; `regexp`, `terms` lookups, `geo_*`, `more_like_this`, `percolate`, `span_*`, `intervals`, `rank_feature` and `random_score` are refused, as are per-function `filter`s and `min_score`; a range's `time_zone` is not applied (dates are UTC). - **Prefixes**: a prefix (`prefix`, `wildcard`'s trailing `*`, the last word of `match_bool_prefix`, `match_phrase_prefix` and `bool_prefix`, a `word*` in `query_string`) is matched as typed against the field's terms, and on an `english` field also stands for the stems of the words it may be the start of: `prefix: battery` finds *batteries*, which the field keeps as `batteri`, where OpenSearch's `prefix`, which does not analyse its value, finds none, and `match_bool_prefix` analyses its last word into the prefix `batteri`. Each letter typed keeps the documents a shorter prefix found, so a search box gets about the documents OpenSearch's `match_bool_prefix` gives it. **Changed:** `match_bool_prefix` and `multi_match`'s `bool_prefix` ignored `operator`, `minimum_should_match` and `fuzziness` before and needed one word only; they take them as OpenSearch does, `operator` and `minimum_should_match` counting the prefix as one of the words and `fuzziness` reaching the words but not the prefix. - **Searches**: aggregations read one index at a time; `collapse` takes no `inner_hits`; point-in-time searches are refused (a `pit` in a search body too); `track_scores` is ignored (a field sort scores nothing); `terminate_after` is ignored (every match is counted, and no answer says `terminated_early`); a scroll ordered by score or a field is limited to 10,000 hits. Options of OpenSearch's queries taken and not applied: a query's own `analyzer` (the field's search analyzer reads its text), `match_phrase`'s `slop`, the fuzzy options `prefix_length`, `max_expansions`, `transpositions` and `rewrite`, `lenient` and `cutoff_frequency`; `boosting` ranks by its `positive` query alone. - **Aliases**: an alias's `filter` applies to a get by id through it as well (`_doc`, `_source`, `_mget`): a document it does not match is not found there, where OpenSearch, which applies the filter to searches alone, finds any document of the index. `routing`, `index_routing` and `search_routing` are kept and shown, and route nothing: an index is one table, which every search reads. A filter takes no `knn` query. `_reindex` and index templates are not answered: copy an index with a scroll and `_bulk` (opensearch-py's `helpers.reindex` does both), then move an alias to it in one `_aliases` request. - **Aggregations**: `composite` returns at most 9,999 groups a page; `cardinality` is exact; a `histogram` of a number field that some documents hold an array of is refused; scripts are refused. - **Documents**: a keyword holds at most 256 bytes as a term; `_source` holds at most 1,000 values, objects 16 deep and paths of 256 bytes (a document past them is refused, naming the limit); a date field holds one date; versions are read before the write, so two writers of one document at once can both pass an `if_seq_no` check. - **Cluster**: one node and one shard are reported; settings other than `max_result_window` and the analysis are kept and ignored. A write is searchable once it returns, so `refresh` is accepted and needs no wait. A search that a shard with no copy answering fails is answered 503, with or without aggregations, which OpenSearch's clients retry on another node. **Changed:** a search with aggregations was answered 400 `query error` then. ## Numbers OpenSearch 2.11 (its default 1 GB heap) and ChloeDB's OpenSearch API on the same machine, one at a time, the other stopped: a cloud container of 4 vCPUs (Intel Xeon @ 2.10GHz) and 15.7 GB, 2026-11-08. [BEIR's TREC-COVID](https://huggingface.co/datasets/BeIR/trec-covid) (171,332 abstracts) in one index, written with `_bulk`, then ten kinds of search 300 times each from one client, the same requests to both; OpenSearch's request cache off. The script, its output and how it was run: [`chloedb-server/results/opensearch`](https://github.com/chloetech-ai/chloedb/tree/main/chloedb-server/results/opensearch). | search | OpenSearch p50 / p99 ms | ChloeDB p50 / p99 ms | |---|---|---| | `match`, one word | 2.96 / 8.06 | 1.70 / 3.06 | | `match`, a topic's words | 6.41 / 18.99 | 2.22 / 4.79 | | `match` + `term` + `range` filters | 9.47 / 31.87 | 3.69 / 7.57 | | `multi_match` | 6.89 / 30.16 | 4.10 / 9.75 | | `match_phrase` | 2.97 / 5.84 | 1.86 / 4.86 | | `term` filter | 2.00 / 7.00 | 1.49 / 2.23 | | `range`, sorted by date | 2.96 / 6.46 | 1.52 / 2.44 | | `terms` aggregation | 6.82 / 18.93 | 4.30 / 5.56 | | `date_histogram` of every document | 9.73 / 15.50 | 6.71 / 8.80 | | `match` + `highlight` | 7.69 / 24.84 | 3.27 / 5.66 | | | OpenSearch | ChloeDB | |---|---|---| | searches a second, 8 clients | 638 | 1,183 | | `_bulk` of the 171,332 documents | 21.4 s | 39.0 s | | resident memory, empty | 1,348 MiB | 50 MiB | | resident memory, after the searches | 1,652 MiB | 726 MiB | | on disk | 415 MB (195 MB after a `_flush`) | 260 MB | All 3,000 searches find as many hits on both. Of the 2,400 that return hits, 808 return the same first page in the same order, and 1,292 the same scores or dates in the same places, with ties in another order (ChloeDB's by `_id`); the 300 phrase searches find the same documents and rank them otherwise ([Differences](#differences)). --- # Tenants: a database kept in an object store (experimental) > **Experimental.** This is a first slice of the design in > [`docs/design/0.7.0-file-per-agent.md`](../design/0.7.0-file-per-agent.md), > which is a proposal. The objects it writes are `layout: 0`, and a later > version may refuse to read them. Do not keep data in it that you cannot > load again. Nothing uses it unless you ask. A **tenant** is one ChloeDB database that lives whole in an object store: a directory, or S3 and the stores that speak its API. A node that serves it works on a local copy, which is only a cache. Any node pointed at the same store can open the same tenant, and a node can lose its disk without losing a write. ```text /HEAD names the rest; the only object that is replaced //base/-.chloedb the database up to a transaction, as one ordinary file //log/-.arc the transactions after it ``` A write is committed by replacing `HEAD` on the condition that it is still the version the node last read. The store decides: of two nodes that write one tenant at once, the later is refused and nothing of its write is kept. There is no lease and no clock to trust. ## From Rust ```rust use std::sync::Arc; use chloedb::query::Params; use chloedb::storage::DirStore; use chloedb::tenant::{Tenant, TenantError, TenantOptions}; let store = Arc::new(DirStore::new("/mnt/tenants")?); // or chloedb::storage::open_store("s3://bucket/prefix/")? let t = Tenant::create(store.clone(), "agent-7", TenantOptions::new("/var/cache/agent-7"), |db| { db.sql("CREATE TABLE notes (id INT PRIMARY KEY, body TEXT)", &Params::new()).map(|_| ()) })?; // Committed when this returns: one conditional put of HEAD. t.write(|db| db.sql("INSERT INTO notes VALUES (1, 'the harbour at dawn')", &Params::new()))?; // Reads run on the local copy. t.read(|db| db.sql("SELECT id FROM notes WHERE MATCH(body, 'harbour')", &Params::new()))?; // Another node, with an empty cache: two reads of the store. let other = Tenant::open(store, "agent-7", TenantOptions::new("/var/cache/elsewhere"))?; match other.write(|db| db.sql("INSERT INTO notes VALUES (2, 'two')", &Params::new())) { Ok(_) => {} // this node is the writer now Err(TenantError::NotWriter) => { /* another node wrote first: nothing was committed, wait a moment and try again */ } Err(e) => return Err(e.into()), } ``` | call | what it costs | what it sees | |---|---|---| | `read` | nothing from the store | what this handle committed, and what others had at its last `refresh` | | `read_latest` | one read of `HEAD`, and the new transactions if any | every write committed before the call | | `write` | one conditional put (two the first time, when the handle becomes the writer; one more upload when the log is sealed), shared with the writes that waited for the one before | | | `make_base` | one upload of the database, one put | (the next open is two reads) | | `tenant::list(store)` | one listing, and eight bytes of each `HEAD` | the ids of the store's tenants | Writes of one handle that arrive while a commit is on its way to the store wait, and the next commit takes all of them: their statements run one after another, each on its caller's thread, and one put of `HEAD` commits them together or not at all. A handle holds its cache directory: a second handle on the same directory, in this process or another, is refused. The directory keeps the tenant's working copy, and the next handle to open the tenant there takes it up again when it is a copy of the tenant as the store has it (the last transaction it holds is in `HEAD`'s history), and fetches only the transactions after it. Otherwise it starts from the base. A write fails in one of three ways. `NotWriter`: another node committed first, nothing was written, and the handle has loaded the tenant again; wait a random while before trying again, longer after each refusal in a row (up to a few times what the refused write took). A node that is not the writer takes the tenant with one put of `HEAD` and commits with a second, and a node that takes the tenant between the two refuses the first node's commit: nodes that try again at once can take it from each other for as long as they keep trying, with none committing, when the store's puts are slow. `InDoubt`: the store did not answer and could not be asked again, so the write may or may not be there. Anything else: not committed. The writes that shared its commit fail with it, the same way. A handle does not take a store's refusal for `NotWriter`: it loads the tenant again and looks. A store's client may send a put twice (after an answer it lost) and report the store's refusal of the second; the write is then committed, and the handle says so. ## From the server ```bash chloedb-server --db main.chloedb --tenants /mnt/tenants --tenant-cache /var/cache/tenants # or --tenants s3://bucket/prefix/ (configured by the environment, as `import` reads S3) chloedb-server tenants check-store /mnt/tenants # does this store refuse a put whose condition fails? chloedb-server tenants list /mnt/tenants # the ids of its tenants ``` The server probes the store when it starts, and does not start on one that takes a put whatever the condition. It opens a tenant when a request names it and closes the ones no request has named for `--tenant-idle-s` seconds (300), or the least recently used beyond `--tenant-open-max` (1,000). A tenant it wrote is given a new base before it is closed, so that the next open, here or on another server, is two reads. The routes need an admin key until tenants have keys of their own. | route | does | |---|---| | `POST /v1/admin/tenants` | creates one: `{"id": "agent-7", "sql": ["CREATE TABLE notes (id INT PRIMARY KEY, body TEXT)"]}` | | `GET /v1/admin/tenants` | the ids of the store's tenants, and those this server has open | | `GET /v1/admin/tenants/:id` | its epoch, base, logs and last transaction | | `POST /v1/admin/tenants/:id/sql` | one statement: `{"sql": "…", "params": {}, "latest": false, "objects": false}` | | `POST /v1/admin/tenants/:id/base` | makes a new base now | | `DELETE /v1/admin/tenants/:id` | deletes it | A statement that reads (a query or an `EXPLAIN`, as the engine reads the statement, not by its first word) runs on the server's copy, through what cannot write; `"latest": true` looks at the store first. Any other statement is a write. A write that another server beat answers 409: send it again. Two servers started on one store answer for the same tenants. ## A blackboard for agents A **blackboard** is a tenant that many agents share to work one job: tasks they claim under a lease, findings they post for each other, and the events of both in order. It is made from a template, and its tools are calls of the server or an MCP server an agent is pointed at. ```bash curl -H "Authorization: Bearer $ADMIN" $URL/v1/admin/tenants \ -d '{"id": "migration", "template": "blackboard"}' curl -H "Authorization: Bearer $ADMIN" $URL/v1/admin/tenants/migration/board/add_tasks \ -d '{"agent": "lead", "tasks": [{"id": "lexer", "title": "port the lexer", "spec": "..."}]}' curl -H "Authorization: Bearer $ADMIN" $URL/v1/admin/tenants/migration/board/claim \ -d '{"agent": "worker-7", "key": "claim-1"}' # an agent, named by the URL it is given claude mcp add --transport http board "$URL/v1/admin/tenants/migration/mcp?agent=worker-7" \ --header "Authorization: Bearer $ADMIN" ``` | tool | does | |---|---| | `add_tasks(tasks, key?)` | takes tasks in; one whose id the board has already is left as it is (a list with a task that has no id needs a `key`) | | `claim(key, n?, lease_s?)` | gives the caller up to `n` tasks, oldest first: open ones, and claimed ones whose lease has passed | | `heartbeat(task, lease_s?)` | extends the caller's lease; refused once another agent has the task | | `complete(task, result, key)`, `fail(task, why, key)` | end the caller's claim; refused once another agent has the task, so a task is done once | | `post(body, key, task?)` | records a finding, as a duplicate (`dup_of`) of an earlier one that says the same | | `search(q, limit?)` | findings and tasks by their words, best first; a finding's duplicates are counted, not listed | | `timeline(since?, limit?)` | what happened, in order: tasks taken in, claims, tasks done or failed, findings | | `status()`, `get_task(id)` | the board in numbers; one task | `POST /v1/admin/tenants/:id/board/:tool` takes a tool's arguments and `"agent"` in its body. `POST /v1/admin/tenants/:id/mcp?agent=NAME` is the same tools over the Model Context Protocol (Streamable HTTP, no session). From Rust they are `chloedb::blackboard::Board`. - **One winner.** A call that writes is one transaction, committed by the tenant's replacement of `HEAD`, so the store orders every claim: of two agents that claim the same task, through one server or two, one is given it. - **Leases.** A claimed task is its owner's until its lease passes (300 seconds unless asked, a day at most), by the clock of the server that answers. After that another agent's `claim` may take it, and the first agent's `heartbeat` and `complete` are refused. - **Applied once.** A `key` is the caller's own name for one call. A call that failed or timed out may be sent again with the same `key`: if the first was committed, the second changes nothing and answers what the first answered. Keys are kept in the tenant, so any server knows them, and a key is its agent's: two agents that choose the same word are not answered each other's calls. Over HTTP and MCP the calls that are not the same when made twice (`claim`, `complete`, `fail`, `post`, and `add_tasks` of a task without an id) are refused without a key (400; over MCP, an invalid-parameters error). From Rust the key is the caller's choice. Keys are never deleted yet. - **Duplicates.** Two findings say the same when they share at least 80% of their words (letters and digits, in any case). This is a comparison of words, not of meaning: the design's comparison by vectors is not built. A refused call answers 409 over HTTP, and an answer marked `isError` over MCP. A call that another server beat to the tenant is tried again by the server, twice, before it answers 409. ## What it does not do yet - It has run on a directory store, and its S3 code against a mock of S3 (moto) only, not against a real bucket. A store must refuse a put whose condition fails (AWS S3, R2, MinIO, GCS and Azure say they do; DigitalOcean Spaces is not known): `chloedb-server tenants check-store URL` tries it. - A base is always the whole database as one file, fetched whole when a node opens the tenant. Reading a large index by range, without a local copy, is the design's next step. - A write waits for a round trip to the store, its own or the one it shares. Nothing is acknowledged before the store has it. - Bulk loads and attached segments skip the log, so they are not committed through `write`: use SQL or transactions. - The server has no per-tenant keys, quotas, routing or directory: every server on a store answers for every tenant, and two that write the same one take it from each other (each write that loses answers 409). An agent of a blackboard therefore holds an admin key of the server: run one only where that is acceptable, until tenants have keys of their own. - The format is not frozen. Log objects are written as version 1 of `STRARC01`, the experimental one; the accepted format begins at 2, and its readers will not take what is written now for theirs. --- # Compatibility What this code promises about the files it reads and writes, the protocol its servers speak to each other, and the names it was known by before; and what it does not promise yet. It describes the code as it is on `main` (November 2026, every crate and package at version 0.3.11). The [changelog](../CHANGELOG.md) says what changed. ChloeDB is pre-1.0: the statements below are the current behaviour, which the code enforces, not a support commitment with a time limit. ## The database file A database is one file (or, with `directory`, a directory with a `CURRENT` file naming its manifest). Its format has two layers. **Format version.** The file's meta slots carry a format version (`FORMAT_VERSION` in `chloedb/src/storage/pager.rs`, now 3): | format | what it is | |---|---| | 1 | a database holding only the table it was created with | | 2 | a database of several tables | | 3 | format 2 with the list of features the database uses; the last format number: later changes add features instead | This code opens formats 1 to 3 and refuses a higher number ("unsupported format version"). **Features.** A format-3 manifest lists the features it uses, `{required: [...], optional: [...]}` (`chloedb/src/storage/manifest.rs`). A reader refuses a database that requires a feature it does not know, and names the feature; it ignores optional features and keys it does not know. This code knows: `added_fields`, `bool`, `cluster_by`, `cold_segments`, `compact_keys`, `default`, `derive`, `derive_keyword`, `derive_text`, `edge_table`, `expire_by`, `field_ids`, `functions`, `json`, `json_text`, `media`, `multi_vector`, `not_null`, `packed_positions`, `rank_profiles`, `rabitq`, `retain`, `semantic_id`, `seq_no`, `shard_by`, `sources`, `sparse_embed`, `substring:1`, `timestamp`, `vector_partition` and `zstd` (the list `FEATURES` in `manifest.rs` is the authority), and `analyzer::` for each analyzer but `english` (`Analyzer::feature` in `chloedb/src/text/analyzer.rs`). 0.3.0 added `analyzer::1` for its new analyzers (`simple`'s, from before, is unchanged), `substring:1` (a substring index), `sparse_embed` (a SPARSE field a model fills) and `derive_keyword` (a KEYWORD field derived from a text). Each is written only by a database that uses it: a 0.2.x build refuses such a database by name and opens every other database 0.3.0 wrote. **What it writes.** Every database this code creates is format 3 with feature `field_ids` (each field named by an id rather than its position). Other features are added as a database starts using them (a BOOL or TIMESTAMP field, a NOT NULL field or a DEFAULT, sequence numbers with `--seq-no`, a rank profile, ...). So a database stays readable by an older build exactly as long as it uses only features that build knows, and an older build that meets a newer feature refuses the file by name rather than misreading it. Starting to use a feature cannot be undone. **Rollups.** A rollup made by 0.3.3 or later keys its rows by number, where one made by 0.3.1 or 0.3.2 keys them by text. 0.3.3 reads and refreshes both. 0.3.2 reads the new kind but cannot refresh it, so its definition carries the option `needs_chloedb_0_3_3`, which 0.3.2 refuses by name ("no option needs_chloedb_0_3_3"): a refresh by 0.3.2 fails with that message rather than leaving the rollup's newest buckets stale. Open a database whose rollups 0.3.3 made with 0.3.3 or later. A rollup made by 0.3.4 or later that counts a field's values (`COUNT(f)`, or `AVG(f)`, which keeps `count_f` so that its mean skips NULLs) has a column 0.3.3 does not write; its definition carries `needs_chloedb_0_3_4`, which 0.3.3 refuses by name in the same way. 0.3.4 refreshes a rollup made before with `AVG(f)` as it was made, without `count_f`. **Databases from before field ids.** A database written before field ids (format 1, 2, or 3 without `field_ids`) no longer opens for use. `upgrade()` (`chloedb.upgrade(path)` in Python, `upgrade(path)` in JavaScript; `chloedb/src/upgrade.rs`) copies it into a new database of this format in its place and keeps the old files beside it as `.before-field-ids`. It refuses a database that numbers its writes (replication) or keeps stream offsets (`_sources`), since the copy could not continue their numbers: such a database is rebuilt from its source or from a replica instead. **Not promised.** There is no downgrade: a file a newer build changed may not open in an older one. There is no stated period for which an old format stays readable by new builds; formats 1 to 3 and the `upgrade()` path are what this code has, and a change to that will be in the changelog. ## The packages and the engine The Python wheel, the JavaScript addon and the Java library each compile the engine (`chloedb/`) into themselves from the same commit. A package version therefore opens what the engine of its commit opens (above), no more: a wheel built from an older commit refuses a file that uses a feature added since, by name. The Java jar checks that its native library is from the same checkout (`Native.ABI`) and refuses a mismatched pair. The HTTP clients (`chloedb.connect` in Python, `chloedb/client` in JavaScript) contain no engine: they speak the server's `/v1` HTTP JSON API and work with any server that has the routes they call. A client newer than its server may send an option the server does not know, and an older server may ignore it rather than refuse it (one from before Arrow answers ignores `"format": "arrow"`): the clients detect and fall back where their documentation says so (Arrow answers, scrolls), and otherwise assume a server of their own commit. **Not promised.** A package does not yet expose the engine commit or the format version it was built with, and nothing checks that a client and a server are of the same release. Every crate and package carries the version of the last release (0.3.11), and keeps it between releases: name a build from a commit after a release by its commit. ## A cluster of mixed versions Servers of a cluster (coordinators, shards, replicas, followers) talk over gRPC with a numbered shard protocol (`chloedb-server/src/grpc.rs`: `MIN_PROTOCOL` 1, `PROTOCOL` 21; [the list of what each adds](chloedb/server.md)). - When a coordinator or a peer connects it calls `Hello` with the range it speaks (1 to 21) and the server answers its own range, the plan version it reads (plan IR version 1) and the plan features it has. The two use the highest protocol both speak; if the ranges do not meet the connection is refused, naming both ranges. A coordinator asks again every minute and after a copy fails, since it may have restarted on another version. - A coordinator keeps each shard copy's protocol, speaks the oldest any of them speaks, and uses a newer call only where every server it needs speaks it. Where one does not, it refuses that request by name ("a coordinator refuses a scroll while a shard speaks an older one") or falls back (rows instead of Arrow columns; a read sent to the primary when a replica is older than protocol 5) rather than sending a call the shard would misread. - A server refuses a protocol newer than its own, and a plan of a newer version or one that needs a feature it lacks, by name. 0.3.0 added the plan feature `terms_syntax`, which only a search with query expansion (`bm25(.., expand => n)`) uses: a 0.2.x shard refuses such a search by name, so upgrade the shards before using it. 0.3.1 added the plan features `asof_join` (`ASOF JOIN`), `date_bin` (a `GROUP BY` of `date_bin` or `date_trunc` run on the columns) and `approx_percentiles` (`approx_percentile`): a 0.3.0 shard refuses a query that uses one by name, so upgrade the shards first here too. 0.3.2 moved the shard protocol to 21 (write receipts' counts, strict writes, `insert_if_absent`) and added the plan feature `full_join` (`FULL JOIN`): a coordinator counts and writes strictly only through shards of 21, and a 0.3.1 shard refuses a full join by name, so upgrade the shards before the coordinator. 0.3.4 keeps the shard protocol at 21 and adds no plan feature: the terms a read after a write passes back (`min_seq_term`, `min_seq_terms`) are new fields that a 0.3.3 server leaves out, reading by the number alone, so 0.3.3 and 0.3.4 mix in either order. A key's statement budget is kept by 0.3.4 only: a 0.3.3 server admits the key without it, so give keys budgets once every server runs 0.3.4. 0.3.5 keeps the shard protocol at 21 and adds no plan feature and no field, so 0.3.4 and 0.3.5 mix in either order. One step is ordered: a 0.3.5 coordinator of a cluster with a cluster token adds a server (a shard, a copy, or a plan's step that adds one) only with that token, and answers an API key or the admin token 403 `cluster_token_required`. On Kubernetes, upgrade the operator before the coordinators: the 0.3.5 operator adds servers with its `clusterTokenSecret`, and an older one sends the admin token. 0.3.6 keeps the shard protocol at 21 and adds no plan feature and no field, and a slot move's flip from a replicated shard waits for a mark that the shard's primary writes through its log: a replica of it takes the flip only once it applied that mark. A primary of 0.3.5 or earlier writes none, so a 0.3.6 replica under one refuses that flip and the maps after it, until a later flip from the shard is marked or the replica is replaced. Finish the upgrade before moving slots. 0.3.7 keeps the shard protocol at 21 and adds no plan feature and no field, so 0.3.6 and 0.3.7 mix in either order. 0.3.8 keeps the shard protocol at 21 and adds no plan feature and no field, so 0.3.7 and 0.3.8 mix in either order. A cluster that follows Postgres (`follow-postgres`) upgrades its coordinators before its shards: a coordinator of 0.3.8 passes the follower's name on to its shards (`x-chloedb-postgres-follower`), and a server of 0.3.8 refuses other writes to a table a follower follows, so behind a 0.3.7 coordinator a 0.3.8 shard can refuse the follower's own writes. 0.3.9 keeps the shard protocol at 21 and adds the plan feature `sql_functions` (`substr`, `trim`, `ltrim`, `rtrim`, `replace`, `floor`, `ceil`, `date_diff` and `STRING_AGG`, with `STRING_AGG`'s separator as a new field of the plan's aggregate): a 0.3.8 shard refuses a query that uses one by name, and refuses `hash()` in a ranking, so upgrade the shards before using them. Otherwise 0.3.8 and 0.3.9 mix in either order. A 0.3.9 coordinator keeps its alert rules, audit log and Timeline on its shards' copies; a copy of 0.3.8 keeps nothing of them, so they survive the coordinator's restart once its shards run 0.3.9. The OpenSearch API's aliases move to a table of their own (`opensearch_aliases`) at the first alias change: a database taken back to 0.3.8 after that sees its aliases as they were before the change. 0.3.10 keeps the shard protocol at 21 and adds two plan features: `keyword_ranges` (a single-valued `KEYWORD` compared with `<`, `<=`, `>`, `>=` or `BETWEEN`) and `graph_given` (a coordinator's walk of `REACHABLE`, `PATH`, `hops()` or `ppr()` over a cluster, whose answer goes to the shards in a new field of the plan's `Graph`, `given = 14`): a 0.3.9 shard refuses a plan that names one, so upgrade the shards before using them. Otherwise 0.3.9 and 0.3.10 mix in either order. A JSON field's segments written by 0.3.10 also index the plain values of an array path (the term `path \0 v`), which 0.3.9 does not read and does not need: it reads such a row from its object. The keys file can hold two new kinds of key, a key that only appends (kept as `read` of `append:`) and a key bound to a tenant on the OpenSearch API (kept as a key of no table): a 0.3.9 server reads the file and lets neither key read or write any table. Alert rules and routes are kept in `DB.alerts.json` beside `--db`, which 0.3.9 does not read: a server taken back to 0.3.9 has only the rules of its `--alerts` file, if it is given one. 0.3.11 keeps the shard protocol at 21 and adds one plan feature, `geo` (the trigonometric functions, `haversine`, H3 cells and shapes kept as text, the protocol's function numbers 32 to 58): a 0.3.10 shard refuses a plan that names it, so upgrade the shards before using them. Otherwise 0.3.10 and 0.3.11 mix in either order. So a rolling upgrade works shard by shard: while versions are mixed, the cluster serves what the oldest server involved speaks, and the newer features turn on as the last server is upgraded (some, such as slot maps, only once the coordinator restarts after that). A replica is sent copies of its primary's rows and files, so the file-format rules above apply between them too: a replica older than its primary refuses a feature the primary started using. Upgrading the replicas of a shard before its primary avoids that. **Not promised.** There is no stated lowest version a cluster can be upgraded from in one step, and mixed-version clusters are tested for the protocol fallbacks above, not as a matrix of releases. ## Old names ChloeDB was called Strata, and ChloeCtx was called Engram, until November 2026. The old names below are still accepted, and are promised "for a release": they will be removed in a release that the changelog names in advance. | what | new name | old name, still accepted | |---|---|---| | programs | `chloedb-server`, `chloedb-crawl`, `chloedb-sheets` | `strata-server`, `strata-crawl`, `strata-sheets`, in the image and the release archives | | container image | `ghcr.io/chloetech-ai/chloedb-server` | `ghcr.io/chloetech-ai/strata-server` | | settings | `CHLOEDB_*` | `STRATA_*` | | the server an app writes to | `chloedb-crawl --server URL`, `chloedb-sheets --server URL` (0.3.2) | `--strata URL` | | models folder | `~/.local/share/chloedb/models` (0.3.2) | `~/.local/share/strata/models`, used where it exists and the new folder does not | | HTTP headers and gRPC metadata | `x-chloedb-*` | `x-strata-*` | | Python package | `import chloedb`, `ChloeDBError` | `import strata`, `StrataError` (with a `DeprecationWarning`) | | JavaScript errors | `ChloeDBError` | `StrataError` | | JDBC URLs | `jdbc:chloedb:` | `jdbc:strata:` | | ChloeCtx program | `chloectx` | `engram`, a link to it | | ChloeCtx settings | `CHLOECTX_*` | `ENGRAM_*` | | repository | `chloetech-ai/chloedb` | `chloetech-ai/strata` and `rkonow/engram`, which GitHub redirects | | website | https://chloetech-ai.github.io/chloedb/ | the old address does not redirect | For the server in particular: when both a `CHLOEDB_*` setting and its `STRATA_*` name are set, the new one wins; an answer carries its headers under both names (`x-chloedb-took-ms` and `x-strata-took-ms`); the browser UI moves what it saved under `strata.*` to `chloedb.*` the first time it loads; the MCP server introduces itself as `chloedb`, and the OpenSearch API's cluster is named `chloedb`. The Kubernetes operator's pods start the programs by their old names, with `STRATA_*` settings, which every image understands. The metrics were renamed outright, from `strata_*` to `chloedb_*`: a dashboard over servers from before and after the rename can match `{__name__=~"(chloedb|strata)_.*"}`. So were the alert messages, which begin `[chloedb FIRING ...]` rather than `[strata FIRING ...]`. Some names have not been renamed yet and keep the old spelling: the file format (`STRATADB` magic, ChloeCtx's `memory.strata` and `engram.sock`), the gRPC services, the Kubernetes operator's resources (the `StrataCluster` kind, the `strata.chloetech.ai` API group, the `strata-system` namespace), and the app engine in `chloedb-apps/`. The default models directory is `~/.local/share/chloedb/models` from 0.3.2 (`~/.local/share/strata/models` before); a machine that has the old folder and no `~/.local/share/chloedb` keeps using it, as a machine that already has ChloeCtx's old folder, `~/.local/share/engram`, does. ## Experimental features These parts of chloedb-server work and are documented, but carry no compatibility promise yet: their routes, settings and what they store may change in any release, including a patch release, with no upgrade path promised. Each answer of their routes carries the header `x-chloedb-experimental: `, `GET /v1/catalog` marks their routes (`"experimental": ""`, and the features under `experimental`), and the command center marks their pages. | feature | routes | what it is | |---|---|---| | `cloud` | `/v1/admin/cloud/*`, `/v1/admin/aws/*`, `/v1/admin/digitalocean/*`, `/v1/admin/gcp/*` | [clusters made on AWS, DigitalOcean or Google Cloud](chloedb/server.md#in-the-cloud) from the command center | | `hub` | `/v1/admin/hub/*`, `/c//` | [the hub](chloedb/server.md#many-clusters-from-one-command-center): a book of other clusters, and calls forwarded to them | | `autoscale` | `/v1/admin/kube/autoscale/*`, `/v1/admin/autoscale/*`, the `StrataCluster`'s `spec.autoscale` | [the operator's autoscaler](chloedb/server.md#autoscaling) | | `oncall` | `/v1/admin/oncall/*` | [the on-call agent](chloedb/server.md#the-on-call-agent) | The list is `EXPERIMENTAL` in `chloedb-server/src/catalog.rs`. A feature leaves it when its shape is settled; the changelog says so. ## Demos These apps show what ChloeDB can do and are not part of ChloeDB's promises (`chloedb-netops` is attached prebuilt to the server's release, as the crawler and Sheets are, but carries no promise of its own): - `chloedb-netops`, network operations on a simulated carrier network; - `chloedb-hn`, Hacker News searched, asked in sentences and completed as typed; - `chloedb-arxiv`, every arXiv paper with search, the recommender and feeds; - `chloedb-gh`, GitHub's public history since 2011: repos by what they do, why they trend, what people use instead; - `chloedb-img`, public-domain pictures searched by what is in them; - `chloedb-sound`, free sounds searched by how they sound, with the moments inside long recordings; - `chloedb-backbone`, the internet's routing from public data: what is wrong now, where, and how it connects; - `chloedb-earth`, California and Chile from orbit: fires as GOES sees them, places by how they look, their twins across the equator and how they changed; - `chloedb-packets`, packet captures decoded by tshark: Wireshark's display filters over every packet, and what went wrong in each conversation; - `chloedb-grants`, open federal grants ranked against a nonprofit's mission, and applications drafted from its own writing with every fact cited; - `chloedb-swarm`, simulated users, an internal test instrument; - `chloedb-experiments`, A/B tests of rankings on simulated users, and rankings valued on the log of another, checked against the users' truth; - `examples/feature-store`, a shop ranked on features ChloeDB keeps; - `examples/parley`, a social network of LLM agents. They are on a release train of their own. CI's required check, `CI result`, does not test them, and a change only under them runs nothing there; the `Demos` workflow (`.github/workflows/demos.yml`) tests them against a chloedb-server of the same commit, on a pull request that touches one and every night. A fault in a demo does not hold a ChloeDB release, and fixing one does not wait for the engine's tests. An app whose manifest says `"maturity": "demo"` is marked as a demo in the command center. ## Not promised yet - Semantic versioning, or any version bump rule. - A support period for releases; fixes go to `main` and the next release ([SECURITY.md](../SECURITY.md)). - That a release tag is never rebuilt: the release workflows replace the assets of an existing tag (`--clobber`). Check a download against the release's `SHA256SUMS` (Python, JavaScript) or `.sha256` (server), or PyPI's attestations ([checking what you download](../SECURITY.md#checking-what-you-download)). - Signatures and SBOMs on every download. The server archives carry GitHub's build provenance and a CycloneDX SBOM from 0.3.8, the PyPI packages attestations, and the npm packages npm's provenance from 0.3.9; the Python and JavaScript archives on GitHub are checked by their `SHA256SUMS` alone, and releases before 0.3.8 by their `.sha256` ([checking what you download](../SECURITY.md#checking-what-you-download)). - Stability of anything not described above: the Rust crate's API, the command center's routes, the operator's resource beyond its documented fields. --- # ChloeCtx: long-term memory for Claude Code ChloeCtx gives Claude Code a memory that outlives its sessions. It records every prompt, answer, tool call and compaction summary of a project into a ChloeDB file on your machine, has a small model write down the decisions and rules each turn agreed, and brings the relevant ones back when a session starts and with each prompt, without the model having to ask. The model also gets tools to search that history itself. This page starts with what you install and use day to day. [How it works](#how-it-works-the-problem) follows, for those who want the design: what it stores, when it brings history back, and how it ranks. ## Install it ChloeCtx runs on macOS and Linux (on Windows, inside WSL 2), and needs the [Claude Code](https://claude.com/claude-code) CLI, logged in (`claude auth status` shows `"loggedIn": true`). The quickest way is the Claude Code plugin, which downloads a prebuilt `chloectx` on its first session; in Claude Code: ```text /plugin marketplace add chloetech-ai/chloedb /plugin install chloectx@chloedb ``` Or install it from a checkout, for every session or for one project: ```sh git clone https://github.com/chloetech-ai/chloedb && cd chloedb ./install.sh # every Claude Code session on this machine ./install.sh --project /path/to/your/project # or one project ``` Then start a **new** Claude Code session: a session that was already open has neither the hooks nor the memory tools. `chloectx doctor`, run in a project's folder, checks the setup and says how to fix each line that failed. A project install covers that one folder: a git worktree of the same repository is a folder of its own and needs its own `chloectx install` (they then share one store), or install for every session instead. [Install ChloeCtx](setup.md) has every route (the plugin's details, a prebuilt binary, remote machines and dev containers), what each one changes in Claude Code's settings, upgrades and removal. ## What happens on its own Once it is installed there is nothing to run. In each session: - **At the start**, Claude gets a briefing of at most 6,000 characters: the rules first, then decisions, planned work with its requirements, and facts. It is the same text from one session to the next while the notes are; what changes (how many records, the open tasks, where the last session stopped) comes with the first prompt, and in the briefing itself when a session is resumed (`claude --continue`, `--resume`) or compacted. Claude Code puts the briefing after the session's first prompt, so its prompt cache serves it to a session whose first request is the same as an earlier one's (the same prompt, nothing else added), not to every session ([what that costs](#what-the-prompt-cache-holds)). - **A question that stands on its own** ("What is 17 times 3?", "Is 2027 a leap year?"), for which nothing is recalled, gets nothing: no notes, no search, and where the last session stopped waits for the next prompt. A question that weighs a choice or asks how to do something ("How should retries back off?") is not one. Answered in a few lines without a tool, its turn is not written down, and later prompts are not given it, though a search still finds it. - **With each prompt**, up to four notes that match the prompt come with it, and earlier records about it when the evidence is strong enough. Once the store holds 20 records, a small model also searches memory for the prompt in the background; what it finds comes with the turn's next tool result or with the next prompt, so a quick question answered without a tool call is answered before it arrives. - **After each turn**, a small model (`haiku` by default) writes down the decisions, rules, facts and planned work the turn agreed. - **When Claude decides to**, it calls the memory tools: `memory_ask`, `memory_search`, `memory_timeline`, `memory_sql`, `memory_remember` and `memory_forget`. ChloeCtx's own model calls run through `claude -p` and are billed to the CLI's login: about $0.003 a turn in all with Haiku once the store holds 20 records, none of it holding up a turn ([what each call costs](setup.md#what-you-need)). `chloectx doctor` shows what your own store measured over the last 30 days. A rule is only as good as the note it became. The briefing shows the newest 40 rules, 12 decisions, 10 items of planned work and 10 facts while its 6,000 characters last, each note whole up to 600 characters (a fact up to 300), so a project with many long notes can push the oldest out. The rules come under a line that tells Claude to follow them and, when a request would break one, to ask you first rather than take the request as lifting the rule. A rule that must never be missed is safest as its own short note (`chloectx remember preference "Never suggest recurring todos in v1"`), or in `CLAUDE.md`, which Claude Code always loads. Memory is per project: a preference you want in every repository (a test runner, a commit style) belongs in `~/.claude/CLAUDE.md`, which Claude Code loads in every session; `chloectx remember` keeps it for this project only, and says so after a preference. ### What the prompt cache holds Claude Code sends the hooks' context in one block after the first prompt, with the cache's last mark at its end, so the cache can serve a session's first request only when an earlier session sent the same one: the same prompt, the same briefing, nothing that changes. A new session's first request is therefore written to the cache in full when its first prompt is new (5,900 tokens in the measurement below, the briefing among them), as it would be without ChloeCtx; from the second request of a session on, the cache serves all of it. ChloeCtx keeps the first request the same where it can: the briefing names no counts or ages, and a question that stands on its own gets nothing added. Measured with `claude -p --output-format json` and Haiku, in a fresh project after two working sessions, the same question in three new sessions: before, each wrote 6,100 to 7,700 tokens to the cache and read 15,000 to 15,600 ($0.0014 to $0.0017), with 10 to 12 unrelated records recalled into it; now the first wrote 5,900 and read 15,000 ($0.0014), and the next two wrote none and read 20,900 ($0.00024 each). That holds for a first prompt that is a question standing on its own, which gets nothing added. Any other first prompt gets what changes from session to session (how many records, where the last session stopped, the records recalled, which can include the earlier sessions themselves), so each new session's first request is written to the cache in full: in a persona study on a 4-core cloud container (2026-11-18, `claude -p --model sonnet`, a project with ten working sessions), the same instruction as the first prompt of five new sessions wrote 7,500 to 9,300 tokens to the cache each time ($0.031 to $0.039 a session), and with `CHLOECTX_DISABLE=1` none after the first ($0.0020 each). ## Use it from a shell Run these in a project's folder: except `ui` and `stores`, which cover every store, each one works on that project's store. ```sh chloectx doctor # is it set up and working here? chloectx ui # the inspector: what it stored, per project and per session chloectx briefing # the briefing a new session would get now chloectx ask "how do invoice totals get rounded?" # what memory holds on it: rules, notes and excerpts, by search alone chloectx ask --deep "..." # the same through the query engine (two model calls; --model sonnet for a stronger one) chloectx search "why did the planner pick post-filtering" chloectx sql "SELECT ts, text FROM memory WHERE kind = 'error' AND MATCH(files, 'exec') ORDER BY ts DESC LIMIT 5" chloectx remember decision "Prices are integer cents" # or preference, fact, todo, note chloectx forget a1b2c3d4:42 # delete a record for good (read "Forget something" below first) chloectx report [--days 7] [--session ID] [--json] # where the project's time went chloectx repeats [--days 30] [--json] # instructions you had to give again, and the rules kept for it chloectx blame src/pay.rs:42 # which session wrote a line, and what memory had shown it chloectx backup ~/backups/chloectx-2026-10-28 # a consistent copy of this project's store chloectx redact [--all] [--dry-run] # redact secrets a store recorded before redaction caught them chloectx stores # every store on this machine; `chloectx prune` removes the unused ones chloectx stats | stop chloectx pack ./work.capsule # a capsule another agent mounts chloectx mount ./work.capsule # serve it as MCP tools (stdio) ``` `chloectx ask` prints the context a model would be given, not a written answer. Three commands are for maintenance and cost model calls: `chloectx ingest-transcript ~/.claude/projects//.jsonl` back-fills a session ChloeCtx did not record (one it recorded live is stored a second time); `chloectx distill` writes down the notes of the turns not distilled yet, one model call per turn (`--again` distills every turn again but a forget's, `--dry-run` counts them without a model call); `chloectx consolidate` merges overlapping notes now. `distill` and `consolidate` print one line of JSON when they are done (for `distill`: the turns, how many it distilled, and the notes it wrote). A capsule hands a slice of this memory to another agent as one read-only file it queries: [capsules](capsules.md). Beside the memories of projects, ChloeCtx keeps one of your own: your chats with ChatGPT, Claude.ai and Gemini, and a persona card drawn from them, which any assistant you connect reads: [personal memory](personal-memory.md). [Blame and receipts](receipts.md) explain `chloectx blame`. ### Where the time went `chloectx report` reads the store and writes nothing. For each session of the last `--days` days (7 by default; `--session` picks one by its id or the start of it) and in all, it splits the time between the records into: | share | from | to | |---|---|---| | model | a prompt, or a tool's result | the next tool call, or the answer | | tools | a tool call | its result (while any call runs) | | waiting | an answer, or a notification (a permission prompt, an idle notice) | the next prompt; one wait counts up to 30 minutes, the rest is *away*, counted apart | | compaction | a compaction's start | its summary | Anything that ends in a prompt is waiting (a turn the user interrupted, which has no answer). A permission wait lasts until the tool's result, so it includes the tool's own run after the user answered. Records keep Unix seconds, so every span is whole seconds, and a tool call has a length only when its record says how long it took: calls under a second, and calls recorded before ChloeCtx timed them, count as instants. Then: the commands that took most time, normalised as [error to fix](#when-to-load) matches them (`cd x && cargo test 2>&1 | tail` is `cargo test`), with their runs, time per run and failures; time by tool; errors seen three or more times, by signature, with the session they came back most often in; files read four or more times in one session; compactions per hour of use. Last, up to five suggestions, each with the numbers behind it: a slow command run often, a loop on one error, a file reread often, permissions waited on often, frequent compactions. `--json` prints the same as JSON. ## Where it keeps what it stores Each project's store is a folder outside the repository, because transcripts can contain secrets: `~/.local/share/chloectx/projects/-/` (under `$CHLOECTX_HOME/projects/` when that is set, and in `~/.local/share/engram/projects/` on a machine that has that folder from before the rename). It holds the ChloeDB file `memory.strata` and its write-ahead log, `state.json` (each session's live window and last prompts), `events.log` (the recall, search and distillation decisions), `receipts.strata` ([receipts](receipts.md)) and `snapshots/`. `chloectx doctor` names the store of the folder it runs in. A repository has one store, whichever of its git worktrees a session runs in: the store of a linked worktree (a folder whose `.git` file points at `/.git/worktrees/`) is that of the same folder in the main checkout, so agents in different worktrees read and add to one memory, through one daemon. A main checkout and a folder outside git keep the store they always had. Each session remembers the folder it runs in (in the store's session state, and in `events.log` with its branch): its paths are stored relative to it, and notes tied to the code are checked against its files, not the main checkout's. `CHLOECTX_PER_WORKTREE=1` gives each worktree its own store again. A redaction pass replaces keys, tokens, private keys, passwords in URLs and headers, and values assigned to names such as `DB_PASSWORD` with markers before anything is stored or synced, also a secret named just before its value in a sentence ("the staging password is …", "api key …"); a password written in any other way is not caught. When a prompt held a secret, the session is told that its prompts are recorded with the secret replaced, so that Claude does not tell the user nothing was saved. `chloectx redact` applies it to a store written before ([what is redacted](setup.md#secrets-and-chloectx-redact)). Treat a store like your shell history. A part of a prompt you mark private is not kept: "off the record", "don't save this anywhere", "between you and me", "keep that name private", with the sentence it points to, or a parenthesis that says so. It is cut before anything is stored, distilled or synced, and the prompt is kept with `[private aside left out]` in its place. The session is told what was left out, so Claude can say so truthfully, and the sentences of its replies that repeat the aside, in that turn or later in the session ("I didn't save your interview note"), are cut too. A prompt that is private as a whole ("Off the record, don't save any of this: …") keeps nothing of its turn: not the prompt, the reply or the tool calls. A store written before ChloeCtx cut asides out still holds them: the rules picked from them are retired, sync sends those records without them, and `chloectx forget` deletes the rest ([forget](setup.md#forget-something-chloectx-forget)). ## Forget something `chloectx forget` (and the model's `memory_forget`) deletes what ChloeCtx stored, for good: read [Forget something](setup.md#forget-something-chloectx-forget) in the install guide for what it matches and what it leaves before you use it. ## Settings Set these in the environment Claude Code starts in, or in the `env` of its settings. | variable | effect | |---|---| | `CHLOECTX_DISABLE=1` | turns the hooks off: nothing is recorded or recalled. The memory tools stay; start Claude with `--disallowedTools mcp__chloectx` to leave them out of a session too (`mcp__plugin_chloectx_chloectx` with the plugin, whose tools are named `mcp__plugin_chloectx_chloectx__*`) | | `CHLOECTX_PER_WORKTREE=1` | a store for each git worktree, instead of one for the repository | | `CHLOECTX_HOME`, `CHLOECTX_MODELS` | relocate the store and the models | | `CHLOECTX_DISTILL=0` | turns distillation off (or `"distill": {"enabled": false}` in the store's `config.json`) | | `CHLOECTX_DISTILL_MODEL` | the model the distiller and consolidation use (`install --distill-model` writes it into the settings) | | `CHLOECTX_DEEP` | query engine mode: `off`, `tool`, `async` (default), `sync` | | `CHLOECTX_DEEP_MODEL`, `CHLOECTX_DEEP_PLANNER_MODEL`, `CHLOECTX_DEEP_RANKER_MODEL`, `CHLOECTX_DEEP_HARD_MODEL` | the query engine's models (default `haiku`; the hard model is unset) | | `CHLOECTX_DEEP_PLAN`, `CHLOECTX_DEEP_RANK` | `none` skips the planner; `local` ranks without a model call (defaults: `model`, `model`) | | `CHLOECTX_CONSOLIDATE=0` | turns consolidation off | | `CHLOECTX_SESSION_CONTEXT=1` | recall also searches with the session's last records ([session context](#ranking); or `"rank": {"tail": {"enabled": true}}` in the store's `config.json`) | | `CHLOECTX_NEXT_FILES=1` | before an edit, also the files usually edited next, with a note on each ([when to load](#when-to-load); or `"next_files": true` in the store's `config.json`) | | `CHLOECTX_ERROR_FIXES=0` | turns error to fix off ([when to load](#when-to-load); or `"error_fixes": false` in the store's `config.json`) | | `CHLOECTX_EMBEDDER` | `static` (default), `bert`, or `hash:` for a model-free hash embedder | Each is still read under its name from before the rename, `ENGRAM_*`, when the new one is not set. ## How it works: the problem A long session on a complex project outgrows any context window. Claude Code then compacts it into a summary of about 15,000 characters. Summaries keep the plan and lose the particulars: - exact numbers, error messages and file paths; - the reason an approach was rejected; - a preference the user stated once, three hours earlier. A new session starts with only `CLAUDE.md` and the auto-memory index. The session that built ChloeDB ran for 32 hours and wrote 43.7 MB of transcript across two compactions; its summaries hold under 0.1% of that text. Three requirements follow: 1. **Store without being asked.** Capture must not depend on the model remembering to save. 2. **Load without being asked, but only when it helps.** Injected context costs tokens and attention, and irrelevant context hurts accuracy. Injection must be gated, budgeted, and must skip what the model can already see. 3. **Let the model ask precisely.** When the model knows it needs history, it gets search, timeline and SQL tools over the same store. ## Architecture ![ChloeCtx's architecture: hooks and the MCP server talk to one daemon per project, which owns the ChloeDB file](../assets/img/engram-architecture.png) Only one process at a time may write a ChloeDB file, and hooks are short-lived processes that run concurrently with the MCP server. So one daemon per project owns the database, and hooks and the MCP server are its clients over a Unix socket. - **Lazy start.** The first client to find no socket spawns the daemon under a spawn lock; the daemon exits after 30 idle minutes. Its first hook takes 50–72 ms, because the 129 MB embedding table is memory-mapped rather than read. - **Warm state.** The embedder, segment readers and the memtable stay in memory between hooks. - **Reads in parallel, one writer.** Reads run on each client's own thread against a snapshot, any number at once, and the searches behind one prompt share that snapshot and run side by side while cores are free. Every write goes to one writer thread, which commits whatever is queued in one transaction and builds the new version before the write returns, so a reader never waits for a write or for the index build after it. In-memory chunks hold 256 records and scan their vectors instead of building an HNSW graph, so that build stays cheap. A full memtable becomes a segment, and segments merge, on ChloeDB's background threads, not on the writer's: with 150,000 appends back to back in the cloud container (4-core Xeon), the longest took 0.2–0.4 s, against 12–15 s when the writer flushed and merged itself ([results](https://github.com/chloetech-ai/chloedb/tree/main/chloectx/results/writes)). - **Never in the way.** A client that cannot reach the daemon within its deadline prints nothing and exits 0. A memory failure never blocks a prompt or a tool call. A daemon that cannot start (its model gone, its store unreadable) is said once in the session ("ChloeCtx could not start its daemon, so this session is not being recorded", with the daemon's own last words and `chloectx doctor`), and is not tried again for 30 seconds, so each hook answers at once meanwhile (`start-failed.json` in the store's folder says why). The store lives outside the repository, one folder per project, and a repository's worktrees share one ([where](#where-it-keeps-what-it-stores)). A redaction pass replaces secrets with markers before anything is stored or synced ([what is redacted](setup.md#secrets-and-chloectx-redact)). ## The data model One ChloeDB table, `memory`. Each record is one key–value pair with attributes. | field | type | meaning | |---|---|---| | `id` | KEYWORD, primary key | `:` | | `session` | KEYWORD | Claude Code session id | | `kind` | KEYWORD | `prompt`, `answer`, `tool_call`, `tool_result`, `error`, `episode`, `summary`, `decision`, `preference`, `fact`, `todo`, `note`, `entity`, `event` | | `tag` | KEYWORD | tool name, summary section, `distilled`, `planned`, `superseded`, … | | `turn`, `seq`, `ts` | INT | user turn, project-wide sequence number, Unix seconds | | `importance` | FLOAT | salience prior in [0, 1]; for an entity, how many records link to it | | `files` | TEXT | paths the record touches (path components are terms) | | `text` | TEXT, stored | the value: one chunk of at most 400 bytes, injected as is | | `ctx` | TEXT, stored | the turn's request (≤ 200 characters); for notes also the situations they matter in (`When:`) and the code they were written against (`Anchor:`); part of the lexical key, never shown | | `body` | TEXT, generated from `text` + `ctx` | the lexical key that `bm25` and `MATCH` search | | `emb` | VECTOR(d), HNSW | the dense key: an embedding of `text` alone (for notes, `text` and its `When:` situations) | | `links` | EDGES | edges to the turn a record came from, the files it touches (`f:path`) and the entities it is about (`e:name`), which are records of kind `entity` | ![One record: a captured event is redacted, trimmed and cut into 400-byte records](../assets/img/engram-record.png) Keys are small and precise. A 400-byte window matches a question better than a 1,500-byte chunk in which the answer is one fact among many, and a context budget holds about ten such windows instead of five snippets. The turn's request joins the lexical key, so that a terse tool result ("test result: ok") is found by the words of the task it served; it stays out of the vector, where it would pull every response towards its request. The study behind these choices is in [the results](results.md#what-a-record-should-be). Records come in three levels: ```mermaid flowchart LR L0["L0 · events
    prompts, answers,
    tool calls and results, errors
    (400-byte records)"] --> L1["L1 · episodes
    one card per user turn:
    prompt, files, commands,
    errors, outcome"] L1 --> L2["L2 · knowledge
    decisions, rules, facts,
    planned work, compaction
    summary sections"] ``` The kind sets a salience prior ι: preference 1.0, decision 0.9, summary 0.8, prompt 0.7, error and episode 0.6, answer 0.5, tool call and result 0.3. ## When to store: always Storage is cheap (a durable commit costs about 4 ms on a Mac, where it flushes the drive's write cache, and runs off the hook's path) and a missed record cannot be recovered later. | hook | stored | |---|---| | `SessionStart` | session registered; live window opened | | `UserPromptSubmit` | `prompt`, less a [private aside](#where-it-keeps-what-it-stores), plus `preference` records for cue sentences ("always", "never", "from now on", …), but not for how to do this turn ("don't commit yet", "no code changes") | | `PostToolUse` | `tool_call` and `tool_result` (or `error`), asynchronously; a call that took a second or more says how long (`Took: 12s` in its context, timed from its message in the transcript) | | `Stop` | the answer, the commentary written between tool calls, the turn's `episode`, then distilled knowledge | | `PreCompact` | commentary not yet captured; an `event` (`compact_start`) | | `PostCompact` | the summary, by section; the live window restarts here | | `Notification` | an `event` tagged `notification:` (`permission_prompt`, `idle_prompt`, ...) | | `SubagentStop` | an `event` tagged `subagent_stop` | | `SessionEnd` | flush | Events are records of when something happened rather than of what was said: a permission prompt, an idle notice, a built-in sub-agent that finished, a compaction that started. They are never injected or returned by search, recall or a timeline unless asked for by kind; [`chloectx report`](#where-the-time-went) reads them. `chloectx ingest-transcript` back-fills old sessions from Claude Code's JSONL transcripts. ### Distilled knowledge Raw records hold what was *said*; a later session needs what was *agreed*: a decision and its reason, a client's rule, the requirements of work announced for later. Much of it never reaches the code, and a request that depends on it rarely sounds like earlier work, so search alone misses it. ![Knowledge records: a small model writes down what each turn agreed](../assets/img/engram-knowledge-records.png) After each `Stop`, off the prompt's path, the daemon gives the turn (request, commands, reply) to a small model through `claude -p`, with up to 40 live notes for context: the ones most related to the turn wherever they are in the history, then the newest. Seeing the related ones is what lets the model update a note written weeks ago instead of adding a near-copy next to it. The prompt names the day the turn took place, so a relative date in it ("tomorrow", "next Tuesday") is counted from that day even when the turn is distilled later (`chloectx distill`, a backlog). The model returns JSON lines: | item | stored as | tag | |---|---|---| | decision, with the reason | `decision` | `distilled` | | rule, constraint, convention | `preference` | `distilled` | | requirement of work planned but not done | `todo` | `planned` | | fact about the project or its environment, failed approaches | `fact` | `distilled` | | an instruction for the task at hand ("don't touch cart.py"), or how to do this turn ("no code changes", "don't commit yet") | `note`, kept to its session | `task` | | `replaces: id` | the old item is retagged, and names its successor (`superseded_by`) | `superseded` | | `done: id` | the planned item is retagged | `done` | | `retired: id`, a noted item about work the turn scrapped, reverted or dropped ("scrap it", `git restore`) | replaced by the turn's note that says so (the one sharing most of its words), else retagged | `superseded`, else `retired` | A new item whose analysed terms overlap an existing one by a Jaccard index J ≥ 0.6 is dropped. A note is superseded only by a stored note that names it and shares at least 30% of its words; when the replacement was dropped or is about something else, the old note stays live. A decision the prompt stated, kept at once in the user's words (below), is superseded by the turn's distilled decision or rule that holds at least half of its words, so one decision is one note. Retired and superseded notes leave the briefing and recall. What the user only asks about or assumes is not the project's: "write a function for a 2.5% fee, code in the reply only" does not make 2.5% its fee, and an answer the assistant gave from what is noted already adds nothing. A question how to build something ("I want a toggle for the PDF renderer. How should I add it?") plans nothing: a turn that asks it and changes no file files no planned work. A decision keeps what was decided and why, not whether its work is built yet ("Not implemented yet; planned for a later session" is left out), and a note kept with `memory_remember` replaces the copy of it the session kept already (the prompt's words kept as a rule or decision, a distilled note), so one decision is one note. **Who said it.** Every item says whether the request stated it or the assistant found it, and the record keeps its source in a `By:` line: `user`, `workbench` (a brief Workbench wrote), `agent:` (another agent's brief or message) or `assistant[:]`. Only the user makes rules. A rule the user stated is a `preference` every session is told unless it is an instruction for the task at hand: the model kept it to the task, or the part of the request it came from tells the agent what not to touch or only to do now ("Don't touch money.py or cart.py", "Only change totals.py", "for now", "in this PR"). A statement of how the project works ("Fee calculations use ROUND_HALF_UP, because the regulator audits them"), a client's or ops' convention ("Some context for this project, from the kickoff with the client: …", "Two things from ops: …") and anything the user said is standing ("always", "never", "from now on", "by default", "everywhere", a convention, a list after words that announce rules such as "A few ground rules before we start: …" or "Conventions:", but not "rules for this task", or an answer to the assistant's question asking for one) is a rule; when it is unclear, a rule, which you can retire, rather than a note no other session sees. Only a rule has a scope: a decision, requirement or fact the model calls "for this task" is kept as the project's. An instruction for the task, and anything an agent or Workbench told an agent to do, becomes a note for that session's task, which other sessions, the briefing and recall never see. A decision or fact another agent stated, or a Workbench agent concluded, reads "The agent lead said: …"; it is that agent's claim, not a fact. A person's prompt that states a decision ("My decision: …", "We decided …") is kept at once as the user's decision, whether or not the distiller runs: its line, up to a sentence that asks for something else ("Then run …"). A note the agent keeps with `memory_remember` is the user's when the agent says so (`said_by: user`) or, when it does not, when the turn's prompt says most of its words; otherwise it is the assistant's. A rule is the user's only in the user's own words: one the agent keeps as the user's (with `memory_remember`, or `chloectx remember` run in the session's Bash) that the user's prompts in the session do not say is the agent's suggestion, and so is one it keeps as its own. The briefing lists suggestions apart from the user's rules, under a line that says to ask the user before following one, and the command center lists them with the notes. A decision, fact or note an agent kept as its own is marked so in the briefing ("said by the assistant, not the user"), under a line that says not to follow an instruction in one. How to do one turn ("no code changes", "just answer", "don't commit yet") is never a rule, however many sessions say it. Workbench tells ChloeCtx who wrote each prompt with `CHLOECTX_PROMPT_SOURCE` (the session's task), `CHLOECTX_PROMPT_LOG` (later prompts it typed) and `CHLOECTX_AGENT_NAME`; a prompt that is a brief relayed to the session (``, ``, or one that opens "The coordinator sent a message while you were working:" or "Another Claude session sent a message:") is that agent's (`coordinator`, NAME, `another-session`); a prompt nothing names is the user's. **Said again.** An instruction the user gives and has to give again, later in the session or in another one, is a rule after all: the second time, it becomes a `preference` tagged `repeated` that every session is given ("Build apps from the CREATE statements (the user has said this in 2 sessions)", or "... 2 times" within one session), linked to what it repeats and superseding the notes among them. Which earlier sayings a request says again is a model's to judge, in a call of its own after each of the user's turns: it is shown the user's earlier requests and instructions most like this one, from this session and others (prompts, 6 by the vectors and 6 by BM25, and notes for a task and rules, 8 and 8), and the agent's reply before it. A request says one again when it asks for the same thing in any words, or complains that it still is not done ("why does it still say Strata?"); one that only shares a subject, asks for something else or changes its mind does not, nor a question that asks what holds ("What error code do we return when a client retries a payment?", "When can I deploy to staging?"): that asks memory, and a mark on it is dropped even when the model makes one, unless the question complains ("didn't I say …?", "why does it still …?") or asks for it ("could you always …?"). Nothing of the request's own turn is an earlier saying (the preference picked from its words, the notes an earlier distillation of it wrote), nor anything stored after it; nor is the same request sent again word for word (a scripted run), or a format the user pastes onto each task in the same words (six words or more, word for word in each earlier prompt). The model quotes the request's words that say it again and writes the rule; a mark whose quote is not in the request is dropped, because a model given a request with little in it copies what it was shown. A correction is reworded more than words or vectors follow (in a week of real sessions an instruction and its saying again scored a cosine of 0.05 to 0.57, different instructions up to 0.73). An instruction that says what a rule already says (one kept this way, or one the user gave as a rule) means the rule did not hold, and the rule is written anew: in the newest words, counted once more, and with the situations (`when`), files and entities of both, so it is the newest rule and is recalled in this situation from now on. It counts the sessions and times it was said, the times it was said again once kept, and of those the times the session's context already held it when the prompt came (`Sessions:`, `Said:`, `Said again:`, `Said again after it was shown:`): shown and said again, the agent broke a rule it had; not shown, the rule was missing when it mattered. Only the user's own words count, said on this machine: a teammate's, pulled from a [sync server](setup.md#keep-the-memory-on-a-chloedb-server), are theirs, and count on their machine. `chloectx repeats [--days 30] [--json]` lists, without a model and without writing, the rules said again and what the store holds that was said again in nearly the same words; `--judge FILE` asks the model about cases of real sayings and counts the repeats it finds. Distillation costs about **$0.0013 a turn** and 8 s with a small model, and the check of what the user said again about $0.0005 more for each of the user's turns; neither delays a prompt. Each note also carries **the situations it will matter in** (`when`), written at the same time: "choosing a library or standard-library module", "parsing a config file" for a note that the client machines run Python 3.8. A later request rarely uses the words of the note it needs; it uses the words of the task. The situations join the note's lexical key and its embedding, so "add a settings.toml loader" finds the Python 3.8 note although they share no word. This is document expansion (doc2query) done once, when the note is written. ### Consolidation Notes accumulate. Every eight distilled turns (or on `chloectx consolidate`), the daemon groups live notes that say related things: pairs whose embeddings have a cosine of at least 0.80, or 0.55 when they share an entity, joined strongest first into groups of at most ten. A small model rewrites each group as the smallest set of notes that keeps every detail, number, name and reason that still holds: a later change replaces the earlier version ("30 days, changed from 14"), duplicates merge, notes on different subjects stay apart, and rules, requirements and reasons are never dropped. Each merged note links to the notes it replaces (`supersedes`), which are retagged `superseded` and leave the briefing and recall, and is dated by the newest of them, not by when it was merged; a note the model would only reword is kept as it is. Nothing the model writes is taken as true because it wrote it: a merged note replaces its sources only when it says what the newest of them and the newest of the user's say (no word such as accepts or rejects turned around, no "not" added or dropped), keeps the newest one's numbers, names and paths, makes up none, and its sources are about the same thing (not the old parser with the new one, nor notes tied to different files). Otherwise the notes stay as they are, and `chloectx consolidate` lists the merge under `rejected` with why. A merged note is the user's only when all its sources are; when an agent's note is among them, it is the agent's. ### Notes tied to the code A note about code goes stale when the code changes. Each note records what it was written against: the commit and branch, a content hash of the files it names or the turn changed (up to six), and the identifiers it mentions (`ROUND_HALF_UP`, `load_config`). When a note is shown (briefing, recall, file notes, the query engine), ChloeCtx checks those files in the working tree, reading each once: | what changed | decision or fact | rule or requirement | |---|---|---| | nothing | shown as is | shown as is | | a file it names, its identifiers still there | "app/billing.py changed since this note; check the current code" | the same | | the file is gone, or an identifier it names no longer occurs | **may be out of date**: moved to its own briefing section | **the code may now break it**: stays with the rules, with "the code changed since this was stated; check that it still follows it" | A rule does not go stale because the code moved away from it: a teammate who switched invoices to banker's rounding did not cancel the client's requirement, so the rule stays where the model will see it, with a warning that the code may now break it. **Branches.** Worktrees of one repository share one store, but not their code. Each session's worktree, branch and commit are kept as an event when its hooks first name them and whenever the branch changes, so every record has a branch: its anchor's, else its session's at the time. A file an agent read or changed is anchored too (commit, branch, content hash). When a record is shown in another worktree, ChloeCtx asks git for the merge base of the record's branch with this HEAD: a record written after that commit came from work this worktree does not have, and is labelled "from branch wb/paybutton, not merged here: not a description of this worktree's code", unless its anchored files are the same here. A rule the user gave holds on every branch and is never labelled, and a note that names no file (a decision or fact said in conversation) is labelled only when its branch has commits this HEAD lacks. A decision the user made is not a description of code either: it stays with the other decisions, whole, and its label says only that what it says of files may not hold here ("the user's decision, made on branch wb/retry, not merged here …"). A file a note from another branch names that this worktree never had is "not in this worktree", not "no longer exists". The briefing moves the other notes from another branch to the section of notes that may be out of date, and the query engine's ranker is told never to present them as the current code. ## When to load Records still inside the model's context are never injected. For each session *s* the daemon keeps the window start ws, the sequence number at session start or at the last compaction, and every query excludes $$ \{\, r : r.\text{session} = s \;\wedge\; r.\text{seq} \ge w_s \,\} \;\cup\; \text{injected}_s $$ where injecteds is the set of records already injected since ws. ![The live window: what the model can still see is never repeated](../assets/img/engram-live-window.png) There are three push points and one pull path: ```mermaid sequenceDiagram autonumber participant U as User participant C as Claude Code participant E as ChloeCtx daemon participant S as ChloeDB C->>E: SessionStart E->>S: planned work, rules, decisions, facts, last checkpoint E-->>C: briefing (≤ 6,000 chars) U->>C: prompt C->>E: UserPromptSubmit E->>S: knowledge query (kind IN decision, preference, fact, …) E->>S: BM25 top 50 + vector top 50, live window excluded E->>E: priors, gate G, pack E-->>C: knowledge block + full / brief / no recall E->>E: query engine: plan, search, rank (background) C->>E: PreToolUse Edit(path) E-->>C: up to 2 earlier errors or decisions about path C->>E: PostToolUse E-->>C: the query engine's picks, once ready C->>E: memory_ask / memory_search / memory_timeline / memory_sql (pull) E-->>C: results C->>E: Stop E-->>C: picks not delivered yet: reconsider once E->>S: answer, commentary, episode E->>E: distill the turn, check notes against code, consolidate every 8 turns (background) ``` 1. **`SessionStart`: a briefing**, always, at most 6,000 characters: the rules first, then decisions, planned work with its requirements and facts, each note whole (a note longer than 600 characters, which the distiller never writes, is cut at a word, says that `memory_timeline` shows the rest, and is not counted as shown) and checked against the current code. It opens with an instruction to search memory before a design decision. It names no counts and no ages (a note's date, not "4 min ago"), so it is the same text from one session to the next while the notes are, and a session whose first prompt an earlier session sent too is served from Claude Code's prompt cache ([what it holds](#what-the-prompt-cache-holds)); what changes every session (how many records, the last activity, the open tasks at the last checkpoint and where the previous session stopped) comes with the session's first prompt, or with the first one that is not a question standing on its own (a question of at most 60 words that names no "we" or "our", no repository, file or name in code, and no earlier work, and does not weigh a choice or ask how to do something), which gets nothing at all when nothing is recalled for it. After a compaction or on a resume that part is in the briefing itself, and after a compaction it also recalls the records most relevant to the last two prompts. 2. **`UserPromptSubmit`: knowledge, then gated recall.** Up to four knowledge records not yet shown that match the prompt on their own text, bypassing the gate: $$ \cos\bigl(\phi(q), \phi(r)\bigr) \ge 0.40 \;\lor\; \mathrm{cov}(q, r) \ge 0.30, \qquad \mathrm{cov}(q, r) = \frac{\sum_{t \in q \cap r} \mathrm{idf}(t)}{\sum_{t \in q} \mathrm{idf}(t)} $$ Then the main search and a three-way gate: strong evidence injects the top records up to 4,000 characters; weak evidence injects three records up to 1,200, marked as a weak match; otherwise nothing. 3. **`PreToolUse` on `Edit`/`Write`: file notes.** Up to two older errors, decisions or rules anchored to that path, once per file per window. With `CHLOECTX_NEXT_FILES=1` (an experiment, off by default) the hook also names the files earlier sessions usually edited next: B follows A when an edit of B came within three edits after one of A (consecutive edits of one file count once), weighted by one over the gap and summed over sessions, and files above 1 are shown, at most two, each with its newest note. The daemon counts these from the edits the store holds as tool calls, reading only what was stored since it last looked, so nothing new is written. On the memory bench it changed neither how many tasks were solved nor which files were edited ([results](results.md#next-files)), so it stays off. 4. **`PostToolUse` and `PostToolUseFailure` on `Bash`: error to fix.** A command that fails and then passes, with edits or other commands between, is written down as a fix: an `error` record tagged `fix` holding the error's line, the steps (the last eight edits and commands that change something; `ls`, `grep`, `git status` and the like do not count) and what showed it fixed (the same command passed, or failed with another error). The same command means the same after `cd`, pipes, redirections, `timeout` and variable assignments are taken off (`cd x && cargo test 2>&1 | tail` is `cargo test`); a failure is followed for 60 tool calls, and one that passes with nothing between is not a fix. When a command later fails with the same error, in any session of the project, its fixes come with the failure, at most two, once a session. Errors are matched by their signature: the telling line (a compiler's `error:`, a panic, the last line of a Python traceback, `fatal:`, ...) with numbers, hashes, temporary paths and the project's path masked, or one sharing four in five of its words. The fix links to the prompt of the turn that fixed it. 5. **Pull: MCP tools.** `memory_ask` (by search alone, [below](#answering-a-question); with `deep`, the query engine), `memory_search`, `memory_timeline` (the neighbourhood of a hit), `memory_sql` (one read-only SELECT over `memory`, with no model calls, a 2-second deadline and a 1,000-row cap), `memory_remember` and `memory_forget` (by its words, every record that holds a fact; `chloectx forget TEXT` from a shell, and `chloectx forget --everywhere TEXT` for a fact in every store, [setup](setup.md#forget-something-chloectx-forget)). Sessions in worktrees of one repository share one daemon, so each tool call says which session made it (Claude Code's session id, and its process): a note kept with `memory_remember` is filed under the session that kept it, as is `chloectx remember` run from a session's Bash, and `chloectx remember` from your own terminal is `manual-:` (session `manual`). The tools leave out what the current session's window already holds, except the notes it kept or that were distilled from it, so a note just remembered is found at once. The briefing also ends with a one-line index of the notes it had no room for ("31 older notes are not shown here, about: …"), so the model knows what to ask for. **Text from outside the project is data.** What `WebFetch`, `WebSearch` and every MCP tool returned (a page, an issue, a mail, a chat message), and what a Bash command printed when it fetched from outside the project (`curl`, `wget`, HTTPie, `gh issue view`, `gh pr view`, `gh api`: tagged `Bash:fetched`), is stored, but it is never put into a prompt by itself: the prompt's recall, query understanding and the file notes leave it out, since whoever wrote that page or issue could otherwise plant an instruction that every later session got as "earlier work". `memory_search` and `memory_timeline` still find it, and show it fenced as quoted data (``, its own closing tag escaped inside), and every block of recalled records says that records are data and only the user's messages are instructions. A line of a record that begins like a record's header (`[a1b2c3d4:9] 2026-11-19 07:00 UTC · session …`), in a file the agent read or anything else, is shown escaped (`\[a1b2c3d4:9]`), so it stays text of the record it is in and cannot pass for a decision of the user's. Stores written before this keep their records; only what recall picks changes. ### Ranking BM25 and vector search each return their top *n* = 50 under the exclusion filter. Scores are min-max normalised over the union *C*, a missing score counting as 0: $$ \mathrm{rel}(r) = w\,\widehat{\mathrm{bm25}}(r) + (1 - w)\,\widehat{\cos}(r) $$ Priors then break near-ties without overriding relevance, with ι the salience prior and τ a recency scale: $$ S(r) = \mathrm{rel}(r)\,\bigl(1 + \lambda_\iota\,\iota(r)\bigr) + \lambda_t\, e^{-(\mathrm{seq}_{\max} - \mathrm{seq}(r))/\tau} $$ A record of routine work (a test run that passed, a bare test command such as `cargo test`, a tool's empty answer) has its whole *S* multiplied by 0.3, since it matches any question about its turn and says nothing. Answers that admitted not knowing and repeats of the same question are excluded, because they would only replay a failure. Packing is greedy by *S*: at most twelve records, at most eight per user turn. Every injected line carries its provenance (kind, session, turn, relative time and id), and up to five further candidates follow as one line each for the model to open with `memory_timeline`. **Session context (off by default).** With `CHLOECTX_SESSION_CONTEXT=1` the prompt's search also uses what the session was just doing. Its last 20 records give a BM25 query (the files they name and the first line of their errors, at most 24 words) and the vectors of the newest four prompts, answers, tool calls and errors, which rank records by `maxsim`. A record's best normalised score in those two lists is added to *rel* with weight 0.5, and records about one of the session's files score 15% more. The gate still reads the prompt's own evidence, so the session reorders what is injected but not whether anything is. On the memory bench it made no measurable difference (198 of 208 runs against 199) and it adds 5.8 ms to a prompt's searches at a million records ([results](results.md#the-session-tail)), so it stays off. ### The gate Min-max scores cannot gate, since the best candidate always scores 1. The gate uses absolute evidence about the best candidates: the highest cosine and term coverage among the top five, how far the best BM25 and cosine scores stand above the tenth, whether BM25 and vectors agree on the top record, and whether the prompt refers back ("earlier", "we decided", "last time", …): $$ G = a\,\cos_{\max} + b\,\mathrm{cov}_{\max} + c\,\mathbb{1}_{\text{cue}} + d\,\mathbb{1}_{\text{agree}} + e\,(\cos_1 - \cos_{10}) + f\,\Bigl(1 - \frac{\mathrm{bm25}_{10}}{\mathrm{bm25}_1}\Bigr) $$ ![Three tiers: no injection, a brief injection of three records, or the full budget](../assets/img/engram-gate-tiers.png) The weights come from a logistic fit on LongMemEval-S (`chloectx/scripts/fit_gate.py`): positives are questions whose evidence the packed injection contains; negatives are questions asked against another conversation's store, abstentions and misses. θhi holds precision 0.9 on the fit and θlo precision 0.7. The gate is the weakest part of the design; [the results](results.md#the-gate) say why. ![The query path: the exclusion predicate runs inside both searches](../assets/img/engram-query-path.png) ## Answering a question `memory_ask` (and `chloectx ask`) answers by search alone: no model call runs between the question and the answer, because the work was done when memory was written (the messages, the notes the distiller wrote, the user's rules). Four searches run side by side on one snapshot of the store ([`context.rs`](https://github.com/chloetech-ai/chloedb/blob/main/chloectx/src/context.rs)), each with the live-window exclusion: | search | over | what the context shows | |---|---|---| | rules | preferences, by vector, cosine at least 0.3; with them the rules the notes search finds, and every rule of a store that has at most four | at most four, first, in at most a fifth of the budget | | notes | decisions, rules, facts, plans (hybrid) | current versions only, each with the note it replaced ("changed DATE; was: …"), dated and ordered by the message each came from (a merged note by its newest source) | | replies | the assistant's answers (hybrid) | the three exchanges these hits rank first: the start of the user's message (200 characters) and the part of the reply closest to the question (1,000) | | excerpts | prompts and answers (hybrid) | the 400 characters of each closest to the question | Notes take 40% of the 12,000-character budget the rules leave, excerpts 25%, and both then fill the rest in rank order; the replies come on top, so a context is about 15,500 characters (about 3,900 tokens). A question about order or a summary ("in what order", "summarize", "a timeline of") has its answer spread over many exchanges, which a search for its words misses: it gets one and a half times the budget, the replies of eight exchanges (500 characters each), and every live note in place of the searched ones, oldest first (at most 50,000 characters, the newest kept), about 43,000 characters in all on BEAM. It takes about 6 ms a question on BEAM's stores, 11 ms for a summary. On BEAM 100K (20 conversations, 400 questions; [results](results.md#search-alone-against-observational-memory)) this context scores 62.9, against 55.0 for the query engine's picks and 63.4 for an observational memory that hands the reader its whole log of observations, about 153,000 characters, with the same reader and judge. Both sides move when their notes are written again: over two runs each, search alone averages 61.6 and observational memory 62.1. With `deep: true` (`chloectx ask --deep`, or a `model`) `memory_ask` runs the query engine below instead. ## Query understanding One search, however good its ranking, cannot answer "where does an unknown product code get caught, and why do we raise instead of skipping the line?". The answer is spread over a file, a decision and the error that led to it, and each is found by different words. The query engine turns a request into several searches, runs them all, and has a model pick what answers it. ```mermaid flowchart LR R["request
    (+ the session's last prompts)"] --> P["planner
    small model:
    1–8 typed searches"] P --> Q1["text"] & Q2["keywords"] & Q3["semantic"] & Q4["notes"] & Q5["entity"] & Q6["file"] & Q7["sql"] R --> B["the request itself:
    text + notes"] Q1 & Q2 & Q3 & Q4 & Q5 & Q6 & Q7 & B --> F["reciprocal-rank fusion
    30 candidates"] F --> K["ranker
    small model, or a stronger
    one for hard requests"] K --> O["picked records, why each matters,
    a short reading, confidence"] ``` 1. **Plan.** The planner sees the request, the session's two previous prompts, the store's size and time span, and the names of the entities and files notes are about. It writes up to eight searches, several of one type if that helps, covering each part of a question and the constraints a task touches without naming them (the machines it runs on, file formats, earlier failed attempts). It also says whether memory can matter at all, and whether the request is hard. 2. **Search.** Every search runs in parallel, plus two on the request itself, each with the live-window exclusion: | type | runs | |---|---| | `text` | the hybrid search above (BM25 and vectors) | | `keywords` | BM25 alone: identifiers, error text | | `semantic` | vectors alone, with a sentence phrased like the record hoped for | | `notes` | decisions, rules, requirements and facts only | | `entity` | records linked to named entities (matched by id, stem or embedding), two hops through the graph | | `file` | records about a path (`MATCH(files, …)`) | | `sql` | a `WHERE` and `ORDER BY` over `memory`, checked to be a single condition | 3. **Fuse.** Lists are merged by reciprocal rank, Σ 1/(61 + rank), so a record found by several searches comes first; the best 30 go on. 4. **Rank.** The ranker reads the 30 (600 characters each, with kind, date and any staleness label) and picks at most eight, each with why it matters, plus a one-to-three sentence reading that cites ids, and a confidence. Only picks the session has not seen are shown. It runs in one of four modes (`"deep": {"mode": …}` in the store's `config.json`, or `CHLOECTX_DEEP`): | mode | when it runs | how its result arrives | |---|---|---| | `off` | never | | | `tool` | only when the model calls `memory_ask` with `deep` (or `chloectx ask --deep`) | the tool's result | | `async` (default) | after every prompt of four words or more, once the store holds 20 records, in the background | with the next tool result; if the turn ends first, with the next prompt, when the picks are still new and the ranker's confidence is high or medium. The end of a turn does not wait for it, but a search already finished then whose picks hold a rule or decision of the user's that the session was not shown is given at once, and Claude Code runs the model again to check its answer against it (the turn may be the session's only one). With `"stop_recheck": true` the end of the turn waits up to `stop_wait_secs` (at most 3 s) and, when the picks are new, asks the model once to check its answer against them (Claude Code runs the model again for that, and it says only what changed) | | `sync` | the same prompts, before the model starts | in the prompt's context, after a wait (12 s at the median and 16 s at p90 in the cloud container, six requests at a time) | Both model calls go through `claude -p` with no tools and no prompt caching (each prompt is new, so a cache write would cost more than it saves), like distillation, and together read about 5,800 tokens and write 1,150: $0.0012 a request with a small model ($0.58 for 500 LongMemEval questions). Two settings make it cheaper. `"planner": "none"` (`CHLOECTX_DEEP_PLAN=none`) skips the planning call: the ranker reads the best 30 of the request's own two searches, taken deeper. `"ranker": "local"` (`CHLOECTX_DEEP_RANK=local`) replaces the ranking call with a logistic model over twelve features of each candidate (fused rank, similarity, term coverage, kind, length, recency) and keeps the top 5, with no model call; with `planner` also `none` the engine is free. On LongMemEval the default answers best: ranker only loses temporal questions, and the local ranker keeps about a quarter of the gain ([results](results.md#the-query-engine)). The models are parameters: `planner_model` and `ranker_model` (default `haiku`, or `CHLOECTX_DEEP_MODEL` for both), and `hard_model`, a stronger ranker used only when the planner calls a request hard (`CHLOECTX_DEEP_HARD_MODEL`). `memory_ask` also takes a `model` for one question, so a user who allows a more expensive model can have it for the questions that need it. ## Cost and latency targets | path | target | measured | |---|---|---| | `PostToolUse`, `Stop` client | < 10 ms | queued; embedded and committed in the background | | `UserPromptSubmit` | < 100 ms p99 at 1M records | 24.9 ms p50, 38.6 ms p99 as a hook process | | `SessionStart` | < 150 ms (daemon up), < 1 s with spawn | 50–72 ms including daemon start | | ingest | > 1,000 records/s | 48,000–52,000 records/s with the static embedder | | `memory_ask` (search alone) | < 100 ms | 6.9 ms a question on BEAM 100K's stores, one thread (11 ms for a summary) | | query engine (planner and ranker) | off the prompt's path unless `sync` | 12 s p50, 16 s p90, $0.0012 per request with Haiku | The default embedder is static (Model2Vec potion-retrieval-32M: token lookup and mean, 512 dimensions, microseconds per record). BGE-small (384 dimensions) is optional (`--features bert`) and costs about 50 ms per record on a CPU. The full design, including the evaluation plan, is in [`chloectx/DESIGN.md`](https://github.com/chloetech-ai/chloedb/blob/main/chloectx/DESIGN.md). --- # Install ChloeCtx on your machine ChloeCtx runs next to your own Claude Code: hooks record each session into a local ChloeDB file per project, and a small MCP server lets the model search that history. This page takes a fresh macOS or Linux machine to a working install in a few minutes, shows how to check it, and covers remote boxes, dev containers and upgrades. ## What you need | | why | check | |---|---|---| | macOS or Linux (Windows through WSL 2) | the daemon talks to the hooks over a Unix socket | `uname -s` | | Rust, stable | to build ChloeCtx from source (not for [the prebuilt binary](#prebuilt)) | `cargo --version` (install from [rustup.rs](https://rustup.rs)) | | a C compiler | to build from source: the tokenizer's regex library is C | `cc --version` (`xcode-select --install` on macOS, `build-essential` on Debian/Ubuntu) | | `curl` | downloads the 129 MB embedding model once | `curl --version` | | [Claude Code](https://claude.com/claude-code) CLI, **logged in** | the hooks and the MCP server plug into it, and the distiller calls `claude -p` after each turn | `claude auth status` shows `"loggedIn": true` | Python 3 is only needed for the scripted demo and the evaluation harnesses, not for ChloeCtx itself. The CLI login matters more than it looks. The distiller runs `claude -p` in the background, so an expired CLI login breaks it even while interactive sessions (or the desktop app) keep working. Recording and recall still work in that state, but nothing new is written down. `chloectx doctor` checks for it. ChloeCtx makes model calls of its own, through `claude -p` with a small model (`haiku` by default), billed to the CLI's login: one after each turn to write down decisions and rules (about $0.001 to $0.002); after each of your own turns that is like something you said before, one more to see whether you had to say it again, which makes it a rule (about $0.0005); and, once a project's store holds 20 records, two more after each prompt of four words or more, in the background, to search memory for it ([query understanding](index.md#query-understanding), about $0.001 to $0.002 a prompt). `chloectx doctor` shows what these calls cost in your own store over the last 30 days. None of them holds up a turn: what the search finds comes with the turn's next tool result, or at the next prompt; a find that holds a rule or decision of yours the session was not shown, ready when the turn ends, is given then, and Claude checks its answer against it. `CHLOECTX_DISTILL=0` turns the first two off, `CHLOECTX_DEEP=off` (or `tool`, only when the model asks) the last. The session's own model reads ChloeCtx's context too: the briefing, up to 6,000 characters (about 1,500 tokens), at the start of each session and again on each `claude --continue` or `--resume`, and the notes that come with a prompt. The daemon that makes these calls finds the `claude` CLI where Claude Code's hooks found it, on its own `PATH`, or in the usual install places (`~/.local/bin`, `~/.claude/local`, `/opt/homebrew/bin`, `/usr/local/bin`); `CHLOECTX_CLAUDE` names it outright. `chloectx doctor` shows which one the running daemon uses. ## As a Claude Code plugin The repository is a Claude Code plugin marketplace, named `chloedb`, with ChloeCtx as its plugin `chloectx`. In Claude Code: ```text /plugin marketplace add chloetech-ai/chloedb /plugin install chloectx@chloedb ``` On Claude Code 2.1.275 or later, `/plugin install chloectx --marketplace chloetech-ai/chloedb` does both. From a shell, `claude plugin marketplace add chloetech-ai/chloedb && claude plugin install chloectx@chloedb` installs it for every session, and `--scope local` (in the project's folder) for one project only. The plugin's name comes from the repository's `.claude-plugin/marketplace.json`, not from the address it is added by: `chloetech-ai/strata`, the repository's old address, still redirects and gives the same `chloectx@chloedb`. It needs no Rust and no clone of your own. Then start a **new** session. Its hooks and its MCP server run a small launcher in the plugin (`scripts/chloectx-launch`), which runs the first `chloectx` it finds: `$CHLOECTX_BIN`, `chloectx` on your `PATH`, or `~/.local/bin/chloectx`. When there is none, it sets ChloeCtx up once, in the background: 1. it downloads the prebuilt `chloectx` of the release that matches the plugin's version (the archive `chloectx-.tar.gz` of the release `chloedb-server-v`, from [the releases](https://github.com/chloetech-ai/chloedb-releases/releases); the newest release when that one has none), checks its SHA-256 against the release's `.sha256` and refuses one that differs, checks its build provenance where GitHub's CLI (`gh`) is installed (releases from 0.3.8; one that does not verify is refused; `CHLOECTX_VERIFY=require` refuses to install without `gh`, `=off` skips the check: [checking what you download](../../SECURITY.md#checking-what-you-download)), and installs it as `~/.local/bin/chloectx`, so `chloectx doctor`, `chloectx ui` and the other commands work from a shell too; 2. where there is no prebuilt one (Windows outside WSL 2, Alpine and other musl systems, glibc older than 2.35), or the download failed, it builds it from a checkout with `cargo` (Rust and a C compiler; `install.sh --no-wire` in `$CHLOECTX_SOURCE`, or in the clone of the marketplace), which takes several minutes; 3. it fetches the embedding model (`chloectx fetch-model`, 129 MB, SHA-256 checked). Until that is done, which is usually well under a minute, the hooks record nothing, and the first session's start says so; the memory tools come with the next session if they were not ready within 25 seconds. The launcher writes what it did to `~/.claude/plugins/data/chloectx-chloedb/setup.log`, and when it cannot set up, the next session's start says why. To watch it, or to try again by hand: `~/.claude/plugins/cache/chloedb/chloectx//scripts/chloectx-launch setup`. When the plugin is updated (`/plugin update`, or Claude Code's auto-update) to a new version, the launcher replaces a `chloectx` it downloaded with the new version's; one you installed yourself is yours to upgrade. Claude Code clones the whole repository for the marketplace, into `~/.claude/plugins/marketplaces/chloedb`: 665 MB on 17 November 2026 (Claude Code 2.1.326), of which 213 MB is `.git` and most of the rest benchmark results the plugin does not use. `claude plugin marketplace add chloetech-ai/chloedb --sparse .claude-plugin chloectx/plugin` checks out only the plugin, about 2 MB, which leaves no checkout to build from on a machine without a prebuilt `chloectx`. Either way, the prebuilt `chloectx` takes another 137 MB in `~/.local/bin` and the embedding model 129 MB. How it differs from `chloectx install --user`: | | the plugin | `chloectx install --user` (`./install.sh`) | |---|---|---| | hooks | the same eleven events, from the plugin, through its launcher | in `~/.claude/settings.json` | | MCP server | `plugin:chloectx:chloectx`, tools `mcp__plugin_chloectx_chloectx__*` | `chloectx` at user scope, tools `mcp__chloectx__*` | | the memory tools' permission | asked the first time each is used (add `mcp__plugin_chloectx_chloectx` to `permissions.allow` to stop asking) | allowed by the install (`mcp__chloectx`) | | distillation model | `haiku`, unless `CHLOECTX_DISTILL_MODEL` is set (in the settings' `env`, say) | `--distill-model`, written into the settings' `env` | | upgrade | `/plugin update chloectx@chloedb` | `chloectx upgrade` | | remove | `/plugin uninstall chloectx@chloedb` (keeps `~/.local/bin/chloectx`, the model and the stores) | `chloectx uninstall --user` (keeps the binary and the stores) | Both use the same stores, one per project. A project with its own `chloectx install` keeps using that one, and the plugin's hooks step aside there, as the user-level ones do. With both the plugin and `chloectx install --user`, the hooks of the user settings record and the plugin's step aside, but a session has the memory tools twice; `chloectx doctor` warns, and `chloectx uninstall --user` leaves only the plugin. Doctor shows the plugin: ```console ok plugin: chloectx@chloedb 0.3.11, enabled in /home/you/.claude/settings.json (11 hook events, through /home/you/.claude/plugins/cache/chloedb/chloectx/0.3.11/scripts/chloectx-launch) ok MCP server: the plugin's, plugin:chloectx:chloectx (its tools are mcp__plugin_chloectx_chloectx__*) ``` | launcher variable | effect | |---|---| | `CHLOECTX_BIN` | the `chloectx` to run, wherever it is | | `CHLOECTX_PREFIX` | where a downloaded or built `chloectx` goes: `DIR/bin` (default `~/.local`) | | `CHLOECTX_VERSION` | the release to download, instead of the plugin's version | | `CHLOECTX_RELEASES_URL` | where the releases are (default `https://github.com/chloetech-ai/chloedb-releases/releases/download`) | | `CHLOECTX_SOURCE` | a checkout to build from when there is no prebuilt `chloectx` | | `CHLOECTX_BUILD=0` | never build from source | | `CHLOECTX_PLUGIN_WAIT` | how long the MCP server waits for the setup, in seconds (default 25) | ## Prebuilt From release 0.3.2, the ChloeDB installer fetches `chloectx` prebuilt (macOS 11 or later, Linux with glibc 2.35 or later), with no Rust and no clone; then fetch the model, wire it into Claude Code and check: ```bash curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh -s -- --with ctx # ~/.local/bin/chloectx ~/.local/bin/chloectx fetch-model # potion-retrieval-32M, 129 MB, SHA-256 checked ~/.local/bin/chloectx install --project /absolute/path/to/project --distill-model haiku # or: install --user --distill-model haiku, every session ~/.local/bin/chloectx doctor ``` Without `--distill-model`, the distiller runs the Claude Code CLI's default model, and `chloectx doctor` warns that a small one is enough; `install` again with `--distill-model haiku` to change it. Release 0.3.1 and earlier have no prebuilt `chloectx`: build it from source, below. This installer (the website's `install.sh`) is not the repository's `./install.sh`, which installs ChloeCtx from a checkout and wires it in one step (next section), and takes the same prebuilt binary when it can. ## Install in one command, from source ```bash git clone https://github.com/chloetech-ai/chloedb && cd chloedb && ./install.sh ``` `install.sh` does five things and can be run again at any time: 1. builds `chloectx` in release mode (a few minutes the first time), or takes the release's prebuilt one (below); 2. copies it to `~/.local/bin/chloectx`, the path the hooks call; 3. stops any running ChloeCtx daemons, so they restart on the new binary; 4. downloads the embedding model (potion-retrieval-32M) unless it is already there; 5. runs `chloectx install --user --distill-model haiku` and then `chloectx doctor`. | option | effect | |---|---| | `--project DIR` | install into one project's `.claude/settings.local.json` and `.mcp.json` instead of every session | | `--distill-model NAME` | the model that writes down decisions and rules after each turn (default `haiku`; `--distill-model ""` uses the CLI's default model) | | `--prefix DIR` | install the binary to `DIR/bin` (default `~/.local`) | | `--no-wire` | install the binary only, and leave Claude Code's settings alone | | `--no-model` | do not download the embedding model (run `chloectx fetch-model` later) | | `--prebuilt` | take the release's prebuilt `chloectx`, never build | | `--source` | build from the checkout, never download the binary | From the release after 0.3.2, `install.sh` can take the binary that release carries instead of building it. Without `--prebuilt` or `--source`, it takes the prebuilt binary of release `chloedb-server-v` (the version in `chloectx/Cargo.toml`), checked against the release's SHA-256 and, where `gh` is installed, its build provenance (from 0.3.8; `CHLOEDB_VERIFY=require` or `=off` as for the plugin), in two cases: when the checkout is that release's (the tag, with `chloectx/` and `chloedb/` unchanged since), and when there is no Rust on the machine (then it says the checkout may be newer than the release). Otherwise it builds, so a checkout of main, or one you changed, runs what is in it. To install such a release with nothing to compile, clone its tag: `git clone --branch chloedb-server-v https://github.com/chloetech-ai/chloedb`, then `./install.sh` in it. (A checkout of 0.3.2 or earlier has the `install.sh` that always builds.) A prebuilt binary does not know the checkout it came with, so `chloectx upgrade` and `chloectx doctor` cannot compare it with one or rebuild it, even when `./install.sh` took it in a checkout of yours. To upgrade a checkout of a release tag, move it to the new release's tag and run the installer again, which takes that release's prebuilt binary: `git fetch --tags && git checkout chloedb-server-v && ./install.sh`. `CHLOECTX_SOURCE=/path/to/chloedb chloectx upgrade` is for a checkout on a branch, such as main, which it pulls and builds; on a tag (a detached HEAD) it stops and says so. Sessions that were already open pick ChloeCtx up when they restart. ## Or let your agent do it Tell Claude Code (or another coding agent) in any session: > Clone https://github.com/chloetech-ai/chloedb and set ChloeCtx up for my Claude Code by following its AGENTS.md. [`AGENTS.md`](https://github.com/chloetech-ai/chloedb/blob/main/AGENTS.md) tells the agent to check the prerequisites without installing anything unasked, to ask you whether to install for every session or one project, to run `install.sh` and `chloectx doctor`, and to report what failed. Two things stay with you: `claude auth login` if the CLI is logged out (it is interactive), and starting a new session afterwards, because the session that ran the install started before the hooks existed. ## Or step by step ```bash git clone https://github.com/chloetech-ai/chloedb && cd chloedb/chloectx cargo build --release --bin chloectx cargo install --path . --bin chloectx --root ~/.local # a stable path for the hooks: ~/.local/bin/chloectx chloectx fetch-model # potion-retrieval-32M, 129 MB, at a pinned revision, SHA-256 checked chloectx install --user --distill-model haiku # or: chloectx install --project /path/to/project --distill-model haiku chloectx doctor ``` `chloectx install --user` merges eleven hooks and a permission for the memory tools into `~/.claude/settings.json` and registers the MCP server at user scope with `claude mcp add-json`. Each run saves the previous `settings.json` next to it as `settings.json.chloectx-
    .token` in ChloeCtx's home). `chloectx sync status` says which key the project sends (`key_from`), and `setup` and `chloectx doctor` name the table a refused key needs. A setup the server refuses fails rather than saying it is set up: `--token-stdin` with nothing on stdin is an error (a script that failed to make the key), `setup` exits 1 when the server answers 401 or 403 (unless the key is to come from a `--token-env` variable this shell does not have), and `doctor` FAILs on a project the server refuses, asking it once when the project has not synced yet. A key for operations (role `propose` or `ops`, an on-call agent's) reads no synced memory and no local store through ChloeCtx's app, whatever else it reads. **Only the projects you set up sync.** `setup` syncs the project in whose folder it runs, and no other: another project of the machine sends nothing until `setup` runs in its folder too (they are listed in `sync.json`'s `projects`). `--every-project` syncs every project on the machine, and keeps the key as the machine's too (`sync.token`), which a project without a key of its own sends: an admin's key, or one that may write several projects' tables. `CHLOECTX_SYNC_URL` in the environment syncs every project that environment runs (a cloud environment's). `setup`, `chloectx sync status` (`syncs`, `projects`) and `chloectx doctor` say which projects sync. `chloectx sync off` stops the project it runs in and removes its key, and `chloectx sync off --every-project` stops every project but those set up in their own folders and removes `sync.token`; the server keeps what it was sent. (0.3.8 and earlier kept the first key set up as the machine's, and every project's daemon pushed its store with it. From 0.3.9 that key is sent for no project, and a project set up with 0.3.8 or earlier without a key of its own (with `--token-env`, or with none) syncs again once `setup` runs in its folder. `chloectx sync status` and doctor say when a project that does not sync now sent records before, and into which table: an admin removes them there with `DROP TABLE`.) **What another machine sent waits for you.** Each row names the machine that pushed it (`origin`: `CHLOECTX_SYNC_ORIGIN`, else a random id ChloeCtx keeps in `sync-origin` in its home) and, in its `links_json`, the name of the key it pushed with (`pushed_by`, as the server told that machine: "Make a sync key" names a key `chloectx-sync--
    `). A record pulled from another machine is stored with a link to that machine, and its rules, decisions and to-dos stay out of the session's briefing, the prompt's context and searches until you accept the machine (a to-do such as "Agreed requirement: …" would read as your plan): `chloectx sync accept` lists the machines by the name their key gives (`ana-laptop (m-1a2b3c4d5e6f)`), how many of their records wait and a few of them, and `--origin NAME` (the machine's name, its key's name or its id; repeatable) or `--all` (every machine listed now, and none that pushes later) accepts them in this project, now and on later pulls of it (the machines are added to the project's list under `accepted` in `sync.json`). A machine accepted in one project waits in another until it is accepted there. `trusted: ["*"]`, which `--all` wrote before 0.3.9, is no longer honoured, and the machines accepted before 0.3.9 (`trusted`) stay accepted in every project. Facts, notes and the conversation itself are not held back, and so do not wait: they are shown at once, each saying which machine it came from. A key that may write a project's table could otherwise plant a "user preference" that every machine of the project showed as its own. A cloud container is a new machine each time: give it a stable `CHLOECTX_SYNC_ORIGIN` in the environment, and accept that one once. **A team on one server: whose notes are whose.** A note pulled from a teammate's machine says so wherever a session is shown it, accepted or not: `(a1b2c3d4:42, 2026-11-18, from alice-laptop)` in the briefing, `[decision, from alice-laptop]` in the prompt's context, `· from alice-laptop ·` on a recalled or searched record, by the name of the key it was pushed with, else by the machine's id. A rule kept for being said again ([said again](index.md#distilled-knowledge)) counts only what was said on this machine: a teammate's request or rule, pulled from theirs, is not an earlier saying of yours. **Retire a rule for the whole project.** `chloectx sync retire ID`, in the project's folder, retires a rule, decision, fact, to-do or note on this machine and on the server, and every machine of the project retires its copy on its next pull, so a rule one teammate's session wrote down by mistake leaves every session's briefing in one place. On a cluster's command center, a synced project's **Memories** (the ChloeCtx page) has a Retire button on each current note, which does the same: the app works out the change and the page sends it to the server with the key you signed in with, so the app's own key, which only reads the projects' tables, needs no more. Either needs a key that may write the project's table (the project's sync key does, as does an admin's); the row keeps the name of the key that retired it (`retired_by` in its `links_json`), and the server's audit log keeps the command center's writes. A retired note stays in the project's history (**With history**), and a row that says otherwise later does not reopen it on a machine that retired it. **When someone leaves the team.** Their key and what their machine sent are removed on the server, and every other machine follows on its next pull: 1. Revoke their key: **Access** on the command center, or `DELETE /v1/admin/keys/ID` (`GET /v1/admin/keys` lists the keys by name: "Make a sync key" names theirs `chloectx-sync--
    `). Their machine can then neither push nor pull. 2. Find their machine's id in the project's table: `chloectx sync accept` on any machine lists the machines it pulled from by name and id, or, on the server, `SELECT origin, COUNT(*) FROM chloectx_mem_acme_web_1a2b3c4d WHERE links_json LIKE '%bob-laptop%' GROUP BY origin` (rows pushed with the server's own token name no key: their id is in `sync-origin` in ChloeCtx's home on that machine). 3. Delete what should not stay, and keep what the team agreed: `DELETE FROM chloectx_mem_acme_web_1a2b3c4d WHERE origin = 'm-1a2b3c4d5e6f' AND kind NOT IN ('decision', 'fact')` keeps their decisions and facts and removes their rules, to-dos, notes and the transcripts of their sessions. Every machine that pulled those rows forgets them at its next pull (each pull when ChloeCtx starts there, as a session starts, or with `chloectx sync pull`), and a new machine never sees them. A rule of theirs the team keeps can be accepted again by its new owner, or retired with `chloectx sync retire`. 4. Their laptop keeps its own store, which the server cannot reach: on it, `chloectx uninstall --user` removes ChloeCtx and keeps the stores, which are under `~/.local/share/chloectx/projects/` (`chloectx stores` lists them), and `chloectx forget --everywhere` removes one fact from all of them. **From 0.3.3 and before.** Every project shared one table, `chloectx_memory`, and any key that could write it read every project's transcripts. A project's rows there are still pulled, where the key may read that table (a key limited to its project's table is not sent there, so its pulls fill the audit log with no refusals), held back as from a machine no one accepted (`unknown`); nothing is pushed there any more. Once every machine of a project syncs into its own table, an admin removes the old rows (`DELETE FROM chloectx_memory WHERE project = 'acme/web'`) and revokes the old shared keys. `CHLOECTX_SYNC_URL` and `CHLOECTX_SYNC_TOKEN` override the settings (`CHLOECTX_SYNC_URL` for every project, as above). What is sent is what the store holds, transcripts of your sessions included, redacted again on the way ([secrets](#secrets-and-chloectx-redact)) and without the [private asides](index.md#where-it-keeps-what-it-stores) a store kept before ChloeCtx cut them out: use a server you control, over HTTPS, with a key (plain `http://` is refused except to this machine, `127.0.0.1` or `localhost`; `CHLOECTX_SYNC_ALLOW_HTTP=1` allows it). Sync adds records, and carries what was forgotten, deleted and retired to every machine: one forgotten here has its row on the server replaced by a tombstone, which every machine's next pull forgets, and is never pulled back ([forget](#forget-something-chloectx-forget)); another machine's rows deleted on the server (an admin's `DELETE`) are forgotten on each machine that pulled them, at its next pull; and a record retired or replaced on the server, or whose context a forget cut, is retired, replaced or cut on each machine that has it. A machine's own rows deleted on the server stay in its store, which is that person's to forget. A record pulled from another machine is not sent back (`chloectx sync push --again` sends it too, to fill a table that lost rows), so a delete on the server holds. A table dropped and made again, holding no row, is not read as a delete of every record: fill it again with `chloectx sync push --again` from one machine. A note retagged here after it was pushed is not sent again, but for one retired with `chloectx sync retire`. A key limited to the project's table cannot delete its rows in the table of 0.3.3 and before, `chloectx_memory`; those stay there, held back, until an admin removes them. A note kept with `chloectx remember` in a terminal has an id of its own, `manual-:`, so two machines that pulled the same records never give their next notes one id (in earlier versions both were `manual:`, and the server kept only the last one sent: `chloectx sync status` now warns when the server holds another machine's row under one of this store's ids). A note from a session's Bash has that session's id. ## For a team Two ways to share memory, which a team can use together: | | sync (`chloectx sync`, [above](#keep-the-memory-on-a-chloedb-server)) | team spaces ([ChloeCtx on a cluster](app.md)) | |---|---|---| | what it holds | each teammate's sessions in a repository, recorded by the hooks, and the rules, decisions and facts distilled from them | notes and exchanges that people and agents write to a space on purpose, through the app's API or a space's MCP server | | who reads it | every session in that repository, on every teammate's machine: the briefing and the recall at each prompt | an agent that asks the space before a task (`ctx_`), in any repository | | fed by the hooks | yes | no | | use it for | a team working in the same repositories, so that one person's decision reaches the next person's session | knowledge that is not one repository's: runbooks, on-call notes, a product's decisions | To roll ChloeCtx out to a repository's team with the plugin, commit the repository's `.claude/settings.json` with the marketplace, the plugin and its tools' permission: ```json { "extraKnownMarketplaces": { "chloedb": {"source": {"source": "github", "repo": "chloetech-ai/chloedb", "sparsePaths": [".claude-plugin", "chloectx/plugin"]}} }, "enabledPlugins": {"chloectx@chloedb": true}, "permissions": {"allow": ["mcp__plugin_chloectx_chloectx"]} } ``` Claude Code reads the committed marketplace only once the folder is trusted, and does not install a plugin a project's settings enable by itself: until it is installed, its hooks record nothing, `chloectx doctor` fails on it, and `/plugin` says so. And `chloectx` exists on a fresh laptop only after the plugin's first session start (or `chloectx-launch setup`) has downloaded it. In a folder not trusted yet, a scripted session (`claude -p`) also leaves the committed permission out. So a new teammate, in their clone of the repository, does these in this order: ```bash # 1. Let Claude Code know the marketplace: open `claude` in the clone and trust the folder, # or, with no interactive session (scripts, CI), add it by hand: claude plugin marketplace add chloetech-ai/chloedb --sparse .claude-plugin chloectx/plugin # 2. Install the plugin for the project. claude plugin install chloectx@chloedb --scope project # 3. Download chloectx and the model, and set up the sync, with the key an admin made for # them and this machine ("Make a sync key" on the ChloeCtx page). Do this instead of # waiting for a first session; the launcher is in the plugin's folder: LAUNCH=$(ls -d ~/.claude/plugins/cache/chloedb/chloectx/*/scripts/chloectx-launch | tail -1) printf %s "$THEIR_KEY" | "$LAUNCH" setup --sync-url https://chloedb.example.com # 4. Check. ~/.local/bin/chloectx doctor ``` Step 3 is `chloectx-launch setup` (which does what a first session start does, in the foreground) and, with `--sync-url`, `chloectx sync setup --url URL --token-stdin --no-create` in the current folder. A session started after step 2 also downloads chloectx by itself, in which case step 3 is only `printf %s "$THEIR_KEY" | chloectx sync setup --url https://chloedb.example.com --token-stdin --no-create`. Give each person a key of their own for each project, so that a key revoked when someone leaves ([when someone leaves the team](#keep-the-memory-on-a-chloedb-server)) stops only theirs. What is said in a session reaches every teammate's: say so to the team, and keep private asides marked ([where it keeps what it stores](index.md#where-it-keeps-what-it-stores)). That holds for secrets too: [redaction](#secrets-and-chloectx-redact) catches keys by their shape, assignments, flags, a sign-in's password in a sentence ("to log into the console use V with user ops") and a secret named before its value, but a password typed in any other way is kept as typed and recalled into every teammate's sessions, so tell the team to put passwords in a secrets manager, not in a prompt, and that `chloectx forget` removes one from the server and from the machines that pull after it. ## Upgrade and remove ```bash chloectx upgrade --check # is there a newer version? (fetches the checkout's main branch) chloectx upgrade # git pull --ff-only in the checkout it was built from, rebuild, reinstall, doctor chloectx stop --all # restart daemons by hand (they start again on demand) chloectx uninstall --user # or `chloectx uninstall` in a project; stores are kept ``` The binary knows the commit and the checkout it was built from (`chloectx --version` names the commit). `chloectx doctor` fetches that checkout's upstream branch (waiting at most 3 s; `upgrade --check` waits 20 s) and says how many commits on it change ChloeCtx or ChloeDB since the build, or, when the fetch failed, that it could not check and what the last fetch said (`upgrade --check` then exits 1), and a session that starts while the binary is behind says so once a day, from what the checkout last fetched. `doctor`, `upgrade --check`, the session notice and the inspector say what `chloectx upgrade` would do: when it would stop (the checkout is on a detached HEAD, on a branch with no upstream, or on one with commits its upstream lacks) they say why and how to fix it rather than "installs them", and a build that is not on the upstream at all (a local or rebased commit, or a checkout whose history is not the upstream's) is said to be apart from it rather than so many commits behind. `chloectx upgrade` pulls the checkout (fast forward only: it stops before pulling when the checkout is in one of those states, or when local changes are in the way, and `--no-pull` builds the checkout as it is), stops the daemons of the old build, runs `install.sh --no-wire` into the binary's own prefix, writes the user-level install again (a version may add hook events; the distillation model you chose is kept), and ends with `doctor`. A prebuilt binary, or one built outside a checkout (no `.git`), cannot upgrade itself: `chloectx upgrade` and `doctor` say to run the installer again (`curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh -s -- --with ctx`, which replaces the binary, keeps the stores and installs `chloedb-server` too), or point `CHLOECTX_SOURCE` at a checkout on a branch. A checkout of a release tag upgrades by moving to the new tag ([above](#install-in-one-command-from-source)), and one on main with `git pull && ./install.sh`. ## Keep the stores tidy: `chloectx stores` and `chloectx prune` Every directory a session runs in gets its own store, including the throwaway folders tools make under the system's temporary directory, so stores pile up over months. A health check of the MCP server makes one too: `claude mcp get chloectx` starts the server, and with it a daemon and a store, for the folder it runs in, even one where no session ever ran. `chloectx stores` lists them all, most recently used first, with the project each records, its size on disk and when it was last used, and marks the ones `prune` would remove: - the project folder no longer exists, and the store was not used for a week (a folder missing for less, or on a drive that is not mounted, such as `/Volumes/…` or `/media/…`, may have moved and is only marked; `chloectx move OLD NEW` attaches the store to the folder's new place); - the project is in a temporary folder (`/tmp`, `/var/folders` on macOS) and the store was not used for a day; - the store names no project (one from before the daemon wrote `project.txt`, whose `daemon.log` does not name it either) and was not used for a month. `chloectx prune` lists those and asks before it removes them (`--yes` skips the question, `--dry-run` only lists, `--older-than DAYS` adds every store not used for that long). A store whose daemon is running is never removed. Removing a store deletes that project's memory for good. `chloectx doctor` counts the stores and says when ten or more could go. The repository was called `rkonow/engram` until October 2026. A checkout made before then keeps working, because GitHub redirects the old address: upgrade it with `git pull && ./install.sh` in its folder (still named `engram`), and `git remote set-url origin https://github.com/chloetech-ai/chloedb` points it at the new name. ## ChloeCtx was called Engram ChloeCtx was called Engram until November 2026. `git pull && ./install.sh` moves an install to the new names, and leaves what it stored where it is: - The program is `~/.local/bin/chloectx`, and `~/.local/bin/engram` is a link to it for a release, so whatever still calls the old name keeps working. - `chloectx install` (which `install.sh` runs) replaces the entries the old install wrote into Claude Code's settings: the hooks that called `engram`, the MCP server `engram` and its permission `mcp__engram` (the server is `chloectx` now, and its tools `mcp__chloectx__*`), and `ENGRAM_DISTILL_MODEL`, which becomes `CHLOECTX_DISTILL_MODEL` with the same model. An `engram` server or permission is taken for ChloeCtx's only when the same settings hold the old hooks of the program it runs, since another tool may be called engram. `chloectx uninstall` removes both the old and the new entries. Until you run it again, `chloectx doctor` warns about the old ones. - The settings are `CHLOECTX_*`, and each `ENGRAM_*` one is still read when the new one is not set. - The stores and the embedding model stay in `~/.local/share/engram` on a machine that has that folder and no `~/.local/share/chloectx`: `install.sh` moves nothing, and `chloectx doctor` warns which folder is in use. `chloectx upgrade` moves it: with the daemons stopped, it renames `~/.local/share/engram` to `~/.local/share/chloectx` and leaves `engram` as a link to it (not when `CHLOECTX_HOME` is set). A new install uses `~/.local/share/chloectx`. A store's files keep their names (`memory.strata`, `engram.sock`), and a daemon started by the old program keeps serving until it stops, which `install.sh` asks it to do. Sessions that were already running keep the old tool names until they restart. ## Troubleshooting | symptom | cause and fix | |---|---| | `doctor`: **Claude Code login** fails, a session starts with *ChloeCtx is not writing down decisions or rules*, or `DISTILL` events show *OAuth session expired* | the CLI's own login expired; run `claude auth login`. Recording and recall keep working meanwhile, but turns from that period are not distilled again later. Until a distillation works again, each session's start says so, to you and to the model | | recalled records or rules that are a harness's markup (``, ``, ``) | stored by an earlier version, which kept the envelopes some harnesses wrap prompts in. Prompts are now stored without them, recall and the briefing pass the old ones over, and a daemon retires the rules it had picked out of them once, when it first starts on the store | | no records for a session | the session started before ChloeCtx was installed (restart it), `CHLOECTX_DISABLE=1` was set, or the project has its own install that points at a binary that moved (`chloectx doctor` in that directory says which) | | the model has no `memory_*` tools | the MCP server is not registered or the session predates it: `claude mcp get chloectx`, then restart the session. With the plugin, `/mcp` lists `plugin:chloectx:chloectx`; when it failed to start, the plugin was still setting up (see its `setup.log`), and the next session has the tools | | a session starts with *ChloeCtx could not set itself up* (the plugin) | the launcher found no `chloectx` and could not download or build one; the message and `~/.claude/plugins/data/chloectx-chloedb/setup.log` say why. Install `chloectx` another way (above), or point `CHLOECTX_BIN` at one, and start a new session | | `daemon did not answer in time` | read the store's `daemon.log`; a missing embedding model is the usual cause (`chloectx fetch-model`) | | distillation costs | about $0.001 to $0.002 a turn with a small model, after the turn has ended; `chloectx doctor` shows the cost and the median time your store measured over the last 30 days, and `CHLOECTX_DISTILL=0` turns it off | | `doctor`: **distillation** warns that it *uses the Claude Code CLI's default model* | the install was made without `--distill-model`. Install again with it: `chloectx install --project /path/to/project --distill-model haiku` for a project install (the warning names `--user`, which is for every session) | | `doctor`: **last distillation** failed with something other than the login | the line shows what the CLI wrote on stderr and its exit status (an old CLI that does not know a flag, a crash, a proxy), and doctor makes one small model call to say whether it still fails | | `doctor`: **daemon's Claude Code CLI** fails | the running daemon was started by a process that has no `claude` on its `PATH`, and it is not in the usual places either: set `CHLOECTX_CLAUDE` to its path, or `chloectx stop` so that the next Claude Code hook starts the daemon | | a project folder was moved or renamed, and its sessions start with an empty memory | stores are kept by the folder's path: `chloectx move OLD NEW` attaches the old store to the new folder. `stores` marks a store whose folder went missing in the last week, or is on a drive that is not mounted, and `prune` leaves it alone. A linked `git worktree` uses its main checkout's store, whatever folder it is in | | `doctor` in a git worktree: **hooks** fails with *none in ~/.claude/settings.json or …/.claude, and the chloectx plugin is not enabled* | a project install writes its hooks into that folder's `.claude/settings.local.json`, which git does not carry into other worktrees. Run `chloectx install --project` in the worktree too (it then shares the main checkout's store), or install for every session | | a project should not be recorded | add `"env": {"CHLOECTX_DISABLE": "1"}` to that project's `.claude/settings.local.json`, or set `CHLOECTX_DISABLE=1` in the shell you start `claude` from | | the memory tools are still there with `CHLOECTX_DISABLE=1` | it turns the hooks off, not the MCP server: start Claude Code with `claude --disallowedTools mcp__chloectx` to leave the tools out of a session too (with the plugin, whose tools are named `mcp__plugin_chloectx_chloectx__*`: `--disallowedTools mcp__plugin_chloectx_chloectx`) | --- # The live inspector A local web app for watching ChloeCtx work: what the hooks store, what the distiller writes down and what recall injects, for your own sessions or for a chat in a scratch project. Every panel is a query against the project's ChloeDB file, made through the same daemon the hooks talk to. Nothing is simulated: chat turns are real `claude -p` runs. [Try it in your browser](https://chloetech-ai.github.io/chloedb/demo/inspector.html) A static copy replays a recorded session. Its SQL runs in a JavaScript model of ChloeDB over the recorded records and vectors. The inspector runs in two ways: `chloectx ui` points it at the stores of your own sessions, and `demo/run.sh` runs it with a chat column against a scratch project. ## On your own stores: `chloectx ui` ```bash chloectx ui # http://127.0.0.1:8765/?token=..., opened in your browser ``` ![chloectx ui: a session rebuilt from its records, with the briefing, recall decisions and distilled notes; the store's knowledge on the right](../assets/img/inspector-ui-conversation.png) Once ChloeCtx is [installed](setup.md), `chloectx ui` serves this page from the binary over every store under `~/.local/share/chloectx/projects` (or the folder from before the rename, `~/.local/share/engram`, on a machine that has it; or `--home DIR`). Pick a store (one per project directory) and a session. The left column then replays the session from its records, in place of the demo's chat: - the prompts, the answers and the narration between tool calls; - each tool call, with its stored result loaded when you open it, and errors in red; - the briefing injected at session start and, for every prompt, the recall decision, its gate score and the records it injected (each one a link); - the notes the distiller kept after each turn, with what they superseded or closed, and the turn's episode card. A session that is still running grows as it goes, and the panels on the right work as described below, against the chosen store. The page reads through each project's daemon with the same read-only operations the demo allows, so the inspector can stay open while sessions write. The one thing it changes is what you tell it to forget: every knowledge card and every record has a **Forget…** button, and the Knowledge tab forgets everything that says some words. It first lists what would go (the records deleted, those that only lose a line of context, and the session state, log lines and receipts that hold it), and only **Forget** deletes, as `chloectx forget` does ([forget something](setup.md#forget-something-chloectx-forget)). The server listens on 127.0.0.1 and wants the random token in the URL it prints (kept in a cookie after the first load); on a remote machine, forward the port with `ssh -L 8765:127.0.0.1:8765`. The address keeps the view (`?store=…&session=…&tab=knowledge`). The page speaks plainly by default: the Live feed says what ChloeCtx did ("gave Claude 3 earlier records", "gave Claude nothing", "wrote down 2 notes"), and the record drawer shows the text, where it came from and what is closest in meaning. **Advanced**, at the top right, shows the store's internals as well: the Table, Graph, Vectors, Query and Storage tabs, record ids, the embedder and the store's file, the recall gate's score and evidence, and each record's vector. The page remembers the choice in your browser (`?advanced=1` turns it on from the address). The header shows the version the server runs and the commit it was built from, and whether the checkout it came from has a newer one: when the page opens it fetches the checkout's upstream branch (at most every ten minutes; **check** fetches again) and counts the commits since the build that change ChloeCtx or ChloeDB, as `chloectx upgrade --check` does. It says what `chloectx upgrade` would do, as `doctor` does: a prebuilt binary shows **prebuilt** and how to upgrade it (the installer again), a checkout `upgrade` would stop on (a detached HEAD, a branch with no upstream or with commits its upstream lacks) says why instead of offering **Update**, and a build that is not on its upstream at all (a local or rebased commit) says that rather than counting. When `chloectx upgrade` would pull and install, **Update** runs `chloectx upgrade` (pull, build, install, `doctor`) and shows its output as it goes, kept in `upgrade.log` beside the stores. The build takes several minutes. The page that started it keeps running the old binary: restart `chloectx ui` to use the new one. ChloeCtx's daemons restart new on the next hook, and new Claude Code sessions use it on their own. A pull that cannot fast-forward fails as it does on the command line, and nothing is installed. ![chloectx ui with the live feed: every record and daemon event of the store as it happens](../assets/img/inspector-ui-live.png) ## The demo: chat in a scratch project ```sh cd chloectx demo/run.sh --model --distill-model # opens http://127.0.0.1:8765 ``` | option | effect | |---|---| | `--model` | the model for the chat (default: the `claude` CLI's) | | `--distill-model` | the model ChloeCtx distills each turn with (default: `--model`) | | `--embedder hash:256` | a model-free hash embedder, so nothing needs downloading | | `--data DIR` | where the scratch project and its store live (default `~/chloectx-demo`; `~/engram-demo` on a machine that has that one from before the rename) | | `--budget USD` | maximum spend per chat turn (default 2.0) | The server is standard-library Python (`chloectx/demo/server.py`) and the page is one HTML file (`chloectx/demo/index.html`). Chat turns run with `--setting-sources project,local`, so your own plugins and hooks stay out of the demo. The browser can only call the daemon's read-only operations. ## A walkthrough The screenshots on this page come from one short session recorded for this documentation, with a small model for the chat and for distillation and the hash embedder. Two turns in a first session: > We're starting a small Python CLI for a community library to track book loans. Decisions: store loans in a JSON file (loans.json), not SQLite, because the librarian's laptop is locked down and nothing can be installed. Always use ISO 8601 dates. Later we will need an overdue report that prints at most 40 characters per line, for the receipt printer. For now, create loans.py with `add` and `return` commands. Keep it short. > Add a small unittest for add and return, and run it. Then a **new Claude Code session**, whose context starts empty: > Add the overdue report now. Before you start, tell me what storage we chose and why, and any constraint on the report's output. ![The new session answers from ChloeCtx's briefing](../assets/img/inspector-new-session.png) The new session answered correctly: JSON in `loans.json` because nothing can be installed on the librarian's laptop, only the standard library, and at most 40 characters per line for the receipt printer. None of it was in the new session's context when it started. It came from the **briefing** ChloeCtx injected at `SessionStart` (1,741 characters), built from the knowledge the distiller wrote after the first turn. Recall for the prompt itself was skipped by the gate (G = 3.61 on 30 candidates), because the briefing had already delivered what mattered. By the end, the three turns had become 42 records in three segments: prompts, tool calls and results, answers, episode cards, entities, and the distilled decision, rule and planned work. ## The panels ### Finding an entity, a file or words The box at the top right completes the names of entities and the paths of files as you type (`count` finds `count sheet`, `src/` the files under `src`), most linked first: an entity row counts the records that link to it. It is a prefix query on the `id` column, `PREFIX(id, 'e:count')` for names and `PREFIX(id, 'f:src/')` for paths, ordered by that count. When the exact prefix leaves room in the list of ten, names one typo away (two from six letters) follow, marked as typos, so `cuont` still finds `count sheet`. Picking one opens it with the records that link to it, and Enter opens the first. Words that name no entity or file are searched for, as Claude's `memory_search` would, and the drawer lists what memory holds about them, best first, with a button to forget everything that says them. The graph's seed box completes the same way. ### Live ![Live: every record and daemon event as it happens](../assets/img/inspector-live.png) Every record the hooks and the distiller write, and every step ChloeCtx takes, as it happens, in words: the briefing a new session got and its size, what each prompt was given ("gave Claude 3 earlier records", or "gave Claude nothing" when nothing bears on it clearly enough), what was written down after the turn and what it cost, and a question that stood on its own, which is given nothing and, answered in a few lines, not written down. With **Advanced** on, each step also shows its raw fields: for a recall, the decision, the gate score and its evidence features (`max_cos`, `max_cov`, `bm_gap`, `cos_gap`, `agree`, `cue`). ### Knowledge ![Knowledge: decisions, rules and planned work written down by the distiller](../assets/img/inspector-knowledge.png) The durable knowledge: decisions, preferences (rules), facts and planned work. Each item says where it came from (`distilled` by the model, or `cue` when a sentence like "Always use ISO 8601 dates" was picked up directly from the prompt), and links to the turn and entities it is about. Superseded and completed items can be shown too. **Forget…** on a card lists what would go and forgets it once you confirm; the box above the cards does the same for every record that says some words. ### Table ![Table: the memory table, filterable by kind, session and full text](../assets/img/inspector-table.png) With **Advanced** on, as are Graph, Vectors, Query and Storage. The `memory` table itself, paged, filterable by kind, session and a `MATCH` expression; it scrolls sideways rather than squeeze the text. ### Graph ![Graph: records, their links and the entities they mention](../assets/img/inspector-graph.png) Records are linked to the turn they came from, the files they touch (`f:loans.json`) and the entities they are about (`e:receipt printer`). These are ChloeDB `EDGES` fields, so the panel can run `REACHABLE` traversals from any seed, as in the [graph queries](../chloedb/graphs.md). ### Vectors ![Vectors: every record's embedding projected on two principal components, with a query's nearest neighbours](../assets/img/inspector-vectors.png) Every record's vector, projected on its first two principal components. A text query is embedded with the store's embedder and its top ten neighbours are drawn and listed with their similarity. Here *why JSON instead of SQLite* finds the distilled decision first (0.415). ### Query ![Query: an SQL console over the memory table, with plans](../assets/img/inspector-query.png) An SQL console over the store, read-only, with the executor's plan and timings. A text parameter bound as a vector is embedded by the store's embedder, so hybrid queries work as written. It can also run ChloeCtx's own hybrid search, the one recall uses. ```sql SELECT id, kind, text FROM memory WHERE kind IN ('decision', 'preference') ORDER BY similarity(emb, :q) DESC LIMIT 5 ``` ### Storage ![Storage: the table's schema, segments and file layout](../assets/img/inspector-storage.png) The table's schema and fields, its segments, the memtable, and the file's size by component. --- # Capsules: handing work to the next agent A capsule is a slice of a project's memory packed into one read-only ChloeDB file, which one agent hands to another. The receiving agent does not read it: Claude Code mounts it as MCP tools, and the agent asks it questions, under its own budget, when it needs to. **What we measured.** A handoff note alone is enough when it is long and complete. A capsule pays off when the note is short and loses things, as a sub-agent's report usually does. With a short note (about 2,000 characters), the next agent solved 72% of follow-up tasks. With the same note plus a capsule, it solved 89%, about 20,000 more input tokens and $0.0013 more per run. A capsule answers in 8 to 9 ms and mounts in about 65 ms. Making one takes 0.2 s and no model calls. ## Use it ```sh # On the machine (or in the session) that did the work, where ChloeCtx recorded it: chloectx pack ./billing.capsule # distilled notes, entities and the conversation chloectx pack ./billing.capsule --since-days 7 --kinds decision,preference,fact,todo,note,entity # In the next agent's Claude Code (one session, or `claude mcp add` for a project): claude --mcp-config '{"mcpServers":{"capsule":{"command":"chloectx","args":["mount","/path/to/billing.capsule"]}}}' ``` `pack` writes a directory with two files: - `memory.strata`: the chosen records with their vectors, links and indexes, in one file. By default it holds decisions, rules (`preference`), facts, open tasks, notes, the entities they link to, and the conversation (prompts, replies, episodes, summaries, errors). Raw tool calls and their results stay behind, because they are bulky and where secrets pass. Every record is redacted again on the way out. - `manifest.json`: what it holds (counts by kind, the entities it is about), the embedder its vectors need, the source store's last sequence number, and the file's SHA-256. `mount` serves one or more capsules over stdio as `capsule_ask` (the question answered from the capsule, packed to a token budget, with no model call), `capsule_search`, `capsule_timeline` and `capsule_sql`, the same code as ChloeCtx's `memory_*` tools. It copies the file into a private temporary directory, checks the copy against the manifest's hash and opens it, so mounting never changes the capsule. A capsule can come from someone else, so `mount` treats it as data: a file that carries stored functions or rank profiles (which `pack` never writes, and which could call a model with your API key from inside `capsule_sql`) is refused, the embedder must be the one the manifest names (or one given with `--embedder`), and the manifest's title and topics are cut to one line of bounded length and shown as the packer's words, not instructions. With ChloeCtx installed in the receiving project, the capsule tools' calls and answers are not recorded into that project's memory, whatever the MCP server is named. A record that redaction changed while packing gets a vector of its redacted text, `--max-records` keeps the newest records, and the manifest names the project's folder, not its path. Its MCP instructions say what the capsule holds, so the agent knows when to ask. `--log FILE` (or `CHLOECTX_CAPSULE_LOG`) writes one JSON line per call with its time. Not yet done: signatures (the hash names the file but does not say who made it), the receipts' named snapshots, and peer queries against another agent's live memory. ## Results **Method.** The four held-out projects of the [memory benchmark](results.md#memory-systems-compared) (stockroom, slotwise, bakehouse, kestrel; 52 follow-up tasks) were used. ChloeCtx recorded each project's history once. Every handoff lane then ran on that same history and repository, with ChloeCtx turned off for the run (no hooks, no memory tools), and handed the next agent one of the following: | lane | what the next agent gets | |---|---| | nothing | nothing | | long note | a handoff note in its system prompt. Haiku wrote it from the transcripts of every history session, with no length limit (5,800 to 12,100 characters) | | short note | a note Haiku was asked to keep under 1,500 characters (it wrote 1,900 to 2,300), about the size of a sub-agent's final report | | capsule | the capsule, mounted as MCP tools | | long note + capsule, short note + capsule | both | | ChloeCtx | ChloeCtx itself: briefing, recall and memory tools | | whole history | a fork of one session that holds the whole history, as an upper bound | Each task ran four times per lane, for 1,664 runs. Haiku did all the work. The harness is [`chloectx/scripts/memory_bench.py`](https://github.com/chloetech-ai/chloedb/blob/main/chloectx/scripts/memory_bench.py) (its `BENCH_HANDOFF` variants), the pooling is [`capsule_report.py`](https://github.com/chloetech-ai/chloedb/blob/main/chloectx/scripts/capsule_report.py), and every run, note and history is in [`chloectx/results/capsules/`](https://github.com/chloetech-ai/chloedb/tree/main/chloectx/results/capsules). The runs were measured on 12 November 2026 in a 4-core cloud container, with four projects running side by side, and that load is in the wall times. | lane | solved | needs an earlier session: solved | $ per run | input tokens per run, p50 | wall s, p50 / p95 | runs that asked the capsule or memory | |---|---|---|---|---|---|---| | nothing | 94/208 (45%) | 42/156 | 0.0047 | 131,037 | 15 / 31 | 0 | | short note | 149/208 (72%) | 97/156 | 0.0048 | 132,284 | 17 / 35 | 0 | | capsule | 189/208 (91%) | 137/156 | 0.0063 | 160,170 | 18 / 37 | 154 | | short note + capsule | 186/208 (89%) | 134/156 | 0.0061 | 147,227 | 18 / 39 | 147 | | long note | 198/208 (95%) | 146/156 | 0.0049 | 139,422 | 17 / 39 | 0 | | long note + capsule | 198/208 (95%) | 146/156 | 0.0061 | 150,554 | 18 / 39 | 125 | | ChloeCtx | 197/208 (95%) | 145/156 | 0.0071 + 0.0019 (its query engine) | 165,094 | 20 / 37 | 50 | | whole history | 198/208 (95%) | 146/156 | 0.0117 | 194,426 | 11 / 32 | 0 | Paired comparisons (labels shuffled within each task, 20,000 times): | comparison | solved | p | input tokens per run | wall s per run | |---|---|---|---|---| | short note + capsule against short note | +17.8 points | < 0.0001 | +20,340 | +1.7 | | long note + capsule against long note | 0 points | 1.0 | +21,646 | +1.2 | | capsule alone against long note | −4.3 points | 0.011 | +30,998 | +0.7 | | capsule alone against nothing | +45.7 points | < 0.0001 | +24,753 | +3.3 | What this shows: - **A complete note is as good as anything here.** A long note did as well as ChloeCtx and as the whole history in context, at 42% of the whole history's cost per run. Adding a capsule to it bought nothing and added about 22,000 input tokens per run. - **A capsule recovers what a short note drops.** The short note lost facts on two of the four projects (slotwise 28/40, bakehouse 34/72). Adding the capsule brought them to 38/40 and 60/72. On the other two projects the short note was already enough. - **Agents do use it.** With a capsule mounted, the agent asked it in 60 to 74% of runs, almost always through `capsule_ask`. - **The cost is the answer's size, not the engine.** Each `capsule_ask` returned about 16,000 characters (about 4,000 tokens, the default budget), which accounts for most of the extra input. A smaller default budget is the next thing to try. The capsule's own numbers: | measure | value | |---|---| | records and size | 273 to 770 records; 0.95 to 2.5 MB (3.3 to 3.5 KB a record, vectors and indexes included) | | `chloectx pack`, backup and cut included | 161 to 223 ms | | model calls to pack or to query | none (its notes were distilled while ChloeCtx recorded the history, which cost $0.03 to $0.12 per project) | | mount ready, hash check and copy included | 61 to 67 ms p50, 82 to 87 ms p95 | | one call | 8 to 9 ms p50, 11 to 14 ms p95, 18 ms at most, over 433 calls | A handoff note cost $0.007 to $0.019 to write. Both are made once per handoff. **Limits.** Four small projects, one history each, and one small model. The tasks were written alongside the histories and aim at facts the histories state. The long note was written from complete transcripts by a model asked for completeness, which is the best case for a note. A sub-agent writing from its own context, under its own budget, is closer to the short note. --- # Receipts and `chloectx blame` ChloeCtx puts records from earlier work into an agent's context: on every prompt, after a compaction, and when the agent calls `memory_search`. Each of those recalls now writes a **receipt**, and the store is **kept as a snapshot** after a recall that showed something, so any recall can be replayed later on exactly the data it read. `chloectx blame` starts from a line of code and walks back to the edit that wrote it, the prompt behind the edit, and the receipts of what memory had put in the agent's context before it. ```text $ chloectx blame src/payments/retry.rs:88 line sleep(backoff_delay(attempt)); commit 3f9a2c1b0e 2026-11-10 14:05 UTC · Retry with the new backoff edit 2026-11-10 14:02 UTC · session 7f3a91c2 turn 4 · 7f3a91c2-…:212 (the newest recorded edit whose new text holds the line) prompt use the new backoff policy for payment retries before it 3 tool calls in the turn: Read src/payments/retry.rs (120 lines) $ rg backoff src/payments Read src/payments/policy.rs (40 lines) recalled in the edit's turn: receipt rc-19a6… · prompt · Inject · store commit 48211 # kind record score cos tok decision k decision 1c2e…:31 0.812 0.812 35 knowledge ← superseded since, by 1c2e…:58 2 preference 1c2e…:12 0.640 0.700 15 take 3 tool_result 88aa…:90 0.520 0.610 310 excerpt ← untrusted source: the web replay of rc-19a6…: on the snapshot kept at commit 48211 (auto-48211): identical: the same rows, scores and decisions on today's store (commit 49007): different 1c2e…:31 (decision, knowledge) is no longer returned 1c2e…:58 (decision) is new: knowledge worth a look: - 1c2e…:31 (decision) was in context before the edit and is superseded since, by 1c2e…:58 - 88aa…:90 (tool_result) was in context before the edit and is untrusted source: the web - the same request today recalls different records ``` (The values above are made up to show the layout.) ## What a receipt holds | field | what | |---|---| | `id`, `ts`, `session`, `turn`, `source` | which recall: `prompt`, `compact` or `search` | | `snapshot` | the store's commit the recall read (`txn`, and `seq_no` in a store that numbers its writes), the newest record's number (recency is measured from it) and the record count | | `inputs` | everything else the result depends on: the query, the session's live window, the records already shown to the session, and the ranking, gate, packing and knowledge parameters as they were | | `decision`, `gate`, `evidence` | the gate's score and what it decided (`Inject`, `Brief`, `Skip`) | | `rows` | each candidate (up to 40): its rank, final score, raw BM25 and cosine, importance, distance from the newest record, the tokens it took or would have taken, a hash of its text, and the decision | | `text`, `text_sha`, `tokens` | the context the agent was given, as given | A row's decision is one of `knowledge` (a decision, rule or fact shown on its own text, ahead of the gate), `take`, `excerpt` (taken as a snippet), `listed` (named by id under "Further candidates", or a `memory_search` result), or `skip: ` with the reason: `shown before`, `over budget`, `per-turn cap`, `record cap`, `uncertain`, `same question`, `shown as knowledge`, `the gate held back`, `below the limit`. The words are those of ChloeDB's `PACK` receipts, so a ChloeCtx receipt and a `PACK ... WITH RECEIPT` answer read alike, and tokens are counted as `PACK` counts them (`chloedb::query::pack::count_tokens`). Receipts live in their own ChloeDB file beside the store, `receipts.strata` (table `receipts`). The store's file and its format are unchanged. A receipt is written once the hook has answered, so it adds no write to the prompt's critical path. The file is flushed every 256 receipts and when the daemon stops, so its write-ahead log (replayed when a daemon starts) stays small, and receipts older than 90 days, or past the newest 20,000, are dropped when the daemon starts. ## Kept snapshots After a recall that showed records, once the hook has answered and before anything else is written, the daemon keeps a snapshot of the store, at most once an hour (`min_interval_secs`, 3600 by default): `snapshots/auto-/` in the store's directory, a checkpoint in ChloeDB's directory layout. It is not taken when the store has not changed since the last one. What a snapshot costs: - **Time.** The checkpoint flushes the store's memtable, then reads every segment whole and checks its checksums, and checks the copy: a few passes over the store, whether or not a segment is linked. Tenths of a second for a store of tens of MB; seconds for one of a GB. This runs after the hook has answered; when it runs, the prompt's own record is stored after it, and `chloectx stop` waits for both. - **Space.** Each snapshot hard-links the segment files of the one before it that no merge has replaced since, and writes the rest. The live store is a single file, which a directory snapshot cannot share bytes with, so the first snapshot is a full copy, and every segment a merge writes is copied again by the next snapshot while older ones keep its inputs. The store's smallest merge tier spans up to 8,000 live rows, so each snapshot's flush makes a small segment that is merged again and again within it, and each snapshot keeps one of those outputs. With no budget, a simulation of the merge policy at 50 turns a day, 60 records a turn and hourly snapshots over an 8-hour day (the fourth audit, not a measurement) gave snapshots of about 3 times the store after a week (143 MB beside 46.5 MB) and 4 times after 30 days (1.16 GB beside 279 MB); taken after every turn (`min_interval_secs: 0`), about 10 times after a week. On a file system where hard links fail (some network and FUSE mounts, exFAT), every snapshot is a full copy, and `chloectx doctor` says so. So the automatic snapshots are kept to a budget: at most the store's size (`budget_store_ratio`, 1.0; at least 32 MB; `max_bytes` sets one in bytes, and 0 for both sets none), counting each file once however many snapshots link it, and counting named snapshots too, which are never dropped for it. Past it, the oldest automatic ones go, never the newest. Automatic snapshots older than 3 days are thinned to the last of each day (`daily_after_days`; 0 keeps them as taken). Those older than `keep_days` (30), or past the newest `max_auto` (2,000), are dropped too. All of this runs when the daemon starts and before each new snapshot, whatever the settings say now. Anything under `snapshots/` that no snapshot owns (a checkpoint a stopped daemon left half written) is removed when the daemon starts. `chloectx stats` shows the bytes of the store, the receipts and the snapshots, and the budget (`receipts`, `snapshots`, `total_bytes`), and `chloectx doctor` says them in one line, `disk`. A receipt replays exactly on the snapshot kept at its commit: the replay runs the same retrieval code (`receipt::retrieve`, which the recall itself runs) with the receipt's inputs, and must give the same rows, scores and decisions. When no snapshot was kept at that commit (a recall that showed nothing, or one inside `min_interval_secs`), it replays on the nearest later one and says so. With hourly snapshots that is most receipts: about one in six replays exactly at 6 recalls an hour, and the rest on the next snapshot, whose store holds the records written since; after 3 days only the last snapshot of each day is left, and after the budget fills, fewer. It is also replayed on today's store, which shows what has changed since: a record superseded, deleted or outranked. `chloectx snapshot keep NAME` keeps one by name, until `chloectx snapshot drop NAME`; `chloectx snapshot list` lists them. Settings, in the store's `config.json`: ```json {"receipts": {"enabled": true, "snapshots": {"after_recall": true, "min_interval_secs": 3600, "keep_days": 30, "max_auto": 2000}, "retention": {"keep_days": 90, "max_receipts": 20000}}} ``` `chloectx receipts off` turns receipts and automatic snapshots off for the project's store (it writes `receipts.enabled` in its `config.json`), and `chloectx receipts off --purge` also removes the receipts and automatic snapshots kept so far; `chloectx receipts on` turns them back on. Without `receipts.enabled` in `config.json`, `CHLOECTX_RECEIPTS=0` in Claude Code's environment turns them off: each hook sends it to the daemon, whichever process started the daemon. With receipts off, `memory_forget` and `chloectx redact` still scrub the receipts kept before. ## Commands ```bash chloectx blame src/retry.rs:88 # or a whole file: chloectx blame src/retry.rs chloectx blame src/retry.rs:88 --json --no-replay chloectx receipts [--session S] [--limit N] # S: a session id, or its first characters as listings show them chloectx receipts off [--purge] | on chloectx receipt rc-19a6… [--text] [--no-replay] [--json] chloectx snapshot keep before-release | list | drop before-release ``` `blame path:line` reads the line from a regular file inside the project, after links and `..` are resolved, of at most 8 MiB; any other path is refused, so neither the command center's Blame tab nor the daemon's socket can be used to read a file elsewhere. Every `memory_search` answer ends with its receipt's id, so an agent (or the person reading its transcript) can ask why a record ranked where it did. ## In the command center ChloeCtx's page in ChloeDB's command center (`chloedb-server --app chloectx=URL`, then Apps → ChloeCtx) lists every space it can read; a Claude Code store of the machine the app runs on opens with three more tabs (Receipts, Blame, Snapshots and capsules) beside Overview, Ask, Memories, Sessions, Graph and Connect (`#/app/chloectx/store//receipts`, `…/blame/`): - **Receipts**: the store's newest receipts (when, which recall, what it was for, records and tokens shown, the gate's decision, the session and turn). Open one for its candidates (rank, score with a bar, BM25, cosine, tokens, decision), the query and the gate, the text the agent was shown, and the replay on the kept snapshot and on today's store. The kept snapshots are under **Snapshots and capsules**: keep one by name, drop a named one, or cut a capsule (pick the kinds of record) with the `claude mcp add` line that mounts it. - **Blame**: type `path:line`. It shows the line, its commit, the edit, the prompt and the tool calls before it, the notes from the turn, each receipt of what memory had recalled before the edit (with what has become of each record since), the replay, and a "worth a look" list. Each receipt links to its page under Receipts. They read the Claude Code stores of the machine `chloectx app` runs on, so they are off unless it is started with `--local-stores` (or `CHLOECTX_APP_LOCAL=1`): a store is a transcript of its sessions, and every user of the command center could read it. Without it the tabs say how to turn it on. A store whose daemon is stopped is started when read. The API behind them, under the app's prefix (`/v1/apps/chloectx`): | request | answer | |---|---| | `GET /v1/local` | this machine's stores | | `GET /v1/local/:store/receipts?session=&limit=` | the newest receipts | | `GET /v1/local/:store/receipts/:id?replay=0` | one receipt, replayed unless `replay=0` | | `GET /v1/local/:store/blame?target=path:line` | blame, as `chloectx blame --json` | | `GET`, `POST {name}` `/v1/local/:store/snapshots`, `DELETE /v1/local/:store/snapshots/:name` | the kept snapshots; keep one; drop one | | `GET`, `POST {title?, kinds?, since_days?}` `/v1/local/:store/capsules` | the capsules cut from the store, newest first; one cut, its manifest and folder | | `GET /v1/local/:store/overview`, `/sessions`, `/records`, `/notes[/:id]`, `/graph`, `POST /v1/local/:store/ask` | what the other tabs read, as a team space's calls of the same names answer ([the app](app.md#spaces-and-what-each-shows)) | | `GET /v1/local/:store/stats` | `chloectx stats --json` | ## How blame finds the edit Blame reads the line from the file and looks among the stored tool calls (`Edit`, `MultiEdit`, `Write`, `NotebookEdit`) of that file for the newest that added it: the line is a whole line of the edit's new text and not of the text it replaced (an edit that only kept the line around its change did not write it). A relative path is taken from where `chloectx blame` runs; in a request to the daemon, from the project. When none does (the line was written outside a recorded session, or changed by hand since), it takes the newest edit of the file before the line's commit (from `git blame`), and says which it did. Stored edits keep up to 1,100 characters of their new text, so a line deep inside a long `Write` may only be found this second way. The edit's turn gives the prompt, the tool calls before the edit and the notes distilled from the turn. The receipts of that turn, and of up to three earlier turns of the session that showed records, give what memory had put in context. Each record shown is checked against the store as it is now: deleted, superseded (and by what), or from an untrusted source (a tool's output; the web for `WebFetch` and `WebSearch`). ## Forgetting and redaction A receipt and a snapshot hold copies of what was recalled. So `memory_forget` (and the `forget` request) scrubs the text of the receipts that showed the forgotten records (their rows keep ids and scores, and lose the record's text hash) and removes a forgotten prompt from the query of the receipts it was asked as, in one pass over the receipts however many records went. Forgetting by text (`memory_forget` with `text`, `chloectx forget TEXT`) also replaces every string of every receipt that holds it (a query, the text shown), and then `receipts.strata` is compacted and its free pages written with zeros. The forget drops every automatic snapshot, and rewrites the store's segments that held the records without them, with no snapshot taken until that is done, so no snapshot taken afterwards holds their bytes. Only the segments that held them are rewritten (those whose live rows fell with the delete, and those a flush or a merge wrote since that still hold them, marked deleted), not every segment with an older delete, and then the free pages of the store's file, where the old segments were, are written with zeros (`Database::zero_free_pages`); pages an open snapshot still reads are left, and said. `memory_forget` answers before the rewrite, which runs after the answer, and `chloectx forget` waits for it. Named snapshots are kept and listed, for you to drop. `chloectx redact` redacts the receipts as it does the records, and drops the automatic snapshots too. Replays of the receipts before then can no longer be exact. --- # ChloeCtx as an app of a ChloeDB cluster `chloectx app` runs ChloeCtx beside a ChloeDB cluster, as the crawler and Sheets do, and the command center shows it under Apps. Its memory is not a file on one laptop: it lives in the cluster's tables, so any number of agents and people can write to it and ask it for context. Its first page lists every memory it can read, as *spaces* to pick from, and a space opens on what it knows now: - **Team spaces.** Memory that any agent writes notes and conversations to and asks for context before a task, within a token budget: a table of the cluster each. An answer is found by search alone (BM25 and vectors, no model call), and it says what went in, why, and what was left out. - **Claude Code projects.** What Claude Code sessions remembered: a project `chloectx sync` copied into the cluster (a table per project, `chloectx_mem_`; `chloectx_memory` for one synced before 0.3.4), and, with `--local-stores`, the stores of the machine the app runs on, where Receipts, Blame and capsules are too ([Receipts and blame](receipts.md#in-the-command-center)). A store and its synced copy show as one project. - **Seen before**, a page of its own: the cluster's firing alerts, each beside the past incidents it looks like and the fix that worked. One button hands the alert to the cluster's on-call agent with those incidents as its context. ![A team space's Ask tab: the question "Who approves a refund of 1,200 EUR?", answered first by the current refund decision with the 500 EUR version it replaced struck through, then the notes that also bear on it, the past conversations folded, and the context's size](../assets/img/chloectx-app-context.png) *The demo's team space, asked "Who approves a refund of 1,200 EUR?". The answer leads with the current decision (over 1000 EUR or 900 GBP, a second approver from finance) and what it replaced, then what else bears on it; the scores, what was left out and the context as the agent gets it are below. 14.4 ms, no model call.* ## Start it A chloedb-server with `chloectx` installed beside it (in the same directory, as an install puts them) starts it by itself, with a token and a key of its own ([apps the server starts](../chloedb/server.md#apps-the-server-starts)); its key may make and write `ctx_*` tables and read `chloectx_mem_*` and `chloectx_memory`, so the on-call hand-off of Seen before, which needs an admin key, is refused there. Started by hand: ```bash cd chloectx && cargo build --release --bin chloectx ./target/release/chloectx fetch-model # the embedding model, 129 MB, once # the key and the token from the environment, not flags, which every user of the machine sees in ps CHLOEDB_KEY="$ADMIN_KEY" CHLOECTX_APP_TOKEN="$APP_TOKEN" \ ./target/release/chloectx app --server http://127.0.0.1:7700 --port 7760 # and the coordinator shows it: CHLOEDB_APP_TOKEN="$APP_TOKEN" chloedb-server --shards ... --app chloectx=http://127.0.0.1:7760 ``` | option | default | what | |---|---|---| | `--server` (`CHLOEDB_URL`) | `http://127.0.0.1:7700` | the chloedb-server (a coordinator, or a server on its own) the spaces live in | | `--key` (`CHLOEDB_KEY`) | none | its key for the app's reads and writes: an admin key, since a new space is a new table and the on-call agent takes admin calls. Give it in `CHLOEDB_KEY`: a flag shows in `ps` | | `--token` (`CHLOECTX_APP_TOKEN`) | none | the token every caller must send (`Authorization: Bearer`); chloedb-server sends its `CHLOEDB_APP_TOKEN`. Without one, `chloectx app` refuses to start unless `--insecure`. Give it in `CHLOECTX_APP_TOKEN`, as the key | | `--insecure` | off | serve any caller with no token; without it, `chloectx app` refuses to start with no token, on loopback too, since whoever reached the port (on loopback, any program of the machine) could read and write every space and start model calls billed to its key. On loopback it then answers only requests whose `Host` is this machine (`127.0.0.1`, `localhost`, `[::1]`), so that a page reaching it through DNS rebinding is refused | | `--host`, `--port` | `127.0.0.1`, `7760` | where it listens | | `--embedder` (`CHLOECTX_EMBEDDER`) | `static` | `hash:` for tests without the model | Model calls (writing a conversation's notes down, drafting an incident from a postmortem) go to Anthropic's API when `ANTHROPIC_API_KEY` is set (model `CHLOECTX_APP_MODEL`, by default Haiku), else to the `claude` CLI when it is on the PATH (`CHLOECTX_DISTILL_MODEL`). `CHLOECTX_APP_MODEL=off` turns them off. Everything else, asking included, works without a model. At most four conversations are distilled at once and 256 wait; past that an exchange is stored without notes (its answer says `skipped`, and `/v1/info` counts it under `distill.skipped`). The app serves 64 requests at once and answers one more with 503. The app refuses requests that carry an `Origin` header. chloedb-server checks the signed-in key and reaches the app with the app's token and who called (`x-chloedb-scope`, and `x-chloedb-tables` for a key limited to tables); start the app with a token (`CHLOECTX_APP_TOKEN`) wherever it runs (see [Security model](../chloedb/security.md)). The app's manifest says `"checks_callers": true`, and it refuses what the caller's key may not do itself: reading a space or asking it needs read on its table (`ctx_`), adding or retiring notes and exchanges write there, making a space admin there (it makes the table), the incidents are the space `incidents`'s (`ctx_incidents`), and what is not a space's (building apps, handing an alert to the on-call agent, this machine's stores) needs an admin key of every table to change and a key of every table to read. So a write key records notes, and a key limited to `ctx_ops_*=write` writes the spaces `ops_*` and nothing else (`GET /v1/spaces` lists the spaces it reads). A request with none of those headers (a program calling the app itself with its token) may do anything, as before. ### On Kubernetes A cluster the [operator](../chloedb/server.md#on-kubernetes) runs gets ChloeCtx from its `StrataCluster`, with nothing to start by hand: ```bash kubectl -n strata patch strata demo --type merge -p '{"spec": {"chloectx": {}}}' ``` The operator runs `chloectx app` from the cluster's own image (it carries it, as it carries the crawler and the spreadsheets) as a Deployment of one pod, `-chloectx`, behind a Service of that name on port 7760, and restarts the coordinators so that they list it: **Apps → ChloeCtx** appears in the command center. It reads and writes with the cluster's admin token (`tokenSecret`), which its API requires too, so the coordinators send it that token and nothing else reaches it (a cluster without a `tokenSecret` is open to whoever reaches it, and the operator starts its ChloeCtx with `--insecure` to match), and it calls the model with the cluster's `secretEnv` (`ANTHROPIC_API_KEY`; without one, everything but writing a conversation's notes down and drafting incidents works). The embedding model is not in the image, which every server pulls: an init container downloads it from Hugging Face (125 MB) into the pod's scratch volume each time the pod starts. The spaces are tables of the cluster, so a pod started again (a new image, a node replaced) has them all; the upgrader moves it with the servers, since it runs their image (from the image of 2026-11-10 on: an older one has no `chloectx`). | `spec.chloectx` | default | | |---|---|---| | `paused` | `false` | no pod for now (the coordinators still list it, as an app that does not answer; the spaces stay) | | `embedder` | `static` | `hash:` for a cluster that cannot reach Hugging Face: no download, vectors from hashed words. Notes keep the vectors they were written with, so after a change earlier ones match by their words only | | `args`, `resources` | | more arguments of `chloectx app`, and its container's resources (50m CPU and 128 MiB asked, 1 GiB at most; it uses about 40 MiB) | Removing `spec.chloectx` deletes its Deployment and Service and restarts the coordinators without it; the spaces stay in `ctx_spaces` and `ctx_`. ## Where the memory is Each space is a table of the cluster, `ctx_`, with ChloeCtx's own records ([the data model](index.md#the-data-model)): notes (`decision`, `preference` for rules, `fact`, `todo`, `note`), messages (`prompt`, `answer`), entities, and links between them. The spaces themselves are rows of `ctx_spaces`. A table per space keeps BM25's statistics per space, so one team's words do not weigh on another's ranking, and SQL reads a space like any table: ```sql SELECT kind, text, ts FROM ctx_billing WHERE kind IN ('decision', 'preference') AND tag != 'superseded' ORDER BY ts DESC LIMIT 20 ``` The app keeps nothing of its own: a restart, or another copy of it, finds every space in the cluster. It numbers the records it writes, so one app writes to a cluster's spaces at a time. Notes are never overwritten. A note that `replaces` another marks the older one `superseded` and links them both ways (`supersedes`, `superseded_by`); a context shows the current version with what it changed, and the history keeps every version. ## The API JSON over HTTP; through chloedb-server, the same paths under `/v1/apps/chloectx`. | call | body | answer | |---|---|---| | `GET /v1/spaces`, `POST /v1/spaces` | `{name, title?, description?, kind?}` | the spaces with their counts (`by_kind`, every record; `live_by_kind`, the notes not replaced, retired or done); the new space (one that exists is left as it is); `kind` is `notes` (the default) or `incidents`, a team's own incidents for Seen before | | `DELETE /v1/spaces/:s` | | the space, deleted by an admin of its table: its table `ctx_` dropped and its row of `ctx_spaces` removed, `{deleted, table, kind}`; it cannot be undone | | `POST /v1/spaces/:s/notes` | `{kind, text, replaces?, entities?, session?, when?}` | the note (`kind`: `decision`, `rule`, `fact`, `todo` or `note`); `when` (or `ts`) is when it happened, for a note written down after the fact: seconds since 1970, or ISO 8601 text (`2026-09-14`, `2026-09-14T03:10:00Z`); by default, now | | `GET /v1/spaces/:s/notes?kind=&limit=&all=1` | | the notes, newest first; the current ones unless `all=1` | | `GET /v1/spaces/:s/notes/:id` | | the note, the versions it replaced and those that replaced it | | `DELETE /v1/spaces/:s/notes/:id` | | the note, retired: kept, tagged `retired` (not `superseded`: nothing replaced it), and in no context again | | `POST /v1/spaces/:s/exchanges` | `{user, assistant, distill?}` | the two messages; with a model, their decisions, rules and facts follow as notes in a few seconds (`GET /v1/info` counts them) | | `POST /v1/spaces/:s/ask` (or `GET ?q=&budget=`) | `{question, budget?}` | `{context, tokens, ms, items, left_out}`; `budget` is 200 to 50,000 tokens (4,000 left out), and one outside that is refused | | `GET /v1/incidents?space=`, `POST /v1/incidents` | `{title, symptom, cause, fix, alert?, replaces?, when?, space?}` | the incidents of every incidents space the key reads (or of `space`), each with its space and the fixes it replaced; the new one, in `incidents` or the team's `space`, dated `when` (the incident's own date) | | `GET /v1/incidents/firing?space=` | | the cluster's firing and pending alerts, each with its closest incidents and the context the on-call agent would get | | `GET /v1/incidents/match?q=&alert=&space=` | | the incidents closest to a description | | `POST /v1/incidents/match` | `{lines \| text, space?, alert?, n?}` | the incidents closest to log lines pasted from an outage (redacted as notes are, at most 4,000 characters) | | `POST /v1/incidents/draft` | `{text}` or `{run}` | incidents a model drafted from a postmortem or an on-call run's report; nothing is kept | | `POST /v1/incidents/handoff` | `{alert}` | the on-call agent's run, started with the closest incidents | | `POST /v1/spaces/:s/apps/suggest` | `{n?}` (2 or 3) | apps a model suggests from the space's notes: `{apps:[{title, pitch, why, kinds, description}]}`; nothing is built | | `GET /v1/spaces/:s/apps/estimate` | | what a build costs: the median of the app engine's past first builds, its model and what is left of its cap | | `POST /v1/spaces/:s/apps/items` | `{kinds?, exclude?}` | the notes a build would copy | | `POST /v1/spaces/:s/apps` | `{title, description, kinds?, exclude?, confirm: true}` | the build, started (409 without `confirm`, 402 when the engine's cap is spent) | | `GET /v1/spaces/:s/apps` | | the space's builds: `building`, `loading`, `ready` or `failed`, with their cost and rows loaded | | `POST /v1/spaces/:s/apps/:id/open` | | a one-time link into the app engine's studio, at the built app | An answer of `ask` has, for each record in the context, its `section` (`rule`, `note`, `timeline` for a question about the whole history, `reply` and `excerpt` for past conversations), its `tokens` (about four characters each), its scores (`bm25` for the question's words, `cos` for its meaning) and, for a note that replaced another, `replaced`: what it changed. `left_out` names what the searches found and the context leaves out, and why: `superseded` (a later note replaced it), `retired`, `uncertain`, or `budget`. The context is built as ChloeCtx's own `memory_ask` builds it for Claude Code ([how](index.md)), with its sizes scaled to the budget. ### A space as an MCP server `POST /v1/spaces/:s/mcp` speaks the Model Context Protocol (streamable HTTP, JSON answers; a `GET` gets 405) with three tools on that space: `ask` (`question`, `budget`: the context, as `ask` above, with the ids of its notes), `remember` (`kind`, `text`, `replaces?`, `entities?`: a note, session `mcp`) and `notes` (`kind?`, `limit?`: the current ones with their ids). A space that does not exist is 404, not a new space. To connect Claude Code, through chloedb-server: ```bash claude mcp add --transport http ctx-billing https://chloedb.example.com/v1/apps/chloectx/v1/spaces/billing/mcp \ --header "Authorization: Bearer $KEY" ``` A space's page in the command center has a **Connect Claude Code** card that makes the key and shows this line with it filled in: a key limited to the space's table, `ctx_billing=write`, which may read and write that space and nothing else (below). ### Keys limited to tables chloedb-server lets a key limited to tables call the app, because the app's manifest says `"limited_keys": true`: it tells the app the key's grants (`x-chloedb-tables`), and the app, which writes with a key of its own, holds the caller to them: a space is its table `ctx_` (read to read and ask it, MCP included, write to add, replace or retire notes and hand over exchanges), the incidents are `ctx_incidents` (read, write to record or draft), a Claude Code project is read from its table (`chloectx_mem_`, or `chloectx_memory` for one synced before 0.3.4), and `GET /v1/memory` lists the projects whose tables the key reads. A key for operations (role `propose` or `ops`, which the server says in `x-chloedb-role`) reads no Claude Code project and no local store: those are people's sessions. Creating a space and building apps from one take an unlimited admin's key, and no limited key reads the machine's local stores (Receipts, Blame). `GET /v1/spaces` lists the spaces the key may read. A caller with no such header (an admin's key, the server's token) is not limited. ## Spaces and what each shows `#/app/chloectx` lists the spaces, grouped (team spaces; Claude Code projects) with what each holds, and a filter. A space's page (`#/app/chloectx/space/`, `…/project/`, `…/store/`) has a switcher to another space and these tabs: - **Overview**: how many rules, decisions, facts and open to-dos it holds now, its sessions and records, the rules (which go into every context), the latest decisions and facts, the open to-dos, *what changed* (notes that replaced an earlier one, with the old text struck through) and the latest sessions. - **Ask**: a question, answered as an agent would be: the note that answers it first, the rules that apply, what else bears on it and what past conversations said, then the scores behind each (BM25, cosine, section, tokens), what was left out and why, and the context as the agent gets it. A link carries the question (`…/ask/`). A synced project, which has no store to build a context from, answers with its records ranked by BM25. - **Memories**: every note, by kind, current or with its history; a note opens on the versions it replaced and those that replaced it. A team space's notes can be replaced or retired here. - **Sessions**: each session titled by its first prompt, read as the conversation it recorded: turn by turn, the prompt, the tool calls (folded), the answer and the notes written down from the turn. *Every record* searches all of them (BM25) and filters by kind. A record opens in a drawer with its whole text (up to 4,000 characters), its context, files, links and id. - **Graph**: how its memory is connected: each note (a circle, by kind; a replaced one hollow), the subjects it is about (entities, larger the more notes name them), the files it touched, the session it came from (off by default) and the note it replaced (a dashed link). A click lights up a node's neighbours and lists them, with its history, its session, *Ask about it* or *Blame it*; a search finds a subject, file or note; the link carries the selected node (`…/graph/e:refund`). - **Connect**: how to use the space. A team space: the `claude mcp add` line with a key limited to its table, the HTTP calls and the SQL that read it, and apps built from it. A Claude Code project: its MCP tools, its CLI, and how to sync it here. - **Receipts**, **Blame**, **Snapshots and capsules**: a store of this machine only ([Receipts and blame](receipts.md#in-the-command-center)). The older links (`#/app/chloectx/inspector/`, `…/receipts/`, `…/blame/`) open the same space's tab. Until a project is synced, the projects group offers a setup instead: given the project (`owner/name`) and the machine, a button (for an admin) makes the project's table and a key that may read and write only it, named for the machine, and shows the `chloectx sync setup` command with the key filled in. One key per project and machine: a key of one project reads no other's sessions, and a key revoked stops one machine. Rules and decisions one machine sends reach another's sessions once someone there accepts it (`chloectx sync accept`). This needs ChloeCtx 0.3.4 or later; an older one syncs every project into `chloectx_memory`. `GET /v1/memory/table?project=` answers the table's name and CREATE TABLE. A project is its git repository, so every checkout shares one memory ([keep the memory on a ChloeDB server](setup.md#keep-the-memory-on-a-chloedb-server)). What the tabs read, beside the space calls above: | call | answer | |---|---| | `GET /v1/spaces/:s/overview` | `{records, sessions, first, last, by_kind, live, rules, decisions, facts, todos, changes, recent_sessions}`: `live` counts the current notes by kind, each list holds the newest 12, `changes` the notes that replaced another with `was` (the older texts) | | `GET /v1/spaces/:s/sessions` | `{sessions: [{session, records, first, last, turns, title}], by_kind}`: the latest first; `title` is the first prompt's first line, `turns` its prompts | | `GET /v1/spaces/:s/records?session=&kind=&q=&limit=&before=` | `{records, more}`: a session's in order, else the latest first (`before`, a `seq`, pages back), or the best matches for `q` (BM25); at most 500 | | `GET /v1/spaces/:s/graph` | `{nodes, edges}`: nodes `{id, type, label}` of type `note` (with `kind`, `text`, `tag`, `current`, `ts`, `session`), `entity`, `file` (`f:`) and `session` (`s:`, its title); edges `{s, t, label}`: `about`, `touches`, `from` (the session) and `supersedes`; the newest 1,500 notes | | `GET /v1/memory` | `{table, exists, projects: [{project, records, sessions, last}], create}` (`create`: the table's `CREATE TABLE`) | | `GET /v1/memory/overview?project=`, `/v1/memory/notes?project=&kind=&all=1`, `/v1/memory/graph?project=` | a synced project's overview, notes and graph, as a space's | | `GET /v1/memory/sessions?project=`, `/v1/memory/records?project=&…` | its sessions and records, as a space's | A store of this machine answers the same calls under `/v1/local/:store/` ([the list](receipts.md#in-the-command-center)). ## A demo to show it `chloectx/demo/seed.py` plays a scripted Claude Code history into ChloeCtx, so every page has something to show: twenty sessions over four weeks on *harbor*, a made-up order and payments service (refunds, webhooks, rate limits, migrations, a double-refund incident, a release process), with corrections along the way (a refund limit raised twice, a currency added, a rate limit changed for partners, a debug print that logged a key). It runs the real hooks and daemon, each turn at its date in the story (`CHLOECTX_CLOCK_OFFSET`), with a scripted distiller (`demo/scripted_distill.py`) in place of the model, so it makes no model call and takes about 15 seconds: ```bash python3 chloectx/demo/seed.py --dir ~/chloectx-demo # a Claude Code store, with receipts and snapshots CHLOECTX_HOME=~/chloectx-demo/home chloectx app --server http://127.0.0.1:7700 --local-stores python3 chloectx/demo/seed.py --dir ~/chloectx-demo --no-local \ --server http://127.0.0.1:7700 --space harbor --sync # the same story as a team space, and synced ``` `--space` writes the story into a new team space through the API (`--space-reuse` adds to one that exists), `--sync` copies the store into the cluster as the project `acme/harbor`, in a table of its own, `chloectx_mem_acme_harbor_58e121ba` ([keep the memory on a ChloeDB server](setup.md#keep-the-memory-on-a-chloedb-server)), and `--key-env` names the variable holding the server's key. All of it is made up: no transcript of anyone's sessions is in it. ## Seen before ![Seen before in the command center: four firing alerts of a local cluster, each with the past incidents it looks like; the disk alert's closest incident was recorded for the same alert](../assets/img/chloectx-app-seen-before.png) *Seen before on a two-shard cluster in the cloud container (the alerts are real: its disk was over 90% full, and a test load raised the p99). "Disk full within 12 hours" finds the incident recorded for the same alert first, and the p99 alert the merge incident, whose first fix (a restart) was replaced by a better one.* An incident is a note in the space `incidents`, or in a team's own space of kind `incidents` (`POST /v1/spaces {name, kind: "incidents"}`): a title, the symptom, the cause, the fix, and the alert rule it fired, if one did. Seen before reads every incidents space the signed-in key may read, so a team that keeps its own sees its incidents beside the shared ones, and log lines pasted from an outage find the incidents that look like them as an alert does. For each firing alert, it searches the incidents with what the alert says (its name, metric, description and the copies it fires on). The incidents recorded for the same rule come first; another must be close in meaning (cosine 0.3, or 0.2 when it shares a word) and at least half as close as the closest. A match shows the fixes it replaced struck through, so an agent does not repeat one that was given up. **Hand to the on-call agent** starts the cluster's on-call agent (`POST /v1/admin/oncall`) on the alert with the closest incidents and the incident space's rules in its question; the server needs a Claude key for it. When the run ends, **keep what it found** drafts an incident from its report for a person to check and record. A postmortem pasted into **Record an incident** is drafted the same way. ## Create an app from a space A space's page has **Create an app from this context**. **Suggest apps** asks the model for apps the space's notes could become (one call, on at most 150 notes); each says why, and which kinds of notes it reads. **Build this...** opens the build: its name, the request the app engine gets (editable), the kinds of notes, and every note that goes in, each with a tick to leave it out. Before anything is spent it shows what a build costs, the median of the engine's past first builds (`sa_requests`), and what is left of the engine's cap; the build starts only on **Build it**, which sends `confirm: true`. The cluster's app engine (the app `apps`, [chloedb-apps](../../chloedb-apps)) builds the app from the request and leaves out its example rows. When it is done, ChloeCtx maps the picked notes, 30 at a time, onto the new app's tables with its model and inserts them through the engine; a row that names a note it was not given, or a table the app does not have, is dropped. The app gets copies of the picked notes and nothing else: no exchanges, no notes of other spaces, and later notes do not follow. Builds are rows of `ctx_builds`, and a restart follows those still building. **Open in the studio** asks the engine for a one-time link to the app. ## Tests `chloectx/tests/app_cluster.rs` runs the app against two shard servers and a coordinator of this build, with a stub of Anthropic's API: spaces, notes replaced and retired, contexts within a budget, an exchange distilled, incidents matched to an alert rule that fires, a handoff refused without a key, an app suggested and built from a space against a stub of the app engine (refused without `confirm`), the inspector's overview, sessions and records of a space and of a local store, a capsule cut, and a restart. CI runs it in its server smoke test: ```bash cd chloedb-server && cargo build --profile ci cd ../chloectx && CHLOECTX_NEED_SERVER=1 cargo test --profile ci --test app_cluster ``` `CHLOECTX_UI_DIR=chloectx/ui` serves the page from disk, without a rebuild. --- # Personal memory: one memory, many models ChloeCtx keeps a memory of your own beside the memories of your projects: the chats you had with ChatGPT, Claude.ai and Gemini, and a persona card of what they say about you, each line linked to the chats it came from. It is one ChloeDB file on your machine, and any assistant you connect reads it through the same tools: ChatGPT as a connector, Claude.ai as a custom connector, Claude Code and any MCP client. A slice of it can be shared with a key of its own. ``` ChatGPT export ─┐ ┌─ ChatGPT (connector) Claude.ai zip ──┤ chloectx import ├─ Claude.ai (custom connector) Gemini Takeout ─┤ ─────────────┐ ├─ Claude Code, any MCP client browser capture ┤ ▼ │ API proxy ──────┘ ┌──────────────────────┐ MCP │ │ me: chats + persona │──────┤ /mcp, OAuth sign-in │ one ChloeDB file │ │ └──────────────────────┘ └─ shares: /s//mcp signed, read-only, expiring ``` Why not a file of notes about yourself? A plain file has no sources (you cannot tell where "vegetarian" came from or whether it is still true), no search (an assistant reads all of it or none), no history (an edit loses what it replaced), and no scope (you share the whole file or nothing). Here every line of the card says which chat it came from, an assistant asks for what bears on its question and gets those records with their chats, a changed line keeps the old one as history, and a share holds only the sections and topics you picked, signed, logged and revocable. ## On a Mac with Claude Desktop The shortest way in needs no terminal. Each release has `chloectx-claude-desktop-macos.mcpb`, a Claude Desktop extension that holds chloectx and its model. Open it in Claude Desktop (double-click it, or drag it onto Settings, Extensions) and press Install. Then ask Claude: 1. "Import my ChatGPT export." Claude finds the exports in Downloads, Desktop and Documents (or says how to ask for one) and imports the one you pick. 2. "Draft my persona card." Claude reads your own messages a part at a time and proposes lines, each naming the messages it came from. They show as suggested. 3. "Show me the card." Claude goes through the suggested lines with you, and confirms, rewrites or drops each. You do not have to fetch the exports yourself. The extension has a prompt, `bring_my_history`, for Claude with computer use or Claude in Chrome: it opens ChatGPT, Claude.ai and Google Takeout in turn, asking you before each, and requests your export there (`request_export`). It never types a password. When the email with the link comes, Claude or you click it. While a request is waiting, the extension looks in Downloads, Desktop and Documents about every ten seconds and imports the export when it lands; `export_status` says what came in. If you use the hosted beta, give the extension your account's address and capture key in its settings, and what it imports goes there as well. It is the same memory as the commands below use, so `chloectx me serve` can later serve it to ChatGPT as well. [Its README](../../chloectx/claude-desktop/README.md) lists its tools and how it is built and checked. ## Import your chats Ask each service for an export, then give ChloeCtx the file as it came: | from | where to ask | what you get | |---|---|---| | ChatGPT | Settings, Data controls, Export data | a zip with `conversations.json` (and your custom instructions) | | Claude.ai | Settings, Privacy, Export data | a zip with `conversations.json` and `memories.json` | | Gemini | Google Takeout, My Activity, Gemini Apps | `MyActivity.json` (pick JSON) or `MyActivity.html` | ```bash chloectx import ~/Downloads/chatgpt-export.zip --dry-run # what it holds, nothing written chloectx import ~/Downloads/chatgpt-export.zip chloectx import ~/Downloads/claude-export.zip chloectx import ~/Downloads/takeout/ # a folder: every export found in it chloectx me # what the memory holds, by source ``` Each message is kept once, so importing a newer export of the same account adds only what is new. Every record says which assistant and which chat it came from, with the chat's title and address. ChatGPT's custom instructions and Claude.ai's memories come in as chats of their own. Any other source can be written as JSON lines, one message each, and imported with `--from jsonl`: ```json {"source": "chatgpt", "conversation": "c-1", "title": "Kyoto trip", "role": "user", "text": "I'm vegetarian.", "ts": 1763600000} ``` The memory is the `me` folder in ChloeCtx's data folder (`~/.local/share/chloectx/me`). The usual commands read it with `--me`: `chloectx --me search kyoto`, `chloectx --me ask "what do I eat?"`. ## The persona card The card is what an assistant reads first: short lines about you, in sections (About me, Work, Health & diet, Travel, and so on), each with the chats it came from. ```bash chloectx me card build # drafts the card from your own messages with a model (claude -p, --model sonnet) chloectx me card # the card, each line with its source chats chloectx me card edit # in $EDITOR; a line you change or keep becomes yours chloectx me card add "Health & diet" "Vegetarian; avoids mushrooms." chloectx me card confirm # make a drafted line yours chloectx me card drop # take it off (kept as history) ``` `build` reads only what you wrote, never the assistants' answers, and keeps a drafted line only when it names the messages it came from. Building again replaces the drafted lines and keeps every line you wrote or confirmed. A line an assistant adds through `remember` shows as suggested, by that assistant, until you confirm it. The assistant you connect can draft it instead, with no model of ChloeCtx's own: `persona_draft` gives it your messages a part at a time with the same rules, and `persona_suggest` adds the lines it proposes, each with the ids of the messages it came from, as suggested. A line that names no message of yours is left out. `persona_review` confirms, changes or drops lines as you tell it. ## Connect ChatGPT, Claude.ai and other assistants `chloectx me serve` serves the memory over MCP with OAuth sign-in: the assistant registers itself, sends you to a consent page that asks for your passcode, and gets a token for 24 hours (renewed for 90 days). The passcode and a capture key are made and printed once on the first run; `chloectx me connect --new-passcode` makes a new one. ```bash chloectx me serve # http://127.0.0.1:7781 cloudflared tunnel --url http://127.0.0.1:7781 # or: tailscale funnel 7781 chloectx me serve --public-url https:// ``` ChatGPT and Claude.ai reach a connector at a public HTTPS address, so put a tunnel in front of it and pass the tunnel's address as `--public-url`. Then: - **ChatGPT**: in Settings, under Apps & Connectors, turn on developer mode, then create a connector with `https://
    /mcp` and OAuth. - **Claude.ai**: Settings, Connectors, Add custom connector, with `https://
    /mcp`. - **Claude Code**: `claude mcp add --transport http me https://
    /mcp` (or the local address). The consent page asks whether the assistant may also write. It gets these tools: | tool | what | |---|---| | `persona` | the card, with each line's sources | | `search` | records that answer a query: id, title (the assistant and the chat), address, text | | `fetch` | one record in full: the exchange it belongs to, or a card line with its sources | | `ask` | the context for a question, within a budget | | `remember` | (with write) a line for the card, shown as suggested, or a note | | `persona_draft`, `persona_suggest`, `persona_review` | (with write) the card drafted by the assistant, and the person's review of it | `search` and `fetch` answer as ChatGPT's connectors expect. Every call is written to an access log, `chloectx me log`, with the tool, the query and who asked, never what came back. `chloectx me connect` lists the assistants signed in, and `--signout` signs them all out. ## Keep it current **The browser extension** (`chloectx/extension/`, for Chrome and other Chromium browsers) records your chats on chatgpt.com, claude.ai and gemini.google.com as you have them, into the server's `/capture`. It is off for every site until you turn that site on, and it sends only the messages of the chat open in that tab, to the address you give it, with the capture key. [Its README](../../chloectx/extension/README.md) says how to load it. On a site that is on, the extension's **ChloeCtx** button suggests questions that ask the assistant what it knows about you (everything it remembers, how you like answers, your projects and goals, the people and places in your life). Picking one puts it in the message box, and you send it. When the answer is complete, the extension sends it once to `/capture/memory`, which makes each of its lines a suggested line of the card, as pasting it on the account page does. You keep or drop each one. The options page turns the button off. **Your whole history.** The options page's **Bring my whole history** brings every past chat of chatgpt.com or claude.ai, not only those you open: a tab of the site reads them with the requests the site's own page makes, signed in as you are there, and sends each to `/capture`, one at a time, with a panel in the tab that shows how far it is. Each message is kept once, with the same text an export gives, so pressing it again, or importing the site's export later, adds only what is new. When a site has changed those requests, it sends you to the site's export instead. For Gemini it opens Google Takeout. [The extension's README](../../chloectx/extension/README.md#your-whole-history) has the details. **The API proxy** records what apps send to OpenAI's and Anthropic's APIs and what they get back. Point an app's base URL at the server, with the capture key in the path, and keep its own API key: ```bash export OPENAI_BASE_URL=http://127.0.0.1:7781/p//openai/v1 export ANTHROPIC_BASE_URL=http://127.0.0.1:7781/p//anthropic ``` Requests go through unchanged, streamed or not, and the exchange is recorded after it ends. A request with `x-chloectx-record: off` is not recorded; `x-chloectx-conversation` and `x-chloectx-title` name the chat it belongs to (by default, its first message). ## Share a slice A share is a signed, read-only copy of part of the memory, with a key of its own: ```bash chloectx me share create "diet and travel" --sections "Health & diet,Travel" --topic kyoto --expires 30d chloectx me share list chloectx me share log # every call made with its key chloectx me share revoke ``` It holds the card's lines in the sections named (every section by default, none with `--no-card`), the records that answer each `--topic`, and with `--sources` the messages the card's lines were drawn from. Whoever has the key connects to `https://
    /s//mcp` with no sign-in and sees only that slice; the key stops working when it expires or is revoked. The copy is a [context capsule](capsules.md) signed with your key (Ed25519), so `--out DIR` also writes it for `chloectx mount`, which checks the signature and names the signer. ## On a ChloeDB cluster `chloectx app` serves a space of the cluster the same way, for a memory that should live in a cluster rather than on a laptop ([ChloeCtx on a cluster](app.md)): ```bash CHLOECTX_CONNECT_PASSCODE="" CHLOECTX_CONNECT_CAPTURE_KEY="ctxc_" \ chloectx app --server http://127.0.0.1:7700 --port 7760 --connect-url https://me.example.com ``` The space (`--connect-space`, `me` by default) is made if it is not there, and the sign-in, the tools, `/capture` and the proxy are served at the app's address beside its own API, which keeps its token. `--connect-state FILE` keeps the sign-ins across restarts. Shares are served by `chloectx me serve` only. ## The hosted beta `chloectx app --hosted-url` serves many people's memories from one app on a cluster, for people who will not run anything themselves. Each person signs up on its page with an invite, a name and a passcode of their choosing. Each gets a space of their own (`me_`) and an address of their own for Claude.ai or ChatGPT, `https://
    /u//mcp`. The sign-in, the tools and `/capture` at that address are the same as `chloectx me serve`'s, with the account's passcode. The API proxy is not served there, and shares are the share links below. ```bash chloectx app --server http://127.0.0.1:7700 --port 7760 --token "$CHLOECTX_APP_TOKEN" \ --hosted-url https://me.example.com --hosted-state /data/hosted --hosted-invites /data/invites.txt ``` The person's pages are made for a phone first, with a guide of three steps on the first visit. On them they: - paste what ChatGPT, Claude or Gemini answers to "List everything you remember about me", each line of which becomes a suggestion, or upload an export as it came (in parts of 3 MB, up to 2 GB), which is imported in the background; - check each suggested line of the card (keep, fix or remove, with undo), add lines of their own, and see the chat messages each line came from and what it said before it was changed; - read their chats, and search them and the card; - connect Claude, ChatGPT or any other MCP app by the steps shown, with their connector's address, and see the assistants signed in and what each read, and sign them all out; - share lines of the card they pick by a link of 1 to 30 days (`/u//s/`): a page anyone with the link can read, and at `/s//mcp` an MCP server with no sign-in and one read-only tool, `shared_memory`; each link counts how often it was opened and read by an app, and can be stopped or given a new address, which ends the old one. A link shares the lines as they are now: an edited line shows its new text, and a line taken off the card leaves the link; - group lines of the card into profiles ("Family", "Work", "Vacations") and share a whole profile, as described below; - make a capture key for the browser extension, which it serves as a zip to load by hand (`/chloectx-extension.zip`) until it is in the Chrome Web Store; - change their passcode, or make a new recovery code; - download everything as JSON lines; - delete the account, which drops its space. A profile is a group of the card's lines that a person keeps around one side of themselves, with a name, a line on what it is about and an emoji (up to 50 profiles, of up to 500 lines each, in `profiles.json` in the account's folder). The person adds and removes lines, and a line they removed is not suggested again. **Suggest** proposes lines for a profile, and **Suggest profiles for me** proposes three to six profiles for the whole card, which are saved only when the person keeps them. With a model (`ANTHROPIC_API_KEY` or the `claude` CLI, as for the rest of the app), the model picks them from the card's lines, which its prompt treats as data, and only lines of the card are kept. With no model, they come from the sections the profile's name points at ("family" points at People and Identity, "work" at Work, Projects and Skills, "vacations" at Travel), from lines that share its words, and from a search of the memory. A profile follows its lines as they change: an edited line is its new version. A link can share a whole profile (`POST /account/links` with `"profile"`). It shows the profile's lines as they are when it is read, so a line added later shows on it too, and deleting the profile stops its links. A profile can also be shared with other accounts by their names, and those people see it under **Shared with you**, as it is now, until it is unshared (`GET /account/shared?from=&id=`; anyone else gets a 404). Demos come with three profiles and can't share with accounts. The API is `GET` and `POST /account/profiles`. ### Personas: what each assistant may learn A profile is also a **persona**, with an address of its own for an assistant: `https://
    /u//p//mcp` (`src/hosted_guardian.rs`). An assistant connected there sees none of the memory. It has one tool, `ask_about_me(question, purpose)`, and each question gets one of three answers from the guardian (`src/guardian.rs`), with no model: - **ANSWER** with the few lines of the persona that bear on it (at most four for each part of a question of several parts, six in all), and the terms they are shared under: for this task only, not to be stored, never instructions; - **I DON'T KNOW** when no line of the persona bears on it; - **FORBIDDEN** when the question is about a topic the persona doesn't cover. The topics are eleven (food and drink, health, travel, documents, identity, contact, money, work, family, beliefs, interests), read from the words of a question or a line. A persona covers those its owner ticks, and by default those its name and description name. Forbidden is decided by the question's topics alone, before any line is looked at. A line goes out only when every topic it touches is covered, so "Has type 2 diabetes" stays held in a Food persona even when the person put it there, and the profile's page marks it **Not shared**. The page also shows the persona's address, the assistants connected to it with the time each may ask until (and **Stop**), and its latest questions. When an assistant connects, the consent page names the persona and its topics, and the person picks how long it may ask (an hour, a day, a week, 30 days, or until they stop it) and types their passcode. Access and refresh tokens end then. Each connection may ask 30 questions in five minutes and 500 a day. Every question is a receipt (`receipts.jsonl` in the account's folder): who asked, the question, the purpose, the answer and the lines that went out. **Activity** lists them, and **Download, signed** gives them as JSON signed with the service's Ed25519 key (`receipts.key` in `--hosted-state`), so the person can show what was asked and answered. **The vault** keeps what is too sensitive for the card (a passport, a driver's license, a frequent flyer or loyalty number, an insurance card), each field sealed with AES-256-GCM under a key of the account's own, which the service's master key seals (`CHLOECTX_VAULT_KEY`, 32 bytes in base64, or `vault.key` in `--hosted-state`) (`src/vault.rs`). The page shows its numbers masked until the passcode is typed again. A persona names the items it may speak of: `claim` tells that the item is on file with its country and expiry, never its number, and `full` tells every field. **Order histories** import like chats: DoorDash's, Uber Eats' and Amazon's CSV exports (`src/orders.rs`). Each store's orders become a chat, and the lines they suggest for the card (the cuisine ordered most, a favorite place, a dish ordered again and again) wait for the person to check them, with the orders they came from. **Passkeys** sign in to the page as well as the passcode (Settings, then **Add a passkey**; `src/passkey.rs`, ES256 and Ed25519, no attestation). The passcode stays what a consent page asks for. `tests/guardian_eval.rs` asks 100 questions that the rules were worked out on and 60 written afterwards without seeing the code, and fails when any line goes out about a topic the persona doesn't cover; its table is `chloectx/results/guardian-eval.md`. `chloectx/demo/guardian_seed.py` fills an account with a card, an order history, a passport and three personas, and `chloectx/demo/guardian_e2e/e2e.py` signs a real Claude in to one of them the way a claude.ai connector does and gives it tasks. `--hosted-state` keeps the accounts (passcodes as PBKDF2, recovery codes, capture keys and share links' keys as SHA-256), each account's sign-ins, links, profiles and access log, in files of mode 0600. `--hosted-invites` holds one invite a line, each used once; without it anyone may sign up, up to `--hosted-max-accounts` (200 by default). Signing up shows a recovery code once: with it and their name, a person who forgot their passcode picks a new one, which signs out every browser and makes a new code. The page's requests that change anything must come from its own origin, and sign-in and recovery each stop for 15 minutes after 5 wrong tries. `/privacy` says in plain words what is kept and who can read it. `/demo`, and **See a demo** on the first page, open a demo with one click and no invite: an account of the visitor's own (`demo`) filled with a made-up person's memory (`chloectx/src/hosted_demo.json`: a year of chats with ChatGPT, Claude and Gemini, lines of the card with the messages they came from, some to check, three profiles and a share link). Its pages say it is a demo and show its passcode, so an assistant can be connected to it. A demo is deleted after a day; `--hosted-demos` is the most open at once (30; 0 turns demos off), and when that many are open the oldest over an hour old makes room. Demos don't count toward `--hosted-max-accounts`, and take exports up to 20 MB. --- # Apps on a cluster Some programs built on ChloeDB run beside chloedb-server and show in its command center under **Apps**: the [crawler](../chloedb/crawler.md), which turns a site into a table, [Sheets](../chloedb/sheets.md), spreadsheets whose cells are rows of ChloeDB, and [ChloeCtx](../chloectx/app.md), memory spaces that agents write to and ask for context. Each is a program of its own that talks to the server over HTTP and serves a small API and a view; the server lists it and forwards to it. This page starts a server with Sheets and ChloeCtx beside it and uses both through the server, the way the command center does. You need `chloedb-server`, `chloedb-sheets` and `chloectx` on your `PATH`. From release 0.3.2, the installer puts the three there prebuilt, with nothing to compile: ```sh # install curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh -s -- --with sheets,ctx ``` Release 0.3.0 and earlier have no prebuilt Sheets or ChloeCtx. With those, or to build from source, build each in its directory of a checkout of the repository with `cargo build --release --bin` and its name (`chloedb-server`, `chloedb-sheets`, `chloectx`; Rust and a C compiler, several minutes) and add their `target/release` directories to `PATH`. ## How an app attaches The server learns of an app from `--app name=URL`, and sends each request under `/v1/apps//` on to it with a token of its own, `CHLOEDB_APP_TOKEN`, in place of the caller's key. Callers never reach an app directly: the server checks their key first (read scope to read, admin to change anything), and an app refuses requests that do not carry the token. ```mermaid flowchart LR B["browser or program
    (with a ChloeDB key)"] -->|"/v1/apps/sheets/..."| S["chloedb-server
    checks the key"] S -->|"Bearer CHLOEDB_APP_TOKEN"| SH["chloedb-sheets
    :7820"] S -->|"Bearer CHLOEDB_APP_TOKEN"| CX["chloectx app
    :7760"] SH -->|"SQL over HTTP"| S CX -->|"SQL over HTTP"| S ``` The apps keep everything in the server's tables, so a restart, or another copy of the app, finds it all there. ## Start a server and two apps One token for the apps, a server that lists both, and the two apps pointed at the server: ```sh export CHLOEDB_APP_TOKEN=$(python3 -c 'import secrets; print(secrets.token_hex(16))') chloedb-server --db ./apps.chloedb --listen 127.0.0.1:7700 --grpc off --start-apps off \ --app sheets=http://127.0.0.1:7820 --app chloectx=http://127.0.0.1:7760 > server.log 2>&1 & until curl -sf http://127.0.0.1:7700/v1/health > /dev/null; do sleep 0.2; done chloedb-sheets serve --server http://127.0.0.1:7700 --token "$CHLOEDB_APP_TOKEN" > sheets.log 2>&1 & chloectx app --server http://127.0.0.1:7700 --token "$CHLOEDB_APP_TOKEN" --embedder hash:64 > chloectx.log 2>&1 & ``` `--start-apps off` keeps the server from starting the apps installed beside it on its own (it does by default, which is all a first run needs; this page starts them by hand to show how they attach). `--embedder hash:64` makes ChloeCtx's vectors from hashed words, which needs no download; leave it out to use its embedding model (`chloectx fetch-model` fetches it once). Without `--token` the server listens on loopback only and anything on this machine that reaches `127.0.0.1:7700` can change it; give it a token, and its clients keys, before it serves anyone else ([security](../chloedb/server.md#security)). The server lists the apps once they answer, which is what the command center's **Apps** menu shows: ```sh until curl -sf http://127.0.0.1:7700/v1/apps | python3 -c 'import json, sys; sys.exit(0 if all(a.get("up") for a in json.load(sys.stdin)["apps"]) else 1)'; do sleep 0.3; done curl -s http://127.0.0.1:7700/v1/apps | python3 -c ' import json, sys for app in json.load(sys.stdin)["apps"]: print(app["name"], "|", app["title"], "|", app["description"])' ``` ```text output sheets | Sheets | Spreadsheets kept in ChloeDB: formulas, charts and pivots, xlsx, CSV and SQLite in and out, and the cluster's tables as sheets chloectx | ChloeCtx | Memory spaces any agent writes to and asks for context, by search alone; and Seen before: the cluster's firing alerts beside the past incidents they look like ``` Open `http://127.0.0.1:7700` in a browser to use them; the rest of this page drives them from a script. ## Sheets: a workbook with a formula and a query A small client for the apps' APIs through the server: ```python file=apps.py import json import urllib.request SERVER = "http://127.0.0.1:7700" def call(app, path, body=None): """A request to an app, through the server.""" req = urllib.request.Request( f"{SERVER}/v1/apps/{app}{path}", data=None if body is None else json.dumps(body).encode(), headers={"content-type": "application/json"}, method="GET" if body is None else "POST", ) with urllib.request.urlopen(req) as r: return json.load(r) ``` A workbook of sales by region with a total, saved as a table of the server, then a SQL query of that table written into the sheet: ```python from apps import call book = call("sheets", "/v1/books", {"name": "Sales"})["id"] call("sheets", f"/v1/books/{book}/ops", {"ops": [ {"op": "set_many", "sheet": 0, "row": 1, "col": 1, "values": [ ["Region", "Sales"], ["North", "10"], ["South", "32.5"], ["East", "7"], ["Total", "=SUM(B2:B4)"]]}, ]}) call("sheets", f"/v1/books/{book}/to-table", {"sheet": 0, "table": "regions", "key": "region"}) call("sheets", f"/v1/books/{book}/query", { "sheet": 0, "row": 8, "col": 1, "sql": "SELECT region, sales FROM regions WHERE sales > 8 AND sales < 40 ORDER BY sales DESC"}) # Each cell is [row, column, what it shows, ...]. shown = {(c[0], c[1]): c[2] for c in call("sheets", f"/v1/books/{book}/cells?sheet=0&r0=1&r1=10&c0=1&c1=2")["cells"]} for row in range(1, 11): if (row, 1) in shown: print(row, shown[(row, 1)], shown.get((row, 2), ""), sep=" | ") ``` ```text output 1 | Region | Sales 2 | North | 10 3 | South | 32.5 4 | East | 7 5 | Total | 49.5 8 | region | sales 9 | South | 32.5 10 | North | 10 ``` The total is a formula, computed by IronCalc; the rows from row 8 are the query's answer, and **Refresh** in the view (or `POST /v1/books//refresh`) runs it again when the table changes. The workbook's cells are themselves rows of the server, so the server can search every workbook at once. ## ChloeCtx: a memory space and its context A space is a table of the server, `ctx_`, that agents write notes to and ask for context within a budget of tokens. A decision, then a newer one that replaces it: ```python import datetime as dt from apps import call def ts(when): """A note's time, in Unix seconds (left out, it is now).""" return int(dt.datetime.fromisoformat(when).replace(tzinfo=dt.timezone.utc).timestamp()) call("chloectx", "/v1/spaces", {"name": "billing", "title": "Billing"}) old = call("chloectx", "/v1/spaces/billing/notes", {"kind": "decision", "ts": ts("2026-09-01T10:00"), "text": "Refunds above 500 EUR need a team lead's approval."}) call("chloectx", "/v1/spaces/billing/notes", { "kind": "decision", "replaces": old["id"], "ts": ts("2026-10-15T09:00"), "text": "Refunds above 1000 EUR need the finance manager's approval; team leads approve up to 1000 EUR."}) call("chloectx", "/v1/spaces/billing/notes", {"kind": "fact", "ts": ts("2026-10-20T12:00"), "text": "Refunds are paid back to the original card within 5 working days."}) answer = call("chloectx", "/v1/spaces/billing/ask", {"question": "a customer wants a 700 EUR refund, who approves it?", "budget": 500}) print(answer["tokens"] <= 500) print(answer["context"]) ``` ```text output True Notes from earlier sessions, in their current versions, oldest first (date, kind, who said it when it was not the user, note; what it replaced in brackets). Rules that apply come first; a later note can change what an earlier one says: - 2026-10-15 decision: Refunds above 1000 EUR need the finance manager's approval; team leads approve up to 1000 EUR. (changed 2026-10-15; was: Refunds above 500 EUR need a team lead's approval.) - 2026-10-20 fact: Refunds are paid back to the original card within 5 working days. ``` The context holds the current decision and says what it replaced; the old one is left out. No model is called to answer: it is a BM25 and vector search under the space's rules ([how ChloeCtx searches](../chloectx/index.md)). ## The crawler The crawler attaches the same way (`--app crawler=URL`), and `chloedb-crawl serve --local DIR` starts a cluster with it already listed. [Crawl a site into search](crawl-to-search.md) runs it end to end. ## On Kubernetes A cluster the operator runs gets each app from a field of its `StrataCluster`: `spec.crawler`, `spec.sheets`, `spec.chloectx`, `spec.netops` ([network operations](../chloedb/netops.md)) and `spec.apps` (the app engine, a prototype). The operator runs them from the cluster's own image and lists them on its coordinators, with nothing to start by hand ([server on Kubernetes](../chloedb/server.md#on-kubernetes)). --- # chloedb-crawl: a site into a table `chloedb-crawl` takes a URL, reads the site's pages, finds their fields, makes a table from them and fills it, and adds shards to the cluster as the table grows. It is a program of its own, in Rust, that talks to chloedb-server over HTTP only, so it runs on the machine next to the cluster or on another one; the command center shows it as an app. ## Run it On one machine, install both programs, then start the crawler with a cluster of its own (on Kubernetes, one field of the cluster's resource starts it: [below](#on-kubernetes)). The installer puts both in `~/.local/bin` prebuilt, and the crawler finds the server beside it: ```bash curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh -s -- --with crawl ~/.local/bin/chloedb-crawl serve --local ./crawl-cluster ``` Or build both from a checkout (any platform with Rust; the only way before release 0.3.2): ```bash (cd chloedb-server && cargo build --release --bin chloedb-server) cd chloedb-crawl && cargo build --release target/release/chloedb-crawl serve --local ./crawl-cluster --server-bin ../chloedb-server/target/release/chloedb-server ``` Open `http://127.0.0.1:7700` and go to **Apps → Crawler**. Type the site's address under **New crawl** and press **Crawl**, or **Preview** first to see the table it would make; **Options** holds the rest of the settings below. Each crawl gets its own page, where you watch it fill the table and grow the cluster, and pause or stop it. ![The Crawler in the command center: the New crawl form, the crawls, and the cluster's shards](../assets/img/strata-crawler-new-crawl.png) `--local DIR` starts one shard server and a coordinator on `127.0.0.1:7700` with their databases and logs in `DIR`, and adds a shard each time one holds more than `--split-rows` rows of a crawl's table (100,000 by default, at most `--max-shards`, 8). The same `DIR` again serves the same cluster, with the shards it grew. ### From the command line The same crawl runs without the command center too. `crawl` takes the address, prints its progress every two seconds, then what it did (the table it made and why, the columns it added, the shards it added) and the `CREATE TABLE` it ran; add `--stay` to keep the cluster serving after the crawl. `preview` prints what the form's **Preview** shows, without ChloeDB: ```bash target/release/chloedb-crawl crawl https://books.toscrape.com/ --local ./crawl-cluster \ --server-bin ../chloedb-server/target/release/chloedb-server --max-pages 600 target/release/chloedb-crawl preview https://books.toscrape.com/ --pages 10 ``` At the default pace, a page a second for one site ([below](#what-it-does-with-a-page)), 600 pages take about ten minutes. books.toscrape.com is a sandbox made for crawlers, so `--per-host 4 --delay-ms 100` is fine there; keep the defaults for sites you don't run. ### Against a cluster that runs elsewhere The crawler writes to any chloedb-server, one server or a coordinator, with a key that can write (and an admin key to grow a cluster): ```bash chloedb-crawl serve --server http://coordinator:7700 --key "$CHLOEDB_KEY" --token "$CRAWL_TOKEN" \ --listen 0.0.0.0:7800 --grow kube --split-rows 5000000 ``` `--server` was `--strata` before 0.3.2; the old name still works. and the coordinator shows it as an app when told where it is, with the crawler's token: ```bash CHLOEDB_APP_TOKEN="$CRAWL_TOKEN" chloedb-server --shards ... --app crawler=http://crawler-host:7800 ``` `--grow` says how the cluster gets a shard: `kube` asks the Kubernetes operator for one more (`POST /v1/admin/kube`, the coordinator must run under the operator), `servers=URL,URL` adds empty servers started for it, by their gRPC URLs, one at a time, and `off` never grows. Each new shard gets its share of the slots by a rebalance (`POST /v1/admin/rebalance`) while the crawl keeps writing. ### On Kubernetes A cluster the [operator](server.md#on-kubernetes) runs gets a crawler of its own from its `StrataCluster`, with nothing to start by hand: ```bash kubectl -n strata patch strata demo --type merge -p '{"spec": {"crawler": {}}}' ``` The operator runs `chloedb-crawl serve` from the cluster's own image (it carries both programs) as a Deployment of one pod, `-crawler`, behind a Service of that name, and restarts the coordinators so that they list it: **Apps → Crawler** appears in the command center, and a crawl starts from its form. The crawler writes with the cluster's admin token (`tokenSecret`), which its API requires too, so the coordinators send it that token and nothing else reaches it. It grows the cluster through the operator, a shard at a time: | `spec.crawler` | default | | |---|---|---| | `grow` | `true` | add a shard (one more in `spec.shards`) when a crawl's table holds more than `splitRows` rows on one | | `splitRows` | 100,000 | | | `maxShards` | 8 | the most shards it grows the cluster to | | `paused` | `false` | no crawler pod for now (the coordinators still list it, as an app that does not answer) | | `args`, `resources` | | more arguments of `chloedb-crawl serve` (as `["--contact", "ops@example.com"]`, whom site owners reach), and its container's resources (50m CPU and 64 MiB asked, 1 GiB at most) | The upgrader moves the crawler with the servers, since it runs their image. Removing `spec.crawler` deletes its Deployment and Service and restarts the coordinators without it; the tables it filled stay. Its crawls live in its pod, so a pod started again (a new image, a node replaced) starts with none. ## What it does with a page **Fetching.** One queue per host, read breadth first. robots.txt is read before a site's first page and again once a day (RFC 9309: the longest rule wins, `*` and `$` in paths, its own groups, `chloedb-crawl` and `strata-crawl` (its old name), or else `*`); a 4xx answer for it allows everything, and a 5xx, a 429 or no answer keeps the crawler off the site until it reads it again, a minute later (or when its `Retry-After` says, up to 10 minutes). Sitemaps named there, or at `/sitemap.xml`, add their pages as seeds. Only HTML is kept, at most `max_bytes` a page; a URL is normalised once (no fragment, no tracking parameters, the query's parameters sorted) and fetched once, redirects included; a redirect (5 at most) is followed only to a page the crawl would follow as a link (its scope, `include` and `exclude`) and its site's robots.txt allows; robots.txt is read to 500 KB and a sitemap to 50 MB; a page whose text another page already had is counted as a duplicate and not written. Links are queued in turn from each shape of link on the page (`/catalogue/*/index.html`, `/catalogue/category/...`), so the first pages read are a site's items as well as its lists. `rel="nofollow"` links and pages with `noindex` or `nofollow` robots meta tags are honoured. **Reach.** The crawler fetches the public internet only: an address on its machine (`localhost`, `127.0.0.1`), a private network (`10.x`, `192.168.x`, `fd00::/8`), a link-local one (`169.254.169.254`, cloud metadata) or another reserved range is refused, whether a page links to it, redirects to it or its name resolves to it (checked again as each connection is made). An intranet crawl says so when the crawler starts: `--allow-host HOST[:PORT]` (repeatable) for one site, `--allow-private` (or `CHLOEDB_CRAWL_ALLOW_PRIVATE=1`) for everything. A proxy named by `HTTPS_PROXY` is reachable whatever its address, and resolves the names it is asked for itself. **Politeness.** A site gets at most `per_host` requests at once (1), and between the starts of two the longest of `delay_ms` (1 s), its robots.txt's `Crawl-delay` (up to 10 minutes; every site the crawl reaches, not only the seeds') and twice the time it has been taking to answer (up to 30 s), so a site that slows down is asked less often. A site that pushes back waits before its next request: a 429, 502, 503 or 504 as long as its `Retry-After` says, else 5 s, doubled at each refusal in a row up to 5 minutes, and the page is asked again later (4 times at most); a 403 or no answer waits the same, and the page is not asked again. After 10 refusals in a row, or when a site asks to wait more than 10 minutes, the crawl gives up on that site and drops its queued pages; the crawl's events say when a site was made to wait and when it was given up. The user agent names the crawler and links to [the page for site owners](crawler-bot.md), with the crawl's `contact`; a crawl's own `user_agent` keeps the crawler's name after it. Answers are asked compressed (gzip, Brotli). **Fields.** Each page gives: | from | as | |---|---| | the fetch | `url` (the key), `host`, `depth`, `status`, `fetched`, `bytes`, `fetch_ms` | | the page | `title`, `body` (the main text: `
    `, `
    ` or `[role=main]`, else the body without navigation, headers and footers), `words`, `links`, and when the page has them `description`, `headings`, `lang`, `canonical`, `published`, `modified`, `author`, `image`, `site_name`, `kind`, `keywords` | | JSON-LD | `ld.*`: the page's main entity (`Product`, `Article`, `Recipe` ...), `@type` as `type` | | Open Graph and other meta tags | `og.*` (`og:price:amount` is `og.price_amount`) | | microdata | `md.*` | | tables and lists of terms | `specs.*`: rows of a key and a value (`
    `, `
    `/`
    `) | | the site's template | `page.*`: learned from the first pages (below) | | your selectors | `rule.*`: `name=selector`, `name=selector@attr`, `name[]=selector` for every match | **The template.** On the first pages (`sample`, 30), the crawler looks for an element of one tag and classes (`p.price_color`) that most pages have at most three times, whose text changes from page to page and is not the title. Those are the site's own fields, named from their classes (`price_color`, `stock_level`), and read from every page after. **The table.** It is made from the first pages: the fetch's and the page's columns above, a column for each other field that at least `promote_at` (0.3) of the pages have, typed by its values (a type fits when 90% of the values read as it: `BOOL`, `INT`, `FLOAT` with currencies and thousands separators read, `TIMESTAMP`, `KEYWORD` for short values, else `TEXT`, and lists), and `data JSON` holding every field of the page, so a field that is not a column is still a [path](query-language.md#json-fields-keys-no-schema-names) to query (`WHERE data.specs.isbn = '...'`). An existing table is used as it is, with the columns it lacks added. With `embed`, a vector field `emb` is embedded from the title and body by that model. **As it grows.** Every 100 pages the crawler looks again at the fields the pages since the start have had: one that has reached `promote_at` (over 50 pages at least) gets a column (`ALTER TABLE ... ADD COLUMN IF NOT EXISTS`), and the rows written before it get its value from their `data` (a `set` by key for each). Rows are written in batches of `batch` (200) through `POST /v1/write`, each under an idempotency key, so a batch sent again after a lost answer writes once; a 429 waits as the server asks, a partial write is sent again with the key it returns, and rows a server refuses are found by halves and listed as problems. ## The command center's view **Apps → Crawler** lists the crawls and the cluster's shards, each a bar of its rows against the split threshold, with the shards it added and the rebalances. **New crawl** takes a URL and the options above. **Preview** reads the URL and up to nine pages it links to and shows the table they would make: its columns with their types and where each comes from, the `CREATE TABLE`, the pages read, the template learned, every field found with the share of pages that had it, and three rows as they would be written. **Crawl** starts it. A crawl's page shows pages fetched and rows written a second, with the moments the table was made and shards were added; the shards filling and splitting; the table's columns, with when each was added, and the fields found so far with the column each went to; a search of the table through ChloeDB (`MATCH` and `bm25` over the body, or the latest rows); what it did, with the SQL it ran; the last pages read; and problems (robots.txt, timeouts, answers that were not HTML, refused rows). Pause, Resume and Stop act at once; a stopped crawl writes the pages it has read. The view is a module the crawler serves (`chloedb-crawl/ui/view.js`, compiled in; `CHLOEDB_CRAWL_UI_DIR=chloedb-crawl/ui` reads it from disk), loaded and run by the command center as the [apps](server.md#apps) section describes. ## Options The same names are the JSON fields of `POST /v1/crawls` and `POST /v1/preview`, and the command line's options (`--max-pages`, `--no-robots`, `--rule`, ...). | option | default | | |---|---|---| | `seeds` | | the URLs to start from | | `table` | from the first seed's host (`books_toscrape_com`) | the table to fill | | `scope` | `host` | which links to follow: `host` (the seeds' hosts), `domain` (their sites, subdomains included), `prefix` (under the seeds' paths), `any` | | `include`, `exclude` | | regular expressions on URLs: follow only links that match one of `include`, never those that match `exclude` | | `keep` | | regular expressions: write rows only for pages that match (the others are read for their links) | | `max_pages` | 1,000 | URLs to fetch at most | | `max_depth` | 5 | links from a seed; a list's next page (a link with `rel="next"`, or named "Next", "Next page", "Older posts" or an arrow) is as deep as the list, so a long list is read to its end. A crawl that ends says why: its page limit, its depth (with the links it left out, also in the status's `beyond_depth`), or no links left | | `concurrency`, `per_host` | 16, 1 | requests at once, and to one host | | `delay_ms` | 1,000 | between the starts of two requests to a host (longer when its robots.txt asks, or when it is slow to answer) | | `robots`, `sitemaps` | on | obey robots.txt; read sitemaps | | `sample` | 30 | pages the table is made from | | `promote_at` | 0.3 | the share of pages a field needs to be a column | | `rules` | | fields from CSS selectors, as above | | `learn` | on | learn the site's template | | `embed` | | a model to embed the title and body with, into `emb` | | `user_agent` | `chloedb-crawl/0.3.11 (+https://chloetech-ai.github.io/chloedb/chloedb/crawler-bot.html)` | a crawl's own is sent with that after it, unless it names `chloedb-crawl` (or `strata-crawl`, its old name) | | `contact` | `--contact` of `chloedb-crawl serve` (or `CHLOEDB_CRAWL_CONTACT`) | whom a site's owner reaches about the crawl, an email address or a URL, sent in the user agent: `chloedb-crawl/ (+https://...; ops@example.com)` | | `timeout_ms`, `max_bytes`, `batch` | 20,000, 5 MB, 200 | | ## API `chloedb-crawl serve` answers on `--listen` (`127.0.0.1:7800`). It takes no request that carries an `Origin` header, so no web page can drive it from a browser, and with `--token` (or `CHLOEDB_CRAWL_TOKEN`) none without `Authorization: Bearer `; with `--local` and no token it makes one and gives it to the coordinator it starts. | request | | |---|---| | `GET /v1/info` | the crawler's version, the ChloeDB it writes to and what it is, the growth policy and the default options | | `POST /v1/crawls` | starts a crawl from the options: `{id, table}`; two crawls may not fill one table at once | | `GET /v1/crawls` | the crawls, newest first | | `GET /v1/crawls/:id` | one crawl: its phase, counts, rates and a second-by-second series, the table's plan and SQL, the fields found, the last pages and problems, what it did, and the cluster's growth | | `POST /v1/crawls/:id/pause`, `/resume`, `/stop` | | | `DELETE /v1/crawls/:id` | forgets a crawl that has ended (its table stays) | | `POST /v1/preview` | the options and `pages` (6, at most 20): the preview, nothing written | | `GET /v1/grow` | the shards' rows of the crawls' tables, slots moving, and the shards added | | `GET /app.json`, `GET /ui/view.js` | the manifest and view the command center reads | Through chloedb-server the crawler checks its callers (`"checks_callers": true` in its manifest): a key that may write starts crawls, which are its own, and pauses, resumes, stops and forgets only those (an admin of every table steers any); a key limited to tables lists only its own crawls. A crawl writes its table as the key that started it: the crawler sends its token narrowed to that key's grants (`x-chloedb-as-tables`, [server](server.md#apps)), so a key limited to `crawl_*` crawls into `crawl_*` tables only, and a table it may not write is the server's 403. Called directly with its token, it answers as before. ## Limits - Pages are read as their HTML arrives: a page built by JavaScript in the browser shows only what its HTML holds (JSON-LD and meta tags often carry its fields anyway). - A crawl lives in the process: its queue and seen set are in memory, and a restarted crawler starts again (rows are written by URL, so a page written twice is one row). - A site's scope (`domain`) takes the last two labels of a host, or three when the second last is short (`example.co.uk`), without the public suffix list. - The growth policy counts the rows of the crawls' tables on each shard, not their bytes, and adds a shard at a time; it does not remove shards. - A list column added during the crawl is filled from the rows written after it only (a `set` by key takes one value). --- # chloedb-sheets: spreadsheets in ChloeDB `chloedb-sheets` is a spreadsheet app that keeps its workbooks in ChloeDB. A workbook has the things you expect of one: sheets, formulas (IronCalc's engine, over 300 of Excel's functions, array formulas and spills), number formats, fonts, colors, borders, merged cells, frozen panes, conditional formats, named ranges, sorting, filters, find and replace, charts and pivot tables. It also has what a spreadsheet kept in a database can have: - **Every cell is a row of a ChloeDB table**, so every workbook can be searched at once (BM25 over the cells' text), and a workbook opened in two windows shows what the other changed. - **The cluster's tables open as sheets**, live: rows paged in as you scroll (past the server's result window, by the sort's key: the key's column or a number, time or boolean column, so a table of any size is read to its end), sorted by any column, filtered with a SQL `WHERE` and searched with `MATCH`, and edited in place (each change is a write to the table). - **Cells can be filled by SQL**: a query of the cluster's tables writes its answer into a sheet from a cell on, is kept with the workbook, and runs again when you refresh it, so the cells (and the formulas and charts over them) follow the table. - **A sheet becomes a table**: its first row names the columns, each column gets the type its cells hold, and its rows are written to ChloeDB by a key you choose. - **Files come in and go out**: Excel workbooks (.xlsx, formulas and formats kept), CSV and TSV, and SQLite databases, whose tables become sheets of a workbook or tables of the cluster; a workbook goes out as .xlsx, a sheet as CSV. Like [the crawler](crawler.md), it is a program of its own, in Rust, that talks to chloedb-server over HTTP only, and the command center shows it as an app. ## Run it Install both programs, then start chloedb-sheets with a cluster of its own. The installer puts both in `~/.local/bin` prebuilt, and chloedb-sheets finds the server beside it: ```bash curl -fsSL https://chloetech-ai.github.io/chloedb/install.sh | sh -s -- --with sheets ~/.local/bin/chloedb-sheets serve --local ./sheets-cluster ``` Or build both from a checkout (any platform with Rust; the only way before release 0.3.2): ```bash (cd chloedb-server && cargo build --release --bin chloedb-server) cd chloedb-sheets && cargo build --release target/release/chloedb-sheets serve --local ./sheets-cluster --server-bin ../chloedb-server/target/release/chloedb-server ``` Open `http://127.0.0.1:7700` and go to **Apps → Sheets**. ![Sheets in the command center: search over every workbook, the workbooks, an import area, and the cluster's tables](../assets/img/strata-sheets-home.png) `--local DIR` starts a chloedb-server on `127.0.0.1:7700` (`--local-listen`) with its database in `DIR`, lists chloedb-sheets on it as the app `sheets`, and stops it when chloedb-sheets stops; the same `DIR` again serves the same workbooks. Against a cluster that runs elsewhere, give chloedb-sheets the server (a coordinator or one server) and a key, and give the server the app. Its first start creates the two tables it keeps workbooks in, which takes an admin key; after that a key that can write is enough: ```bash chloedb-sheets serve --server http://coordinator:7700 --key "$CHLOEDB_KEY" --token "$SHEETS_TOKEN" --listen 0.0.0.0:7820 chloedb-server ... --app sheets=http://sheets-host:7820 # with CHLOEDB_APP_TOKEN=$SHEETS_TOKEN ``` `--server` was `--strata` before 0.3.2; the old name still works. `--token` (or `CHLOEDB_SHEETS_TOKEN`) is the bearer token its API requires; the server sends its `CHLOEDB_APP_TOKEN` ([apps](server.md#apps)). Requests that carry an `Origin` header are refused, so a page on another site cannot reach the app even from inside the network. It checks its callers itself (`"checks_callers": true` in its manifest), so chloedb-server sends it keys limited to tables, and keys that may only write, with who they are (`x-chloedb-principal`, `x-chloedb-scope`, `x-chloedb-tables`). A key that may write makes workbooks, which are its own: it changes them, shares them (**Share**, `POST /v1/books/:id/share {shared}`) and deletes them, and another key opens one only once it is shared, or when it is an admin of every table. A workbook made before owners existed is everyone's. What a workbook reads from the cluster (its query blocks, the tables opened as sheets, a sheet copied to a table) runs as the caller's key: chloedb-sheets sends its own token narrowed to the caller's grants (`x-chloedb-as-tables`, [server](server.md#apps)), so a query reads only the tables the signed-in key may read, and a refusal is the server's 403. The analyst preset's keys make their own workbooks this way. Called directly with its token (not through chloedb-server), it answers as before, as the token's. ### On Kubernetes A cluster the [operator](server.md#on-kubernetes) runs gets spreadsheets of its own from its `StrataCluster`, with nothing to start by hand: ```bash kubectl -n strata patch strata demo --type merge -p '{"spec": {"sheets": {}}}' ``` The operator runs `chloedb-sheets serve` from the cluster's own image (it carries it, as it carries the crawler) as a Deployment of one pod, `-sheets`, behind a Service of that name, and restarts the coordinators so that they list it: **Apps → Sheets** appears in the command center. It reads and writes with the cluster's admin token (`tokenSecret`), which its API requires too, so the coordinators send it that token and nothing else reaches it. Its workbooks are rows of the cluster's tables, so a pod started again (a new image, a node replaced) has them all; the upgrader moves it with the servers, since it runs their image. | `spec.sheets` | default | | |---|---|---| | `paused` | `false` | no pod for now (the coordinators still list it, as an app that does not answer; the workbooks stay) | | `args`, `resources` | | more arguments of `chloedb-sheets serve`, and its container's resources (50m CPU and 96 MiB asked, 1 GiB at most) | Removing `spec.sheets` deletes its Deployment and Service and restarts the coordinators without it; the workbooks stay in `sheets_books` and `sheets_cells`. ### From the command line `import` and `export` move files without the UI: ```bash target/release/chloedb-sheets import budget.xlsx --server http://127.0.0.1:7700 target/release/chloedb-sheets import shop.sqlite --tables orders,customers --name Shop --server http://127.0.0.1:7700 target/release/chloedb-sheets export -o budget.xlsx --server http://127.0.0.1:7700 ``` ## The app **Sheets** lists the workbooks, newest first (**Mine**, **Shared** or **All**, with each one's owner), the cluster's tables, a search over every workbook, and an import area that takes a file dropped on it. A SQLite file asks which of its tables to bring and where: as sheets of a new workbook, or as tables of the cluster (through chloedb-server's own SQLite import, with the signed-in key, keeping the columns' types, keys and indexes). A file is not trusted: a SQLite file's views come in only when named (a view runs its query as it is read, and that query may not end), and reading one stops after 60 s for the list of tables and 180 s for the import; an xlsx file may expand to at most 512 MB and hold at most 2 million cells. ![A workbook: a color scale, data bars, number formats, a frozen header row and a stacked column chart over the sheet](../assets/img/strata-sheets-workbook.png) **A workbook** is a grid drawn on a canvas, so a sheet of a million rows scrolls as one of ten; its cells are read a tile at a time as they come into view. Above it: - the **toolbar**: undo and redo, the format painter, number formats (and decimals, currency, percent), font size, bold, italic, underline and strikethrough, text and fill colors, borders, merging, alignment and wrapping, frozen rows and columns, sorting and filters, Σ (sum, average, count, max, min, median of the cells above or of each column), charts, pivot tables, conditional formats, named ranges, SQL queries, and clearing formats; - the **formula bar**, with the name box (a cell, a range or a name to go to) and, as a formula is typed, the functions that match and the arguments of the one the caret is in; clicking or dragging over cells while typing a formula puts their reference in, and the ranges a formula refers to are outlined in color. The grid does what a spreadsheet's does: arrows, Tab, Enter (back to the column a run of Tabs started from) and Ctrl+arrows to move, Shift to extend, typing to replace a cell and F2 or a double click to edit it, Ctrl+Enter into every selected cell, the fill handle (drag it, or double click it to fill down the data), column and row resizing (double click a column's edge to fit its contents), cut, copy and paste (within the app formulas move and formats come along; from other programs, tab-separated text), right-click menus to insert, delete, hide and show rows and columns, and the usual shortcuts (**More → Keyboard shortcuts** lists them). The sheet tabs below rename, recolor, duplicate, hide, move (drag them) and delete sheets, and the status bar shows the sum, average, count, minimum and maximum of the selection. A **filter** puts buttons on the header row of a range: each lists the column's values with their counts, to choose the ones shown, and sorts. It is kept with the workbook. A **chart** (column, bar, line, area, pie or scatter, stacked or not) is drawn over the sheet from a range whose first row names the series and first column holds the categories; drag it by its title, resize it from its corner, double click it to edit it. **Summarize** makes a pivot table of a range on a new sheet: its rows grouped by the values of the columns chosen, with sums, counts, averages, minimums, maximums or distinct counts of others, and a total row. **Conditional formatting** colors cells by their value (greater than, between, text that contains, duplicates, the top 10, above average, a formula), and draws color scales, data bars and icons. **Queries** lists the workbook's SQL blocks, to go to, edit, run again or drop. ![The cluster's products table opened as a sheet: typed columns, the key in bold, a WHERE box and a text search](../assets/img/strata-sheets-table.png) **A table of the cluster** opens at `#/app/sheets/t/
    UPCa897...
    ` as a sheet whose columns are the table's, named and typed in the header. Rows are read a page of 100 at a time as they come into view, ordered by the key (or by the column whose header you click, then by the key), and read again every five seconds. Typing into a cell sets that field of that row (`{"op": "set"}` by key); pasting sets many; Delete clears them. **Row** adds one, **Column** runs `ALTER TABLE ... ADD COLUMN`, **Delete rows** deletes the rows selected (after asking), and **Open as a workbook** copies the rows shown (the filter and order included) into a new workbook, for formulas, charts and pivots over them. A row's key does not change in place. **Numbers** are shown as Excel's General format shows them, to 15 significant digits and no more (`226159459.83`, `4.1271186440678`, `1.5E+20`), in the grid, a CSV and an xlsx file alike; a number format of the cell's own still applies. **Charts do not go into an .xlsx file**: the file keeps the cells, formulas and formats, and the download says how many charts it left out (the `x-app-left-out` header of `GET /v1/books/:id/xlsx`). ## How workbooks are kept Two tables hold every workbook. chloedb-sheets creates them at its first start: | table | one row | what it holds | |---|---|---| | `sheets_books` | a workbook | its name, where it came from, its sheets' names, its counts, and its frame: the workbook without its cells (styles, column widths, row heights, merges, names, conditional formats, frozen panes), IronCalc's model encoded with bitcode, as base64; and its charts, queries and filters as JSON | | `sheets_cells` | a cell | `book:sheet:row:col` as its key, the sheet's name, its reference (`B7`), what it shows (`text`, searched with BM25), its number, its input (a formula, or what was typed), its style's index and kind | `sheets_cells` is sharded by the workbook (`shard_by`), so a workbook's cells sit on one shard and are read in one pass, and clustered by it, so they are read in order. After each change chloedb-sheets compares every cell it touched with what it wrote last, and writes only the cells that changed, in one transaction with the workbook's row; the 350,000 cells of a 50,000-row SQLite import took 8.7 s to write, a change to one cell of it 0.1 to 0.15 s, on the container this was built in. A workbook is held in memory while it is used and let go after 30 minutes unused, or sooner, the least recently used first, when the open workbooks hold more than 1.5 million cells together (`CHLOEDB_SHEETS_OPEN_CELLS`); a write ChloeDB refuses is retried every 30 seconds, and the workbook says it is not saved yet until one succeeds. Changing an open workbook from two places is safe: chloedb-sheets applies changes to a workbook one at a time, and each viewer reads what changed since the version it holds (`GET /v1/books//changes?since=`) every three seconds, or redraws the sheet when rows or columns moved. ## Its API Each route is under the app's address (through chloedb-server: `/v1/apps/sheets/...`), and takes the token. | route | what | |---|---| | `GET /v1/books?whose=mine\|shared\|all`, `POST /v1/books {name}` | the workbooks the caller may open (with `owner` and `shared`, and the caller as `me`); a new one, the caller's | | `POST /v1/import?name=&format=&tables=&header=` | a file (the body) as a new workbook: xlsx, csv, tsv or sqlite (by default what the bytes are); a SQLite file's `tables`, a CSV file's `header` | | `POST /v1/sqlite/tables` | a SQLite file's tables, their columns and row counts, and its views (`"kind": "view"`, not counted) | | `POST /v1/from-table {table \| sql, name, limit}` | a table of the cluster, or a SELECT's answer, as a new workbook | | `GET /v1/search?q=&limit=` | the cells and workbooks that hold the words | | `GET`, `DELETE /v1/books/` | a workbook's summary (sheets, names, charts, queries, filters, whether it can undo); deleting it | | `POST /v1/books//ops {ops}` | changes, in order, each one step to undo: `set`, `set_many`, `array_formula`, `clear`, `style`, `border`, `insert_rows`, `delete_rows`, `insert_cols`, `delete_cols`, `move_rows`, `move_cols`, `col_width`, `row_height`, `hide_rows`, `hide_cols`, `freeze`, `grid_lines`, `merge`, `unmerge`, `add_sheet`, `delete_sheet`, `rename_sheet`, `move_sheet`, `duplicate_sheet`, `sheet_color`, `hide_sheet`, `autofill`, `paste`, `paste_text`, `sort`, `filter`, `replace`, `define_name`, `update_name`, `delete_name`, `add_format`, `delete_format`, `undo`, `redo`, `rename_book`, `chart`, `delete_chart`, `summarize`; the answer has the cells that changed | | `GET /v1/books//cells?sheet=&r0=&r1=&c0=&c1=`, `/layout?sheet=`, `/values?sheet=&range=` | an area's cells (what each shows, its type, style and input); a sheet's layout; a range's values as numbers | | `GET /v1/books//changes?since=` | what changed since a version | | `POST /v1/books//copy {sheet, area}` | an area as a clipboard for `paste`, and as tab-separated text | | `GET /v1/books//find?q=&sheet=&case=&whole=&formulas=` | the cells that hold a text | | `GET /v1/books//export?format=xlsx\|csv&sheet=` | the workbook as a file | | `POST /v1/books//query {sheet, row, col, sql, limit, id}`, `POST /v1/books//refresh`, `DELETE /v1/books//queries/` | a SQL block (new, or `id`'s again); every block again; one dropped (its cells stay) | | `POST /v1/books//to-table {sheet, table, key}` | a sheet as a table of the cluster | An import holds at most 2,000,000 cells, and a query block or a table copied into a workbook at most 100,000 rows. --- # chloedb-netops: network operations on ChloeDB > **A demo.** chloedb-netops shows what ChloeDB can do; it is not part of ChloeDB's releases or their promises. It is tested on a train of its own (the `Demos` workflow, `.github/workflows/demos.yml`), outside CI's required check, so a fault in it does not hold a ChloeDB release, and the command center marks it as a demo ([compatibility](../compatibility.md#demos)). `chloedb-netops` is a network operations center kept in ChloeDB: the inventory, the topology, a point a minute of telemetry, device logs, alerts, incidents, changes, configurations, runbooks, and agents that work an incident and say what they looked at. It comes with a simulated carrier network, *Meridian* (10 sites, 64 devices, 120 links, 12 services), and a simulator that writes each minute of it and breaks it in six ways, so the whole app can be used, and its agents checked, without a network of your own. It is there to show what one database does for an operations team when search, SQL, graphs and time all live in it: - **An incident is a query, not a pile of alerts.** Alert rules are SQL over the telemetry tables. The alerts they raise are grouped into one incident by walking the topology (`REACHABLE` over the links table), so a fibre cut is one incident with eight alerts, not eight pages. - **The root-cause agent shows its work.** It ranks the alerting devices over the graph (personalised PageRank), reads the logs, changes, optics and flows around them, tests six causes, and names one with a confidence and the evidence for it. Every step keeps the SQL it ran, the rows it read and the time it took. What it packed into its context, and what it left out, is kept as a receipt (`PACK … TOKENS WITH RECEIPT`). - **Nothing runs without an approval.** The agent proposes actions (reroute a span, roll a change back, restart a process, open a ticket with the circuit's provider) with their risk and the exact commands. A person approves or rejects each one; autopilot, off by default, lets the low-risk ones through. - **The topology is found from the logs.** LLDP neighbour and routing-adjacency lines in syslog imply links; the app builds them and compares them with the inventory: links the logs confirm, links nobody documented, and documented links nothing has spoken on. - **Logs are searched three ways in one place**: by words (BM25), by any substring (`LIKE` answered from an FM-index, for an interface name or half an address), and runbooks and past incidents by meaning (a static embedding model on the server, no API call). - **Most of a shift is not an incident.** The home page is the shift: a handover written from the tables, and one list of what waits (approvals, unowned alerts, changes due, carrier notices that collide). A box at the top takes whatever a ticket says (an address, a circuit id, a customer, an interface) and answers what it is and how it is doing. - **Every incident has a room that its people shape.** The room opens with a board of panels chosen for the suspected cause. Anyone on the call adds a panel by asking for it in a sentence, removes what is noise, and everyone sees the same board. A panel is one read-only query kept as a row. - **Engineers and leadership read the same tables.** A switch at the top turns the shift's pages into objectives, incident cost, risk, carriers and a written weekly report, and each number opens the rows behind it. - **The past is a table.** Every version of each device's configuration is a row, so the change behind an incident is a diff, and "who put this line here" is a query. Which runbook closed which incident is kept as a grade the ranking can learn from. Like [the crawler](crawler.md) and [the spreadsheets](sheets.md), it is a program of its own, in Rust, that talks to chloedb-server over HTTP only, and the command center shows it as an app. ![My shift: the handover written from the tables, what waits most urgent first, the changes and carrier windows coming up, and notes for the next shift](../assets/img/netops-shift.png) ## Run it Build both programs, then start chloedb-netops with a server of its own (releases after 0.3.2 carry it prebuilt too: the installer's `--with netops` puts it beside the server, which it then finds without `--server-bin`): ```bash (cd chloedb-server && cargo build --release --bin chloedb-server) cd chloedb-netops && cargo build --release target/release/chloedb-netops serve --local ./netops-data --server-bin ../chloedb-server/target/release/chloedb-server ``` Open `http://127.0.0.1:7700` and go to **Apps → Network operations**. The first start makes the tables and writes six hours of history (`--history-hours`), which takes some seconds; the page shows its progress. From then on the simulator writes a minute of telemetry every minute, evaluates the alert rules, and injects a fault every 45 minutes (`--fault-every`; `0`: only when you press **Inject a fault**). `--local DIR` starts a chloedb-server on `127.0.0.1:7700` (`--local-listen`) with its database in `DIR`, lists chloedb-netops on it as the app `netops`, and stops it when chloedb-netops stops; the same `DIR` again is the same network, with its incidents. Against a server or a cluster that runs elsewhere, give chloedb-netops the server (a coordinator or one server) and a key, and give the server the app: ```bash chloedb-netops serve --strata http://coordinator:7700 --key "$CHLOEDB_KEY" --token "$NETOPS_TOKEN" --listen 0.0.0.0:7840 chloedb-server ... --app netops=http://netops-host:7840 # with CHLOEDB_APP_TOKEN=$NETOPS_TOKEN ``` The key needs admin scope on the tables `netops_*` (a key [limited to tables](server.md#security), `netops_*=admin`, is enough: the app touches no other table). `--token` (or `CHLOEDB_NETOPS_TOKEN`) is the bearer token its API requires; the server sends its `CHLOEDB_APP_TOKEN` ([apps](server.md#apps)). Requests that carry an `Origin` header are refused, so a page on another site cannot reach the app even from inside the network. On a coordinator over shards the graph steps (`REACHABLE`, `ppr`, `PATH`) are walked by the app over the same links table, as before a coordinator walked graphs ([graphs on a cluster](graphs.md#on-a-cluster)); every page says which of the two it used. The app knows a coordinator from its `/v1/health`, or from the first graph statement an older coordinator refuses, and then sends it none. `--no-simulate` turns the simulator off: the app reads its network from the inventory tables and writes no telemetry of its own ([your own network](#your-own-network)). `--topology` (or `CHLOEDB_NETOPS_TOPOLOGY`) says where the network comes from. The default, `both`, serves two from one app: the network as its inventory lists it, and beside it the same simulated network read back from what it reports (its BGP-LS, LLDP, SNMP, BMP and ONT tables: [a network that reports itself](#a-network-that-reports-itself)). The switch at the top of the page, **Inventory | Discovered**, moves between them, and the page remembers the choice. The second is built the first time it is opened, which takes a minute or two (the page says how far), in tables of its own (`netops_disc_*`, under `/d/` in the app's API); from then on the app simulates both, each with its own faults. `inventory` serves only the first and `discovered` only the second, each in the `netops_*` tables. With `--no-simulate`, `both` is `inventory`. ### On Kubernetes A cluster the [operator](server.md#on-kubernetes) runs gets the app from its `StrataCluster`, with nothing to start by hand: ```bash kubectl -n strata patch strata demo --type merge -p '{"spec": {"netops": {}}}' ``` The operator runs `chloedb-netops serve` from the cluster's own image as a Deployment of one pod, `-netops`, behind a Service of that name (port 7840), and restarts the coordinators so that they list it: **Apps → Network operations** appears in the command center. It holds a key limited to `netops_*` and a token of its own (the Secret `-netops-credentials`), or the cluster's admin token until the coordinators make such keys. Its network is rows of the cluster's tables, so a pod started again goes on from them. | `spec.netops` | default | | |---|---|---| | `paused` | `false` | no pod for now (the coordinators still list it, as an app that does not answer; the tables stay and nothing is written to them) | | `tables` | `netops_*=admin` | the tables its key may touch | | `args`, `resources` | | more arguments of `chloedb-netops serve` (`--fault-every 0`, `--history-hours 2`, `--no-simulate`), and its container's resources (50m CPU and 96 MiB asked, 1 GiB at most) | Removing `spec.netops` deletes its Deployment and Service and restarts the coordinators without it; the tables `netops_*` stay. ## The pages | page | what it is for | |---|---| | **My shift** | the home page: a handover of the last twelve hours written from the tables, what waits for you most urgent first (approvals, alerts nobody owns, changes due, carrier notices that collide, open tickets), the changes and carrier windows of the next day and a half, and notes left by the shift before | | **Diagnose** | [where it is broken](#where-is-it-broken): the stack by place, the lowest broken layer named as where to start, one broken thing investigated five ways, and a trace between two points hop by hop | | **Network** | the open incident, the network's map with each link's load, traffic and loss, services against their objectives, time to detect and to resolve by cause | | **Incidents** | every incident; an incident's room has the likely cause with its confidence, what happened, why it is probably the cause (each claim with the rows behind it) and what it is not, the proposed actions, [its board](#an-incidents-board), a map of where it is that replays it minute by minute, the agent's steps with their SQL, the receipt of what it was shown, the timeline, the blast radius and similar incidents | | **Alerts** | what fires and who owns it (acknowledge, hand back, silence), the silences in force, and the rules: each is a SQL query you can read, test against the last hours and save | | **Changes** | the change calendar by day, the collisions (two changes whose devices overlap in a window, `&&` over `INT[]`), the change-risk agent's score, and carrying a change out: start it (its devices are silenced for the window), verify it against the network as it was before, complete it or roll it back | | **Customers** | every customer with where they attach and whether anything is wrong on their path; a customer's page answers "is it the network?" with what was checked along the path from their port to the backbone, and a reply ready to send | | **Carriers** | carriers' maintenance notices, each matched to the circuit it names and checked for what it collides with: the other plane's maintenance in the same window, a change on the router that carries the other plane, and whether the surviving plane has the capacity; a notice can be pasted as it arrived | | **Discovery** | on the discovered network only (the switch's **Discovered**, or `--topology discovered`): the seven feeds the network was read from with their rows, the rules that turn them into an inventory, and every site, device, link, BGP session and estate hub with the feeds that found it and how ([below](#a-network-that-reports-itself)) | | **Topology** | the network as the inventory has it, as the logs say it is, and the difference; the path between two devices; the lines of syslog a link was read from | | **Services** | each service's success rate and latency against its objective, the devices it rides on and the customers on it | | **Explore** | logs by words or by substring, flows (who talks to whom), and one search box over runbooks, incidents, configurations and tickets | | **Devices** | the inventory with each device's metrics, what happened on it in the last day, logs, configuration history and blame | | **Agents** | the six agents, their runs and what each cost in queries, rows and tokens; capacity, advisories and configuration drift; autopilot | | **Map** | the whole network on one plane, from regions down to one customer's router: zoom in and detail appears, what is broken colours the place that holds it at every zoom, a click on an object says what is wrong and what it has to do with everything around it, and a search box takes a sentence ([below](#the-map)) | | **Dashboards** | the backbone's busiest links (utilisation, loss, received optical power), the busiest devices and the slowest services over three hours, what is not ok by metro and by kind, faults a day by cause over two weeks, and incidents by cause; the estate's panels follow the place in view on the map | | **Data** | the 48 tables (each network has its own) with their definitions and row counts, where each one's rows come from and whether they are arriving, and the simulator's settings | | **Leadership** | the switch at the top: services against what was sold, incidents with their cost in customer-minutes and revenue exposed, time to detect and resolve, what caused them and which followed a change, the risk register (spans that cannot fail over at their measured peak, software with open advisories, contracts ending), carriers by cost and downtime, and the week written as a report | The box above every page searches, and completes as it is typed ([below](#the-box-above-every-page-and-the-assistant)). An id, a site or a circuit opens on the map; a sentence becomes the map's query; anything else is looked up: an address (matched to the customer whose prefix holds it), a circuit id, a customer, a device, an interface, an AS number, with what the thing is and whether it is healthy. Each page has a **SQL** button that lists the queries behind what it shows, with their times. ![An incident's room: the cause the agent named, what happened, and why it is probably the cause, each claim with the rows behind it](../assets/img/netops-incident.png) ## The map ![The whole network: regions and metros, coloured by what is broken inside them](../assets/img/netops-map.png) The backbone of 64 devices is what a carrier's core is. What it carries is far more: metro hubs with their routers and power plants, street cabinets, cell sites and business parks, and the ONTs, radios and customer routers behind them. The simulator makes that estate too (`--estate N`, about 200,000 objects by default, `0` for none): 18 kinds of object in `netops_estate_nodes`, what feeds what in `netops_estate_edges` (an edge table, upstream to downstream), and two months of faults and changes on every object in `netops_estate_events`. A few dozen faults are kept going, some of them caused by a change a few minutes before. Two alert rules watch it (`estate-outage` and `estate-degraded`, SQL over the two tables like the others): an access node, a hub router or a hub's power plant that is down or degraded with objects behind it raises an alert, grouped by its hub; a down one with 20 or more behind it is major and opens an incident, which the estate's agent works (what it reported, how far it reaches and which customers, a change before it, who is on call) and proposes sending field services. The degraded ones wait on **My shift**, and **Diagnose** lists them under the backbone's layers. Pasting an object's id into the search opens it. The Map page draws all of it without ever asking for all of it. Places are boxes, one inside the other: a region holds its metros, a metro its core devices and its hubs, a hub its routers, its power plant and its sites, and a site its access node and what is behind it. A box shows a name and a count until there is room for what is inside it, and then it is divided by layer: the backbone in a band along a metro's top, aggregation and power along a hub's, the premises under a site's access node. Shapes say what a thing is: a cell site is a circle with its sectors around the tower, a business park a box with its corners cut, a router a diamond, a power plant or a tower a triangle. - **Zoom is a query.** Every object has a place on a plane and a level of detail from which it is worth drawing. Regions, metros and hubs are read once; from there on the page asks for the objects and links in its window at its level of detail, two range queries, and draws what comes back. - **Red is a `GROUP BY`.** The objects that are down or degraded, and a count by place of what is behind them, are two queries every ten seconds; the page adds them up through site, hub, metro and region, with the backbone's open incidents. A place is coloured by how much the broken things inside it carry: a hub's router weighs more than a cabinet, a cabinet more than one home. - **A click is a walk.** For one object: what it hangs from (`REACHABLE` against the edges) and the nearest of those that is broken, which is where its trouble comes from; what depends on it, counted by kind and state (`REACHABLE` along the edges, grouped); what else is in trouble within three hops; the changes and faults of thirty days on it and on everything around it, with the change made just before the trouble began; and how faults that read like this one ended before (BM25 over the events). ![One object: where its trouble starts, what it hangs from, what depends on it, and the trouble around it](../assets/img/netops-map-object.png) A click on an object also lights what it hangs from and what depends on it, and fades the rest; the panel beside the map has tabs for the object: **Overview** (the walk above), **Metrics** (a minute's series for the backbone's devices and their links; for the estate, its latest reading and its faults and changes a day over sixty days), **Events**, **Logs** (syslog for the backbone; the estate's events as lines), **Related** (the chain it hangs from, what depends on it by kind, the customers behind it, the trouble around it), **Incidents** and **Config** (its properties, and for the backbone the latest configuration). They are read by `/v1/map/detail`. ### The box above every page, and the assistant The box has two modes, **Search** and **Ask** (the buttons before the box switch them; Tab completes the suggestion chosen with the arrows, or moves on to the page), and a chip that says where it looks: the object picked, the place the map shows, or everywhere (a click on the chip searches everywhere). As it is typed, `/v1/suggest` completes it from the tables, from what was typed before the word, and from where the person is: | typed | completed with | how | |---|---|---| | the start of an id ("swi", "hr1-h3") | objects, the broken ones first, in the place in view | `PREFIX(id, :w)` over the column's dictionary; with `fuzzy => 'auto'` when nothing matches exactly | | a word of a name ("park 7", "insur", "Lon") | sites, hubs and metros, customers | `ILIKE` from the substring index, at the start of a word | | the start of a circuit ("LUM-A") | circuits, with their carrier and plane | `PREFIX(circuit, :w)` | | `kind:`, `state:`, `vendor:`, `in:` | the values in the place in view, with counts | a `GROUP BY` | | the start of a sentence ("OLTs in London ") | what the map's reader has not been told yet: a state (with how many it would find), what happened, by whom, a reading, a place in the graph | the reader's plan of the words so far, and one `GROUP BY state` | | a word that asks for the next ("that is not", "changed in", "about", "by") | the words that can follow it | | | words of an earlier question | questions asked before | BM25 over `netops_searches` | In Ask mode it offers questions about the object picked, and after a question the ones that usually follow it (after "what is wrong", what changed before it started, who is affected, what to do). The assistant, on the right of every page, answers them from the app's own API: what is wrong and where the trouble starts, the change made before it, what depends on it and the customers behind it, what to do (the change to check, how such faults ended before, runbooks by BM25), how it went before, what depends on it lit on the map, and a watch that reads the object every 30 seconds and says when it changes. Each answer lists the queries it ran. Anything else becomes the map's sentence search. The answers are written from the query results by fixed rules, not by a model; the command center's own Ask (Ctrl+J) is the server's agent over any table. Each completion is one to four queries of 1 to 3 ms on one server with 170,000 objects (a name matched at a word's start takes up to 70 ms the first time). ChloeDB has no next-word model: the sentence's next words come from the reader's vocabulary, and earlier questions from BM25. ### Asking in a sentence The search box takes a question such as "everything changed in the last week about a firmware upgrade by m.rossi with latency above 15 ms", or "customer routers in Frankfurt behind hr1-h03-fra that are not ok". It names up to five kinds of condition, and ChloeDB answers them in one statement: ```sql SELECT id, kind, name, state, latency_ms, ... FROM netops_estate_nodes WHERE layer != 'container' AND latency_ms > :latency_ms -- its latest reading AND id IN ( -- what happened to it SELECT node FROM netops_estate_events WHERE event = 'change' AND ts >= :since AND author = :author AND MATCH(text, :about)) AND REACHABLE(netops_estate_edges, 'ag1-fra', -- where it sits in the graph hops => 6, dir => 'out', through => layer != 'core') ORDER BY latency_ms DESC LIMIT 300 ``` | in the sentence | becomes | |---|---| | a kind, a vendor, a version, a place, a state ("degraded Nokia OLTs in Frankfurt") | comparisons on keyword columns | | a customer's name | `ILIKE` from the substring index | | a reading ("latency above 40 ms", "high latency", "loss over 1%") | a comparison on the object's latest reading, or of two of its columns (`latency_ms > base_ms * 2`) | | what happened, when, about what, by whom ("changed last week about QoS by a.khan", "went down in the last 3 days because of power", "not changed in the last month") | a subquery over the events table: time, author, cause, and `MATCH` on the words; `NOT IN` for what did not happen | | where it sits ("behind ag1-fra", "upstream of ...", "within 2 hops of ...") | `REACHABLE` over the edge table | The same conditions run a second time grouped by place, so the map shows the matches at every zoom: a count on each region, metro, hub and site that holds some, and a ring on each object once it is drawn. ![A sentence read into conditions, the one statement it became, and the matches by place](../assets/img/netops-map-search.png) A sentence becomes a plan, and only a plan becomes SQL: every value in it is one the estate has or a parameter. Two readers make plans. With `--rewrite-model` (default `anthropic/claude-haiku-5-5`, empty for none) the app asks the server's own [`llm()`](query-language.md#language-models-llm) to rewrite the question, over the row it was saved as in `netops_searches`; the model is told the plan's shape and what it may name, and its answer is checked field by field. When the server has no model (no key, no network), a reader of fixed vocabulary answers instead, and the page says which of them read the sentence. The fixed reader lists the words it took nothing from beside the count, which is then the answer to the rest of the question; an id, a place or a name the estate does not have refuses the question rather than being dropped from it ("ag9-zzz is not an object of the estate", "Did you mean London?"), and a place one letter off is read and said. A customer is matched by its whole name when the question gives it ("Northwind Energy"), and "this week", "this month" and "this year" start on their first day. The model's path is covered by a unit test of the checking, not by a run against a model: this build was only run where the server had none. Measured on one server in a 4-vCPU cloud container, with 170,337 objects, 173,133 links and about 470,000 events: the estate is written in about 25 seconds; a window is read in 10 to 75 ms depending on how much is in it; the eight queries behind one object take about 17 ms together; the statement above takes 5 to 10 ms, a walk of the 20,000 objects behind one aggregation router with a condition 22 to 30 ms, and "not changed in the last month" about 290 ms. On a cluster of shards the range queries, the grouping and the subquery run through the coordinator as they are. The walks are done by the app over the estate it made, as before a coordinator walked graphs, and the page says so. The rows a walk reached are then read by key, at most 400 keys a statement, when there are up to 1,600 of them; a larger walk is read as plain queries over the hubs, metros or regions that hold it, 10,000 rows a page, and the app keeps the rows its walk reached. A search counts its matches by place in the app and reads its first 300 in full by key, so no statement names thousands of keys. ## Where is it broken A list of alerts says that things are wrong, not where the trouble begins. The Diagnose page answers that, and then asks about the broken thing in the ways that only one database holding the topology, the logs, the history and the readings can. ![Diagnose: the stack by place with the lowest broken layer outlined, a trace that marks the broken hop, and the start of an investigation](../assets/img/netops-diagnose.png) - **The stack, by place.** A grid with a row per layer (power and reachability, optics, links, capacity, routing, device health, services, customers) and a column per site, plus one for the backbone between sites. Each cell is read from the last three minutes of the tables. A fault shows on its own layer and on every layer above it, so the lowest layer with something broken is named as where to start, and what shows above it is marked as likely following from it. - **Investigate** takes one link, device or service and asks five things, each card saying which of ChloeDB's abilities answered it, with how many queries and in what time: - *Graph queries in SQL*: `ppr()` over the links table ranks the devices closest to everything that alerts now, and `REACHABLE()` with array overlap lists the services and customers it takes down. - *Substring search*: every log line that names its interface, on any device, by `LIKE '%…%'` answered from the FM-index, so the neighbours' view of it is there too. - *History as rows*: the changes whose devices overlap it (`&&` over `INT[]`) and the configuration versions written on it; when there are none, a change is ruled out. - *Hybrid search*: past incidents and runbooks like it, by BM25 and an embedding fused with `rrf()` in the `ORDER BY`. - *Time series*: its last hour, a point a minute. - **Trace a path** walks from a customer, a device or a site to another (`PATH()` over the links table) and shows each hop and the link it was reached over with what they read now, marking the hop where it goes wrong. On the simulated network an investigation is 13 queries; in a 4-vCPU cloud container (one chloedb-server on local disk, the 64-device network with six hours of telemetry) they took about 12 ms together. The page's SQL button lists each. ## An incident's board Most incidents fall into a few kinds, and the first minutes of each kind look alike; what differs is the question someone needs answered at minute twenty. So an incident's room is not built from nothing, and it is not fixed either. - **It starts from its cause's template.** When the room opens it has the panels every incident needs (loss on the links involved, error log lines by kind, the customers at its sites). When the root-cause agent names a cause, that cause's panels join: receive power and input errors for a failing optic, link state, the surviving plane's load and latency for a fibre cut, BGP sessions and configuration versions for a bad change, traffic in and top talkers for a DDoS, CPU and BGP updates for a software defect, reachability and temperature for a power fault. - **People add to it by asking.** `loss on LON-NYC last 2 hours`, `cpu on cr1-fra`, `logs "LINK-3-UPDOWN"`, `who sends the most`, `customers on ag1-ams`. A small reader that knows the readings, the tables and the network's names (devices, links, circuits, sites) turns the sentence into a query and says what it understood; it refuses what it cannot read rather than guess. A `SELECT` can be pasted instead. No model writes code here. - **It is shared and kept.** A panel is a row of `netops_panels` holding one read-only query, so everyone in the room sees the same board, a removed panel stays removed, who added what is on the timeline, and the board is still there for the postmortem. - **It learns in the plainest way.** What people added by hand to other incidents of the same kind is offered, one click each, on the next one. ![The board of a fibre cut: loss, link state, the other plane's load and latency from its template, and panels people asked for](../assets/img/netops-board.png) ![Leadership: services against their objectives, what incidents cost, risk, and the week written as a report](../assets/img/netops-leadership.png) ## The agents | agent | what it does | |---|---| | Triage | sizes a new incident: the alerts, the devices around them, the services and customers that ride on those, and who is on call | | Root cause | ranks the alerting devices over the topology, reads the logs, changes, optics and flows around them, tests six causes, finds similar incidents and the runbook, and proposes actions | | Change risk | scores a planned change: its blast radius, other changes on the same or neighbouring devices in its window, open incidents nearby | | Capacity | finds the links whose 95th percentile runs hot, and the pairs that cannot carry each other's traffic if one fails | | Advisories and drift | joins vendor advisories with the inventory's software versions, and searches every configuration for what should not be there | | Topology from logs | reads LLDP and routing-adjacency lines out of syslog, builds the links they imply, and compares them with the inventory | The agents are code that queries ChloeDB, not calls to a language model: each conclusion comes from rows a query returned, and a hypothesis is kept only when the incident's own alerts and fresh evidence near them support it. That is what makes a run cheap enough to start on every incident, and what lets the page show every step. When the root-cause agent names a cause it says why, in three parts that the incident's room shows under **Likely cause**: - **What happened**: an account in order, written from the evidence: when each end lost the light, where the traffic went, what did not change first, and what that means. - **Why this is probably the cause**: each claim (an alert, log lines, a reading, a change, a flow, an advisory, past incidents with the same cause) with what it points at, as links to the device, link, change or incident, and the query that shows the rows behind it. The page runs the query again on a click, so the rows come from the tables, not from the agent's say-so. A claim that something did not happen (no change on either router, no loss of signal) is made only after its own query came back empty. - **What it is not**: each of the other explanations the agent tests, and the query that rules it out. They are rows of `netops_evidence`, one a claim, kept with the run. The simulator keeps an answer key for each fault it injects (`netops_faults`), which the agents never read. An incident's room can check the agent's answer against it, and the Agents page counts how many were right. ## The six faults | fault | what happens | |---|---| | Fibre cut on a backbone circuit | a backbone circuit loses light; its traffic lands on the other plane, which runs hot | | A change breaks BGP on a border router | a routing-policy change is committed on a border router and its sessions drop | | An optic slowly fails | receive power on a link decays, errors climb, and the link starts to flap | | Volumetric DDoS on a customer prefix | an amplification attack floods a site's borders and its firewalls | | Routing daemon pegs a core router's CPU | a software defect named in a vendor advisory makes the routing process spin | | A site loses one power feed | feed A at a small site fails; the devices on it go dark together | A fault mitigates when its action is approved (or after some minutes on its own) and its incident resolves when the alerts clear. ## Your own network The app only reads tables, with the SQL its pages show. The simulator is one writer of them; anything that writes to ChloeDB can be another. `chloedb-netops serve --no-simulate` is the app on a real network: - **The network is the inventory tables.** At start the app reads `netops_sites`, `netops_devices`, `netops_links`, `netops_services`, `netops_customers` and `netops_bgp` and works from those: the topology graph, an incident's scope, a customer's path, a notice's circuit. With no devices it creates the tables, says which to fill, and stops. The inventory is read at start, so restart the app after it changes. - **It writes no telemetry.** Each minute, once that minute has had a minute to arrive, the alert rules run over whatever is in `netops_link_metrics`, `netops_device_metrics`, `netops_service_metrics`, `netops_flows` and `netops_syslog`; alerts are grouped into incidents over the topology and the agents work them, exactly as on the simulated network. What the app writes is what it derives: alerts, incidents, timelines, agent runs, proposed actions, panels, silences. - **An approved action is recorded, not pushed.** The app does not log in to devices. Approval, who gave it and the commands proposed are kept; carrying them out stays with the people and tools that do that today. - **The Data page says what is arriving.** Each source shows `live` when rows landed in the last five minutes (or, for records, when the table holds any), `silent` or `empty` otherwise, with its rate and lag. With the simulator on, sources read `simulated`. What usually feeds each table: | table | from | |---|---| | `netops_devices`, `netops_links`, `netops_sites`, `netops_circuits` | the inventory (NetBox, or its database followed with `follow-postgres`) | | `netops_link_metrics`, `netops_device_metrics`, `netops_service_metrics` | a rollup a minute from the metrics store (Prometheus), one row per link, device or service | | `netops_syslog` | chloedb-server's [OTLP logs endpoint](server.md), from an OpenTelemetry Collector with a syslog receiver | | `netops_flows` | flow summaries a minute (top talkers), not raw flows | | `netops_changes`, `netops_tickets` | the ITSM tool | | `netops_configs` | a configuration backup tool, a row per version | | `netops_maintenance` | carriers' mail: `POST /v1/maintenance/parse {"text": "..."}` reads a notice as it arrived into its circuit and window; a row written with only `raw` and `status` `new` is read the same way within a minute | | `netops_alerts` | the rules here, and `POST /v1/alerts/webhook` in Alertmanager's format (`{"alerts": [{"status": "firing", "labels": {...}, "annotations": {...}}]}`), which join incidents the same way | A metrics row carries the link's or device's `id` as the inventory has it and a `ts`; the Data page shows each table's columns. The simulator's data is marked as synthetic on every page, and the mark is gone with the simulator off. ## A network that reports itself Nobody has to list a network for the app to know it. A carrier's routers and switches already say what they are and what they are cabled to; the discovered network (the switch's **Discovered**, or `--topology discovered`) is built from that alone. With the simulator on, its network first reports itself into seven tables, as collectors on a real network would fill them, and the app then reads its sites, devices, links, BGP sessions and the estate behind the backbone back from those rows and writes them into `netops_sites`, `netops_devices`, `netops_links` and `netops_bgp` (`netops_disc_sites` and so on when the app serves both), where every page reads them as before: | table | what it holds | on a real network | |---|---|---| | `netops_snmp_system` | each agent's system group (sysName, sysDescr, sysObjectID, sysLocation) and ENTITY-MIB's model, serial and software | an SNMP poller (Telegraf's `snmp` input) | | `netops_snmp_ifaces` | interfaces (IF-MIB's names, speeds and ifAlias) and their addresses (IP-MIB) | the same poller | | `netops_lldp` | LLDP neighbours, a row a port (lldpRemTable) | the same poller, or gNMI's openconfig-lldp | | `netops_bgpls_nodes`, `netops_bgpls_links` | the IS-IS database: routers, and adjacencies with their bandwidth, delay ([RFC 8571](https://www.rfc-editor.org/rfc/rfc8571)) and administrative group | a BGP-LS session ([RFC 9552](https://www.rfc-editor.org/rfc/rfc9552)) from a route reflector to a collector (GoBGP, pmacct) | | `netops_bmp_peers` | each router's BGP sessions and the routes it takes from each | BMP ([RFC 7854](https://www.rfc-editor.org/rfc/rfc7854)) to a collector (OpenBMP, pmacct) | | `netops_gpon_onts` | each OLT's ONTs on its PON ports | the OLT's element manager, or its SNMP ONT table | The rules, in the order they run: - **Devices.** An SNMP agent whose sysLocation names a point of presence (`CODE | City, CC | Region | lat,lon`) is a device there. sysObjectID's enterprise number gives the vendor, sysDescr the operating system, ENTITY-MIB the model, serial and software. Devices are numbered in the order of their management addresses. - **Links.** An LLDP neighbour, or an IS-IS adjacency in BGP-LS, is a link; the two are one link when the adjacency's addresses are on the ports LLDP names. Capacity and delay come from BGP-LS's TE attributes (else the port's speed), the plane from the administrative group, the carrier and circuit from the ports' descriptions. - **Roles.** In the IS-IS database with eBGP sessions in BMP: a border router. Adjacent to another site: a core router. Any other IS-IS router: an aggregation router. Outside the IGP, a switch next to a firewall (its sysDescr says so) is a spine, and the rest are leaves. A fabric makes a site a data centre, two border routers a hub, and anything else a point of presence. - **The estate.** Hub routers are what LLDP shows hanging from the backbone, access nodes what hangs from hub routers. An OLT's ONTs come from its ONT table; a business park's customer routers and a cell site's radios from LLDP (the customer by the port's description). sysLocation names the hub and the site each belongs to. What the network does not report is written beside the feeds: the services sold and the customers who bought them. The simulator's own numbers for how loaded each link is and how fast each service answers are matched to what was found by name; they add nothing to it. Read back, the network is the simulator's, device for device and port for port (`discover.rs` tests it, the estate object for object at 200,000), with one difference that is the point: the two cables the made-up inventory forgot are there, and the two links it kept after they were removed are not. On the simulated network the feeds are about 230,000 rows, read in about 3 seconds as scrolls. Each site, device, link, session and hub says which feeds found it and by which rule in `netops_discovered`, and the **Discovery** page shows them, with the feeds' rows and the queries that read them; the **Network** map places each site where its devices' sysLocation puts it. A restart reads the feeds again and keeps the inventory (and what is down in it) when it finds the same network. A database made one way is refused by the other: start the other way with another `--local` directory, or with `--reset`. With `--no-simulate --topology discovered`, the app reads feeds written by something else, and stops if they name no device. ![Discovery, with the switch between the two networks at the top: the network drawn from its feeds, the feeds in tables of its own, the rules, and how each device was found](../assets/img/netops-discovery.png) ## The tables | table | what it holds | |---|---| | `netops_sites` | sites: points of presence and data centres | | `netops_devices` | devices, as the inventory records them | | `netops_links` | the inventory's links: an edge table, so graph queries walk the topology | | `netops_seen_links` | links read from the logs (LLDP neighbours, routing adjacencies), compared with the inventory | | `netops_circuits` | leased circuits and who provides them | | `netops_bgp` | BGP sessions with transit providers and peers | | `netops_services` | services sold, their objectives and the devices they ride on | | `netops_customers` | customers, where they attach and what they are known by (prefix, port, circuit) | | `netops_snmp_system`, `netops_snmp_ifaces`, `netops_lldp`, `netops_bgpls_nodes`, `netops_bgpls_links`, `netops_bmp_peers`, `netops_gpon_onts` | what the network reports, from which `--topology discovered` builds it ([above](#a-network-that-reports-itself)) | | `netops_discovered` | how each site, device, link, session and estate hub was found: the feeds and the rule | | `netops_link_metrics` | a point a minute per link: the rollup an incident needs, not a metrics store | | `netops_device_metrics` | a point a minute per device | | `netops_service_metrics` | a point a minute per service: requests, errors, latency | | `netops_flows` | flow summaries a minute: who talks to whom | | `netops_syslog` | device logs, searched by words (BM25) and by any substring (an FM-index) | | `netops_alert_rules` | alert rules: each one is a SQL query over these tables | | `netops_alerts` | alerts the rules raised | | `netops_incidents` | incidents: alerts correlated over the topology, with the cause the agent named | | `netops_timeline` | what happened in each incident, in order | | `netops_changes` | changes, planned and done, with the devices each touches (`INT[]`, so scopes overlap with `&&`) | | `netops_configs` | every version of each device's configuration, for blame and search | | `netops_tickets` | tickets, open and closed | | `netops_runbooks` | runbooks, found by words and by meaning | | `netops_judgments` | which runbook closed which incident: grades the ranking can learn from | | `netops_oncall` | who is on call, by team and shift | | `netops_advisories` | vendor advisories, joined with the inventory's software versions | | `netops_agent_runs` | each run of an agent | | `netops_agent_steps` | every step of every run, with the SQL it ran | | `netops_receipts` | what each agent was shown and what was left out | | `netops_evidence` | why the root-cause agent named its cause: what happened, each claim with the query that shows its rows, and what it ruled out | | `netops_actions` | actions agents proposed, and who decided them | | `netops_silences` | what is kept from paging, by whom, why and until when | | `netops_maintenance` | carriers' maintenance notices, each matched to a circuit and a window | | `netops_handovers` | notes left from one shift to the next | | `netops_panels` | each incident's board: one read-only query a panel | | `netops_estate_nodes` | everything the network is made of, from regions down to a customer's router: its place on the map, its level of detail, its state and its latest readings | | `netops_estate_edges` | what feeds what, upstream to downstream (an edge table) | | `netops_estate_events` | faults, their clearing and changes on every object, with their words, cause and author | | `netops_searches` | the questions asked in a sentence: who read each, the plan and the SQL it became | | `netops_faults` | the simulator's answer key (agents never read it) | | `netops_sources` | where each table's rows come from | | `netops_state` | the app's own bookkeeping | The Data page shows each table's `CREATE TABLE`, and they can be queried in the SQL workbench like any other: ```sql -- the links that lost the most packets since a given minute, worst first SELECT link, MAX(loss) AS worst FROM netops_link_metrics WHERE ts >= '2026-11-13T03:00:00Z' GROUP BY link ORDER BY worst DESC LIMIT 5; ``` ## What it is not Out of the box it is a demonstration on synthetic data, and it has been run on real feeds only in its own test (readings written to the server from outside, with the simulator off). The telemetry is a point a minute per link, device and service, which is what an incident needs; ChloeDB is not a metrics store, and a real deployment keeps its high-resolution metrics where they are and writes rollups here. Approving an action changes the simulated network, or is only recorded with the simulator off: nothing is ever sent to a device. The reader behind "add a panel" knows a fixed set of readings and tables; it is not a language model. The inventory is read once at start, and at most 10,000 rows a table. With `--topology both`, once the discovered network has been opened, the app simulates two networks and writes twice the telemetry. The feeds the discovered network is read from are the simulator's own, written the way collectors would write them; its rules expect sysLocation to carry a site code, city, region and coordinates, as an operator's convention would, and have not met a real network's gaps (a port with LLDP off, a hostname that differs from sysName). ## Test it ```bash cd chloedb-netops && cargo test --release ``` `tests/cluster.rs` starts the app on a real chloedb-server (built in `../chloedb-server/target`, or `CHLOEDB_SERVER_BIN`) and checks the tables, the topology found from logs, each of the six faults against its answer key (and that every claim of its evidence has rows behind it, or none when it says nothing happened), an approval, the webhook, where it is broken during a fibre cut (the stack by place, an investigation, a trace), the shift's pages (handover, lookup, a customer's check, acknowledging and silencing, a change carried out and verified, carriers' notices and their collisions), an incident's board, the leadership numbers, a restart on the same folder, and then the simulator off: readings written to the server from outside open an incident that the agent diagnoses. Another starts it with `--topology discovered` and checks the network read back from its feeds, the Discovery page, a fault diagnosed on it, a restart, and that the made-up inventory is refused on its tables. A third starts it as it starts by default, with both, and checks the two networks side by side: each in tables of its own, the SQL shown naming the tables it ran on, a fault on one and not on the other, and a restart that reads the second again rather than building it again. --- # chloedb-hn: Hacker News on ChloeDB > **A demo.** chloedb-hn shows what ChloeDB can do; it is not part of ChloeDB's releases or their promises. It is tested on a train of its own (the `Demos` workflow, `.github/workflows/demos.yml`), outside CI's required check, and the command center marks it as a demo ([compatibility](../compatibility.md#demos)). `chloedb-hn` keeps every public Hacker News item in ChloeDB, about 49 million stories, comments, jobs and polls from October 2006 on, and searches them the way people look for things on HN: a story they half remember, what HN said about a tool, who knows a subject, when something was talked about, or a question asked in a sentence. - **Questions in a sentence, answered by SQL, no model.** "which post has received the most comments", "who posted the most stories about rust", "how many Show HN posts about postgres in 2023", "when was HN most into bitcoin", "what was the first story about docker". A small grammar ([`src/nl.rs`](../../chloedb-hn/src/nl.rs)) reads the question into what it asks (the top item by a measure, a count, people, sites or years), the topic and the filters, and the answer above the results is one query, shown with it. Anything the grammar does not read is searched as words. - **Autocomplete of questions, phrases and people.** As a search is typed the box offers whole questions the grammar reads (`which post` → "which post has received the most comments"), the phrases HN's titles use most (`kubernetes o` → "kubernetes operator"), people and sites. The phrases are a table, `hn_complete`, keyed by kind and text, so completing is a prefix of its sorted key: one run of the dictionary, read from a few blocks (`PREFIX(id, 'p:kubernetes o')`). - **Instant, a keystroke at a time.** Each keystroke shows the stories whose titles hold the words typed so far, the last one as a word or the start of one (`rust asy` is `MATCH(title, 'rust (asy OR asy*)')`), by points while that word is being typed and by BM25 times the votes once a space follows it: one statement, no count, no meaning. Enter runs the full search, which reads the last word whole. It is off until the *Instant* switch beside the box turns it on, and it and *Fast* are one at a time: switching one on switches the other off. A question being typed still gets its completions. - **Words and meaning together.** Titles, texts and the words of each link are ranked by BM25 with typos, stems and synonyms, fused with a static embedding model's similarity on the server, and weighed by points (`pow(points + 1, 0.35)`) and a gentle decay for age. Every word must be there for searches of up to three words, and most of them for longer ones, so the counts and facets match the results. - **Exact text, punctuation and all.** `` `C++` ``, `` `std::move` ``, `` `k8s.io/api` `` in backticks, or *Match by → exact text*, are matched where their characters are, by `ILIKE` answered from each segment's FM-index (`OPTIONS(substring = true)`), which tokenized search cannot do. - **Highlights the way the index reads.** A server of 0.3.7 or later marks each result with `POST /v1/highlight`: stems, synonyms, typos and code as the field's analyzer reads them, cut to the stretch with the most matches. - **Filters in the words.** `by:pg`, `site:github.com`, `points>500`, `comments>100`, `2019..2021`, `before 2015`, `-crypto`, `show hn`, `ask hn`, `"exact phrase"`; each is shown as a removable chip of what was understood. - **Threads, people and the graph.** A story opens as its whole thread; a comment opens in place with the path to it. People pages show what someone writes about, when, and who they talk to (the reply graph, `hn_replies`). *Who knows* ranks the people who comment most on a subject, weighed by the discussion they start. Similar stories by meaning, and the same link discussed again. - **What HN thinks.** A question about opinions gathers the comments that speak to it, packed into a model's budget by the database (`PACK n TOKENS ... DEDUPE ... WITH RECEIPT`), and a model behind the server's `llm()` sums them up with every claim cited to a numbered comment. Answers are kept, so a question asked again costs nothing. It, *Weekly* and *Changed minds* are the parts that call a model. - **A link across HN.** *Links* takes a page or a site and shows everywhere HN met it: each time it was submitted, the comments that cite it in other threads, the people who submitted, discussed or cited it, and the links discussed beside it, drawn as one graph (`GET /v1/link?u=`). A site alone (`sqlite.org`) lists its most discussed pages, the pages submitted again and again, and who posts it most. - **The week on HN.** *Weekly* is a digest of a week's ten most voted stories (one per link, jobs left out): what each is, why it mattered, what the thread said, with the top comments quoted, and an opening over the whole week. The app reads each story's linked page once (public `http` and `https` pages only, with a timeout) and `llm()` writes an entry from the page, the post and its most replied comments; entries are kept in `hn_answers`, so each story is written once (`--digest-model`, at most `--digest-per-day` new entries a day). - **The canon.** *Canon* ranks the books and papers HN recommends, by the people who linked or named each, one person once: for all years, for a span of them (`2010..2014`) or by a word of the title. A work's page shows the people who named it a year, its best received comments with the name marked, and how it was counted. [`canon/build.py`](../../chloedb-hn/canon/build.py) builds `hn_canon` from the cluster: the comments that link Amazon, Goodreads or arXiv, the works' titles from Open Library and the arXiv API, books merged across editions by title and first author, then every work counted. A comment counts when it links the work, uses its short name (SICP), writes the title as a title (each word capitalised: "Getting Things Done", not "getting things done") beside a word about books or papers, or writes it beside one of its authors' names, which is the only way to name a title of one or two words ("Steve Jobs", "Deep Learning"); a paper counts only from the year of its arXiv id. So a title that is also a common phrase, a person or a subject ("World Models", "On Writing") is not counted every time it is written. - **Changed minds.** For a topic (`rust`, `bitcoin`, `remote work`), the people who wrote about it in four years or more, and for one of them an arc: their comments that BM25 finds most about it, three a year at most, read by a model through `llm()` for where each stands (from -2, against, to 2, for, or no view when a comment only explains a detail) with a quote, and what they thought first and last; a year's stance is the mean of its comments that take a side, so neutral and technical comments are shown but do not move it. A quote the comment does not hold word for word is dropped, and every point links to its comment. Arcs are kept in `hn_answers`; a new one counts against `--ask-per-day`. - **Fast mode.** The switch beside the search box ranks by words alone (BM25, no meaning and no reranking) for every search until it is switched off. - **Live.** With `--feed` the app follows the HN API: new items as they are posted, and the points and comments of the stories that change. Like [the crawler](crawler.md) and [network operations](netops.md), it is a program of its own, in Rust, that talks to chloedb-server over HTTP only, and the command center shows it as an app (**Apps → Hacker News**). ## Run it Build both programs, then prepare the archive and start the app with a server of its own: ```bash (cd chloedb-server && cargo build --release --bin chloedb-server) cd chloedb-hn && cargo build --release target/release/chloedb-hn prepare --parquet ./hn-parquet --out ./hn-rows --download target/release/chloedb-hn complete --rows ./hn-rows target/release/chloedb-hn serve --local ./hn-data --rows ./hn-rows --server-bin ../chloedb-server/target/release/chloedb-server ``` `prepare --download` fetches the archive's monthly Parquet files (about 12 GB, from [open-index/hacker-news](https://huggingface.co/datasets/open-index/hacker-news)) and writes the app's rows: stories, comments (each with its story's title, depth, place among its siblings and the discussion under it), people, the reply graph and the links between stories. `--from 2024-01` and `--to` take part of it; `--comments-since` keeps every story and only the newer comments. `complete` writes autocomplete's rows from them. `serve --local DIR` starts a chloedb-server with its database in `DIR`, makes the tables, loads the rows when they are empty, and lists the app as `hn`; open `http://127.0.0.1:7700` and go to **Apps → Hacker News**. Against a server or a cluster that runs elsewhere, load into it and give the server the app: ```bash chloedb-hn load --rows ./hn-rows --strata http://coordinator:7700 --key "$CHLOEDB_KEY" --comment-model none chloedb-hn serve --strata http://coordinator:7700 --key "$CHLOEDB_KEY" --token "$HN_TOKEN" --listen 0.0.0.0:7850 --feed --comment-model none chloedb-server ... --app hn=http://hn-host:7850 # with CHLOEDB_APP_TOKEN=$HN_TOKEN ``` `--comment-model none` keeps the comments without vectors: they take a third of the bytes, and are found by their words and their story's title. The people and sites questions group by author or site; a server whose `--max-groups` (65,536 by default) is below HN's 1.1 million authors answers them for a topic but not over the whole archive, so give it `--max-groups 2000000`. ## The questions it reads | asked | answered by | |---|---| | which post has received the most comments / the most upvoted story about X / the top 5 Show HN posts in 2023 | the top stories by comments, points or date, with the question's filters (`ORDER BY comments DESC`) | | the first / oldest / newest story about X | `ORDER BY created` | | how many stories mention X / number of comments about X in 2020 | `COUNT(*)` with the same match as the results, and its years | | who posted the most about X / who commented the most / who has the most karma | `GROUP BY author`; HN's archive carries no karma, so karma is the points a person's stories earned, and the answer says so | | who knows the most about X | the people who comment most on it, weighed by the discussion they start | | which sites are posted the most about X | `GROUP BY site` | | when was HN most into X / which year did X peak | the years' counts, each as a share of that year's stories (HN grew; raw counts favour late years) | | what does HN think about X | the cited summary above, the one answer a model writes | Each answer shows its SQL (**see the SQL**). The grammar's templates are also autocomplete's questions, so what the box offers it can answer. ## Read the linked pages ```bash chloedb-hn crawl --strata http://coordinator:7700 --key "$CHLOEDB_KEY" --min-points 3 --contact https://your.site ``` `crawl` reads each page the stories link to, once, into `hn_pages`, with [the crawler](crawler.md)'s fetcher and frontier: robots.txt read before a site's first page and obeyed, one request at a time to a site and a second between two (longer when its robots.txt or its answers ask), redirects checked hop by hop, public addresses only, HTML only, at most 5 MB a page. The links are the stories' canonical links (`curl`) of at least `--min-points` points, most voted first. Every link asked becomes a row saying what came of it (`ok`, `noindex`, `robots`, `http_4xx` with its code, `network`, `timeout`, `not_html`, ...), so the table also says which of HN's links still answer, by the year HN first linked them. A page whose `` says `noindex` keeps no text. A run skips the links already in the table, so a crawl that stops goes on where it was; `--again network,timeout` asks those that failed that way again. `--contact` goes in the user agent, for a site's owner to reach whoever runs it. ## Tables | table | what | |---|---| | `hn_stories` | stories, Ask and Show HN, jobs and polls: title, text, link (its site and words), author, time, points, comments, kind, topics, a vector of the title and text | | `hn_comments` | comments: text, author, time, parent and its author, story and its title, depth, place among siblings, replies, the discussion under it (and a vector, unless `--comment-model none`) | | `hn_users` | people: stories, comments, points earned, first and last item, replies received, people talked to | | `hn_replies` | the reply graph: who replied to whom, how often | | `hn_links` | which discussion links to which: a story or one of its comments naming another's `item?id=` | | `hn_pages` | the linked pages as `crawl` read them, keyed by canonical link: what came of asking, the HTTP code, the year HN first linked it, the most voted story and how many link it, the page's title, description, text (at most `--max-text` characters), words, language, date, author and image, and a vector of its title, description and text | | `hn_canon` | the canon: a row a book or paper, with its title, authors, cover, link, the people who named it in all and a year, its best received comments, the statement that found its candidates, the rule that kept them and how many each part kept | | `hn_complete` | autocomplete: phrases of titles (`p:`), sites (`s:`), topics (`t:`) and people (`u:`), each with how many stories hold it and their points | | `hn_answers`, `hn_searches`, `hn_state` | kept answers, the searches people ran (their words and counts only) and the feed's place | ## The API | route | what | |---|---| | `GET /v1/search?q=&only=all\|story\|comment&sort=best\|date\|points\|comments&mode=hybrid\|words\|meaning\|exact\|fast\|instant&page=` | results, what was understood, the answer when it is a question, facets, "did you mean", and every query run with its time | | `GET /v1/suggest?q=` | completions: questions, phrases, people, sites, stories | | `GET /v1/item/:id`, `/v1/item/:id/around` | a thread; similar stories and the same link again | | `GET /v1/user/:id`, `/v1/experts?q=` | a person; who knows a subject, with the replies among them and the community around them (`brief=1`: the people only) | | `GET /v1/trends?q=a,b&by=year\|month` | how often each was talked about | | `GET /v1/ask?q=` | what HN thinks, cited | | `GET /v1/front` | the front page as SQL: points over age, as HN ranks it | | `GET /v1/facets?q=` | a search's facets on their own (the page asks for them once the results are shown) | | `GET /v1/ask/comments?q=` | the comments an answer is made from, before the model is asked | | `GET /v1/trending`, `/v1/spikes?year=` | what titles are suddenly about (the last hours against the year before); the months' strongest spikes | | `GET /v1/link?u=` | a page or a site across HN: its submissions, citing comments, people, related links and the graph of them; with no `u`, the most discussed stories | | `GET /v1/digest?week=YYYY-MM-DD` | a week's digest: the stories picked, the entries and opening already written, the week's totals; the last full week by default | | `GET /v1/canon?kind=book\|paper&from=&to=&q=`, `/v1/canon/work?id=` | the canon, ranked by everyone or by the people of the years asked; one work with its comments and how it was counted | | `GET /v1/minds?topic=`, `/v1/minds/arc?topic=&who=` | the people who wrote about a topic for years, with the arcs already read; one person's arc (read and kept when it is new) | | `GET /v1/digest/write?week=&id=` | writes one entry (`id` a story of the week's picks, or `intro`) and keeps it | ## Experiments The Experiments app ([its README](../../chloedb-experiments/README.md#real-sites)) can study this site's real search. It puts AI agents, playing people written from the stories, on the search with some of it changed. The app takes experiments only when it is started with a token for them: ```bash chloedb-hn serve ... --experiments-token "$HN_EXPERIMENTS_TOKEN" --experiment-index v2=hn_stories_v2 chloedb-experiments serve ... --source hn=app:http://hn-host:7850 # with CHLOEDB_SOURCE_HN_TOKEN=$HN_EXPERIMENTS_TOKEN ``` The token (`--experiments-token`, or `CHLOEDB_HN_EXPERIMENTS_TOKEN`) opens only `/v1/experiment`. These routes read: they write nothing, and hold no key of the cluster. They answer in `--public` mode too. Without the token they answer 404, and with a wrong one 401. | route | what | |---|---| | `GET /v1/experiment` | the site, its knobs, presets and indexes | | `POST /v1/experiment/search` | `{q, knobs, per}`: the site's own search of stories, with the knobs, and what it understood | | `GET /v1/experiment/item/:id` | a story's title, link and text | | `GET /v1/experiment/sample?n=&seed=` | stories to write people from: well voted and ordinary, across the years | | `GET /v1/experiment/log?since=&limit=` | with `--explore-share`: the page's logged searches since `since` (seconds), each with the stories as ranked, as shown and opened, and the policy | | `GET /v1/experiment/interleave`, `POST /v1/experiment/interleave`, `POST /v1/experiment/interleave/stop`, `GET /v1/experiment/interleave/log` | the test interleaving two arms on the page's searches: what runs, start one, stop it, read its searches ([below](#interleaving-two-arms-on-real-visitors-searches)) | The knobs, by group (an arm names the ones it changes; the rest stay as the site is): | group | knobs | |---|---| | Query understanding | `understand`: "by pg", "in 2015", "ask hn", "points>100" and questions in a sentence become filters and sorts; off, every word is searched as typed | | Retrieval | `typos` (fuzzy title words), `synonyms`, `meaning` (stories near the words in meaning are candidates and meaning counts in the ranking), `exact` (code such as `std::move` found as written by the substring index) | | Ranking | `votes` (the exponent of points + 1), `recency` (the share of the score a five-year decay of age decides), `meaning_weight`, `phrase` (the words as a phrase in the title), `body`, `link`; `rank`, a whole `ORDER BY` expression of ChloeDB's SQL over `hn_stories` (`:q`, `:phrase`, `:v`) in place of them; `tiers` (every word in the title first) | | Blending | `max_per_site` (a site's stories past this many in the page move below the others), `fresh` (places of the page for the best stories of the last year) | | Index | `index`: `main`, or an index named by `--experiment-index NAME=TABLE`, the stories indexed another way (other analyzers, fields or embeddings) beside the main one | A knob it does not have, a number out of its range, an index it was not given, or an expression with more than an expression in it (a `;`, a comment, a statement's words) is refused with 400. ### Exploring: the page's searches, logged With `--explore-share ε` (or `CHLOEDB_HN_EXPLORE_SHARE`; it needs `--experiments-token`), the page's searches are logged so that the Experiments app can value a ranking on what real people opened, off-policy, without serving it. A logged search is the page's own (`log=1`): the first page of stories by the best match, with words. The log holds the stories in the order the site ranked them, the order shown and the stories opened from it (`GET /v1/click?r=&id=`, which the page calls, kept only for a recent request that showed the story). With chance ε the top `--explore-top` (10) stories are shown in a uniform random order instead (the rank log's `epsilon` policy), so every story of the top has a known chance at every place. The draw is seeded by the request's id. A search through the API, the Experiments app's agents' included, is not logged. The tables are `hn_explore_log` and `hn_explore_clicks`, and a tune ([Experiments](../../chloedb-experiments/README.md#tune-the-relevance-autopilot-on-a-sites-knobs)) values the site as it is and its proposal on them. ### Interleaving: two arms on real visitors' searches The Experiments app's last step before a decision. When it starts a test (`POST /v1/experiment/interleave` with `{id, name, a, b, share}`, `a` and `b` each a set of the knobs above), a share of the page's logged searches (`log=1`) runs both arms' searches and shows one list drafted from the two by team draft: a coin seeded by the request picks which arm chooses first in each round, and each round both place their best story not yet shown. Each search is kept in `hn_interleave_log` with its query, both arms' stories and times, the order shown, the arm that placed each story and the device (phone or not, from the page's width), and the clicks are the ones the page already logs. Only one test runs at a time; it keeps running across a restart until `POST /v1/experiment/interleave/stop`. `GET /v1/experiment/interleave` says what runs, and `GET /v1/experiment/interleave/log?test=&since=&limit=` reads its searches with their clicks. Each logged row has a `kind`. `drafted` is an interleaved search. It also keeps `meta`, which gives each story's age in days and its site, and `click_ts`, the time each story was first opened. `error` is a search where an arm failed (`err` is `a`, `b` or `ab`): the page was served the usual way, and the row only counts the failure. While a test runs, the page's other logged searches by the same browser are kept as well. `page` is a next page of results (`page` holds its number). `other` is any other search. Those two rows let the app tell whether a drafted search was followed by a next page, or by a search in other words. The page links them with `vid`, an anonymous id of 16 random hex characters that the browser keeps in its local storage. The id is sent only with logged searches, and it names no account or address. Two arms that search alike are refused. No test runs until one is started. ## Measured against hn.algolia.com `eval/compare.py` asks both the same queries, made from stories both hold: a story found again from three words of its title, the same with a typo, the story described in other words, and topics whose top ten a model grades blind to which engine found what. The results are in [`chloedb-hn/eval/results`](../../chloedb-hn/eval/results/), with the machine and the date they were measured on. `eval/instant.py` types six searches a character at a time and asks both at each keystroke, as their pages do. On 2026-11-16, while `crawl` was writing pages into the same cluster, the app's instant search took 10 ms at the median on the server (22 ms at the 90th percentile) against Algolia's 13.5 ms (34 ms), and its round trip from the same cloud machine 48 ms against Algolia's 199 ms ([the numbers](../../chloedb-hn/eval/results/instant-2026-11-16.json)). `eval/latency.py` times the same searches on both, each asked twice, as the server reports it and from end to end. On 2026-11-16 (a cloud machine against the deployment on DigitalOcean, four shards of 16 GB machines with the data on their own disks), the app's whole search took 100 ms at the median the first time a query was asked and 67 ms the second; hn.algolia.com's engine reported 17 ms, and its full round trip from the same machine was 243 ms against the app's 140 ms. `eval/plain.py` times the simplest statements on the same queries: BM25 of the titles alone took 15 ms at the median, as Algolia's 16.5, and the substring index with no ranking took 8 ms ([the numbers](../../chloedb-hn/eval/results/latency-2026-11-16.md)). --- # chloedb-arxiv: arXiv on ChloeDB > **A demo.** chloedb-arxiv shows what ChloeDB can do; it is not part of ChloeDB's releases or their promises. It is tested on a train of its own (the `Demos` workflow, `.github/workflows/demos.yml`), outside CI's required check, and the command center marks it as a demo ([compatibility](../compatibility.md#demos)). `chloedb-arxiv` is an explorer of every paper on arXiv: 3.25 million papers up to this week, the people who wrote them, the citations between them, about 1,100 topics found from what they say, techniques and domains, and a feed per reader that reads like a research newsletter. It is a program of its own, in Rust, that talks to chloedb-server over HTTP only, like [the crawler](crawler.md) and [the spreadsheets](sheets.md), and the command center shows it as an app. Everything it does is a query to ChloeDB, and each page shows the queries it ran and their times (**SQL** at the bottom right): - **Search by words and meaning at once.** Titles and abstracts are ranked by BM25 and by the meaning of their text (a static embedding model on the server, no API call), fused by rank (`rrf`), with typos corrected from the titles' own words and the query's synonyms (*RAG*, *retrieval augmented generation*). A query is read for what it says: a year (*since 2023*), a person (*by Yann LeCun*), a category (*cs.IR*), a kind (*surveys of*), an id. Facets (year, category, technique, domain, kind, people) come from the same query. A question is answered in a paragraph whose claims cite the papers they come from (`llm()` on the server). - **What to read next is ChloeDB's recommender.** Every paper a work cites is a reading event, 5.2 million of them, counted by `CREATE RECOMMENDER reading ON ax_events(...)`: what is read together, what is read after. A paper's **Read next** fuses those counts with PageRank from it over the citation graph (`ppr(ax_cites, :id)`) and the nearest papers by meaning. **For you** does the same from the papers a reader opens and keeps here, which are events of the recommender as soon as they are written. - **People, topics, techniques, domains, categories and venues each have a page**: papers a year, who leads, what rose, the people nearest a person in the coauthor graph (`ppr(ax_coauthors, :who)`), a topic summed up from its papers with each claim cited. - **What's rising**, over a span the reader picks (a month, three, six, a year or two): the techniques, domains and topics whose share of papers grew most against the span before, and only where the growth is beyond chance. - **Gaps.** Rising techniques that have barely reached a domain where the techniques most like them already work. Over the last three years a technique's papers are counted by domain and by area; its look-alikes are the techniques whose domain counts point the same way (cosine, with the domain in question left out), and its expected papers in a domain are its papers times the look-alikes' share of that domain. A gap is a domain with a quarter of the expected papers or fewer, where the technique and the domain both grow faster than the median, their areas overlap, and two of the three closest look-alikes use the domain more than arXiv does. A gap's page shows the few papers that already combine the two, what the look-alikes did in the domain, and the people who write on both. The list is about 320 `GROUP BY` queries, kept for twelve hours (`src/gaps.rs`). - **New topics.** Topics that barely existed and now hold hundreds of papers, born in the last year, two or three. A topic's papers are counted by month over five years (one `GROUP BY topic, month` for 150 topics at a time) and smoothed over three months; it was born in the first month its count reached a fifth of its peak, when the year before held an eighth of the peak or less, so an old topic that merely grew is not new. Each shows its curve with the month it was born, the papers that started it (its most cited from six months before to two after) and where it is now: rising, fading, at its peak or steady, from its share of arXiv's papers over the last six full months against the six before (`src/born.rs`). - **How techniques spread.** When each technique left the field it grew up in and reached the next, year by year, with the most cited paper of its first two years in each. A technique's papers are counted by primary category and year (one `GROUP BY pcat, year` each); it reached a category in the first year with five or more papers there and a twentieth of its best year there, two years running. It grew up in the earliest of the categories that hold a twentieth of its papers, and earlier uses of the same words in small categories, often another meaning (a *transformer* in power systems), are left out. Pick a field to see what reached it and when (`src/spread.rs`). - **Who coined it.** Ask *who coined chain of thought* (or *who first used*, *where does X come from*): the answer names the papers that made the term known, the most cited early papers that use it in the sense of its most cited papers (the sense is their titles' meaning, so a 1996 solar physics paper that says *chain of thought* is set apart as another sense), the literal first use, the year it took off, and when it reached each area. A term in use before arXiv began says so. - **What to cite.** Paste a draft's abstract and references (arXiv ids, DOIs, links or written-out titles): you get the papers others cite together with those references (the recommender's pair counts, normalised by both papers' counts) and those nearest to them by meaning, fused by rank, minus what you already cite, each with why it is there. On 15 papers of October 2026 (posted after the citation data, so their own lists are not in the counts), with a fifth of the references each one resolves hidden, it put 14 of the 72 hidden references in its first 30, against 7 for raw pair counts and the abstract, 3 for the abstract alone and none for PageRank over the citations. - **What is new here.** On a paper's page: the three earlier papers it is closest to (those it cites first, then the most cited of the 40 nearest by meaning posted before it), and what it adds to each and shares with them, written once by `llm()` and kept. - **Trends and the atlas.** Any words, compared as a share of each year's papers. The atlas places the topics on one map, near topics near, colored by arXiv area, sized by papers, a ring on those that grew most last year. - **Feeds you shape yourself.** A feed says what you want in your words: topics, papers like some you name, categories, techniques, domains, people whose new papers always go in, words that keep a paper out, kinds (surveys, benchmarks, datasets, tools), how many papers, how many of one topic, for whom, and how much code, citations and known authors count. The papers an issue would hold are SQL and answer as the knobs move (no model is called). **Write issue** then reads each paper in full from its HTML page on arxiv.org (its sections, figures and tables) and explains it, so the issue can be read without opening the papers: an opening on what the week's papers share, a contents list, and for each paper *in brief*, the problem, the approach, the results with their numbers, the takeaway, the limits, the terms a newcomer needs, the one or two figures that explain it best (copied from the paper, with what to notice in each) and its main results table. A paper without an HTML version is explained from its abstract. While it writes, a screen follows it: the papers it chose, which one it is reading, explaining or copying a figure of, how long each took and about how long is left, with a line to smile at while arXiv's 15 seconds between pages pass; the page can be left and the screen comes back when the feed is opened again (`GET /v1/jobs/` holds the writer's phase, paper and steps). Each issue has a page, a Markdown copy for a newsletter and an RSS feed. A feed set to write itself writes its issue every Monday from 06:00 UTC, so its RSS brings each week's issue to a feed reader with no one pressing a button (an hourly round writes the feeds due, longest waiting first, six at a time; a reader has three such feeds). A feed's owner can share it with a team by a link: whoever opens it can change the feed and write its issues with no sign-in, the feed stays the owner's, and *Stop sharing* makes the link stop working (`POST /v1/feeds//team`); the shorter styles of [a weekly research newsletter](https://recsys.substack.com/) (a paragraph a paper, brief, bullets) remain. - **Standing questions.** Ask once (*tell me when someone uses diffusion models for weather forecasting*) and every new paper that answers it comes to you, on a page and in an RSS feed. Every hour the papers of the last week are searched for the question (all its words and most of them by BM25, and its meaning, fused by rank), and the fifteen closest not read for it yet go to the model in one call (`llm()` on the server), which says for each whether it does what the question asks and why. Every verdict is kept, so a paper is read once per question and an hour with nothing new calls no model; a new question reads the closest papers of the last month at once. A reader keeps ten questions (`src/watch.rs`). - **People to work with.** On a person's page: the people whose work of the last four years is nearest theirs in meaning but who have never written with them or with anyone they write with, with the techniques each would bring, their papers nearest the person's work, and the shortest way to them in the coauthor graph (through people with the fewest papers, since a name with thousands is many people sharing it). Their eight newest and eight most cited papers of the last six years are one text; the 500 nearest papers are read and each author scores by their papers' ranks there (`src/collab.rs`). - **Who could review it.** On a paper's page, or for a title and abstract pasted in with its authors: the people who know its subject (their papers among the 500 nearest to it in the last six years), with eight papers or more and one in the last three years, its authors and everyone who wrote with one of them in the last four years left out and named, each with their nearest papers and seniority. - **Rising people**, on the Rising page: people whose first paper is at most five years old, by the citations to their papers of the last one or two years (two cited papers or more, of 20 authors or fewer), by area. - **Where someone's work went.** A person's page shows their most used techniques year by year as a river, each band a technique and its width their papers using it that year. - **Code and data.** The share of papers that link their code, year by year, in all of arXiv or an area; the repositories behind the most papers; the techniques whose papers share code most and least; the newest and most cited papers with code and those with models or data on Hugging Face (`src/code.rs`). `has:code` in a search keeps only papers with code. - **Labs.** The organisations behind 2.5 million papers (78%), from the authors' affiliations in [OpenAlex](https://openalex.org)'s public snapshot: the labs with the most papers of the last twelve months, those whose share of the papers grew most, who is moving into a technique (a button on its page), and a page per lab with its papers a year, what it is known for and moving into, who writes its papers, the labs and countries it writes with. A paper's page names its organisations. OpenAlex names organisations for fewer of the newest papers, so growth is a lab's share, not its count (`src/labs.rs`). - **Likely classics.** Recent papers that look, in their first months, like the papers that went on to be the most cited 1% of their year and area, by area and by how recently they were posted, each with its chance against the usual 1% and what weighed most. A logistic regression per window (no citations yet, or the arXiv papers citing it in its first 3, 6 or 12 months) is trained on 2016 to 2021 on what was known then: early citations, the authors' earlier papers, how fast its category and techniques grew, team size, code and kind. On 2022, which it did not see, 33% of its top 1% with six months of citations were in the real top 1%, against 18% for ranking by early citations and the authors' record (`tools/classics.py`, which writes `ax_classics` and the models' card; `GET /v1/classics?area=&days=&sort=`). - **For and against.** State a claim (*LLMs can self-correct their reasoning without external feedback*) and get the papers whose results support it, those that contradict it and those that find it holds only in some settings, each with the sentence of its abstract that shows it. The 40 papers nearest the claim are found by the words of its subject (all of them, and all but one) and by its meaning, fused by rank, and the model reads their abstracts against it ten to a call, all at once (`llm()` on the server). A side counts only with a sentence that is in the abstract word for word (spacing, case and punctuation aside), and the answer is kept, so a claim asked again calls no model (`src/claims.rs`). - **Explain at my level.** A paper's page explains it for a student, a practitioner or an expert, each hard term of its abstract with its meaning at that level, the paper the field credits with the term (the earliest of its most cited papers on arXiv, as *Who coined it* reads it, or none when the words were in use before arXiv began) and a link to the full answer. The level is kept in the browser: topic summaries are written for it and a new feed's audience follows it. Each explanation is kept per level (`GET /v1/explain/?level=`). - **From a reading list to related work.** Name up to 30 papers (ids or links, a reading list, or your library) and get their BibTeX at once, made from their rows with no model (authors surname first, the venue when one is known, the arXiv identifiers; keys like `vaswani2017attention`), and a related-work section in LaTeX written by the model from their abstracts, grouped by theme under `\paragraph{}` and citing every paper by its key. A citation of a key not in the list is taken out, a paper left uncited is named, and the section is kept. Given a sentence on your own paper, each paragraph ends with how it differs (`src/related.rs`). - **It stays current.** `--live` reads the new and revised papers from arXiv's OAI-PMH interface every six hours, three seconds between pages, and a new paper goes to the topic whose centroid its text is nearest. ## Where the data comes from - **Papers**: arXiv's metadata ([librarian-bots/arxiv-metadata-snapshot](https://huggingface.co/datasets/librarian-bots/arxiv-metadata-snapshot), CC0), and the weeks after the snapshot from [OAI-PMH](https://info.arxiv.org/help/oa/index.html). - **Citations**: Crossref's references of arXiv papers' published versions ([cometadata/crossref-arxiv-citations](https://huggingface.co/datasets/cometadata/crossref-arxiv-citations)). A citing work that is an arXiv paper, by its DOI, makes an edge of the citation graph; every citing work is a reader of the recommender. - **Topics**: `tools/topics.py` clusters every paper's embedding into 1,500 topics with k-means fitted on 300,000 older papers and 250,000 of the last two years (so recent research is not folded into a few catch-all topics), drops the topics fewer than 150 papers would join (`--min-papers`; 1,093 remain), places each paper in the nearest of its ten closest topics with a small pull toward topics that hold its primary category, puts each topic in one of 17 fields (arXiv's areas, by its papers' categories), names each from its terms and its most cited titles, and places them on the map. A topic that is mostly an old one keeps its id (`--keep`), and its name when its centroid has not moved (`--labels`). New papers are placed by the same rule in `src/live.rs`. - **Organisations** of each paper come from [OpenAlex](https://openalex.org)'s public snapshot (CC0) on S3, read without a key: `tools/oa_orgs.py` reads only the columns it needs (whether a work is on arXiv, its arXiv link, its authors' institutions) from the 744 GB of Parquet files, about 30 GB, and `tools/labs.py` joins them with the papers' rows into `ax_lab_papers` and `ax_labs`. - **Affiliations** for a feed's papers are read from each paper's HTML page on arxiv.org, once a paper and fifteen seconds apart, as arXiv's `robots.txt` asks. The app never reads arxiv.org's search or API pages. ## Run it Build both programs, prepare the rows (a few GB of downloads), then start chloedb-arxiv with servers of its own: ```bash (cd chloedb-server && cargo build --release --bin chloedb-server) cd chloedb-arxiv && cargo build --release target/release/chloedb-arxiv prepare --snapshot ~/arxiv/snapshot --cites ~/arxiv/crossref/all.parquet --out ~/arxiv/rows python3 tools/topics.py --rows ~/arxiv/rows --name target/release/chloedb-arxiv prepare --snapshot ~/arxiv/snapshot --cites ~/arxiv/crossref/all.parquet --topics ~/arxiv/rows/topics.tsv --out ~/arxiv/rows target/release/chloedb-arxiv serve --local ./arxiv-search --local-graph ./arxiv-graph --rows ~/arxiv/rows --server-bin ../chloedb-server/target/release/chloedb-server ``` Open `http://127.0.0.1:7700` and go to **Apps → arXiv**. `--only cs.,stat.ML` on `prepare` keeps a slice, which fits on a laptop. ### Two servers, split by job The papers, people, topics and their words live on one chloedb-server (the **search server**, `--strata`); the reading events, the recommender, the citation and coauthor graphs, what readers keep, and the model calls live on another (the **graph server**, `--graph`). A recommender and a graph walk are fastest with their rows in one database (through a coordinator, a walk takes a round of reads over the shards per hop), so these tables are not sharded; splitting by job gives each server a machine of its own instead. Without `--graph`, one server holds everything. The graph server holds a row per paper and per person (`ax_nodes`) for the walks to rank. ```bash chloedb-arxiv serve --strata http://search:7700 --graph http://graph:7700 --key "$CHLOEDB_KEY" --token "$ARXIV_TOKEN" --listen 0.0.0.0:7860 --live chloedb-server --app arxiv=http://arxiv-app:7860 ... # the command center lists it ``` `deploy/k8s.yaml` and `deploy/app.yaml` run it on Kubernetes: two nodes of 16 GB, a server on each, and the app beside the graph server. Each database is on its node's own SSD rather than a network volume, the graph database (3.6 GB) is read into memory after a start, and the search server allows a GROUP BY of two million groups, since "who writes most" on a broad subject groups every author of tens of thousands of papers. `deploy/backup.yaml` takes a checkpoint of each server a night (`POST /v1/admin/checkpoint` into `--backup-dir`, hard-linking what the previous one has) and keeps the two newest. With `--public` the app serves the page at `/` to anyone, reads and a reader's own library and feeds, within `--per-minute` requests a minute from one address; https://arxiv.chloetech.ai is this, through a web proxy. `--answer-model` names the model of summaries and TL;DRs, and `--issue-model` the one that explains an issue's papers from their full text (both are called through the graph server's `llm()`, which holds the provider's key); `--llm-per-day` caps new calls a day, and everything written is kept, so it is written once. arXiv asks programs to read a page every 15 seconds, so the first issue of ten papers takes about ten minutes; a page and its figures, once read, are kept (`ax_notes`, `ax_figures`). ## The tables | table | server | what | |---|---|---| | `ax_papers` | search | a paper: title, abstract, people, categories, dates, techniques, domains, kinds, counts, topic, and `emb` (its text embedded by the server) | | `ax_authors` | search | a person: papers, citations, h-index, first and last paper, categories and techniques | | `ax_topics`, `ax_concepts`, `ax_cats`, `ax_venues` | search | topics, techniques and domains, categories, venues, with counts by year | | `ax_complete` | search | what the search box completes: phrases of titles, people, techniques, categories | | `ax_nodes` | graph | the graphs' nodes: every paper's id and every person's key | | `ax_cites`, `ax_coauthors` | graph | edges: who cites whom, who writes with whom and how often | | `ax_events` | graph | reading events: a citing work's references, and what readers open and save here | | `reading_*` | graph | the recommender's counts (`CREATE RECOMMENDER reading`) | | `ax_feeds`, `ax_issues`, `ax_notes`, `ax_answers`, `ax_library` | graph | feeds, their issues, the papers' pages as read and what the model wrote, readers' libraries | | `ax_figures` | graph | the figures issues show, each image copied once from the paper's page | | `ax_labs`, `ax_lab_papers` | search | each organisation with its papers in all, in the last twelve months and the twelve before; each paper's organisations with the columns a lab page counts by | | `ax_watches`, `ax_matches` | graph | readers' standing questions, and each paper read for one with the model's verdict and why | ## Experiments The Experiments app ([its README](../../chloedb-experiments/README.md#real-sites)) can study this site's real search. It puts AI agents, playing people written from the papers, on the search with some of it changed. The app takes experiments only when it is started with a token for them: ```bash chloedb-arxiv serve ... --experiments-token "$ARXIV_EXPERIMENTS_TOKEN" --experiment-index v2=ax_papers_v2 chloedb-experiments serve ... --source arxiv=app:http://arxiv-app:7860 # with CHLOEDB_SOURCE_ARXIV_TOKEN=$ARXIV_EXPERIMENTS_TOKEN ``` The token (`--experiments-token`, or `CHLOEDB_ARXIV_EXPERIMENTS_TOKEN`) opens only `/v1/experiment`, with the same routes as [chloedb-hn's](hn.md#experiments): the site, a search with knobs, a paper (`/v1/experiment/item/:id`) and a sample of papers, well cited and ordinary, across the years. These routes read, and write nothing. | group | knobs | |---|---| | Query understanding | `understand`: "by hinton", "since 2020", "cs.CL", "surveys", "newest" and questions in a sentence become filters and sorts | | Retrieval | `typos`, `synonyms` (rag, llm, gnn and the field's others), `meaning`, `authors` (papers whose authors the words name are candidates) | | Ranking | `cites` (the exponent of citations + 1), `recency`, `meaning_weight`, `phrase`, `abstract_weight`, `author_weight`; `rank`, a whole `ORDER BY` expression over `ax_papers` in place of them | | Blending | `max_per_category`, `max_per_author` (a primary category's or a first author's papers past this many move below the others), `fresh` | | Index | `index`: `main`, or an index named by `--experiment-index NAME=TABLE` | ## Tests `tests/cluster.rs` starts two chloedb-servers through `serve --local --local-graph`, loads a small made-up arXiv into them (embedded by the `hash:512` model, so nothing is downloaded), and checks every page: search, a paper's citations and what to read next, a person, a topic, the atlas, events becoming For you, a feed's preview, what to cite for a draft, people to work with, reviewers for a paper and for a pasted abstract with its authors left out, a standing question kept, listed, read as RSS and dropped, and that gaps, new topics, spread, rising people, code, labs and trends answer. ```bash cd chloedb-arxiv && cargo test --profile ci ``` --- # GitHub Explorer: GitHub's public history on ChloeDB `chloedb-gh` is an app of a ChloeDB cluster built on [GH Archive](https://www.gharchive.org): every public event on GitHub since 12 February 2011, about ten billion of them, in a cluster of four shards on machines with 8 GB of memory each. It finds repos by what they do, says why a repo's stars moved, what people use instead, who keeps a repo going, what is rising and what to star next. It is a client of chloedb-server over HTTP, as the crawler and the spreadsheet app are, and the command center shows it as the app `gh` (`chloedb-server --app gh=URL`). Every request needs the token the command center's app proxy sends, unless the app runs with `--public`: then it serves its page at `/` and the page's reads to anyone, at most `--per-minute` (600) requests a minute from one address and `--at-once` (8) answered at once, the rest waiting for a turn. Readers never send SQL: each page asks its own statements. It runs that way at https://gh.chloetech.ai. ## The pages | page | what it shows | from | |---|---|---| | Search | repos by what they do: the words of their name, description and topics, and the meaning of the query against a vector of each repo, ranked by both and by stars | `gh_repos` (`MATCH`, `bm25`, `similarity`) | | A repo | its stars month by month, the days and months they jumped (five and four times the usual) with the releases of those months, and its posts on Hacker News, its vital signs (work this year against last, merged pull requests, how many people do half the work, days since the last), who keeps it going, the repos that do the same job (by meaning and by the stargazers they share), what its stargazers also starred, and the names it had | `gh_events`, `gh_stars`, `gh_repo_months`, `gh_repos`, `gh_repo_names`, `gh_repo_people`, `gh_people` | | A person | what they did, year by year, where they work and what they starred lately (public activity only) | `gh_people`, `gh_events`, `gh_stars`, `gh_actors` | | Rising | the repos whose stars over the last days most outran the four weeks before, and why | `gh_stars_daily` | | Trends | each language's and topic's share of the stars, year by year; growing and shrinking | `gh_lang_months`, `gh_topic_months` | | Ask | a question in a sentence, turned into one statement by patterns, no model ("fastest growing rust repos this year", "who works on rust-lang/rust") | all of them | | For you | repos to star next from a login's stars and work: what the people who starred the same repos starred | `gh_stars`, `gh_people` | | Weekly | the week's rising repos, new ones and releases of the big ones | `gh_stars_daily`, `gh_events` | | How it works | the tables, their rows and each shard's share, and what each page asks | every table | A repo's page comes in two answers: `/v1/repo//` has everything but the alternatives and what its stargazers also starred, and `/v1/repo-more/` brings those two once the rest is shown, since its stargazers' stars take seconds for a big repo. Each answer carries the statements it ran and their times, which the page shows under SQL. ## The data GH Archive keeps each hour of GitHub's public event stream as a gzipped JSON file. Its formats changed over the years, and the load reads them all: - From February 2011 to February 2012 events carry the repo's and the person's ids. - From about March to September 2012 (the timeline format) they carry neither: a repo is `owner/name` and a person a login. - From October 2012 to 2014 repos have ids and people only logins. - From 2015 on, both have ids. The years without ids get them from the years with: the logins and names of 2011-2012 and 2015-2016 (`--logins`, `--names`), the id that held a name first winning; a login or a name no later event explains gets a negative id of its own. From October 2025 GitHub's events no longer carry a repo's description, language or topics, so repos made since have none in the archive; `api-meta` fills them from GitHub's search API (below). Only what the events say publicly is kept: ids, logins, repos, kinds of event and times. The old format's `actor_attributes` (names and email addresses) is never read. ## The tables | table | rows | placed by | |---|---|---| | `gh_events` | every event: `t` (seconds), `kind`, `repo`, `actor`, `n` (commits of a push) | `shard_by repo`, sorted by repo in each segment | | `gh_stars` | every star of a kept repo again, with the person as a `KEYWORD` (`actor_k`) too: an `IN` of a thousand people reads their own lists of rows, where the events in repo order would be read whole | `shard_by repo` | | `gh_stars_daily` | stars and forks of each repo each day | `shard_by repo` | | `gh_repos` | each repo with two stars or more, keyed by its id: latest name, what the events (and GitHub's search, for repos with 50 stars or more) last said of it, its stars counted from the events and GitHub's own count, and for repos with ten stars or more (the ones searched by meaning) a vector of what it does, embedded from `etext`, their name, description and topics: a shard's vectors and graph then fit an 8 GB machine | key `repo` | | `gh_vec` | the 3.3 million repos of `gh_repos` with a vector, with only their stars and language beside it, in a cluster of their own (`deploy/vec.yaml`) that the app's searches by meaning go to (`--vec`): there each part's quantized vectors and graph, about 500 MB, are locked in memory, where beside the events a new search read them from the SSD (1 to 1.5 s; 40 to 110 ms in a cluster of their own) | key `repo` | | `gh_repo_names` | every name a repo had, with when it was first seen | `shard_by repo` | | `gh_people` | each person's events summed, a row a person a shard (`part`, which the page adds up): how many, their stars, their work, by kind, by year and their 24 busiest repos with the first and last work in each, so a person's page reads four rows where its statements over `gh_events` read a shard's whole `actor` column (about 30 s); beside `gh_vec`, in the same database | `shard_by part`, sorted by actor | | `gh_repo_people` | the 30 people who did the most work in each repo of `gh_repos`, with their first and last work there | `shard_by repo` | | `gh_actors` | each person's latest public login | key `actor` | | `gh_repo_months` | what happened in each repo each month: stars, forks, pushes, commits, pull requests opened and merged, issues, comments, releases, people | `shard_by repo` | | `gh_lang_months`, `gh_topic_months` | the same summed by language and by topic, a part a shard (`part`), which queries add up | `shard_by part` | Rows are placed on shards as chloedb-server places them (a key's slot is xxh3-64 of its typed encoding modulo 4096, slot `s` on shard `s * n / 4096` of a new cluster), so each shard's database is built offline, on its own machine, and the cluster's coordinator finds every row where its slot map says it is. ## The load The load runs on the cluster's own machines (`chloedb-gh/deploy/work.yaml`: a pod a node, its folder on the node's SSD, `/work`): 1. **`chloedb-gh prepare --from 2015-01-01 --to DAY --part N/4 --out /work/out`** on each node, every fourth day: downloads each hour, keeps the events, dedupes a day at a time, and writes Parquet rows a table, a shard and a day (`out/TABLE/sS/DAY.parquet`: events, stars, names, actors, meta). A day done is written down (`out/done/DAY.json`) and skipped when it runs again. A worker holds one day in memory (about 1 GB for the busiest days of 2022), so 8 GB machines run three at a time (`--jobs 3`). 2. **The years before 2015**, in the order that gives each its ids: 2011-02-12 to 2012-02-29, then its actors and names to every node (`deploy/pull.py --shard all --tables actors,names`), 2012-10-01 to 2014-12-31 with `--logins` and `--names`, its names to every node, and 2012-03-01 to 2012-09-30. 3. **`chloedb-gh api-meta --out /work/out`**: what GitHub's search API says today of every repo with 50 stars or more (about 876,000), 100 repos a call: the repos made since October 2025 first. Search answers at most 1,000 repos a query, so the walk splits bands of stars, then days of creation, until each part has fewer. Without a token it makes at most 10 calls a minute from one address (a call every 7 s, about a day for the walk); with `GITHUB_TOKEN`, 30. Its rows are `meta` and `names` rows (`api-*.parquet`), which `reduce` reads after the days'. 4. **Each node takes its shard's rows** from the others (`deploy/pull.py --shard N --into /work/in`; each node serves `/work/out` with a list a shard). 5. **`chloedb-gh reduce --input /work/in --input /work/out --shard N`** sums a shard's rows into one row a key (`gh_repos`, `gh_repo_names`, `gh_actors`), months by repo, language and topic, and the star rows of `gh_stars`; only repos with `--vec-min-stars` (10) or more get the `etext` their vector is made of. Once every node has its shard's rows, each deletes its rows of the other shards, so that a shard's rows, its sums and its database fit the node's disk. 6. **`chloedb-server import`** loads each table into the shard's database, with the server of the cluster's image (`--schema chloedb-gh/deploy/schemas/TABLE.json`), after `reduce` and not beside it: the two together go past an 8 GB machine. A table's files go in as one folder (the node's own and the ones it pulled, hard-linked together): an import loads an empty table in bulk from its first folder only, and a second folder goes through the write path, many times slower. 7. **Each shard's slot map** goes beside its database before its server first starts, as `gh.chloedb.slots`: `{"shard": N, "since": 1, "map": {"epoch": 1, "shards": [[[0, 1024]], [[1024, 2048]], [[2048, 3072]], [[3072, 4096]]]}}`, the map its rows were placed by. A shard that a coordinator gives its first map reads the key of every row of every table to check that it belongs there, and on 2.8 billion rows that runs an 8 GB machine out of memory; a shard that already holds the map takes the coordinator's next one without the check. Then `deploy/k8s.yaml` starts a chloedb-server a node on its database (`/mnt/chloedb/gh/db`), the coordinator over them and the app (the shards without the embedding model, `--no-fetch-models`: with it, each start reads the 3.3 million repos that have no vector, to embed them, which takes minutes and more memory than the machine has; the coordinator embeds the words of a search itself, and a write to `gh_repos` brings its vector), and `deploy/backup.yaml` writes a checkpoint of each shard every night and copies the newest off the node to a DigitalOcean volume. `deploy/vec-build.yaml` builds each node's part of `gh_vec` beside its running shard (the repos of its `reduce` output that have an `etext`, imported with the shard's server and model, and the slots file of its part: about seven minutes a node), and `deploy/vec.yaml` serves the four parts, `gh-v0` to `gh-v3`, each beside its shard in a container of its own with no scheduled scrub (reading a part's 4.5 GB against its checksums every day pushed the vectors out) and `tools/pin` beside the server, which locks the part's quantized vectors and graph in memory (`mlock`, about 500 MB: a container of their own was not enough, since after half an hour without searches the node's reclaim took them anyway, and a new search went back to 0.4 to 1 s), and their coordinator `gh-vec`, which embeds the words of a search; the app runs with `--vec http://gh-vec.strata.svc:7700`. Without `--vec`, it searches `gh_repos` by meaning. `deploy/people-build.yaml` adds `gh_people` and `gh_repo_people` to a copy of each part, `gh-side.chloedb`, on a 20 GB volume of its own a node (`gh-side-N`, mounted at `/side`), which `deploy/vec.yaml` then serves: on each node `chloedb-gh people` reads the shard's events in 24 passes, a 24th of the people each (a pass holds a shard's sums for about 2.3 million people in memory, 1.4 to 1.8 GB; 12 passes ran a 3 GB container out, and one of 16 did), `chloedb-gh repo-people` keeps each repo's 30 busiest people, and the server imports both into the copy, since an import needs the database closed (the passes take about 32 minutes a node). With the copy of the part (4.5 GB) and the pass files (3.2 GB), a shard's summaries (2.3 GB once imported) need about 10 GB, where each node's SSD has 4 to 6 GB above the kubelet's eviction line (15% free), below which it evicts the node's pods, the shard among them. Without the two tables the app reads `gh_events` for the same answers. ## Run it on one machine A few days of the archive into one database: ```bash cd chloedb-gh && cargo build --release G=target/release/chloedb-gh $G prepare --from 2025-09-15 --to 2025-09-21 --shards 1 --out gh-rows $G reduce --input gh-rows --shard 0 --shards 1 --out gh-red S=../chloedb-server/target/release/chloedb-server; SC=deploy/schemas $S fetch-model potion-retrieval-32M # the vector of what each repo does $S import --db gh.chloedb --schema $SC/gh_events.json --table gh_events gh-rows/events/s0 $S import --db gh.chloedb --schema $SC/gh_stars_daily.json --table gh_stars_daily gh-rows/stars/s0 for t in repos stars repo_names actors repo_months lang_months topic_months; do src=gh-red/$t/s0; [ -e $src.parquet ] && src=$src.parquet $S import --db gh.chloedb --schema $SC/gh_$t.json --table gh_$t $src done $S --db gh.chloedb --listen 127.0.0.1:7700 --max-groups 2000000 & $G serve --strata http://127.0.0.1:7700 --listen 127.0.0.1:7880 ``` `serve` without `--token` answers anyone on the machine; `CHLOEDB_GH_UI_DIR=chloedb-gh/ui` reads the view from disk without a rebuild. ## Against GitHub's search `chloedb-gh/bench/` holds 99 searches written as a person looking for a kind of project would type them ("terminal file manager", "self-hosted photo and video backup like google photos"), each with the repos that answer it, written before either engine's answers were seen. `search_vs_github.py` asks GitHub's repository search (its default best-match order, within its rate limit) and the explorer's `/v1/search` the same words, compares repos by their GitHub ids (a repo renamed since is the same repo), and scores the first ten: whether an answer is first, whether one is in the ten, and MRR@10. Six searches are close to ones the ranking was compared on while it was written; the report gives the scores with and without them. --- # chloedb-img: pictures searched by what is in them > **A demo.** chloedb-img shows what ChloeDB can do; it is not part of ChloeDB's releases or their promises. It is tested on a train of its own (the `Demos` workflow, `.github/workflows/demos.yml`), outside CI's required check, and the command center marks it as a demo ([compatibility](../compatibility.md#demos)). `chloedb-img` is an explorer of [PD12M](https://huggingface.co/datasets/Spawning/PD12M): 12.4 million pictures that are in the public domain or under CC0, from museums, libraries, archives and Wikimedia Commons, each with a caption written by a model and the vector OpenAI's CLIP (ViT-L/14) gives it. It is a program of its own, in Rust, that talks to chloedb-server over HTTP, like [the arXiv explorer](arxiv.md), and the command center shows it as an app. It embeds words and photos itself, with ChloeDB's CLIP (`clip-vit-large-patch14`, feature `vision`), so the server it searches is the stock build, with no model. Every search is one statement over the pictures' table, `ORDER BY similarity(clip, :v)` on its HNSW index, with the filters a `WHERE`: - **Search by what is in a picture.** *A lighthouse in a storm*, *botanical drawing of a fern*, *children on a beach in the 1920s*: the words are embedded by CLIP's text tower and meet the pictures' vectors. Kind (photo, old photo, painting, print, drawing, map, text page, object, illustration), source, licence, shape and size are facets of the closest 500, and filters of the query. - **Search with a photo of your own.** It is embedded and thrown away; nothing is kept. The answer is the closest pictures, the closest photos and the closest paintings, prints and drawings. - **Search by a detail.** Draw a box on a picture and get the pictures that look like what is in it. - **More like this, less like that.** Mark pictures up or down and the query moves toward and away from them (Rocchio); *strongly* moves it twice as far. - **A picture plus words.** *This harbour, but at night*: the picture's vector and the words' added with a weight the reader slides. - **Between two pictures.** The path from one picture to another in steps along the sphere between their vectors (slerp), the closest picture at each step. - **More variety.** Results re-ranked so that near-copies do not fill a page (maximal marginal relevance). - **Another medium.** A picture's subject as photos, paintings, prints or drawings: its vector plus its subject in words, kept to that medium's kinds. - **Colors.** Pick up to three colors; each picture whose thumbnail has been made has a histogram of its colors in Lab (144 bins, `img_colors`), and a color search is a vector search on it. The page says how many pictures have colors so far. - **A map of themes.** 42 themes found by k-means over the vectors (ships and harbours, botanical plates, medieval manuscripts, old maps and views, moths, ...), placed so that near themes are near, each with the pictures nearest its middle; a theme's page is its pictures in order of closeness to its centre. - **Every picture's page** shows it large, its licence and source with a link to the original and, for a picture from Wikimedia Commons, its page there (found by the file's SHA-1, since PD12M's records do not give it), with the pictures nearest it. ## Where the data comes from - **Pictures**: PD12M's records and CLIP vectors (Parquet and NumPy files on Hugging Face), and the images themselves from PD12M's public bucket on S3. Thumbnails are made the first time a picture is shown and kept on disk: one 400 pixels high for the grids, and one up to 1,600 pixels for a picture's page, made only when that page is opened. The colors and the Commons page are found in the same pass. - **Kinds and themes**: `prepare` names each picture's kind by the closest of a few CLIP sentences (*a photograph*, *an old black and white photograph*, *an oil painting*, ...) and its theme by k-means of a sample of the vectors (spherical, seeded by k-means++ with a fixed seed, so the same slice gets the same themes). Each theme is named by the closest of a list of subjects, or by `--names` (`data/theme-names-1m.json` names those of the first million). `--themes-from` keeps the themes of an earlier prepare (their centres, names and places on the map) and places every picture in the nearest, so a larger slice keeps a smaller one's map. - **Licences**: every picture is shown with its licence as PD12M gives it (CC0 or the Public Domain Mark) and its source, linked back to where it came from. ## Run it PD12M's first million pictures need the first ten Parquet files and the first vector file; CLIP's weights (1.7 GB) come from `chloedb-server fetch-model clip-vit-large-patch14`. ```bash chloedb-img prepare --data ~/pd12m --rows 1000000 --models ~/.local/share/chloedb/models --out ~/img-prepared --names chloedb-img/data/theme-names-1m.json chloedb-img serve --local ~/img-db --models ~/.local/share/chloedb/models --cache ~/img-cache # starts a chloedb-server with img as its app chloedb-img load --data ~/pd12m --prepared ~/img-prepared --rows 1000000 # about three minutes for a million ``` With `--public` the app serves the page at `/` to anyone, within `--per-minute` requests, `--photos-per-minute` photos and details and `--thumbs-per-minute` new thumbnails a minute from one address. There is no SQL from the page and no MCP tools. `deploy/k8s.yaml` runs it on Kubernetes: one 16 GB node with the server and the app, the database and the thumbnails on the node's own SSD, and beside the server `chloedb-gh-pin` (`chloedb-gh/tools/pin`), which locks the vectors' 8-bit codes and graph in memory: over 5 million pictures the vectors (15 GB in float32) no longer fit in the node's memory, and a search that reads its codes from the disk takes seconds rather than tenths of one. `--warm-per-theme` makes the thumbnails of the pictures nearest each theme's middle at start, and `--warm-first N` those of the first N pictures, so that colors cover more of them. ## The tables | table | what | |---|---| | `img_pictures` | a picture: its file, title (the caption's first clause), caption, source, licence, size, shape, kind, theme, and `clip`, its CLIP vector (HNSW) | | `img_themes` | a theme: its name, size, place on the map, the pictures nearest its middle, the themes nearest it and its centre | | `img_colors` | the colors of each picture whose thumbnail was made: its palette and a 144-bin Lab histogram as a vector | | `img_links` | a picture's page on Wikimedia Commons, when one was found | ## Tests ```bash cd chloedb-img && cargo test --profile ci ``` They cover titles from captions, licences, shapes and sizes, colors in Lab and color search, k-means and theme names, filters as parameters, and which routes are public. Searching needs CLIP's weights and PD12M, so CI runs no server for it. --- # chloedb-sound: Sound Explorer on ChloeDB > **A demo.** chloedb-sound shows what ChloeDB can do; it is not part of ChloeDB's releases or their promises. It is tested on a train of its own (the `Demos` workflow, `.github/workflows/demos.yml`), outside CI's required check, and the command center marks it as a demo ([compatibility](../compatibility.md#demos)). `chloedb-sound` keeps free sounds in ChloeDB and finds them by how they sound: field recordings, effects and music that anyone may reuse with credit, each with its author, licence and a link back to where it came from. It listens with CLAP (`clap-htsat-unfused`), which puts sounds and sentences in one space of 512 dimensions, run by chloedb-server itself (built with `--features audio`). - **Search by how it sounds.** "rain on a tin roof", "a crowd cheering far away", "a cello played softly": the words are heard through CLAP's text tower and ranked against every sound's vector, fused with BM25 over its title, tags, labels and description (`0.75 * tmm(similarity(emb, :v)) + 0.25 * tmm(bm25(words, :q))`). *Rank by* picks one of the two. Facets count the source, the kind, the licence and the length of the best 200. - **Steer it.** *More like this* and *Less like this* on any result move the search towards and away from that sound's vector; *not* takes words to move away from ("no thunder"); the chips (heavier, lighter, drier, wetter, closer, farther, busier, calmer) move it between two sentences. Each is shown as a chip of what was understood. - **Moments inside long recordings.** Every sound is cut into ten-second windows every five seconds, each with its own vector (`au_moments`), so a search can land 7:40 into a half-hour dawn chorus. *Moments* returns the best moment of each sound (`DISTINCT ON (sound)`) and the other good moments of each. - **What is in it.** A sound's page shows, along its waveform, which of FSD50K's 200 labels each moment sounds like (each moment's vector against the labels', `au_labels`, embedded by the server from a sentence each). - **Listen.** Record ten seconds with the microphone or drop a file, and find what it sounds like: the clip is embedded by `POST /v1/embed` and searched like any sound; a moment matched above 0.95, or above 0.9 and at least 0.03 ahead of the next recording's, is called the same recording. - **Scenes.** Describe a place ("a rainy café by a harbour") and get its layers: the sounds nearest the words and each part of them, one for each thing they sound like most (their best label by sound), played together with a level for each. - **Drift.** From one sound to another in steps, each step the sound nearest to a point on the way between their vectors (a slerp). - **Map.** Every sound placed by how it sounds (t-SNE of the vectors, made by `tools/prepare.py`), or by where it was recorded when its source says. - **Credit and licences.** Each sound carries its title, author, source page and licence, shown on the page and copied as one line ("“Title” by author, source (page), licence (link)"). Only CC0, public domain, CC BY, CC BY-SA and the Free Art License (and the GFDL on Commons) are kept: no non-commercial, no-derivatives or Sampling+ sound is loaded. Like [the crawler](crawler.md) and [Hacker News](hn.md), it is a program of its own, in Rust, that talks to chloedb-server over HTTP only, and the command center shows it as an app (**Apps → Sound Explorer**). Previews are MP3 files on the app's disk, served by it with HTTP ranges, since a cluster's coordinator keeps no media files. ## Run it Build the server with CLAP and the app, download the sounds, make the rows, and start the app with a server of its own: ```bash (cd chloedb-server && cargo build --release --bin chloedb-server --features audio) cd chloedb-sound && cargo build --release python3 -I tools/fetch.py fsd50k ~/sounds/fsd50k --clips 2500 python3 -I tools/fetch.py fma ~/sounds/fma --shards 9 python3 -I tools/fetch.py commons ~/sounds/commons --files 300 --min-seconds 20 target/release/chloedb-sound serve --local ./sound-data --server-bin ../chloedb-server/target/release/chloedb-server & python3 -I tools/prepare.py --fsd50k ~/sounds/fsd50k --fma ~/sounds/fma --commons ~/sounds/commons --out ./sound-rows target/release/chloedb-sound load --rows ./sound-rows ``` `serve --local DIR` starts a chloedb-server with its database in `DIR`, makes the tables and the labels (the server fetches CLAP, 600 MB, the first time a field names it), and lists the app as `sound`; open `http://127.0.0.1:7700` and go to **Apps → Sound Explorer**. `tools/prepare.py` decodes each sound with ffmpeg, writes its preview and waveform, sends each ten-second window to the server's CLAP (`POST /v1/embed` through `au_labels`' model, about three windows a second on four cores with AVX-512), and writes the rows; it needs ffmpeg and numpy, and a run that stops goes on where it was. `--concurrency` sounds are made at once, and `--embed URL,URL,...` shares the windows among several servers with CLAP (each window to the one with the fewest at work). Of more than 4,000 sounds the map is a t-SNE of 4,000 of them, and each other sound is placed among the ten it sounds most like. Give `serve` the rows with `--rows` and it loads them when the tables are empty, and plays the previews from their `audio/` folder (`--audio` for another). The three sources, and what is kept of each: | source | what | licences kept | |---|---|---| | [FSD50K](https://zenodo.org/records/4060432) | Freesound clips labelled by hand with 200 classes of the AudioSet ontology; the evaluation set's, the same number of each class, or with `--split both --clips 0` every clip of both sets (43,379 of 51,197 qualify) | CC0, CC BY | | [Free Music Archive](https://github.com/mdeff/fma) | 30-second clips of `fma_small`, or with `--set large --shards 0` of all of `fma_large` (9,918 of its 105,024 tracks qualify), with their genres | CC BY, CC BY-SA, CC0, Free Art License (about one track in ten) | | [Wikimedia Commons](https://commons.wikimedia.org/wiki/Category:Sounds_by_type) | sounds under its sound categories, with descriptions and, for some, a place | CC0, public domain, CC BY, CC BY-SA, GFDL | Freesound's own archive is not used: its terms do not allow a copy of it on another site. Against a server or a cluster that runs elsewhere, load into it and give the server the app: ```bash chloedb-sound init --strata http://coordinator:7700 --key "$CHLOEDB_KEY" python3 -I tools/prepare.py ... --out ./sound-rows --strata http://coordinator:7700 --key "$CHLOEDB_KEY" chloedb-sound load --rows ./sound-rows --strata http://coordinator:7700 --key "$CHLOEDB_KEY" chloedb-sound serve --strata http://coordinator:7700 --key "$CHLOEDB_KEY" --token "$SOUND_TOKEN" --audio ./sound-rows/audio --listen 0.0.0.0:7870 chloedb-server ... --app sound=http://sound-host:7870 # with CHLOEDB_APP_TOKEN=$SOUND_TOKEN ``` On Kubernetes, [`deploy/k8s.yaml`](../../chloedb-sound/deploy/k8s.yaml) runs it on one small node of its own (2 vCPUs, 4 GB): the server with CLAP, the app and a pod to work in, with the binaries, the model, the rows, the previews and the database on the node's own disk. A bigger set is made on machines of their own and copied in: [`deploy/batch.yaml`](../../chloedb-sound/deploy/batch.yaml) runs a server with CLAP on each node of a temporary pool, and the first downloads the sounds, makes the rows with `--embed` over all of them and builds the database. The whole of FSD50K and `fma_large`'s clips that qualify, with a sample of Commons, came to 53,591 sounds and 132,486 moments, embedded in about six hours on three DigitalOcean 8-vCPU machines (s-8vcpu-16gb, AMD and Intel, about 6.5 windows a second together, a third of the speed per core of a Xeon with AVX-512); the database is 735 MB and the previews 8.5 GB. `--public` serves the page at `/` and its reads to anyone, without the token, within `--per-minute` requests a minute from one address (120 by default; the previews are not counted) and `--listens-per-minute` clips heard (6), and refuses calls from another site's pages. It serves no SQL: the page's *SQL* drawer shows the statements each answer ran. A server without CLAP (built without the `audio` feature, or without the model) still serves the app: searches by words are ranked by BM25 alone and say so, and the pages that hear words or clips answer with an error. ## Tables | table | a row is | its vector | |---|---|---| | `au_sounds` | a sound: title, words (title, tags, labels, description), author and its page, source page, licence and its link, kind, tags, labels, genres, length, year, place, preview file, waveform (160 peaks), place on the map, number of moments | `emb VECTOR(512)`: the mean of its windows that start every ten seconds, the vector the server makes of the whole file | | `au_moments` | ten seconds of a sound, every five seconds (`shard_by = 'sound'`, so a sound's moments are on one shard) | `emb VECTOR(512)` | | `au_labels` | one of FSD50K's 200 labels, with a sentence ("the sound of rain") | `emb VECTOR(512) OPTIONS(embed = 'prompt', model = 'clap-htsat-unfused')`: the server embeds it, and words and clips are embedded through this field | ## The API Every answer carries `queries`, the SQL it ran, for the page's *SQL* drawer. | route | what | |---|---| | `GET /v1/search?q=&like=&unlike=¬=&steer=&source=&kind=&lic=&min_s=&max_s=&by=&page=` | sounds by words and by sound, steered, filtered and faceted; `by` is `both`, `sound` or `words` | | `GET /v1/sound/:id` | a sound with its credit, what is in it moment by moment, sounds like it and more by its author | | `GET /v1/moments?q=&min=` | the best moment of each recording, and its other good moments, in recordings at least `min` seconds long (15 by default; songs are left to *Music*) | | `POST /v1/listen` | `{audio: base64}` (WAV, FLAC, MP3 or Ogg, at most 2 MB): what it sounds like, and whether it is one of the sounds | | `GET /v1/scene?q=` | a scene's layers: a sound for each thing the place sounds like, with a level | | `GET /v1/drift?from=&to=&steps=` | the sounds on the way from one to the other | | `GET /v1/map` | every sound's place on the map and by where it was recorded | | `GET /v1/home`, `/v1/labels`, `/v1/status` | the front page, the labels, the counts | | `GET /v1/audio/:id` | a preview (MP3), with ranges; `?b64=1` as JSON for the command center | ## Tests `cargo test` runs the app against a real chloedb-server (`CHLOEDB_SERVER_BIN`, or one built in `../chloedb-server`) with nine made-up sounds and their moments: search by sound, steering, filters, words, a sound's credit, drift, the map, previews with ranges, and the public limits. `CHLOEDB_SOUND_CLAP=1` against a server built with `--features audio` tests the pages that hear words and clips too; without it the test checks that words are still searched by BM25. --- # chloedb-grants: Grant Finder on ChloeDB > **A demo.** chloedb-grants shows what ChloeDB can do; it is not part of ChloeDB's releases or their promises. It is tested on a train of its own (the `Demos` workflow, `.github/workflows/demos.yml`), outside CI's required check, and the command center marks it as a demo ([compatibility](../compatibility.md#demos)). `chloedb-grants` helps a small nonprofit find grants and write the applications. It keeps every open federal grant from [Grants.gov](https://www.grants.gov/)'s public API in ChloeDB, ranks them against the organization's mission, keeps a pipeline of the ones it goes after, and drafts each section of an application from the organization's own writing, citing it. - **Find.** Every posted and forecast opportunity, ranked against the mission and any words typed, by one statement: `rrf(bm25(title, :q), bm25(synopsis, :q), similarity(emb, :v), …)` with the mission and the words as the vector's text. Grants the organization cannot apply for (by Grants.gov's applicant types, `applicants && :elig`), that have closed, or that close too soon or pay too little are left out; facets count agencies and categories. Each result shows how well it fits and the words it shares with the mission. - **Pipeline.** Saved, Drafting, Submitted, Won and Not funded, with each move kept in the row's history, and the words drafted so far. - **Library.** The organization's own writing: past applications, annual reports, program descriptions, budgets. Upload a PDF, Word file (.docx), HTML, Markdown or text, or paste; each is cut into passages of about seventy words, kept with their own vectors (`gr_passages`). - **Write.** Each section of an application (a standard six, or the funder's own read from the announcement) is drafted by `llm()` from the passages closest to it, picked by the same kind of statement over the library, and cites them as `[n]`. Ticking and unticking sources changes what the next draft is written from. *Shorten* brings a draft within the section's words. - **Check.** A draft is checked against what the funder asks: by the app (within the words, every source cited, no source cited that it was not given, every number found in a source), and by `llm()` reading the funder's guidelines as a program officer would. The guidelines are the full announcement, read from the opportunity's attachments on Grants.gov (PDF, Word, or HTML, following NIH's pages), or pasted. - **Export.** The application as Markdown, with its sources. It starts with an example organization (Eastbay Harvest, a food bank) and a dozen passages of its writing, so that every page has something on it; *Remove the example* clears them, and the mission page takes the organization's own. Like [Hacker News](hn.md) and [Sound Explorer](sound.md), it is a program of its own, in Rust, that talks to chloedb-server over HTTP only, and the command center shows it as an app (**Apps → Grant Finder**). ## Run it ```bash (cd chloedb-server && cargo build --release --bin chloedb-server) cd chloedb-grants && cargo build --release ANTHROPIC_API_KEY=... target/release/chloedb-grants serve --local ./grants-data --server-bin ../chloedb-server/target/release/chloedb-server ``` `serve --local DIR` starts a chloedb-server with its database in `DIR` (it passes on `ANTHROPIC_API_KEY`, which `llm()` needs), makes the tables and the example organization, syncs Grants.gov (about 1,400 open opportunities, fetched in under half a minute) and syncs again every `--sync-hours` (6), and lists the app as `grants`; open `http://127.0.0.1:7700` and go to **Apps → Grant Finder**. The server fetches the embedding model (`potion-retrieval-32M`, `--model` for another) the first time a field names it. Without a key, finding, the pipeline and the library work, and drafting and the model's checks answer with the server's error. Against a server or a cluster that runs elsewhere: ```bash chloedb-grants init --chloedb http://coordinator:7700 --key "$CHLOEDB_KEY" chloedb-grants sync --chloedb http://coordinator:7700 --key "$CHLOEDB_KEY" chloedb-grants serve --chloedb http://coordinator:7700 --key "$CHLOEDB_KEY" --token "$GRANTS_TOKEN" --listen 0.0.0.0:7890 chloedb-server ... --app grants=http://grants-host:7890 # with CHLOEDB_APP_TOKEN=$GRANTS_TOKEN ``` `sync` fetches what is new, what changed (by the opportunity's revision) and what is older than `--stale-hours` (72), at most `--sync-limit` a run (5000), and marks the rows Grants.gov no longer lists as closed. `--public` serves the page at `/` and its API to anyone, without the token, within `--per-minute` requests a minute from one address (240), and refuses calls from another site's pages; only a sync needs the token. Drafts, shortening and the model's checks are counted against `--llm-per-day` (500) and `--llm-per-hour` (40) calls. A public demo has one organization, shared by its visitors. On Kubernetes, [`deploy/k8s.yaml`](../../chloedb-grants/deploy/k8s.yaml) runs the server and the app on a node of the demo pool, with the database on the node's own disk; it is the one at grants.chloetech.ai. ## Tables | table | a row is | its vector | |---|---|---| | `gr_grants` | an opportunity: number, title, agency and department, status (posted, forecasted, closed), categories, instruments, applicant types, synopsis, eligibility, dates, award ceiling and floor, total, awards, cost sharing, assistance listings, contact, the announcement's attachments, revision | `emb`, of the title and synopsis (`OPTIONS(embed = 'title, synopsis')`) | | `gr_org` | the organization: name, mission, place, budget, applicant type | | | `gr_pipeline` | a grant gone after: stage, the ask, a note, the history of moves | | | `gr_docs`, `gr_passages` | a document of the library, and its passages | `emb`, of the document's name and the passage | | `gr_guidelines` | a grant's guidelines: the announcement's text, where it came from, and what it asks | | | `gr_sections` | a section of a grant's application: name, words, guidance, where it came from | | | `gr_drafts` | a section's draft: text, the passages picked, the last checks | | | `gr_sync` | the last sync: listed, fetched, closed, failed, how long | | ## The API Every answer carries `queries`, the SQL it ran, for the page's *SQL* drawer. Writes are POST. | route | what | |---|---| | `GET /v1/find?q=&dept=&cat=&status=&within=&min=&eligible=&limit=` | grants ranked against the mission and the words, with facets | | `GET /v1/grant/:id` | a grant, how it fits, whether the organization can apply, its pipeline row | | `GET /v1/pipeline`, `POST /v1/pipeline/:id` | the pipeline by stage; `{stage, ask, note}` moves a grant (an empty stage removes it) | | `GET`, `POST /v1/org` | the organization | | `GET /v1/library`, `POST /v1/library/paste`, `POST /v1/library/upload?file=&name=` | the library; paste `{name, text}`, or upload a file as the body (20 MB at most) | | `POST /v1/library/doc/:id/delete`, `POST /v1/library/example/drop` | remove a document, or the example | | `GET /v1/editor/:id?ord=` | a grant's sections, the section's draft, its sources and the passages to pick from | | `POST /v1/draft/:id/:ord`, `/v1/shorten/:id/:ord`, `/v1/check/:id/:ord`, `/v1/text/:id/:ord` | draft from `{picks}`, shorten, check, save the text | | `GET`, `POST /v1/sections/:id`, `POST /v1/sections/:id/read` | the sections, set by hand or read from the guidelines | | `GET`, `POST /v1/guidelines/:id`, `POST /v1/guidelines/:id/fetch` | the guidelines, pasted or read from the announcement | | `GET /v1/export/:id` | the application as Markdown | | `GET /v1/status`, `POST /v1/sync` | the counts, the last sync and the model's calls today; a sync now (token only) | ## Tests `cargo test` runs the app against a real chloedb-server (`CHLOEDB_SERVER_BIN`, or one built in `../chloedb-server`) with a made-up Grants.gov of four opportunities and a made-up Messages API: the sync, finding with each filter, eligibility, the pipeline, the library (paste, a Word file, a refused format), the editor, drafting with citations, checks that catch a made-up number, shortening, reading the announcement through a page that refreshes, sections read from it, the export, and that the API needs the token and refuses another site's pages. --- # Backbone Explorer: the internet's routing on ChloeDB `chloedb-backbone` is an app of a ChloeDB server built on public data about how the internet's networks reach each other: every BGP update a [RIPE RIS](https://ris.ripe.net) collector hears, checked as it arrives against [RPKI](https://www.rpki-client.org) and against the origins [RouteViews](https://www.routeviews.org) saw the day before, with [PeeringDB](https://www.peeringdb.com)'s exchanges and buildings, [CAIDA](https://www.caida.org/catalog/datasets/as-relationships/)'s relationships between networks, [RIPE Atlas](https://atlas.ripe.net)'s measurements to the K root server and [IODA](https://ioda.inetintel.cc.gatech.edu)'s outages. It says what is wrong now, where, and how the problems connect. It is a client of chloedb-server over HTTP, as the crawler and the spreadsheet app are, and the command center can show it as the app `backbone` (`chloedb-server --app backbone=URL`). Every request needs the token the command center's app proxy sends, unless the app runs with `--public`: then it serves its page at `/` and the page's reads to anyone, at most `--per-minute` (600) requests a minute from one address. Readers never send SQL: each page asks its own statements, and shows them under SQL. It runs that way at https://backbone.chloetech.ai. ## The pages | page | what it shows | from | |---|---|---| | Home | what it is and where its data comes from, the open incidents, the world coloured by them, the slowest countries and the busiest prefixes, and how to read the console | `bb_incidents`, `bb_alerts`, `bb_updates`, `bb_ping` | | Console | one screen that stays while you move: every update a minute for the last six hours, with the RPKI-invalid ones and the incidents along it (`/v1/timeline`); the networks you watch, kept in your browser, with their alerts and their routes' updates in the last hour (`/v1/watch`); the open incidents on the left; a map whose camera flies from the world to a country to a network; and an inspector on the right with what is wrong, what changed, the numbers and the records of what is on the map | the pages below | | A country | its buildings, exchanges and RIPE Atlas probes where they are, its networks placed where their buildings are (else their probes), each probe coloured by its time to K, and where slow traceroutes leave it | `bb_fac`, `bb_netfac`, `bb_ix`, `bb_member`, `bb_probe`, `bb_ping`, `bb_trace` | | A network | its buildings, exchanges and probes on the map, a line to where it meets each provider, what it hangs from and what depends on it (`REACHABLE` over the relationships), trouble within three hops, its prefixes and their updates a minute, its alerts | `bb_p2c`, `bb_p2p`, `bb_updates`, `bb_roa` | | A prefix | every update replayed into who holds a route to it now, its origins and their RPKI state, its paths now beside an hour ago (the ones that are new and the ones that are gone), drawn country to country on the map, the routes covering it and inside it, its ROAs | `bb_updates`, `bb_roa` | | An incident | its alerts, who announced, carried and owns the space, its countries on the map, its window on the timeline, and the updates a minute around it | `bb_alerts`, `bb_updates` | | Diagnose | for the slowest countries and those with the most probes, the stack from users to the K root server (time to K, paths that jump, peering, routing alerts, outages) and the lowest layer that is red | `bb_ping`, `bb_trace`, `bb_alerts`, `bb_outage` | | Rules | each alert rule's statement, how long it took and what it found | `bb_rules` | | How it's built | the tables, their rows, and where each source stands | every table | ## The rules Each rule is one statement over the tables, run every minute (`flapping`, which counts an hour of every prefix's updates, every five); its rows are the alerts, kept open while it finds them, and alerts that share an owner, an announcer, a carrier or a country are grouped into incidents. | rule | finds | |---|---| | `rpki-invalid` | a route a ROA gives to another network, or longer than its ROA allows, heard by 3 or more peers (IPv4 /24 and IPv6 /48 or shorter: longer ones are mostly blackholing) | | `new-origin` | a prefix announced by a network that is neither yesterday's origin nor its customer or provider, with no ROA to say which is right | | `more-specific` | a prefix no one announced yesterday, inside space another network announces, from a network that is not its customer and no ROA covers | | `flapping` | a prefix announced and withdrawn 10,000 times an hour or more | | `withdrawn` | twenty or more of a network's prefixes withdrawn by five or more peers at once | | `blackhole` | a prefix tagged for blackholing (`65535:666`) | | `ioda` | a country or a region whose routes, pings or traffic IODA sees fall | | `slow-country` | a country with five or more probes whose median time to the nearest K root server is over 100 ms | ## Running it ```bash chloedb-backbone fetch --dir DATA # RPKI, CAIDA, RIPE's names, PeeringDB, Atlas, IODA chloedb-backbone load --dir DATA # the tables, and their records chloedb-backbone feed --dir DATA --from 6h --live # RIS's archive from six hours back, then RIS Live chloedb-backbone serve --public # the page and its API at 127.0.0.1:7890 ``` `feed --resume` starts the archive after the newest update kept, so a restart fills its gap, and `--hours 24` stops it after a day so a supervisor starts it again after a new `fetch` and `load`. `fetch` keeps a file fetched less than `--fresh-hours` ago (20 by default; 0 fetches every one) and keeps the last file of a source that fails, such as PeeringDB's 429 to an address that asked too often, and `load` loads only the latest Atlas rounds and outages when the other files are those it loaded last: so a restart within the day neither asks the sources again nor writes two million rows again. `serve` works out the pages everyone sees first (Now, the map, the strip) in the background every 15 seconds, after the rules, and answers them from memory. RIS Live sends every collector's messages whatever filter it is asked for, so the feed keeps those of `--collectors` itself. On Kubernetes, `chloedb-backbone/deploy/k8s.yaml` runs the server, the feed and the app on a node of their own, and `deploy/backup.yaml` checkpoints the database each night and copies it to a volume. ## Sizes Measured with one collector, rrc00 (about 90 peers), on 16 and 17 November 2026: about 5.5 million updates an hour, about 100 bytes an update stored, so about 13 GB a day; the updates are kept three days. The pages answered in 0.1 to 0.6 seconds on a 4-core machine. The feed holds RPKI's 1.04 million ROAs and yesterday's 1.44 million origins as prefix maps, about 4 GB with the allocator's share. --- # Earth Explorer: California and Chile from orbit, on ChloeDB `chloedb-earth` is an app of a ChloeDB server built on public pictures and records of the ground: every fire pixel the GOES satellites see over California and Chile, every few minutes, grouped into fires as they come; 103,664 places of 3.84 km a side, each with its Sentinel-2 picture's [SigLIP](https://huggingface.co/google/siglip-so400m-patch14-384) vector from [Major TOM](https://huggingface.co/datasets/Major-TOM/Core-S2RGB-SigLIP) and what is on it (land cover, terrain, people, climate, crops, mines, the years it burned); and the pictures of a few hundred of them every other year since 2017. It is a client of chloedb-server over HTTP, as the crawler and the spreadsheet app are, and the command center can show it as the app `earth` (`chloedb-server --app earth=URL`). Every request needs the token the command center's app proxy sends, unless the app runs with `--public`: then it serves its page at `/` and the page's reads to anyone, at most `--per-minute` (120) requests a minute from one address, and the only POSTs it takes are a picture searched for (`POST /v1/picture`) and a browser's own fire watches. Readers never send SQL: each page asks its own statements, and shows them under SQL. Three things on it are ChloeDB's own: - **Fires like this one.** A fire's first hour, two hours and six hours are each a vector (its power, pixels and spread a quarter hour at a time, then what it started on: slope, trees, shrubs, people, the gusts), and the fires whose first hours were nearest, among those out before it, say how big it got: the median and the middle half of theirs. `backtest` measures how often that range held the size each past fire reached, beside the range of all fires of the region. - **Climate twins.** Each California place is matched with the place of Chile that looks most like it, in the same Köppen class, and the other way round: the two Mediterranean coasts, about 9,000 km apart, side by side. The match is CSLS (`2·sim − r_a − r_b`, each `r` a place's mean similarity to its ten nearest in the other region), so a place that looks like everything does not become everyone's twin. - **Find change.** A place's look each year is a vector; how far it moved from its first year to its last, and in which year most, finds the fields that became houses, the forests that burned and the pits that grew. A search for "shrubland → houses" ranks by `similarity(before, :a) + similarity(after, :b)`. ## The pages | page | what it shows | from | |---|---|---| | Home | a search box for a town, a county or "lat, lon" (and "use my location") that opens a place's report, then each region's fires burning and alerts open, the replays, the largest fires GOES saw, the closest twins, the backtest and how much was read | `ea_fires`, `ea_alerts`, `ea_places`, `ea_backtest`, `ea_scans` | | Live | the region's map with the fire pixels of the last hours (a red light when the newest scan is under three hours old), the fires burning with their alerts, refreshed every 30 seconds | `ea_detections`, `ea_fires`, `ea_alerts`, `ea_scans` | | A replay | a night of the archive played back on the map, a scan at a time, over GOES's picture of the sky at that moment (with `--frames`): Los Angeles on 7 January 2025 (Palisades, Eaton, Hurst) and Valparaíso on 2 February 2024 | `ea_detections`, `ea_scans`, `ea_fires` | | Fire watch | places a browser keeps an eye on (a home, a parent's house, a farm: found by name, by "lat, lon", with "use my location", or many at once as lines of a name and coordinates), each with where the nearest fire is now; a place's page with the heat near it, how far the nearest fire was scan by scan over 12 hours, the alerts sent, what to be told about (a fire within 5 to 50 km, 2 km closer in an hour, past 1,000 MW, a clear night over it, a new satellite picture that looks unlike the one before), the official sources, the ground and the fires that started near it; the browser's notifications while a tab is open and an Atom feed of its alerts; and an example that plays the Park Fire's first 12 hours (24 July 2024) over three made-up places | `ea_watches`, `ea_watch_alerts`, `ea_detections`, `ea_scans`, `ea_fires` | | Clear sky | the region's map of every place's sky now (clear, partly cloudy, cloudy or smoke, from GOES's last scan), or of its clear nights or days over 30 days; a finder for the clearest places near a town, a point or "use my location", within 5 to 400 km, by the sky now, the most clear nights (for the stars) or days, and what they look like in words ("dark hills", "a lake"); and each place's sky on its page | `ea_sky`, `ea_places` | | Land finder | places to build a solar farm on: limits on the slope, the distance to a substation and its voltage, the distance to a main road, protected land and towns, near a town or anywhere in the region, ranked by how much each place's picture looks like the solar farms already built there, by how near the grid is, or by words ("flat dry grassland"); the solar farms built and the places found on the map, a shortlist kept in the browser (as CSV, and a fire watch a click away), and what is around each place for building on it on its page | `ea_places` | | Future climate | each place's climate in 2071-2100 if emissions keep rising (SSP3-7.0) against 1981-2010, on a map (hotter summers, milder winters, rain, and how far away its future climate is today, with the places whose future no place has today edged in red); a place's hottest month, coldest nights, rain and climate class now and later, with the five models' range, the places whose climate today is nearest its future one (in California and Chile, or only its own region) and those whose future is nearest its climate today; and the same on each place's page | `ea_climate` | | A fire | its pixels on the map, its first hours drawn, the fires that began like it with the outlook they give, its alerts, and how well the outlook has done before | `ea_fires`, `ea_detections`, `ea_backtest` | | Past fires | a region's fires by size, year or name | `ea_fires` | | Explore | the map with a layer over it (people, trees, shrubs, grass, crops, built, bare, water, snow, terrain, slope, mines, fire history, climate, land cover, crops by kind), and the place under a click | `ea_places` | | A place | **what happened here**: a headline and a timeline within 10 km, newest first (CAL FIRE's perimeters with distance, direction, acres, cause and dates; years satellites saw fire heat; fires GOES saw within 25 km; nearby places that changed), over a map that draws the perimeters; then its picture, what covers it, its terrain and people, the years it burned, the places that look like it, its twins in the other region, places like it with words added or taken away (`/v1/mix`), the fires near it and its pictures year by year | `ea_places`, `ea_years`, `ea_changes`, `ea_fires`, `ea_perimeters`, `ea_burns` | | Search | places by what they look like, in words ("vineyards on hills", "a lithium mine"): by the picture and what covers it (`rrf(similarity(look, :v), bm25(about, :q))`, the default), by the picture alone, or by the description with names; or by a picture dropped on the page | `ea_places` | | Climate twins | the closest pairs, those of the same land first, by climate and kind | `ea_places` | | Find change | the places whose look changed since 2017, on a map: the most changed, or searched by a change in words ("a lake became a dry lake bed"), within a region or near a town, by the two years it changed most between, by how much and by what it was and became; each with its first and last pictures and a button to watch it for change; a place's years and the places whose change went the same way | `ea_changes`, `ea_years`, `ea_watches` | | Rules | each alert rule's statement, how long it took and what it found | `ea_rules`, `ea_alerts` | | How it's built | the tables, their rows, where each feed stands, the backtest, and every source with its licence | every table | ## The rules Each rule is one statement over the fires, run every minute; its rows are the alerts, kept open while it finds them. "Now" is the newest scan read for the region, not the clock, so a replay raises the alerts it would have raised then. | rule | finds | |---|---| | `new-fire` | a fire GOES saw start in the last three hours, in two scans or more | | `people-near` | a fire burning with 10,000 people or more within 5 km of where it started | | `growing` | a fire past 300 MW and twice its power of an hour ago | | `big` | a fire past 1,000 MW in a scan | | `steep-windy` | a fire that started on slopes of 15 degrees or more, half trees and shrubs, with gusts of 35 mph or more | | `could-grow` | a fire whose twenty nearest fires by their first hours mostly grew past 20 km² | | `first-in-years` | a fire on ground with no fire in NASA FIRMS's records since 2001 | ## Fire watch A watch is a row of `ea_watches`: a point, a name, the distance it asks about and two choices. There are no accounts: the page makes a long random key (a UUID) the first time, keeps it in the browser, and a watch belongs to the key that made it (25 at most a key, 20,000 in all). Every route takes the key as `?w=`, and the feed has it in its address, `/v1/watches/feed/`, so a feed reader needs nothing else. The page's writes are `POST /v1/watches` (a new watch) and `POST /v1/watch/` (a change, or `{"remove": true}`, which takes its alerts too). Every minute `serve` reads each region's scans since it last looked (at most the last six hours after a pause) and, for each watch of the region, the nearest fire pixel of the hour up to each scan. It writes to `ea_watch_alerts`, once per watch, fire and kind: | kind | when | |---|---| | `in` | a fire within the distance the watch asks about (5, 10, 15, 25 or 50 km) | | `near` | a fire within 5 km | | `here` | a fire pixel within 1.5 km (a GOES pixel is 2 to 3 km across) | | `power` | a fire within 50 km past 1,000 MW in one scan, when asked | | `closer` | the same fire 2 km closer than 40 to 90 minutes before, once an hour, when asked | `/v1/watches` (a key's watches, where each stands, and its alerts), `/v1/watch/` (one, with 12 hours of distances, the heat within 55 km and the fires GOES saw start within 25 km since June 2023), `/v1/watches/feed/` (Atom) and `/v1/watches/example` (the Park Fire's first 12 hours, worked out once) are what the page reads. The browser is told of an alert while Earth is open in a tab; pushes to a closed phone are not built yet. ## Clear sky `chloedb-earth sky --region R --live` reads GOES's Clear Sky Mask (ABI-L2-ACMC from GOES-18 over California every 5 minutes, ABI-L2-ACMF from GOES-19's full disk over Chile every 10) and its Aerosol Detection's smoke (ADPC and ADPF) for the same scan, at most one scan every `--every` seconds (600). For each place it takes the share of the pixels inside its square that are clear or probably clear, and with smoke, and keeps a row of `ea_sky`: the last scan's shares, the sun's height, and 30 days of how clear each day's daylight scans (sun above 5 degrees) and each night's dark ones (below -12, past nautical dusk) were, the newest last. A row is written again when a share moved a tenth, a day or night moved five points, a day turned, or three hours passed, so most scans write only the places whose sky changed. `--from 720h` fills the 30 days from the archive first. `serve` reads each region's rows every two minutes into memory: `/v1/sky?region=R` is the map's layer (every place's share clear now and its nights and days), `/v1/sky/find` ranks the places within `km` of `lat, lon` (or the region) by the sky now, by their clear nights (`want=nights`) or days (`want=days`), and with `q` among the 300 places that look most like the words. A fire watch can ask to be told when the night over it is clear: an alert `clear` once a night, when the sun is 12 degrees down, the last scan is 90% clear and the night so far 80%. ## Future climate `tools/climate.py` reads CHELSA 2.1 (Karger et al., CC BY 4.0), the climate of every 30 arc-second cell for 1981-2010 and, from five CMIP6 models (GFDL-ESM4, IPSL-CM6A-LR, MPI-ESM1-2-HR, MRI-ESM2-0, UKESM1-0-LL), for 2071-2100 under SSP3-7.0. Of each place's square it takes the mean of six variables (bio1, the year's mean temperature; bio5, the hottest month's highs; bio6, the coldest month's lows; bio12, the year's rain; bio15, how unevenly it falls; bio18, the rain of the warmest three months) and the commonest Köppen-Geiger class (kg0), for now and for each model, into a row of `ea_climate`: today's values, the models' mean later, their lowest and highest for the hottest month, the coldest nights and the rain, and the class most models give. The six, standardised over every place of both regions today (the rain as its logarithm), are a place's climate as a vector: `clim` for 1981-2010 and `clim70` for 2071-2100. A place's page asks `ORDER BY distance(clim, :clim70) ASC` for the places whose climate today is nearest its future one, and `ORDER BY distance(clim70, :clim) ASC` for those whose future is nearest its climate today, one place a town (`MAX 1 PER town`). The tool keeps the nearest of the first for every place too (`analog`, `analog_km`, `analog_d`), for the map; when it is more than one standard deviation away (167 places), no place of the two regions has a climate close to it today (`novel`). ```bash python3 tools/climate.py places --out DATA # the places' centres, from the server (CHLOEDB_URL, CHLOEDB_KEY) python3 tools/climate.py fetch --out DATA # 42 files of 12 to 490 MB, each cut to the regions and deleted python3 tools/climate.py rows --out DATA # ea_climate_.jsonl chloedb-earth load --dir DATA --only ea_climate ``` ## Land finder `tools/land.py` writes what is around each place for building on it into thirteen columns of `ea_places`: the nearest substation (how far, its voltage, its name) and power line (how far, its voltage) of OpenStreetMap, the nearest motorway, trunk, primary or secondary road, the share of the place covered by solar farms (OpenStreetMap's `power=plant` with `plant:source=solar`, or a generator area with `generator:source=solar`, of a hectare or more) and the nearest one, and the share protected: PAD-US 4.1's fee areas in California (USGS, public domain), strictly when of GAP status 1 or 2, and OpenStreetMap's protected areas in Chile, strictly when a national park, a nature reserve or of IUCN class I to IV. Distances are from the place's centre. In California the median place is 9.9 km from a substation, 1,230 places have a solar farm and 19,840 are mostly protected; in Chile, 30.9 km and 874. The finder is one statement: the limits as its `WHERE` (and never a place that has a solar farm already, nor one mostly water or snow), ranked by `ORDER BY similarity(look, :v) DESC`, where `:v` is the mean of the looks of the region's places at least a third covered by solar farms, or by `sub_km`, or by the words' vector. Near a town it keeps the places within a box and then within the circle. ```bash python3 -I tools/land.py places --out DATA # the places' centres (CHLOEDB_URL, CHLOEDB_KEY) python3 -I tools/land.py osm --region california --pbf california-latest.osm.pbf --out DATA # from download.openstreetmap.fr or Geofabrik python3 -I tools/land.py padus --out DATA # California's PAD-US fee areas python3 -I tools/land.py rows --region california --out DATA # set ops into DATA/land/patch_land_california.jsonl chloedb-earth load --dir DATA --only ea_places # adds the columns to a table made before them python3 -I tools/land.py write --region california --out DATA ``` ## Find change `tools/years.py` keeps a clear Sentinel-2 picture of every other dry season since 2017 (June to September in California, January to March in Chile) for a set of places, each embedded by the server's SigLIP so400m, the model of the places' pictures: a row of `ea_years` a place and year, and a row of `ea_changes` a place, with its first and last looks, how far it moved (`drift`, 1 minus their cosine), the two years it moved most between (`step_year`, the later) and the words nearest each look. `pick` chose the first places from the places' files; `grow` picks more from the server's own rows (the places with a solar farm first, then the burned, the mines, the edges of towns, the water, the farms and some at random, none next to one already kept), and the steps after it fetch, embed and write only theirs. Embedding is the slow step, about 4 seconds a picture on the earth node. Find change is one statement over `ea_changes`: the limits as its `WHERE` (a box around the town, cut to the circle after), ranked by `similarity(before, :a) + similarity(after, :b)` for "a became b", `similarity(after, :b) - similarity(before, :b)` for "became b", or by `drift`. A fire watch can ask to be told of a change (`change`). `years.py watch --loop` fetches its place's years when it has none, then every six hours its newest clear picture since its last, into `ea_years` as `-`; `serve` compares each new picture of a watched place with the one before it, when the two are at most 120 days apart (the same season), and a move of more than 0.09 (about the 90th centile of the two-yearly moves) is an alert. ```bash python3 -I tools/years.py grow --out DATA --per-region 900 --strata URL # CHLOEDB_KEY python3 -I tools/years.py fetch --out DATA python3 -I tools/years.py embed --out DATA --strata URL --parallel 2 python3 -I tools/years.py rows --out DATA --strata URL chloedb-earth load --dir DATA --only ea_years,ea_changes python3 -I tools/years.py watch --out DATA --strata URL --loop # the watched places every six hours; serve --chips DATA/chips ``` ## Running it The places are made once, by `tools/places.py` (Major TOM's fragments and vectors, and the layers read at each place from WorldCover, the Copernicus DEM, GHSL, Köppen-Geiger, the mining polygons, the Cropland Data Layer and FIRMS, a fire year needing three detections), California's fire perimeters by `tools/perimeters.py` (CAL FIRE FRAP's "California Fire Perimeters (all)", public, no warranty from the State: 23,320 fires since 1878 into `ea_perimeters`, and which fire burned how much of which place into `ea_burns`) and `chloedb-earth names`, which gives each GOES fire in California the name of the perimeter it matches (same year, alarm date three days before to two after its start, its centre inside the outline or within 3 km); `serve` does it hourly, and their years by `tools/years.py` (a clear Sentinel-2 scene of each dry season from Element 84's Earth Search, embedded by the server). Both need a server built with `--features vision` and the model `siglip-so400m-patch14-384` (`chloedb-server fetch-model siglip-so400m-patch14-384`, a 3.5 GB download), which also turns a search's words and a dropped picture into vectors. ```bash for r in california chile; do for s in pull layers fires; do python3 tools/places.py $s --region $r --out DATA; done; done python3 tools/places.py twins --out DATA # both regions' twins for r in california chile; do python3 tools/places.py rows --region $r --out DATA; done # ea_places_.jsonl python3 tools/years.py pick --out DATA && python3 tools/years.py fetch --out DATA python3 tools/years.py embed --out DATA && python3 tools/years.py rows --out DATA chloedb-earth load --dir DATA # the tables, and their rows chloedb-earth goes --region california --from 2025-01-07 --to 2025-01-09 # a stretch of GOES's archive chloedb-earth goes --region chile --live # after the newest scan kept, then each new one chloedb-earth sky --region california --from 720h --live # 30 days of clouds and smoke, then each new scan chloedb-earth backtest --region california # how well the fires like each one did python3 tools/frames.py --replay la-2025 --sat 18 --product MCMIPC --from 2025-01-07T17:00:00Z --to 2025-01-09T06:00:00Z --box 33.55,34.75,-119.15,-117.55 --out DATA/frames chloedb-earth serve --public --chips DATA/chips --frames DATA/frames # the page and its API at 127.0.0.1:7790 ``` NASA GIBS keeps GOES's GeoColor pictures for about 90 days, which Live shows under the fires; a replay is older, so `tools/frames.py` draws its own from NOAA's archive of the Cloud and Moisture Imagery product (ABI-L2-MCMIPC over the United States, MCMIPF for the full disk over Chile): the scan nearest every 10 minutes, cut to the replay's box in Web Mercator, true colour by day (the green made from the red, blue and vegetation bands, as ABI has no green band) and the clean infrared band by night, blended by the sun's height, with the fires' own heat (the 3.9 µm band well above the 10.3 µm one) glowing over both, deep red where faint and yellow where hottest. Each scan file is 50 MB (CONUS) or 340 MB (full disk), read and deleted; the pictures are about 60 KB each. The app draws GOES's fire pixels over them as one field of heat per fire, and its "Fire pixels" button hides them to show the fire as the picture has it. `goes` reads GOES-West's CONUS product over California (GOES-17 from February 2019, GOES-18 from January 2023) and GOES-East's full disk over Chile (GOES-16, GOES-19 from April 2025), from NOAA's buckets on AWS, keeping only the pixels within 4 km of a place. Low-probability pixels (masks 15 and 35) are left out: most are hot ground and cloud edges with no power worked out, a whole desert valley on a summer night, and beside a real fire they made it look ten times its size. A fire's area is the ground of the pixels GOES saw burning, each 2 to 4 km a side, so a fire spread by embers reads larger than the ground that burned: the Palisades and Eaton fires read 273 and 182 km², inside perimeters of 95 and 57 km², while the York Fire of 2023 read 377 km² and burned about that. A feed started again takes back the fires burning in the 12 hours before where it starts, and marks out those it left burning longer ago. Without `vision` on the server the app still runs, and searches by the description; searches by a picture or by meaning say why they cannot. ## Tests `cargo test --profile ci` runs the unit tests and `tests/cluster.rs`: made-up places in both regions with their vectors and years, loaded with `load`, a week of made-up GOES scans through the feed (the tracker and writes the archive goes through, seven fires in it, the last inside the Los Angeles replay), then `rules`, `backtest`, four places' skies, a row of places' climates and every page of `serve`, with the token and `--public`. It needs a chloedb-server binary (`CHLOEDB_SERVER_BIN`, else `../chloedb-server/target/{ci,release}/chloedb-server`) and no model, and is skipped without one unless `CHLOEDB_EARTH_NEED_SERVER` is set, as the Demos workflow does. ## Sizes Measured in a cloud session's 4-core container on 18 and 19 November 2026 (not a benchmark): 36,612 places in California and 67,052 in Chile, 1.16 GB of JSON lines with their 1152-number vectors, and 1.2 GB on disk with the fires of the seasons read. A place's page asks six statements and answered in 11.8 ms. A day of GOES's archive at a scan every 15 minutes read in 2 to 3 seconds. SigLIP so400m embeds a 384-pixel picture in about 4.2 seconds and a search's words in 0.75 seconds on that container's CPU when nothing else runs, and in 5 to 8 seconds beside the feeds. With California's summers of 2023 to 2025 and its January 2025 read (5,264 fires) and Chile's three summers from 2023 (4,355), the backtest found the middle half of the sizes of the 20 fires most like one after six hours spanning a factor of 1.9 (its top 1.9 times its bottom) against 3.9 for all earlier fires in California, holding the real size 65% of the time against 53%, and 1.7 against 5.1 in Chile, holding it 59% of the time against 65%; their medians ranked the fires by size with a rank correlation of 0.81 and 0.85. --- # chloedb-packets: what went wrong in a capture > **A demo.** chloedb-packets shows what ChloeDB can do; it is not part of ChloeDB's releases or their promises. It is tested on a train of its own (the `Demos` workflow, `.github/workflows/demos.yml`), outside CI's required check, and the command center marks it as a demo ([compatibility](../compatibility.md#demos)). `chloedb-packets` is a packet explorer: a capture (a `.pcap` or `.pcapng`) is decoded by tshark, Wireshark's own dissectors, into rows of ChloeDB tables, and the page reads them as Wireshark would, then goes further and says what went wrong in each conversation, at the packet that shows it. It is a program of its own, in Rust, that talks to chloedb-server over HTTP, like [the backbone explorer](backbone.md), and the command center shows it as an app. - **Every packet, filtered as in Wireshark.** The display filter bar takes Wireshark's filters (`ip.addr == 10.0.0.0/8 && tcp.port == 443`, `tcp.analysis.retransmission`, `dns.flags.rcode != 0`, `http.request.uri contains "login"`, `tcp.stream eq 12`, a protocol named alone), turns green as it reads and red with where it stops, and shows the SQL it became. Words that are not a filter are looked for in the Info column. The packet list is colored by Wireshark's default rules, a click opens the packet's fields (each with *apply as filter* and *and*), and Wireshark's full tree and bytes of that packet, cut from the capture with its flow's earlier packets so that TCP's analysis reads as it would in the whole file. - **When it happened.** A timeline of the packets that match, stacked by protocol; drag to keep a window. - **Conversations and what went wrong in each.** Every TCP connection, UDP exchange and ICMP pair is a flow, checked for connections refused, unreachable (with the ICMP error that said why) or never answered, slow handshakes, resets (and whether they followed a goodbye), retransmissions, zero windows, stalls that waited out a retransmission timeout, slow or failed DNS answers, HTTP errors and slow answers, SIP errors, and for a call's audio, gaps, lost packets and jitter (RFC 3550). Each finding says what it means and links the packet that shows it. A flow's page has its bytes over time each way with those packets marked, its packets, its filter for Wireshark, and the flows shaped like it. - **Hosts.** Every address, the names it went by (DNS answers, TLS server names, HTTP hosts) and who it talks to, as a graph to pan, zoom and rearrange; a line between two hosts opens all their traffic below it (`/v1/capture/CAP/edge?a=A&b=B`: what passed each way, their packets on a timeline and in a list, picked by `ip.addr == A && ip.addr == B`, and their flows), and a host's neighbours are found by personalized PageRank (`ppr`) over the conversations. - **Odd traffic.** Each flow is a vector of sixteen numbers (packets and bytes each way, duration, packet size, silences, handshake, retransmissions, resets, port, ...), standardized; k-means groups flows of a like shape, the groups are described by what sets them apart, and the flows farthest from their group's centre are listed. *Flows shaped like it* is `ORDER BY similarity(shape, :v)`. - **Ask.** A question in a sentence (*why did the call stall?*, *which connections were refused?*, *which DNS lookups were slow?*, *who talks the most?*, *what is unusual?*) is read for what it asks about and answered from the findings, citing the packets the answer rests on. No model writes the answer; each kind of question is a statement, which the SQL button shows. - **What a conversation carried.** A flow's page reads both sides' bytes from the capture's file, as Wireshark's Follow Stream shows them, each side in its color; with a TLS key log, what HTTPS carried, decrypted. - **Live.** A network interface captured as it goes, privately: see [Capture live](#capture-live). - **Upload.** Drop a capture on the page: it is decoded on the app's machine and loaded while the page waits. ## What is kept What Wireshark decodes, not the capture: each packet's columns (time, addresses, ports, protocol, length, Info) and the fields a display filter names (TCP flags and analysis, DNS names, answers and codes, HTTP method, host, URI and status, TLS server names, SIP methods and Call-IDs, RTP streams, Wireshark's expert notes). Payloads are not kept in the tables; Wireshark's full tree of one packet, and what a conversation carried, are read from the capture's file when asked, and only where that file still is and the app is not public. A capture holds what its network carried: load only captures you may share. ## The samples `chloedb-packets fetch --dir DIR` downloads public samples (tcpreplay's `smallFlows.pcap`, and the Wireshark wiki's captures of a SIP call, HTTP, DNS, TCP trouble, ECN, redirects, a shell over DNS and DHCP); `--only bigFlows.pcap` (368 MB) adds tcpreplay's five minutes of an office's link to the internet. It also makes one capture up, labelled as made up wherever it is shown: the SIP call with 61 of the caller's audio packets (1.2 s) deleted by `editcap`, to show what a stalled call looks like. ## Run it It needs `tshark` and `editcap` (Wireshark's command-line tools: `apt install tshark`, `brew install wireshark`), or `CHLOEDB_PACKETS_TSHARK` and `CHLOEDB_PACKETS_EDITCAP`. ```bash chloedb-packets fetch --dir ~/pcaps chloedb-packets serve --local ~/packets-db --captures ~/pcaps/smallFlows.pcap,~/pcaps/sip-call-stalled.pcap # or, into a server already running: chloedb-packets add ~/pcaps/*.pcap* --out ~/packets-prepared --strata http://127.0.0.1:7700 ``` `serve --local DIR` starts a chloedb-server with the app as its app `packets` (command center: Apps → Packets), keeps uploads in `DIR/uploads`, and adds the `--captures` not loaded yet. `prepare` and `load` are `add`'s two halves: `prepare` writes a capture's rows as JSON lines in a folder, `load` puts a folder in, replacing the capture's earlier rows. With `--public` the app serves its page at `/` to anyone, within `--per-minute` requests a minute from one address, and takes no uploads and shows no packet bytes. On a laptop-sized machine (4 cores), tcpreplay's `bigFlows.pcap` (791,615 packets, 368 MB) decodes in 45 s, most of it tshark's, and loads in 27 s: 28,034 flows and 1,987 hosts. Over it, a page of packets with the count and the timeline takes 0.16 s, `tcp.analysis.retransmission` (55,799 packets) 0.34 s, and the flows, hosts and odd traffic pages under 0.05 s. ## Capture live ```bash chloedb-packets serve --local ~/packets-db --live en0 # or, into a server already running: chloedb-packets live --iface en0 --strata http://127.0.0.1:7700 ``` `--live IFACE` runs tshark on a network interface (`tshark -D` lists them; `en0` is a Mac's Wi-Fi) and keeps what it sees as the capture `live`: the new packets every `--every` seconds (2), the flows they belong to judged again as they come, the hosts and who talks to whom every 10 s, and the groups by shape every 30 s. It keeps the last `--keep` minutes (30), in memory and in the tables, and starts tshark again every hour, since its TCP analysis lives in tshark's memory. With `serve --local DIR` it also keeps each packet's bytes, a file per run of tshark in `DIR/live` (`--contents DIR` names another folder, `--no-contents` keeps only the fields), deleted with their rows, so that a live packet opens with Wireshark's full tree and bytes and a conversation with what it carried. `--live-filter` is a capture filter (`not port 22`, `host 10.0.0.5`); `serve` leaves out its own port and its server's, whose requests would otherwise fill a capture on `any`. The page marks the capture live, its overview draws itself again every 5 seconds, and its packet list follows the newest packets until a packet is picked or a time chosen. `live --file F` reads a capture as if it came live, as the capture `live-`. Most of what a browser sends is encrypted with TLS. A browser started with a key log writes its session keys there, and `--tls-keys FILE` (or `SSLKEYLOGFILE`) has tshark read them: HTTPS then shows as HTTP and HTTP/2 in the packet list, the full tree and what a conversation carried. On a Mac, quit Chrome and start it from Terminal with `"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --ssl-key-log-file=$HOME/packets-db/tls-keys.log`, or Firefox with `SSLKEYLOGFILE=$HOME/packets-db/tls-keys.log /Applications/Firefox.app/Contents/MacOS/firefox`; Safari keeps its keys. The key log opens everything that browser sends while it runs: keep it on the machine, and delete it when done. A live capture holds what the network carries, so it stays on the machine that captures it: `serve --live` refuses `--public`, and a public app shows no live capture even if one is written into its database. Capturing needs the right to: on a Mac, `brew install --cask wireshark-chmodbpf` (beside `brew install wireshark`) lets your account capture without sudo, from a new Terminal window; on Linux, join the `wireshark` group. When tshark cannot capture, the capture says why in its description and the command exits. ## A daily report of what talked A live capture keeps 30 minutes of packets. Beside them it keeps a history, `pk_history`: a row for each conversation, written as the capture writes its flows, with no bytes of it. A row has the day and hour it began (local time), when it began and ended, the local host and port, the remote host and port, the remote's name (the TLS server name, the HTTP host, or the name a DNS answer gave the address), its domain (the name's last two labels, three under a suffix such as `co.uk`), the app, bytes and packets each way, what went wrong, and the process that made it. The window lets the packets go; the history stays for `--history-days` days (30), pruned once a day. `--no-history` keeps none. The process is found by looking at this machine's sockets every 3 seconds: `lsof -nP -iTCP -iUDP` on a Mac, `ss -tunap` on Linux (or `lsof` where there is no `ss`). A flow's local address and port find the socket, and its program's name and pid go on the row. It is best effort: a connection that opens and closes between two looks has no process, and without root `lsof` lists only your own account's programs. `--no-procs` turns it off. A file read with `live --file` names no process, since its packets are not this machine's. The page's **Report** (in the menu once there is history) and `GET /v1/report?day=YYYY-MM-DD` (today by default, else the newest day kept) show a day: - each process, and the domains it reached with bytes sent and received; - the day's top domains, with the names under each; - what was new: domains not seen on any earlier day of the history; - what talked in the quiet hours, `--quiet-hours 0-7` by default (local time; `22-6` wraps past midnight), when the machine is likely idle; - the day by hour, bytes sent above the line and received below. A click on a row or an hour lists the history rows behind it (`GET /v1/report/rows?day=&process=&domain=&hour=&only=quiet`), and a row whose flow is still in the live window opens with its packets. As on the other pages, the SQL button shows each statement and its rows. The history is what this machine talked to, so it stays on it: nothing is looked up by name or address, and a public app answers 404 for `/v1/history`, `/v1/report` and its rows, and leaves `pk_history` out of How it works. ## Has this happened before A flow's page has a card "Like this, before": the troubled flows of every other capture whose shape is nearest this flow's, by `ORDER BY similarity(shape, :v)` over `pk_flows`, those with the same first finding (a stall, a slow lookup) first, then other trouble of a like shape. Each says its capture, when it was (the capture's start plus the flow's), what went wrong and at which packet, so a stall today links to the stalls of last week. `GET /v1/before/` answers it. A capture's overview has a card "Seen before" (`GET /v1/capture//before`): its troubled flows, the newest first, whose nearest earlier troubled flow of the same kind is at least 80% alike, and the list of what went wrong marks them "seen before". On a live capture, "earlier" also takes in the live capture's own flows that began before, so new trouble that looks like trouble of a few minutes ago is marked as it comes. A public app lists no live capture's flows here: the statement leaves out every live capture (`capture NOT IN` them, and any `live-…`), and the answer is filtered again by name; a live flow's own card is a 404 there. ## Compare two captures The page Compare (a capture's overview has "Compare with…") takes two captures, a before and b after, and `GET /v1/diff?a=CAP&b=CAP` answers: - the hosts new in b and gone from a, and the names (DNS, TLS server names, HTTP hosts, a host's names) new in b and gone from a; - the applications and the services by flows and bytes, each with its change; - the latency of each service: the median and 90th percentile of the handshake, the round trip, the DNS answer and the HTTP answer, a against b, with the change of the median and whether it is beyond noise. With fewer than 5 flows on a side it says "too few to tell". Otherwise b's median minus a's is bootstrapped (each side drawn again with replacement, 2,000 times, with a fixed seed, so the same captures give the same answer), and the change is beyond noise when the middle 95% of those differences leaves out zero; - what went wrong, by kind, a against b; - b's flows that did worse than the same conversation in a (the same transport, server port and name, or server address without a name): a kind of trouble the conversation never had in a, a time more than twice a's median and 50 ms more, or a worse score. Each part carries the statements it was read with (`sql`), shown under it on the page. The flows and the times are read 10,000 a capture at most. ## The story of a capture A capture's overview and a flow's page have "Tell me what happened": the app gathers what it already has (the worst flows and their findings with their packet numbers, the flows that carried the most, the packets per tenth of the capture; for a flow, its findings, times and the packets that went wrong) and asks chloedb-server's `llm()` for a short account in which every claim cites packets as `[#123]` or flows as `[flow N]`. The page turns those into links, and the app drops any citation that names a packet or a flow the facts did not give. "What the model was told" shows the facts as sent. `GET /v1/story/capture/` and `GET /v1/story/flow/` give a kept story or say one can be asked for; `?go=1` asks. The model is `--llm-model` (default `anthropic/claude-haiku-5-5`, as chloedb-hn's), and chloedb-server holds its key (`ANTHROPIC_API_KEY` where the server runs). When the server has no key, or `llm()` fails, the card says so in one line. An answer is kept per model and facts, in `pk_stories` (in memory only in a public app), so a reload, or asking again while the capture is the same, costs nothing. It sends what a capture holds to the model's provider, so it is off for live captures unless the app is started with `--llm-live`, and off in a public app unless it is started with `--public-llm`. ## Where your traffic went The Where page of a capture places each remote address on the internet: the network that announces it (its AS number and name), the country its block of addresses was given to, the route's prefix, and whether that route is valid in RPKI. It shows the traffic by country (a world map and bars) and by network (bytes, flows, flows in trouble, the mean time to connect), calls out the destinations whose route RPKI finds invalid, and lists the networks whose flows were most often slow or in trouble, with their time to connect beside the capture's mean, so that a far network reads as far. A network links to its page: its addresses, its flows worst first, its packets as a display filter, and what the reference tables say of it. A host's page and a flow's page say where their ends on the internet are. Private and reserved addresses are not looked up: they are counted under their range (`private`, `loopback`, `multicast`, `carrier NAT`, ...). The lookups use public files downloaded in bulk, the same files for everyone, so nothing about a capture leaves the machine: ```bash chloedb-packets refdata --dir ~/packets-refdata # about 165 MB; again later to refresh chloedb-packets serve --local ~/packets --refdata ~/packets-refdata # or with a capture or a live capture: chloedb-packets add capture.pcap --out prepared --refdata ~/packets-refdata chloedb-packets live --iface en0 --refdata ~/packets-refdata ``` | file | from | what | |---|---|---| | `pfx2as-v4.gz`, `pfx2as-v6.gz` | CAIDA's RouteViews prefix2as | each routed prefix and its origin AS | | `asn.txt` | RIPE NCC's asnames | each AS's name and country | | `delegated--extended-latest` | ARIN, RIPE NCC, APNIC, LACNIC, AFRINIC | the country each block was given to | | `vrps.json` | rpki-client (console.rpki-client.org) | RPKI's validated ROAs | `refdata` keeps a file fetched less than 20 hours ago (`--fresh-hours`), and a file whose download fails keeps its last copy. With `--refdata`, `serve`, `load`, `add` and `live` read the folder into memory (longest-prefix tables, a sorted list per prefix length, so IPv6 prefixes longer than /64 are left out) and place every host as its capture loads, a live capture's as its hosts are written, and at `serve`'s start every capture not placed yet. A route is valid when a ROA covering it names its origin and allows its length, invalid when ROAs cover it but none does, and `no ROA` when none covers it (RFC 6811); a prefix announced by several origins takes the best of them. The country is the registry's, which says where a block was given, not where a server stands. On a 4-core Linux VM with 15 GB (November 2026): the files were 165 MB (vrps.json 108 MB) and downloaded in 19 s; reading them into memory took 1.9 s, and the app held 148 MB with them read (1.17 million IPv4 and 271,000 IPv6 routes, 1.04 million VRPs, 334,000 blocks, 123,000 ASes); writing them into the tables took 29 s, once: a stamp of the files in `pk_refdata` skips it until they change. | table | what | |---|---| | `pk_where` | an address of a capture: its scope (`public` or its range), AS, AS name, country, prefix, RPKI state, and the ASes of the ROAs covering an invalid route | | `pk_prefixes` | every routed prefix, its origin AS (and every origin seen) and its block's country | | `pk_asns` | every AS's short name, full name and country | | `pk_vrps` | every validated ROA: prefix, max length, AS, trust anchor | | `pk_refdata` | each reference file: where it came from, its size and rows, when it was fetched and loaded | With `--backbone URL` (and `--backbone-token`, or `CHLOEDB_BACKBONE_TOKEN`), the Where page also asks your own [chloedb-backbone](backbone.md) app about the 15 networks that carried the most bytes: their alerts (outages, withdrawn routes) over the capture's span, or the open ones for a live capture, and their announcements it found RPKI invalid in its last day. It sends AS numbers and nothing else, and it is off unless you pass it. The backbone app keeps a few days, so an old capture's span finds no alerts. A network's page links to its page in a backbone app (`URL/#/as/`: its routes and their RPKI state, its outages, the networks it buys transit from), https://backbone.chloetech.ai unless `--backbone-link URL` names another (or `--backbone` does, when no link is given); `--backbone-link ''` hides it. It is only a link: the app asks nothing of it, and the AS number goes to that site only when someone clicks. `tests/whereis.rs` makes up a capture to three addresses and a folder of reference data a few lines long (no network), loads them into a real chloedb-server with `add --refdata` and `live --file --refdata`, and checks the Where page, a network's page and the places of a flow's ends, including a route that is RPKI invalid. ## Alerts written as SQL The page's Alerts tab shows what rules found in a capture. A rule is a row of `pk_rules`: a title, a line saying what it means, a severity, and one SELECT over the app's tables. Each row the statement returns is evidence. Rows about the same thing (the same `subject` column, else the same `host` and `remote`) are one alert, a row of `pk_alerts` that keeps the flows (`flow`, `flows`) and packets (`no`) its rows cite, when it began and when it was last seen. An alert stays open while its rule finds it and ends when the rule stops finding it or is turned off. The rules run every minute over a live capture, reading its last five minutes, and once over a capture when it is loaded, reading all of it, so the samples have alerts too. `serve` also runs them once over loaded captures they never read. A statement may name `:cap`, `:scope`, `:since` and `:since_hour` (seconds into the capture where its window starts: five minutes and an hour before the newest packet live, the whole capture loaded), `:until`, `:since_ts` and `:now_ts` (the same as times). | rule | fires on | |---|---| | Beaconing | a host reaching the same remote (a name, or an address and port) six times or more on a steady rhythm: the gaps between contacts vary less than 20% of their mean (their coefficient of variation is under 0.2) and are a second or more | | First contact | a name or remote address never seen before in this database, after the first hour of watching | | DNS failures burst | twenty or more NXDOMAIN or SERVFAIL answers to one host in five minutes | | Plain-text credentials | HTTP without TLS carrying an Authorization header (Basic or a bearer token, not Digest, NTLM or Negotiate) or a posted form with a password-like field | | Unusual ports | TCP connections from a local host to a port outside a common set, on hosts outside its network: one alert per host and port | | Trouble rising | the share of flows in trouble over five minutes at least twice the share over the hour (the whole capture, loaded), at least one in five, with twenty flows or more | | Newly registered domain | a name whose domain was registered in the last 30 days; off unless `serve --rdap` | SQL is awkward at the gaps between a group's rows, so beaconing is measured in Rust (`src/beacon.rs`): `pk_beacons` holds, for each host and remote reached three times or more, the contacts (connections opened within a second of each other count as one), the median gap and the coefficient of variation, and the rule reads that table, so its thresholds stay SQL. Traffic on a timer by design is left out: anything to a multicast or broadcast address (mDNS, SSDP, LLMNR, NetBIOS, DHCP) and NTP, whose clients poll every 64 to 1,024 seconds. `pk_seen` holds each name, remote address and country (from `pk_where`, when the app has `--refdata`) a scope has seen, with when and where first; a live capture's scope is `live`, kept across runs, and each loaded capture is its own. Nothing is first contact in a scope's first hour, so a new database is not all alerts. The credentials rule needs the secret to be read but not kept: tshark prints the Authorization header and the form's field names, and the decoder keeps only a flag in the packet's `issues` (`cleartext-auth`, `cleartext-form`). The header, the form's values and the password are in no table. The Rules tab lists every rule with its SQL, whether it is on, its last run and how many rows it returned. Its editor tries a rule over the capture on screen ("Test" shows the rows and the alerts it would make, and keeps nothing) and saves it. A rule's SQL is checked before it is kept: one SELECT (or WITH … SELECT), not calling `llm()` or `embed()`, parsed and bound by the server (`/v1/sql/check`), then run over the capture. Rules run through `/v1/query`, which takes only a SELECT, within 10 seconds (20 for the minute's run). The built-in rules are written as `serve` starts and rewritten when their text in `src/rules.rs` changes, unless a person edited them; an edited one can go back to its built-in text. A built-in rule is turned off, not deleted. A public app shows the rules read-only (without their last runs) and the alerts of the captures it shows, none of a live capture's; changes and tests need the token and are refused in public mode. `--rdap` turns on the newly registered domain rule: each minute up to 20 new names are looked up at rdap.org (the registrable part of the name, from the last two labels, or three under `co.uk` and the like) for their registration date. It is off by default because it sends the names this network looks up to the registries; nothing else in this feature leaves the machine. ## The tables | table | what | |---|---| | `pk_captures` | a capture: its file, span, packets, bytes, flows, hosts, its protocols, its groups, and how many flows went wrong, by kind | | `pk_packets` | a packet: its columns, the fields a display filter names, its TCP analysis (`issues`), Wireshark's expert note, and its flow | | `pk_flows` | a conversation: its ends, packets and bytes each way, timings (handshake, round trip, DNS, HTTP, jitter, gaps), state, findings (each at a packet), `shape VECTOR(16)`, group and how odd it is | | `pk_hosts` | an address: its names, role, services, bytes each way, peers and trouble | | `pk_talks` | who talks to whom (an edge table, weighted by bytes), read by `ppr` | | `pk_history` | a live conversation kept for days: its day and hour, ends, name and domain, bytes and packets each way, findings and process, no packets | | `pk_stories` | the stories a model told of captures and flows, kept by model and facts | | `pk_rules` | an alert rule: its SQL, the built-in text it came from, on or off, its last run | | `pk_alerts` | an alert: its rule, what it is about, the flows and packets that fired it, the rows (`evidence`), open or ended | | `pk_beacons` | each host's rhythm of contact with each remote: contacts, median gap, coefficient of variation | | `pk_seen` | each name, remote address and country first seen in a scope, when and where | ## Tests ```bash cd chloedb-packets && cargo test --profile ci ``` `tests/cluster.rs` writes a capture byte by byte (a slow DNS lookup, an HTTP request answered 500 and sent again, a refused connection), decodes it with tshark, loads it into a real chloedb-server, and checks every route: the findings and the packets they cite, the display filters against the packets Wireshark would pick, the full tree, the hosts' names, groups and answers to questions; then it reads the same file with `live --file` and checks that the live capture finds the same things, that its newest packets come in order, that its packets open from the file and its conversation shows what it carried, and that a public app on the same database shows none of it, nor any capture's contents. `tests/history.rs` writes a laptop's three days (October, an afternoon and a night in November), reads them with `live --file` and a one-minute window, and checks that the history keeps what the window let go, that October is pruned, each day's report (names from DNS answers and HTTP hosts, what was new, the quiet hours, the hours), the rows behind a number, `--no-history`, and that a public app answers 404. They need chloedb-server (`CHLOEDB_SERVER_BIN`) and tshark, and is skipped without them unless `CHLOEDB_PACKETS_NEED_SERVER` is set, as the `Demos` workflow does. `tests/history.rs` writes a laptop's three days (October, an afternoon and a night in November), reads them with `live --file` and a one-minute window, and checks that the history keeps what the window let go, that October is pruned, each day's report (names from DNS answers and HTTP hosts, what was new, the quiet hours, the hours), the rows behind a number, `--no-history`, and that a public app answers 404. `tests/rules.rs` writes two captures (a laptop that calls a server every 30 seconds or so, fails 25 lookups in half a minute, sends a password in plain HTTP as a header and as a form, and an hour on reaches a new name; and a clean visit to a page) and checks which rules fire, what they cite, that the password is in no answer, the rules' API (test, save, edit, turn off, delete, and what it refuses) and a public app's refusals. Both need chloedb-server (`CHLOEDB_SERVER_BIN`) and tshark, and is skipped without them unless `CHLOEDB_PACKETS_NEED_SERVER` is set, as the `Demos` workflow does. `tests/compare.rs` writes two days of a shopper's computer (six lookups answered in 20 ms, then in 400 ms; a refused connection to the shop, then to a new host), loads both, and reads the second as if it came live. It checks that the second day's refusal finds the first day's, of the same kind and with its date, that a public app lists no live flow and answers 404 for anything live, that the comparison finds the new host, the slower DNS beyond noise, the six lookups that got worse and the SQL of each part, and that the story says in one line that `llm()` could not be asked (the server is started without a key), and is refused for a live capture and in a public app. The citation filter is a unit test in `src/story.rs`. --- # chloedb-apps: apps built from a description `chloedb-apps` is a prototype app engine on ChloeDB. You describe an app in a sentence ("a stock room: items, suppliers, what is low, purchase orders"), and the engine has a model plan and write it, checks what it wrote, stores every piece in ChloeDB and runs it. You then change it by asking ("add a Check price online button on each item"), and every change is a new version you can go back from. Everything an app is lives in ChloeDB, as rows: - **Its pieces are SQL statements.** Screens are `CREATE SCREEN`, rules are `CREATE RULE`, tables are `CREATE TABLE`, and each is a row of `sa_capabilities`. A version is a row of `sa_compositions` that lists the pieces it is made of, so going back is one write. Tables only grow, so an app's data survives every change and every step back. - **Pieces are shared.** Components (`ui.calendar(props)`) and helpers (`lib.dates.addDays(day, 1)`) are written once and used by every app. They are found for a new request by words (BM25) and by meaning (a vector column), and linked in a graph that ChloeDB walks (`REACHABLE`, `ppr`) to offer an app a newer version. 150 of them ship in `chloedb-apps/library/`. - **What people do is recorded** in ChloeDB (`sa_events`), and the engine counts patterns in it (a search typed again and again, the same field changed row after row) to suggest changes, or to build one beside the live version for the owner to try, keep or drop. - **Apps get services:** sign-in, files, email (held in an outbox unless a mail server is set), address search and maps, and, when the owner switches them on, a model and the web (below). It is a program of its own, in Node.js, that talks to chloedb-server over HTTP. Views run in sandboxed frames in the browser, and server functions run in QuickJS compiled to WebAssembly, with no network and a time limit. ![The studio: an app on the left, and on the right the request box, the version's summary, and the Model and web switches](../assets/img/strata-apps-studio.png) ## Run it You need Node.js 20 or later, chloedb-server, and Claude Code signed in (`claude` on the PATH). The engine calls `claude -p`, so it uses that sign-in and needs no API key of its own. ```bash (cd chloedb-server && cargo build --release --bin chloedb-server) cd chloedb-apps && npm ci ./run.sh # the studio at http://127.0.0.1:7730/ ``` `run.sh` starts a chloedb-server of its own on `127.0.0.1:7720`, with its database in `chloedb-apps/data/`. `--strata URL` uses a server that is already running instead (started with `--seq-no`, for live updates). Every option is in [the engine's README](../../chloedb-apps/README.md#run-it). A first version of a small app takes about a minute and a bigger one 2 to 4 minutes; a change takes 20 seconds to 2 minutes. The time and the cost of each build are on its timeline (Versions → Timeline). ## On a cluster A cluster the [operator](server.md#on-kubernetes) runs gets the engine from its `StrataCluster`, beside the crawler and the spreadsheets: ```bash kubectl -n strata create secret generic anthropic --from-literal=key=sk-ant-... # the model's key, once kubectl -n strata patch strata demo --type merge -p '{"spec": { "secretEnv": [{"name": "ANTHROPIC_API_KEY", "secret": "anthropic"}], "apps": {"serviceType": "NodePort", "nodePort": 30731, "publicUrl": "http://203.0.113.5:30731"}}}' ``` The operator runs the engine's own image (`ghcr.io/chloetech-ai/chloedb-apps`: Node, Playwright's Chromium for the drawn checks, and Claude Code) as a Deployment of one pod, `-apps`, behind a Service of that name, and restarts the coordinators so that they list it: **Apps → App creator** appears in the command center. - **The app creator is a page of the command center.** Describe an app and build it there: the conversation of changes and builds (each build's progress, its screens drawn while the model writes the rest, its timeline), the app itself on a phone, a tablet or a computer (drawn 1280 px wide and scaled to fit the stage), and what it is made of: **Made of** measures how much of the code that runs the engine generated from the CREATE TABLE, CREATE SCREEN and CREATE RULE statements the agent wrote, how much the agent wrote from scratch (JavaScript, or a screen written out as JSON), and how much is the library's, piece by piece (`GET /api/apps//made`, `engine/provenance.mjs`); **Code** reads each piece's SQL and edits a CREATE SCREEN with no model; **Time** is where its builds' time and cost went; **Data** (the first tab after a build, with each table as a CSV), **Versions**, **Design** and **Reach** are the app's tables, versions, looks and switches. The bar shows what the app's builds cost in all, and its menu renames the app (`POST /api/apps//rename {name}`; a name given there, or when the app is made, stays: a later plan does not rename it, and a label that starts the description, like `acme-shop`, stays in front of the name the plan picks), duplicates it with its rows (`POST /api/apps//duplicate`), exports its rows as JSON (`GET /api/apps//export`) and deletes it (`POST /api/apps//delete`): its own tables `app__*` and no other app's, its pieces, versions, use, settings, members and files; the shared library stays. **Usage**, beside the app's screens, is the studio's Activity view over the whole stage: each visit step by step, the paths people take between screens, how easy the app is to use and what needs a look. The app's screens run as they do in the studio: in frames with the studio's sandbox and policy (no same origin, so a view reads nothing of the command center's, its key included, and no network), each read and write sent to the page as a message, which calls the engine for that one app. People's sign-in does not pass through chloedb-server, so the creator shows an app as a visitor sees it; with `publicUrl`, **Its own page** opens the app as people use it, and **Studio** opens the standalone studio. Live updates come by long polls of `GET /api/events`, since chloedb-server forwards whole answers. - **Its apps are rows of the cluster, each read and written with a key of its own.** The engine reaches the coordinators with a key limited to its tables, `sa_*` and `app_*` (the operator makes it, `-apps-credentials`, when the coordinators can, [keys for apps](server.md#apps); `spec.apps.tables` changes it; an operator whose ClusterRole cannot make Secrets gives it the cluster's admin token, `tokenSecret`, instead), and gives every app a key made from that one (`POST /v1/keys/own`), limited to the app's tables `app__*` (write) and the table its library's table functions read (`sa_numbers`, read), named `apps-app/app-`. An app's `app.sql`, inserts, updates and removes go with its key, so the server refuses another app's rows, the engine's people and sessions, and every other table of the cluster, whatever the engine's rewrite of the SQL lets through; the keys end when the engine's key is revoked. An engine given the admin token (an operator from before such keys, `deploy/kube.yaml`) makes itself the limited key, follows the feed of changes with it too (the server sends a limited key the operations of its tables alone), and keeps the token only for an older server's feed, and says so in its log; `GET /api/status` shows which (`keys`). Through a coordinator over shards the engine walks its apps' links itself (`engine/walk.mjs`), as it did before a coordinator walked graphs, and it tells the model that an app reads its links a step at a time. - **The studio and each app's own page have an address of their own**, `publicUrl`, through a node's port, a load balancer, or an Ingress of your own in front of the Service. Files and map tiles the creator's frames show are loaded from there too (without it, through chloedb-server, which needs the key the frames cannot send). **Studio** asks the engine, through chloedb-server and so only with an admin key, for a link that signs the browser in once, within two minutes, for 30 days. Anything else that reaches the studio's address gets a page that says where to sign in. - **Keys limited to tables build apps by their tables.** Beside a cluster the engine checks its callers (`"checks_callers": true`, `engine/callers.mjs`): reading an app takes read on its tables (`app__*`), using it as its screens do (rows, functions, files) takes write there, and changing, publishing, renaming or deleting it takes admin there; building a new one, or a copy, takes admin on every app's tables (`app_*`), which the app-owner preset gives. A key limited to tables lists only the apps whose tables it reads, follows one app's events (`/api/events?app=`), and never gets the studio's login or the graph of every app. A key of every table keeps read to look and admin to change. - **Apps their owners publish are open to everyone, as far as the owner says.** **Publish** in the app creator asks *who can see this?* (`POST /api/apps//publish {on, access, name, hosts}`, `engine/publish.mjs`): **only me** (not published, the default), **visitors can look** (`access: "look"`: read what its screens show, no writes), **customers can look and add** (`"add"`: also add rows, upload files and run its functions, and edit or delete only the rows they added themselves, as `sa_events` records who added each), or **anyone can do anything** (`"change"`, which asks for the app's name to be typed). An app that never chose (a publish that names no access, or an app published before the choice existed) is at `look` until its owner picks more. A visitor who may only look is not offered the app's forms, nor the buttons and row actions that add, change or remove; a call their access does not allow is a 403 marked `refused` that says what was refused ("read-only for visitors"), shown as a quiet note, never as an error. **See it as a stranger** opens the app's own page as someone with no account would see it under the choice being weighed (each call carries `x-sa-as: visitor`, which only ever lowers what the studio's session may do), and the tab lists the columns that look like emails, phone numbers or addresses, which a public app shows to anyone. A published app is reached at `/a/` on the engine's address, at `.` when the engine has a domain (`spec.apps.publish`, below), and at hosts of the owner's own (a CNAME to `.`). The public reaches the app as it runs and nothing of how it is made: its page and the runtime's files, its state without its requests, versions, people or outbox, and the calls its screens make under its access, and `app.ask`, `app.fetch` and `app.email` under the app's Reach switches and its model calls a day. What a visitor writes is checked on the server: a column whose forms offer a fixed list of choices takes only those (and the values the app's own code writes to it), a field is at most 10 KB, a row 64 KB and a list 100 items (`STRATA_APPS_PUBLIC_FIELD_MAX`, `STRATA_APPS_PUBLIC_ROW_MAX`), and a refusal is a 400 that says why; a failure tells a visitor nothing of shards or physical tables. An error a visitor's browser or call hits is recorded under Usage and never starts a repair, so nothing a stranger sends reaches the model. The app's people (`GET /api/apps//people`) are listed only to its signed-in members, with their emails only for its owner; one account serves every app on the engine, but a visitor is a member of an app only once they sign up or in on it, and signing up with an email that has an account signs in with the right password and otherwise says only that the email and password cannot be used. Building and changing it, other apps, versions built to try, the library and the studio stay behind the studio's login. Each visitor is held to 240 calls a minute and 20 of the dear ones (model, web, mail, accounts, uploads); `STRATA_APPS_PUBLIC_RATE` and `STRATA_APPS_PUBLIC_DEAR_RATE` change that. - **The model's key is the cluster's** (`secretEnv`'s `ANTHROPIC_API_KEY`, as the agents use), and `spendCapUsd` stops every model call once the engine has spent that much (25 US dollars unless set; 0 for no limit). - **What it keeps outside the cluster** (files people gave its apps, map tiles, what the model has cost, Claude Code's home) is on a volume of its own, `-apps`, kept when `spec.apps` goes and deleted with the cluster. | `spec.apps` | default | | |---|---|---| | `publicUrl` | | where browsers reach the studio and each app's own page; without it the creator works in the command center, but cannot open the studio or an app's own page, and its frames show no files | | `publish` | | open published apps to everyone, at `.`: `domain` is your own (`apps.example.com`, with a DNS record `*.apps.example.com` pointing at the load balancer) or `sslip` (the load balancer's address as a name of sslip.io, `kids-reading.203-0-113-5.sslip.io`, with no record); `email` for Let's Encrypt. The operator adds a load balancer, `-apps-public` (ports 80 and 443; most clouds bill for one), and Caddy beside the engine, which gets a published app's certificate the first time someone opens it, after asking the engine whether the host is one of its apps (`GET /api/tls/ask`), and keeps the certificates on the engine's volume | | `serviceType`, `nodePort` | `ClusterIP` | the Service's type: `ClusterIP` (put an Ingress in front), `NodePort` (30000 to 32767) or `LoadBalancer` (most clouds bill for one) | | `spendCapUsd` | `25` | what the model may cost, in US dollars, counted across restarts | | `storage` | `1Gi` | its volume's `size` (it only grows) and `storageClassName` | | `image` | `ghcr.io/chloetech-ai/chloedb-apps:latest` | the engine's image | | `env` | | the engine's own settings (`STRATA_APPS_MODEL`, `STRATA_APPS_SMALL_MODEL`, ...); secrets go in `secretEnv` | | `paused` | `false` | no pod for now (the apps stay in their tables) | | `args`, `resources` | | more arguments of the engine, and its container's resources (250m CPU and 600 MiB asked, 1.5 GiB at most) | The image runs alone as well, with a chloedb-server of its own on its volume: `docker run -p 7730:7730 -v apps:/data -e ANTHROPIC_API_KEY ghcr.io/chloetech-ai/chloedb-apps` (without `STRATA_APP_TOKEN` there is no login, so keep that on your own machine). ## A model and the web, per app An app's code can ask a model, reach the web and run on a schedule, each only once the app's owner has switched it on in the studio, under **Model and web**: | | what the app calls | limits | |---|---|---| | A model | `app.ask(prompt, {json, system})`: a small model (Haiku; `STRATA_APPS_ASK_MODEL`) summarizes, sorts, extracts or drafts | the same question gets the kept answer (`sa_asks`) at no cost; 200 questions a day per app by default (the owner can change it; `STRATA_APPS_ASKS_PER_DAY`), 20 a minute | | Web search | `app.ask(prompt, {web: true})`: the model searches the web before it answers | kept answers expire after 6 hours; a call stops at $0.25 | | Web pages and APIs | `app.fetch(url, {method, json, headers, secret})`: JSON parsed, an HTML page's readable text and title; `CREATE SOURCE` and `PULL` read feeds and JSON lists into tables | the hosts the owner allowed, on public addresses only (below); 2 MB and 10 seconds a request; GET answers kept 10 minutes; 1000 a day per app | | Schedules | `EVERY ...` on a rule or function, and `CREATE SOURCE` | at most every 15 minutes; stops after 5 failures in a row | Until the owner switches it on, the call answers that it is off, and the app shows that instead of failing (it is not sent to the repair). A build says which of these the code uses, which are still off, and which hosts and secrets it needs that the owner has not given it. In a build's tests the calls answer empty and reach nothing. Under the web, the owner also allows each **host** an app reads from (GET, HEAD) and, separately, each host it may send to (POST); a host covers its subdomains. Hosts the code names, or tried and was refused, are listed for the owner to allow, and every hop of a redirect must be allowed too, so a change (asked for, built from use, or a repair) never widens what an app reaches by itself. Apps switched on before host lists keep "any public host" until the owner replaces it. An API key is a **secret**: the owner pastes it once, binds it to the hosts it may go to, and says where it goes (`Authorization: Bearer`, a header of its own, or a query parameter). Code names it, `app.fetch(url, {secret: 'weather'})`, and never holds it. Secrets are sealed with AES-256-GCM in ChloeDB, apart from the app's code, with `STRATA_APPS_SECRET_KEY` (or a key the engine keeps in `DATA/secret.key`), sent only to their hosts, never shown again, and replaced by `[secret]` in an answer that echoes them. A key written into code fails the build's checks. A fourth switch, **Schedules**, lets rules and functions run on their own: `CREATE RULE brief EVERY DAY AT '07:00' TZ 'Europe/Madrid' AS ...`, or a source that fills a table from a feed or a JSON API, `CREATE SOURCE news FROM FEED 'https://news.example.com/rss' EVERY 1 HOUR INTO stories (title, link, published, summary) KEY link` (each item added once, by its key). A schedule runs at most every 15 minutes, under the app's daily limits, and stops after 5 failures in a row; the studio lists each with its next run, its last result, Run now and Pause. `app.fetch` refuses addresses on the machine or its networks: loopback, private and link-local ranges, carrier-grade NAT, unique-local and link-local IPv6, and IPv4 inside IPv6. Every address a name resolves to is checked when the connection is made, and again after every redirect, so a name that points inside the network is refused too. Only ports 80, 443, 8080 and 8443 are open, and a URL may not carry a name or password. ## Before you share it It is a prototype for one person or a small team: - **Run alone, the studio has no sign-in.** Anyone who can reach it can change any app and spend on the model. Keep it on `127.0.0.1`, put it behind the shared-key gate in `chloedb-apps/deploy/` (a link with a key, kept in a cookie), or run it beside a cluster ([above](#on-a-cluster)), where it signs in the cluster's admins. - **An app is for the people who run the studio until its owner publishes it.** Beside a cluster, an app's own pages need the studio's sign-in, so only the cluster's admins open them, until its owner publishes it ([above](#on-a-cluster)): then anyone with its address uses it as far as the owner chose, and signs up and in with the engine's own accounts. Signing in with Google and others is planned. - **Set a spending limit.** `STRATA_APPS_SPEND_CAP_USD` stops the model once the engine has spent that much, counted from what Claude Code reports and kept across restarts. The apps' own questions count apart: together they stop at a day's share (`STRATA_APPS_ASK_CAP_USD`, a quarter of the limit by default, and $20 a day with no limit set), and builds and checks get the rest, so a published app's visitors cannot stop the studio's builds, nor builds the apps, nor one app the others for more than a day; one app's questions stop at $2 a day (`STRATA_APPS_ASK_USD_PER_DAY`). A published app suggests changes from its use rather than building them, unless its owner sets its mode to build. - **App data is checked in code, not on the server.** People sign in to apps, but row rules (`lib.access`) run in the app's views and functions; the server does not enforce them yet. - **A piece that passes the checks can still be wrong.** The engine opens every view after a build, draws each on a phone and a computer (with Playwright installed), fixes what its rules measure, and runs the app's tests; going back a version is the safety net for the rest. ## Tests ```bash cd chloedb-apps && npm test ``` The tests that need a chloedb-server find `chloedb-server/target/release/chloedb-server` (or `STRATA_SERVER_BIN`) and are skipped without one; CI runs them all against the server it builds (`STRATA_APPS_NEED_SERVER=1`), and again against a cluster of two shards (`STRATA_APPS_TEST_SHARDS=2`, which starts the shards and a coordinator over them in place of a server). No test calls a model.